text stringlengths 10 2.72M |
|---|
package info.cmn.meuapp;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import info.cmn.meuapp.helpers.DBHelper;
public class CursoresActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cursores);
}
@Override
protected void onPostResume() {
super.onPostResume();
deletarRegistros();
}
public void criarRegistros()
{
DBHelper db = new DBHelper(getBaseContext());
SQLiteDatabase banco = db.getWritableDatabase();
ContentValues ctv;
for (int i=1; i<21; i++)
{
ctv = new ContentValues();
ctv.put("nome", "Cliente Manoel"+Integer.toString(i));
ctv.put("email", "email"+Integer.toString(i)+"@gmail.com");
banco.insert("clientes", null, ctv);
}
}
public void editarRegistros()
{
DBHelper db = new DBHelper(getBaseContext());
SQLiteDatabase banco = db.getReadableDatabase();
Cursor cursor = banco.rawQuery("SELECT _id, nome, email FROM clientes", null);
ContentValues ctv;
if (cursor.moveToFirst())
{
//Tem registros
do{
ctv = new ContentValues();
ctv.put("nome", cursor.getString(cursor.getColumnIndex("nome"))+" ALTERADO" );
banco.update("clientes", ctv, "_id = " + cursor.getString(cursor.getColumnIndex("_id")), null);
Log.d("Cursor: ", cursor.getString(cursor.getColumnIndex("nome")));
}while (cursor.moveToNext());
}
cursor.close();
}
public void deletarRegistros()
{
DBHelper db = new DBHelper(getBaseContext());
SQLiteDatabase banco = db.getReadableDatabase();
//getWritableDatabase();
Cursor cursor = banco.rawQuery("SELECT _id, nome, email FROM clientes", null);
ContentValues ctv;
if (cursor.moveToFirst())
{
//Tem registros
do{
banco.delete("clientes", "_id = "+ cursor.getString(0), null);
Log.d("Cursor: ", cursor.getString(cursor.getColumnIndex("nome")));
}while (cursor.moveToNext());
}
else {
Log.d("Cursor", "SEM REGISTRO");
}
cursor.close();
}
}
|
package com.example.BankOperation.controller;
import com.example.BankOperation.model.Credit;
import com.example.BankOperation.model.Payment;
import com.example.BankOperation.service.CardService;
import com.example.BankOperation.service.CreditService;
import com.example.BankOperation.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("api/payment")
public class PaymentController {
@Autowired
private PaymentService paymentService;
@Autowired
private CreditService creditService;
@Autowired
private CardService cardService;
@PostMapping("/credit/{id}")
@ResponseStatus(HttpStatus.ACCEPTED)
public Payment beginPayment(@PathVariable Long id, @RequestBody Payment payment) {
payment.setCredit(creditService.getCreditById(id));
return this.paymentService.beginPayment(payment);
}
@PutMapping("/confirmPayment/{id}")
@ResponseStatus(HttpStatus.ACCEPTED)
public Payment confirmPayment(@PathVariable Long id, @RequestBody Confirmation confirmation) {
return paymentService.confirmPayment(id, confirmation.confirmationCode);
}
@GetMapping("/{id}")
private List<Payment> getPaymentHistory(@PathVariable Long id) {
return this.paymentService.getPaymentHistory(id);
}
// @GetMapping("/{id}")
// private Payment getOnePayment(@PathVariable Long id) {
// return paymentService.getPayment(id);
// }
//
// @PostMapping
// @ResponseStatus(HttpStatus.CREATED)
// private Credit addPayment(@RequestBody Payment p) {
// return paymentService.addPayment(p);
// }
//
// @PutMapping
// @ResponseStatus(HttpStatus.ACCEPTED)
// private Payment updatePayment(@RequestBody Payment p) {
// return paymentService.updatePayment(p);
// }
//
// @DeleteMapping("/{id}")
// private void deletePayment(@PathVariable Long id) {
// paymentService.deletePayment(id);
// }
}
class Confirmation {
Long paymentId;
Integer confirmationCode;
public Confirmation() {
}
public Confirmation(Long paymentId, Integer confirmationCode) {
this.paymentId = paymentId;
this.confirmationCode = confirmationCode;
}
public Long getPaymentId() {
return paymentId;
}
public void setPaymentId(Long paymentId) {
this.paymentId = paymentId;
}
public Integer getConfirmationCode() {
return confirmationCode;
}
public void setConfirmationCode(Integer confirmationCode) {
this.confirmationCode = confirmationCode;
}
}
|
package com.example.lemonimagelibrary.config;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.DrawableRes;
import android.util.Log;
import android.widget.ImageView;
import com.example.lemonimagelibrary.cache.BitmapCache;
import com.example.lemonimagelibrary.cache.CacheMode;
import com.example.lemonimagelibrary.cache.DiskBitmapCache;
import com.example.lemonimagelibrary.cache.DoubleLruCache;
import com.example.lemonimagelibrary.cache.MemoryLruCache;
import com.example.lemonimagelibrary.cache.NoLruCache;
import com.example.lemonimagelibrary.loader.LoaderMode;
import com.example.lemonimagelibrary.policy.IPolicy;
import com.example.lemonimagelibrary.policy.SerialPolicy;
import com.example.lemonimagelibrary.request.BitmapRequest;
import com.example.lemonimagelibrary.request.RequestQueueHelper;
import java.io.File;
/**
* Created by ShuWen on 2017/3/22.
* 参数封装,对于外部暴露
*/
@SuppressWarnings("ALL")
public class BitmapConfig {
//请求地址
private String url;
//加载本地图片
private File file;
//加载本地资源id图片
private int resId;
//显示的imageview控件
private ImageView imageView;
//用于创建硬件缓存所需环境
private Context context;
//加载器策略
private IPolicy policy;
//图片缓存策略
private BitmapCache cache;
//加载过程显示策略
private int loadingResId;
//请求成功回调接口
private BitmapListener bitmapListener;
//用于判断是否需要显示
private boolean hasListener = false;
//加载器选择
private LoaderMode loaderMode;
private BitmapConfig(Builder builder){
if (builder.cache == null){
this.cache = DiskBitmapCache.getInstance(builder.context);
}else {
this.cache = builder.cache;
}
this.url = builder.url;
this.file = builder.file;
this.resId = builder.resId;
this.context = builder.context;
this.loadingResId = builder.loadingResId;
this.imageView = builder.imageView;
this.policy = builder.policy;
this.hasListener = builder.hasListener;
loaderMode = builder.loaderMode;
this.bitmapListener = builder.bitmapListener;
}
public LoaderMode getLoaderMode() {
return loaderMode;
}
public int getLoadingResId() {
return loadingResId;
}
public File getFile() {
return file;
}
public int getResId() {
return resId;
}
public boolean isHasListener() {
return hasListener;
}
public String getUrl() {
return url;
}
public ImageView getImageView() {
return imageView;
}
public Context getContext() {
return context;
}
public IPolicy getPolicy() {
return policy;
}
public BitmapCache getCache() {
return cache;
}
public BitmapListener getBitmapListener() {
return bitmapListener;
}
private void show(){
if (loaderMode != null){
BitmapRequest bitmapRequest = new BitmapRequest(this);
RequestQueueHelper.addRequest(bitmapRequest);
}else {
Log.e(GlobalConfig.TAG,"请调用load方法设置加载数据来源!");
}
}
public interface BitmapListener{
void onSuccess(Bitmap bitmap);
void onFail();
}
@SuppressWarnings("SameParameterValue")
public static class Builder{
//请求地址
private String url;
//加载本地图片
private File file;
//加载器模式
private LoaderMode loaderMode;
//加载本地资源id图片
private int resId;
//显示的imageview控件
private ImageView imageView;
//用于创建硬件缓存所需环境
private Context context;
//加载器策略
private IPolicy policy = new SerialPolicy();
//图片缓存策略
private BitmapCache cache;
//加载过程显示策略
private int loadingResId = -1;
//请求成功回调接口
private BitmapListener bitmapListener;
//用于判断是否需要显示
private boolean hasListener = false;
public Builder(Context context){
this.context = context;
}
//加载网络图片
public Builder load(String url) {
this.url = url;
loaderMode = LoaderMode.HTTP;
return this;
}
//加载本地图片
public Builder load(File file) {
this.file = file;
loaderMode = LoaderMode.FILE;
return this;
}
//加载资源id
public Builder load(@DrawableRes int resId) {
this.resId = resId;
loaderMode = LoaderMode.ASSETS;
return this;
}
public Builder loaderPolicy(IPolicy policy) {
this.policy = policy;
return this;
}
/**
* 缓存策略设置
* @param mode
* @return
*/
public Builder cachePolicy(CacheMode mode) {
switch (mode){
case DISK_LRU_CACHE:
this.cache = DiskBitmapCache.getInstance(context);
break;
case MEMORY_LRU_CACHE:
this.cache = MemoryLruCache.getInstance();
break;
case NO_CAHCE:
this.cache = new NoLruCache();
break;
case DOUBLE_CAHCE:
this.cache = new DoubleLruCache(context);
break;
}
return this;
}
/**
* 占位显示图片
* @param resId
* @return
*/
public Builder placeHolder(@DrawableRes int resId) {
loadingResId = resId;
return this;
}
/**
* 显示的控件
* @param imageView
*/
public void into(ImageView imageView){
this.imageView = imageView;
new BitmapConfig(this).show();
}
public void onFinishListener(BitmapListener bitmapListener){
this.bitmapListener = bitmapListener;
hasListener = true;
new BitmapConfig(this).show();
}
}
}
|
package msip.go.kr.share.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import com.fasterxml.jackson.annotation.JsonBackReference;
import msip.go.kr.common.entity.Item;
import msip.go.kr.common.exception.PermissionDenideException;
@SuppressWarnings("serial")
@Entity
@Table(name="res_master")
public class ResMaster extends Item {
public static final int STATUS_ON = 1000;
public static final int STATUS_OFF = 0;
@Column(name="req_id", columnDefinition="NUMERIC(19,0)")
private Long reqId;
@Column(name="title", columnDefinition="VARCHAR(512)")
private String title;
@Column(name="content", columnDefinition="VARCHAR")
private String content;
@Column(name="file_id", columnDefinition="VARCHAR(13)")
private String fileId;
@Column(name="member_id", columnDefinition="CHAR(20)")
private String memberId;
@Column(name="member_nm", columnDefinition="VARCHAR(2000)")
private String memberNm;
@Column(name="org_cd", columnDefinition="NUMERIC(19,0)")
private Long orgCd;
@Column(name="org_nm", columnDefinition="VARCHAR(2000)")
private String orgNm;
@Column(name="status", columnDefinition="INTEGER default 0")
private int status;
@Column(name="e_mail", columnDefinition="VARCHAR(512)")
private String email;
@Column(name="mbl_phn", columnDefinition="VARCHAR(32)")
private String mblPhn;
@Column(name="opn_cnt", columnDefinition="INTEGER default 0")
private int opnCnt;
@ManyToOne
@JsonBackReference
@JoinColumn(name = "req_id", referencedColumnName="id", nullable=false, insertable=false, updatable=false)
private ReqMaster resMaster;
public ResMaster(){}
public ResMaster(String[] memberInfo){
if(ArrayUtils.isNotEmpty(memberInfo)) {
this.setMemberId(memberInfo[0]);
this.setMemberNm(memberInfo[1]);
if(StringUtils.isNotEmpty(memberInfo[2]))
this.setOrgCd(new Long(memberInfo[2]));
this.setOrgNm(memberInfo[3]);
this.setEmail(memberInfo[4]);
this.setMblPhn(memberInfo[5]);
}
}
public ResMaster(Long id, Long reqId) {
this.setId(id);
this.setReqId(reqId);
}
public ResMaster(Long id, Long reqId, String memberId, String memberNm, Long orgCd, String orgNm, int status, String fileId, int opnCnt, Date regDate, Date modDate) {
this.setId(id);
this.setReqId(reqId);
this.setMemberId(memberId);
this.setMemberNm(memberNm);
this.setOrgCd(orgCd);
this.setOrgNm(orgNm);
this.setStatus(status);
this.setFileId(fileId);
this.setOpnCnt(opnCnt);
this.setRegDate(regDate);
this.setModDate(modDate);
}
public ResMaster(Long id, String title, String fileId, Long reqId,
String endYmd, String deadlineYmd, String deadlineTime,
String regId, String regNm, Date regDate,
String modId, String modNm, Date modDate, int hits) {
this.setId(id);
this.setTitle(title);
this.setFileId(fileId);
this.setReqId(reqId);
this.setRegId(regId);
this.setRegNm(regNm);
this.setRegDate(regDate);
this.setModId(modId);
this.setModNm(modNm);
this.setModDate(modDate);
this.setHits(hits);
}
public ResMaster(Long id, Long reqId, String title, String content, String fileId,
String memberId, String memberNm, Long orgCd, String orgNm,
String regId, String regNm, Date regDate,
String modId, String modNm, Date modDate, int hits) {
this.setId(id);
this.setReqId(reqId);
this.setTitle(title);
this.setContent(content);
this.setFileId(fileId);
this.setMemberId(memberId);
this.setMemberNm(memberNm);
this.setOrgCd(orgCd);
this.setOrgNm(orgNm);
this.setRegId(regId);
this.setRegNm(regNm);
this.setRegDate(regDate);
this.setModId(modId);
this.setModNm(modNm);
this.setModDate(modDate);
this.setHits(hits);
}
public ResMaster(Long id, Long reqId, String title, String fileId,
String memberId, String memberNm, Long orgCd, String orgNm,
String regId, String regNm, Date regDate,
String modId, String modNm, Date modDate, int hits) {
this.setId(id);
this.setReqId(reqId);
this.setTitle(title);
this.setFileId(fileId);
this.setMemberId(memberId);
this.setMemberNm(memberNm);
this.setOrgCd(orgCd);
this.setOrgNm(orgNm);
this.setRegId(regId);
this.setRegNm(regNm);
this.setRegDate(regDate);
this.setModId(modId);
this.setModNm(modNm);
this.setModDate(modDate);
this.setHits(hits);
}
public Long getReqId() {
return reqId;
}
public void setReqId(Long reqId) {
this.reqId = reqId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public String getMemberId() {
return memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public String getMemberNm() {
return memberNm;
}
public void setMemberNm(String memberNm) {
this.memberNm = memberNm;
}
public Long getOrgCd() {
return orgCd;
}
public void setOrgCd(Long orgCd) {
this.orgCd = orgCd;
}
public String getOrgNm() {
return orgNm;
}
public void setOrgNm(String orgNm) {
this.orgNm = orgNm;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMblPhn() {
return mblPhn;
}
public void setMblPhn(String mblPhn) {
this.mblPhn = mblPhn;
}
public int getOpnCnt() {
return opnCnt;
}
public void setOpnCnt(int opnCnt) {
this.opnCnt = opnCnt;
}
public ReqMaster getResMaster() {
return resMaster;
}
public void setResMaster(ReqMaster resMaster) {
this.resMaster = resMaster;
}
public boolean equals(ResMaster entity) {
if(this.reqId.equals(entity.getReqId()) && this.memberId.equals(entity.getMemberId())) {
return true;
} else {
return false;
}
}
public void checkOwner(String esntlId) throws Exception {
try {
if(!this.getMemberId().equals(esntlId)) {
throw new PermissionDenideException();
}
} catch(Exception e) {
throw e;
}
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.saml.idp.preferences;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import pl.edu.icm.unity.saml.idp.preferences.SamlPreferences.SPSettings;
import pl.edu.icm.unity.server.utils.UnityMessageSource;
import pl.edu.icm.unity.types.basic.Attribute;
import pl.edu.icm.unity.webui.common.attributes.AttributeHandlerRegistry;
import com.vaadin.ui.Component;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.ListSelect;
/**
* Shows a single {@link SPSettings}.
*
* @author K. Benedyczak
*/
public class SamlSPSettingsViewer extends FormLayout
{
protected UnityMessageSource msg;
protected Label autoConfirm;
protected ListSelect hiddenAttributes;
protected Label defaultIdentity;
protected AttributeHandlerRegistry attrHandlerRegistry;
public SamlSPSettingsViewer(UnityMessageSource msg, AttributeHandlerRegistry attrHandlerRegistry)
{
this.msg = msg;
this.attrHandlerRegistry = attrHandlerRegistry;
setSpacing(true);
setMargin(true);
autoConfirm = new Label();
autoConfirm.setCaption(msg.getMessage("SAMLPreferences.autoConfirm"));
defaultIdentity = new Label();
defaultIdentity.setCaption(msg.getMessage("SAMLPreferences.defaultIdentity"));
hiddenAttributes = new ListSelect(msg.getMessage("SAMLPreferences.hiddenAttributes"));
hiddenAttributes.setWidth(90, Unit.PERCENTAGE);
hiddenAttributes.setRows(6);
hiddenAttributes.setNullSelectionAllowed(false);
addComponents(autoConfirm, defaultIdentity, hiddenAttributes);
}
public void setInput(SPSettings spSettings)
{
if (spSettings == null)
{
setVisibleRec(false);
return;
}
setVisibleRec(true);
if (spSettings.isDoNotAsk())
{
if (spSettings.isDefaultAccept())
autoConfirm.setValue(msg.getMessage("SAMLPreferences.accept"));
else
autoConfirm.setValue(msg.getMessage("SAMLPreferences.decline"));
} else
autoConfirm.setValue(msg.getMessage("no"));
hiddenAttributes.setReadOnly(false);
hiddenAttributes.removeAllItems();
Map<String, Attribute<?>> attributes = spSettings.getHiddenAttribtues();
hiddenAttributes.setVisible(!attributes.isEmpty());
for (Entry<String, Attribute<?>> entry : attributes.entrySet())
{
if (entry.getValue() == null)
hiddenAttributes.addItem(entry.getKey());
else
{
String simplifiedAttributeRepresentation = attrHandlerRegistry.
getSimplifiedAttributeRepresentation(entry.getValue(), 50);
hiddenAttributes.addItem(simplifiedAttributeRepresentation);
}
}
hiddenAttributes.setReadOnly(true);
String selIdentity = spSettings.getSelectedIdentity();
if (selIdentity != null)
{
defaultIdentity.setValue(selIdentity);
defaultIdentity.setVisible(true);
} else
defaultIdentity.setVisible(false);
}
private void setVisibleRec(boolean how)
{
Iterator<Component> children = iterator();
while (children.hasNext())
{
Component c = children.next();
c.setVisible(how);
}
}
}
|
package com.zauberlabs.bigdata.lambdaoa.realtime.spouts;
import java.util.Date;
import java.util.Map;
import org.apache.commons.lang.time.DateUtils;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
/**
* Spout that emits random records
*
*
* @since 05/07/2013
*/
public class RandomLongSpout extends BaseRichSpout {
private static final long serialVersionUID = -2046124835159328252L;
private SpoutOutputCollector collector;
private Integer c = 0;
@Override
@SuppressWarnings("rawtypes")
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
this.collector = collector;
}
@Override
public void nextTuple() {
c++;
if (c % 10000 == 0) {
collector.emit(new Values(DateUtils.addMinutes(new Date(), -1).getTime()));
}
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("time_frame"));
}
} |
package com.cg.go.greatoutdoor.service;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cg.go.greatoutdoor.entity.OrderEntity;
import com.cg.go.greatoutdoor.service.OrderServiceImpl;
import com.cg.go.greatoutdoor.dao.IOrderRepository;
import com.cg.go.greatoutdoor.exception.OrderException;
@Transactional
@Service
public class OrderServiceImpl implements IOrderService {
@Autowired
IOrderRepository OrderRepository;
// Find the orders based on the user Id in the orders table
@Override
public Optional<OrderEntity>findOrdersByUserId(Integer userId){
Optional<OrderEntity> optional=OrderRepository.findById(userId);
if(!optional.isPresent()) {
throw new OrderException("order not found for id="+userId);
}
Optional<OrderEntity> list= OrderRepository.findById(userId);
return list;
}
// Find all the required orders in the order table
@Override
public List<OrderEntity> findAllOrders(){
List<OrderEntity> list= OrderRepository.findAll();
if(list==null || list.size()==0) {
throw new OrderException("orders not found");
}
return list;
}
// Add orders using the order entity table
@Override
public OrderEntity addOrder(OrderEntity orderEntity) {
boolean exists=orderEntity.getUserId()!=null &&OrderRepository.existsById(orderEntity.getUserId());
if(exists){
throw new OrderException("Order already exists for id="+orderEntity.getUserId());
}
OrderEntity Order=OrderRepository.save(orderEntity);
return Order;
}
// Deleting all orders in the table
@Override
public void deleteAllOrders() {
OrderRepository.deleteAll();
}
// Deleting the orders based on the order ID in the table
@Override
public void deleteOrderById(Integer orderId){
Optional<OrderEntity> optional=OrderRepository.findById(orderId);
if(!optional.isPresent()){
throw new OrderException("Order not found for id="+orderId);
}
OrderRepository.deleteById(orderId);
}
// Update DispatchDate and arrivalDate based on orderId in the table
@Override
public OrderEntity updateDate(Integer orderId, LocalDate dispatchDate, LocalDate arrivalDate) {
boolean exists= OrderRepository.existsById(orderId);
if(!exists){
throw new OrderException("Order does not exists for id="+orderId);
}
Optional<OrderEntity> optional=OrderRepository.findById(orderId);
OrderEntity order=optional.get();
OrderRepository.save(order);
order.setDispatchDate(dispatchDate);
order.setDeliveryDate(arrivalDate);
return order;
}
}
|
package org.dongbin.naver;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import com.dongbin.Billboard.Billboard;
public class NaverNews {
public static void main(String[] args) throws InterruptedException {
NaverNews news = new NaverNews();
news.crawl();
}
//WebDriver
private WebDriver driver;
//ChromeOptions
private ChromeOptions options;
//Properties
public static final String WEB_DRIVER_ID = "webdriver.chrome.driver";
public static final String WEB_DRIVER_PATH = "C:\\Users\\kopo44\\Downloads\\chromedriver_win32\\chromedriver.exe";
//MelonURL
private String naverURL = "https://www.naver.com/";
public NaverNews() {
options = new ChromeOptions();
//options.addArguments("headless");
options.addArguments("--start-maximized");
options.addArguments("--disable-popup-blocking");
//options.addArguments("--disable-default-apps");
//System Property SetUp
System.setProperty(WEB_DRIVER_ID, WEB_DRIVER_PATH);
//Driver SetUp
driver = new ChromeDriver(options);
}
public void crawl() throws InterruptedException {
try {
driver.get(naverURL);
driver.findElement(By.xpath("//*[@id=\"NM_FAVORITE\"]/div[1]/ul[2]/li[2]/a")).click();
List<WebElement> newsHeader = driver.findElements(By.className("hdline_article_tit"));
Thread.sleep(5000);
for (int i = 0; i < newsHeader.size(); i ++) {
System.out.println("뉴스기사 " + i + "번 : " + newsHeader.get(i).getText());
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error");
} finally {
System.out.println("Finish");
driver.close();
}
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.core.services;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import net.datacrow.console.windows.onlinesearch.OnlineSearchForm;
import net.datacrow.core.objects.DcObject;
import net.datacrow.core.resources.DcResources;
import net.datacrow.core.services.plugin.IServer;
import net.datacrow.util.StringUtils;
import org.apache.log4j.Logger;
/**
* A search task performs the actual online search. The search task is used by the
* online search form (see {@link OnlineSearchForm}) and by processed such as the mass
* update.
*
* The search is performed in multiple steps.
* 1) First the online service (web page or web server) is queried using the input
* of the user ({@link #getItemKeys()}).
* 2) For each result the item details are retrieved. See ({@link #run()}) and
* {@link #getItems(String, boolean)}
* 3) The in step 2 retrieved items only contain the bare minimum of information.
* When the user (or any other process) selects one of the items the full details
* need to be retrieved ({@link #getItem(URL)})
*
* This class needs to be extended for specific implementations.
*
* @author Robert Jan van der Waals
*/
public abstract class SearchTask extends Thread {
private static Logger logger = Logger.getLogger(SearchTask.class.getName());
// retrieve minimal item details
public static final int _ITEM_MODE_SIMPLE = 0;
// retrieve full item details
public static final int _ITEM_MODE_FULL = 1;
private boolean isCancelled = false;
protected IOnlineSearchClient listener;
private int maximum = 200;
private String input;
private String query;
// The currently used URL or address
private String address;
// The selected server
private IServer server;
// The selected search mode
private SearchMode searchMode;
// The selected region (EN, US, NL, ..)
private Region region;
// The selected item retrieval mode
private int itemMode = _ITEM_MODE_SIMPLE;
private DcObject client;
/**
* Creates the search task.
* @param listener
* @param server
* @param region
* @param mode
* @param query
*/
public SearchTask(IOnlineSearchClient listener, IServer server,
Region region, SearchMode mode, String query) {
this.listener = listener;
this.region = region;
this.searchMode = mode;
this.server = server;
this.address = region != null ? region.getUrl() : server.getUrl();
this.query = query;//StringUtils.normalize(query);
this.input = query;
}
/**
* Sets the service info. This information is set on every item. This way Data Crow
* knows where the retrieved information originally came from.
*/
protected final void setServiceInfo(DcObject dco) {
String service = server.getName() + " / " +
(region != null ? region.getCode() : "none") + " / " +
(searchMode != null ? searchMode.getDisplayName() : "none") + " / " +
"value=[" + query + "]";
dco.setValue(DcObject._SYS_SERVICE, service);
}
/**
* Sets the item retrieval mode: {@link #_ITEM_MODE_FULL} or {@link #_ITEM_MODE_SIMPLE}.
*/
public final void setItemMode(int mode) {
this.itemMode = mode;
}
public boolean isItemModeSupported() {
return true;
}
/**
* Returns the retrieval mode: {@link #_ITEM_MODE_FULL} or {@link #_ITEM_MODE_SIMPLE}.
*/
public final int getItemMode() {
return itemMode;
}
/**
* Set the maximum amount of items to be retrieved.
*/
public final void setMaximum(int maximum) {
this.maximum = maximum;
}
/**
* Cancel the search.
*/
public final void cancel() {
isCancelled = true;
}
/**
* Indicates if the search was (attempted) to be canceled.
*/
public final boolean isCancelled() {
return isCancelled;
}
/**
* The currently used URL or address.
*/
public final String getAddress() {
return address;
}
/**
* The currently used search mode.
* @see SearchMode
*/
public final SearchMode getMode() {
return searchMode;
}
/**
* The currently used region
* @see Region.
*/
public final Region getRegion() {
return region;
}
public DcObject getClient() {
return client;
}
public void setClient(DcObject client) {
this.client = client;
}
public void setQuery(String query) {
this.query = query;
}
public void setMode(SearchMode searchMode) {
this.searchMode = searchMode;
}
/**
* The used query as specified by the user.
*/
public String getQuery() {
String s = StringUtils.normalize2(query);
s = query.replaceAll(" ", getWhiteSpaceSubst());
s = s.replaceAll("\n", "");
s = s.replaceAll("\r", "");
// replace the & character
int idx = s.indexOf('&');
while (idx > -1) {
s = s.substring(0, s.indexOf('&')) + "%26" + s.substring(s.indexOf('&') + 1, s.length());
idx = s.indexOf('&');
}
return s;
}
/**
* The currently used server
* @see IServer
*/
public final IServer getServer() {
return server;
}
/**
* The maximum amount of items to be retrieved.
*/
public final int getMaximum() {
return maximum;
}
/**
* The character used to substitute white spaces from the query (see {@link #getQuery()}).
* Should be overridden by specific implementations.
*/
public String getWhiteSpaceSubst() {
return "+";
}
/**
* Queries for the specified item. The service information (see {@link #setServiceInfo(DcObject)})
* is used to retrieve the information.
* @param dco The item to be updated.
* @return The retrieved item or null if no item could be found.
* @throws Exception
*/
public DcObject query(DcObject dco) throws Exception {
String link = (String) dco.getValue(DcObject._SYS_SERVICEURL);
if (link != null && link.length() > 0) {
DcObject item = getItem(new URL(link));
item = item == null ? dco : item;
setServiceInfo(item);
return item;
}
return null;
}
/**
* Query for the item(s) using the web key.
* Note that a key is can be a fully qualified URL, an external ID or something else.
* @param key The item key (The specific implementation decides the meaning of a key)
* @param full Indicates if the full details should be retrieved.
*/
protected Collection<DcObject> getItems(Object key, boolean full) throws Exception {
Collection<DcObject> items = new ArrayList<DcObject>();
DcObject dco = getItem(key, full);
if (dco != null) items.add(dco);
return items;
}
/**
* Query for the item using the web key.
* @param key The item key (The specific implementation decides the meaning of a key)
* @param full Indicates if the full details should be retrieved.
*/
protected abstract DcObject getItem(Object key, boolean full) throws Exception;
/**
* Query for the item via the URL
* @param url The direct link to the external item details.
*/
protected abstract DcObject getItem(URL url) throws Exception;
/**
* Get every web ID from the page. With these IDs it should be possible to
* get to the detailed item information.
* @return The item keys or an empty collection.
*/
protected abstract Collection<Object> getItemKeys() throws Exception ;
protected void preSearchCheck() {}
/**
* Here the actual search is performed. This is a standard implementation suited for
* all online searches.
*/
@Override
public void run() {
preSearchCheck();
Collection<Object> keys = new ArrayList<Object>();
listener.addMessage(DcResources.getText("msgConnectingToServer", getAddress()));
try {
keys.addAll(getItemKeys());
} catch (Exception e) {
listener.addError(DcResources.getText("msgCouldNotConnectTo", getServer().getName()));
logger.error(e, e);
}
listener.processingTotal(keys.size());
if (keys.size() == 0) {
listener.addWarning(DcResources.getText("msgNoResultsForKeywords", input));
listener.stopped();
return;
}
listener.addMessage(DcResources.getText("msgFoundXResults", String.valueOf(keys.size())));
listener.addMessage(DcResources.getText("msgStartParsingXResults", String.valueOf(keys.size())));
int counter = 0;
for (Object key : keys) {
if (isCancelled() || counter == getMaximum()) break;
try {
for (DcObject dco : getItems(key, getItemMode() == _ITEM_MODE_FULL)) {
dco.setIDs();
setServiceInfo(dco);
listener.addMessage(DcResources.getText("msgParsingSuccessfull", dco.toString()));
listener.addObject(dco);
sleep(1000);
}
listener.processed(counter);
} catch (Exception exp) {
listener.addMessage(DcResources.getText("msgParsingError", "" + exp));
logger.error(DcResources.getText("msgParsingError", "" + exp), exp);
listener.processed(counter);
}
counter++;
}
listener.processed(counter);
listener.stopped();
}
}
|
package org.reactome.web.nursa.client.details.tabs.dataset.widgets;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import org.reactome.nursa.model.DataPoint;
import org.reactome.nursa.model.DisplayableDataPoint;
import org.reactome.web.nursa.model.ComparisonDataPoint;
import org.reactome.web.nursa.client.details.tabs.dataset.NullSafeCurry;
import org.reactome.web.nursa.client.details.tabs.dataset.NursaWidgetHelper;
import org.reactome.web.nursa.model.Comparison;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.view.client.ListDataProvider;
public class ComparisonDataPointsPanel extends DataPanel<ComparisonDataPoint> {
private Comparison comparison;
public ComparisonDataPointsPanel(Comparison comparison) {
this.comparison = comparison;
}
@Override
protected DataGrid<ComparisonDataPoint> getDataTable() {
// The {gene symbol: fdr pair} map.
Map<String, DisplayableDataPoint[]> fdrs = new HashMap<String, DisplayableDataPoint[]>();
for (int i=0; i < comparison.operands.length; i++) {
for (DisplayableDataPoint dp: comparison.operands[i].dataPoints) {
DisplayableDataPoint[] values = fdrs.get(dp.getSymbol());
if (values == null) {
values = new DisplayableDataPoint[2];
fdrs.put(dp.getSymbol(), values);
}
values[i] = dp;
}
}
// The {gene symbol, fdr pair} records.
ComparisonDataPoint[] rows = fdrs.entrySet().stream()
.map(entry -> new ComparisonDataPoint(entry.getKey(), entry.getValue()))
.toArray(ComparisonDataPoint[]::new);
// The sortable table.
DataGrid<ComparisonDataPoint> table = new DataGrid<ComparisonDataPoint>(PAGE_SIZE);
ListDataProvider<ComparisonDataPoint> dataProvider =
new ListDataProvider<ComparisonDataPoint>();
dataProvider.addDataDisplay(table);
dataProvider.setList(Arrays.asList(rows));
ListHandler<ComparisonDataPoint> sorter =
new ListHandler<ComparisonDataPoint>(dataProvider.getList());
table.addColumnSortHandler(sorter);
// The exact row count.
table.setRowCount(rows.length, true);
// The gene symbol column.
TextColumn<ComparisonDataPoint> symbolColumn = new TextColumn<ComparisonDataPoint>() {
@Override
public String getValue(ComparisonDataPoint dataPoint) {
return dataPoint.getSymbol();
}
};
symbolColumn.setSortable(true);
sorter.setComparator(symbolColumn, new Comparator<ComparisonDataPoint>() {
@Override
public int compare(ComparisonDataPoint p1, ComparisonDataPoint p2) {
return p1.getSymbol().compareTo(p2.getSymbol());
}
});
table.addColumn(symbolColumn, "Symbol");
// The reactome flag column.
TextColumn<ComparisonDataPoint> isReactomeColumn = new TextColumn<ComparisonDataPoint>() {
@Override
public String getValue(ComparisonDataPoint dataPoint) {
return Boolean.toString(dataPoint.isReactome());
}
};
isReactomeColumn.setSortable(true);
sorter.setComparator(isReactomeColumn, new Comparator<ComparisonDataPoint>() {
@Override
public int compare(ComparisonDataPoint p1, ComparisonDataPoint p2) {
return Boolean.compare(p1.isReactome(), p2.isReactome());
}
});
table.addColumn(isReactomeColumn, "Reactome Gene");
// The p-value and fold change columns.
for (int i=0; i < 2; i++) {
Function<ComparisonDataPoint, Double> pValue =
curry(i, DataPoint::getPvalue);
Column<ComparisonDataPoint, Number> pValueCol =
createDataColumn(pValue, sorter, CellTypes.SCIENTIFIC_CELL);
SafeHtml pValueHdr = NursaWidgetHelper.superscriptHeader(i, "p-value");
pValueCol.setSortable(true);
sorter.setComparator(pValueCol, new Comparator<ComparisonDataPoint>() {
@Override
public int compare(ComparisonDataPoint p1, ComparisonDataPoint p2) {
Double pvalue1 = pValue.apply(p1);
Double pvalue2 = pValue.apply(p2);
return nullSafeCompare(pvalue1, pvalue2);
}
});
table.addColumn(pValueCol, pValueHdr);
Function<ComparisonDataPoint, Double> foldChange =
curry(i, DataPoint::getFoldChange);
Column<ComparisonDataPoint, Number> fcCol =
createDataColumn(foldChange, sorter, CellTypes.SCIENTIFIC_CELL);
SafeHtml fcHdr = NursaWidgetHelper.superscriptHeader(i, "Fold Change");
fcCol.setSortable(true);
sorter.setComparator(fcCol, new Comparator<ComparisonDataPoint>() {
@Override
public int compare(ComparisonDataPoint p1, ComparisonDataPoint p2) {
return nullSafeCompare(foldChange.apply(p1), foldChange.apply(p2));
}
});
table.addColumn(fcCol, fcHdr);
}
// The log10(pvalue2/pvalue1) ratio column.
Column<ComparisonDataPoint, Number> ratioCol =
createDataColumn(ComparisonDataPoint::getPValueRatio, sorter, CellTypes.DECIMAL_CELL);
ratioCol.setSortable(true);
sorter.setComparator(ratioCol, new Comparator<ComparisonDataPoint>() {
@Override
public int compare(ComparisonDataPoint p1, ComparisonDataPoint p2) {
return nullSafeCompare(p1.getPValueRatio(), p2.getPValueRatio());
}
});
table.addColumn(ratioCol, "Log p-value Ratio");
// The fold change difference column.
Column<ComparisonDataPoint, Number> fcDiffCol =
createDataColumn(ComparisonDataPoint::getFCDifference, sorter, CellTypes.DECIMAL_CELL);
SafeHtmlBuilder shb = new SafeHtmlBuilder();
shb.appendHtmlConstant("Δ");
shb.appendEscaped( " Fold Change");
SafeHtml fcHdr = shb.toSafeHtml();
sorter.setComparator(fcDiffCol, new Comparator<ComparisonDataPoint>() {
@Override
public int compare(ComparisonDataPoint p1, ComparisonDataPoint p2) {
return nullSafeCompare(p1.getFCDifference(), p2.getFCDifference());
}
});
table.addColumn(fcDiffCol, fcHdr);
formatTableDimensions(table);
return table;
}
/**
* The usual object comparison idiom.
*
* @param value1
* @param value2
* @return
*/
private static int nullSafeCompare(Double value1, Double value2) {
return value1 == null ?
(value2 == null ? 0 : -1) :
(value2 == null ? 1 : value1.compareTo(value2));
}
/**
* Curries the index accessor composed with the given data point accessor
* into a single function.
*
* @param index the index to dereference
* @param accessor the data point accessor function
* @return the composed function
*/
private static Function<ComparisonDataPoint, Double> curry(
final int index, Function<DataPoint, Double> accessor) {
// First dereference the data point, then apply the accessor.
return new NullSafeCurry<ComparisonDataPoint, DataPoint, Double>(
cdp -> cdp.getDataPoints()[index],
accessor);
}
}
|
package com.what.yunbao.setting;
import com.what.yunbao.R;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class SettingAboutActivity extends Activity{
private ImageButton about_back_btn = null;
private TextView mSettingAboutVersionTextView;
private WebView mSettingAboutLinkWebView;
private RelativeLayout about_tel_rl;
private RelativeLayout webView_rl;
private String phone = "10086";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_about);
about_back_btn = (ImageButton) findViewById(R.id.ib_setting_about_back);
about_back_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
mSettingAboutVersionTextView = (TextView) findViewById(R.id.tv_setting_about_version);
PackageInfo pinfo;
try {
pinfo = this.getPackageManager().getPackageInfo(this.getPackageName(), PackageManager.GET_CONFIGURATIONS);
mSettingAboutVersionTextView.setText("v"+pinfo.versionName);
} catch (Exception ex) {
ex.printStackTrace();
}
//webView动态生成 便于回收 使用application
mSettingAboutLinkWebView = new WebView(this);
webView_rl = (RelativeLayout) findViewById(R.id.rl_wv_setting_about_link);
// mSettingAboutLinkWebView.loadUrl("file:///android_asset/setting_about_link.html");
webView_rl.addView(mSettingAboutLinkWebView);
mSettingAboutLinkWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl("http://www.google.hk");
return true;
}
});
about_tel_rl = (RelativeLayout) findViewById(R.id.rl_setting_about_tel);
about_tel_rl.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+phone));
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Toast.makeText(SettingAboutActivity.this, "工作时间:每天9:00-20:00", 3000).show();
startActivity(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
webView_rl.removeView(mSettingAboutLinkWebView);
mSettingAboutLinkWebView.setFocusable(true);
mSettingAboutLinkWebView.removeAllViews();
mSettingAboutLinkWebView.clearHistory();
mSettingAboutLinkWebView.destroy();
}
}
|
package roombook.reservation;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import roombook.guest.Guest;
import roombook.room.*;
/**
* Servlet implementation class ReservationController
*/
@WebServlet(name="/ReservationController", urlPatterns="/Reservation")
public class ReservationController extends HttpServlet {
private static final long serialVersionUID = 1L;
private ReservationService reservationServices = new ReservationService();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("Inside ReservationController GET");
String defaultURL = "/MakeReservation.jsp";
HttpSession session = request.getSession();
/*
* Get the selected room id and then return the room object back to JSP
*/
int roomNumber = Integer.parseInt(request.getParameter("RoomID"));
@SuppressWarnings("unchecked")
List<Guestroom> list = (List<Guestroom>) session.getAttribute("rooms");
Guestroom room = reservationServices.getRoom(roomNumber, list);
session.setAttribute("selectedRoom", room);
getServletContext().getRequestDispatcher(defaultURL).forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// Get user data from reservation
System.out.println("Getting data from user input to make a reservation");
String checkInDate = request.getParameter("checkinDate");
String checkoutDate = request.getParameter("checkoutDate");
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
String notes = request.getParameter("notes");
String numOfAdults = request.getParameter("numberOfAdults");
String numOfChildren = request.getParameter("numberOfChildren");
String earlyCheckIn = request.getParameter("earlyCheckIn");
String lateCheckOut = request.getParameter("lateCheckOut");
String smoking = request.getParameter("smoking");
String pets = request.getParameter("pets");
String parking = request.getParameter("parking");
//Create the guest profile
Guest guest = reservationServices.createGuest(firstName, lastName, email, phone, notes);
IRoom room = null;
IReservation newReservation = null;
if (guest != null)
{
room = (IRoom) request.getSession().getAttribute("selectedRoom");
newReservation = reservationServices.createReservation(guest, room, checkInDate,
checkoutDate, numOfAdults,
numOfChildren, earlyCheckIn,
lateCheckOut, smoking, pets,
parking);
}
String returnURL;
if (newReservation != null)
returnURL = "/ConfirmReservation.jsp";
else
returnURL = "/ReservationNotSuccessful.jsp";
getServletContext().getRequestDispatcher(returnURL).forward(request, response);
}
}
|
package org.point85.domain.dto;
import java.util.List;
/**
* Data Transfer Object (DTO) for a data source id HTTP response
*/
public class SourceIdResponseDto {
private List<String> sourceIds;
public SourceIdResponseDto(List<String> sourceIds) {
this.sourceIds = sourceIds;
}
public List<String> getSourceIds() {
return sourceIds;
}
public void setSourceIds(List<String> sourceIds) {
this.sourceIds = sourceIds;
}
}
|
/**
* https://www.hackerearth.com/practice/data-structures/trees/heapspriority-queues/practice-problems/algorithm/monk-and-multiplication/
* #heap #priority-queue each 3 elements will create to a heap. 0 1 2 3 4 1 6 5 4 3
*
* <p>1 /. ` 3. 5 /. ` 4 6
*
* <p>-1 -1 30 120 120
*
* <p>1 6 5 6 5 4 6 5 4
*/
import java.util.PriorityQueue;
import java.util.Scanner;
class MonkAndMultiplication {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
int tmp = sc.nextInt();
arr[i] = tmp;
}
long[] result = new long[n];
// special case
if (n < 3) {
for (int i = 0; i < n; i++) {
System.out.println(-1);
}
return;
} else {
result[0] = -1;
result[1] = -1;
}
result[2] = (long) arr[0] * arr[1] * arr[2];
PriorityQueue<Integer> pq = new PriorityQueue<>(3);
pq.add(arr[0]);
pq.add(arr[1]);
pq.add(arr[2]);
long multiple = result[2];
for (int i = 3; i < n; i++) {
if (arr[i] > pq.peek()) {
int tmp = pq.poll();
multiple /= tmp;
pq.add(arr[i]);
multiple *= arr[i];
}
result[i] = multiple;
// other way: add two element, poll 3, add 3.
}
for (long i : result) {
System.out.println(i);
}
}
}
|
/**
*
*/
package com.cassandra.TrialWithIText;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
/**
* @author Cassandra Mae
*
*/
public interface HandleingEvents {
/**
*
* @param mouseEvent the event to be handled when mouse clicked or dragged
* or released or pressed.
*/
void Event(MouseEvent mouseEvent);
void Event(KeyEvent keyEvent);
}
|
package interfase;
import date.*;
import task.*;
import utils.*;
import java.io.*;
import java.util.*;
import java.text.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class ConnectSettings extends JFrame {
private static final long serialVersionUID = 1L;
private JFrame f;
private JButton btnQuit; /
private JButton btnOk;
private String host = "";
public ConnectSettings(){
setTitle("Connection Settings");
setSize(382, 227);
Container pane = getContentPane();
pane.add(panel);
MyPanelButton panel1 = new MyPanelButton();
Container pane1 = getContentPane();
pane1.add(panel1, BorderLayout.SOUTH);
setVisible(true);
}
class MyPanelAdd extends JPanel{
private static final long serialVersionUID = 1L;
public MyPanelAdd(){
JLabel hostEnter = new JLabel("Enter IP:");
hostText = new JTextField(20);
add(hostEnter);
add(hostText);
}
private class MyListener implements DocumentListener{
public void insertUpdate(DocumentEvent ev){
try{
host = hostText.getText().trim();
}catch(ParseException e){}
}
public void removeUpdate(DocumentEvent ev){
try{
host = hostText.getText().trim();
}catch(ParseException e){}
}
public void changedUpdate(DocumentEvent ev){
try{
host = hostText.getText().trim();
}catch(ParseException e){}
}
}
private class MyPanelButton extends JPanel {
private static final long serialVersionUID = 1L;
public MyPanelButton() {
JButton OkButton = new JButton("Ok");
add(OkButton);
JButton DeactivateButton = new JButton("Cansel");
add(DeactivateButton);
OkButton.addActionListener(new MyActionOnOk());
DeactivateButton.addActionListener(new MyActionOnCansel());
}
private class MyActionOnOk implements ActionListener {
MyActionOnOk() {
}
public void actionPerformed(ActionEvent event) {
dispose();
}
}
private class MyActionOnCansel implements ActionListener {
MyActionOnCansel() {
}
public void actionPerformed(ActionEvent event) {
dispose();
}
}
}
} |
package com.company;
public class Part implements Comparable<Part> {
private String color;
private String type;
private Board.Unit currentUnit;
private Board.Unit previousUnit;
public Board.Unit getCurrentUnit() {
return currentUnit;
}
public Board.Unit getPreviousUnit() {
return previousUnit;
}
public Part(String color, String type) {
this.color = color;
this.type = type;
}
@Override
public int compareTo(Part o) {
return 0;
}
public String getType() {
return type;
}
@Override
public String toString() {
return "Part{" +
"color='" + color + '\'' +
", type='" + type + '\'' +
'}';
}
}
|
package com.bnrc.busapp;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import u.aly.ap;
import u.aly.da;
import android.R.integer;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.SQLException;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View.OnClickListener;
import cn.domob.android.ads.I;
import com.ab.activity.AbActivity;
import com.ab.view.titlebar.AbTitleBar;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.baidu.mapapi.utils.DistanceUtil;
import com.bnrc.activity.AboutActivity;
import com.bnrc.adapter.MyBusListViewAdapter;
import com.bnrc.adapter.MyListViewAdapter;
import com.bnrc.busapp.R;
import com.bnrc.busapp.BuslineListView.loadDataBaseTask;
import com.bnrc.ui.rjz.AlertService;
import com.bnrc.ui.rjz.BaseFragment;
import com.bnrc.ui.rjz.MainActivity;
import com.bnrc.ui.rjz.SelectPicPopupWindow;
import com.bnrc.ui.rjz.AlertService.onAlertListener;
import com.bnrc.ui.rjz.other.HorizontalListView;
import com.bnrc.ui.rjz.other.HorizontalListViewAdapter;
import com.bnrc.ui.rjz.other.HorizontalListViewOK;
import com.bnrc.ui.rtBus.Child;
import com.bnrc.ui.rtBus.Group;
import com.bnrc.ui.rtBus.StationItem;
import com.bnrc.util.AbBase64;
import com.bnrc.util.AnimationUtil;
import com.bnrc.util.BuslineDBHelper;
import com.bnrc.util.DataBaseHelper;
import com.bnrc.util.LocationUtil;
import com.bnrc.util.NetAndGpsUtil;
import com.bnrc.util.PCDataBaseHelper;
import com.bnrc.util.PCUserDataDBHelper;
import com.bnrc.util.StationOverlay;
import com.bnrc.util.UserDataDBHelper;
import com.bnrc.util.VolleyNetwork;
import com.bnrc.util.VolleyNetwork.requestListener;
import com.bnrc.util.VolleyNetwork.upLoadListener;
import com.bnrc.util.collectwifi.BaseActivity;
import com.bnrc.util.collectwifi.Constants;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.tencent.mm.sdk.modelmsg.GetMessageFromWX;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.net.v;
import com.zf.iosdialog.widget.AlertDialog;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.PopupWindow.OnDismissListener;
public class BuslineListViewParallel extends BaseActivity {
private static final String TAG = BuslineListViewParallel.class
.getSimpleName();
public PCDataBaseHelper mDataBaseManager = null;
public PCUserDataDBHelper mUserDataBaseHelper = null;
private NetAndGpsUtil mNetAndGpsUtil;
private int StationID;
private int LineID;
private int OfflineID;
private int Sequence;
private String LineName = "";
private String StationName = "";
private String StartStation = "";
private String EndStation = "";
private String FullName = "???";
private String startTime = "???";
private String endTime = "???";
private String loadingInfo = " 正在加载...";
private String rtInfo = "";
private List<Child> mStations = null;
private Map<Integer, Integer> mHasRtStationList = null;
private TimerTask task;
private Timer timer;
private ImageView mViewInMap;
private LinearLayout mChangeDirecLayout, mAlertLayout, mConcernLayout,
mCorrectMistakeLayout, mRefreshLayout;
private ImageView mChangeDirecBtn, mAlertBtn, mConcernBtn, mOnOffBtn;
private TextView mStartTime, mEndTime, mLocalStation, mRtInfo, mOnOff;
private HorizontalListViewAdapter mBuslineAdapter;
private ListView mBuslineListView;
private Child mSelectedChild;
private ProgressDialog pd = null;
private RelativeLayout mCanversLayout;// 阴影遮挡图层
private SelectPicPopupWindow menuWindow;
// 定义Handler对象
private Handler mHandler = new Handler();
// private Map<Integer, Integer> offlineParam = null;
private VolleyNetwork mVolleyNetwork;
private AbTitleBar mAbTitleBar;
private LocationUtil mLocationUtil;
private CoordinateConverter mCoordConventer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SDKInitializer.initialize(getApplicationContext());
setAbContentView(R.layout.busline_listview_parallel);
mAbTitleBar = this.getTitleBar();
mAbTitleBar.setTitleTextMargin(20, 0, 0, 0);
mAbTitleBar.setLogo(R.drawable.button_selector_back);
mAbTitleBar.setTitleBarBackground(R.drawable.top_bg);
mAbTitleBar.setTitleBarGravity(Gravity.CENTER, Gravity.CENTER);
mAbTitleBar.setTitleTextSize(18);
initbase();
Intent intent = getIntent();
LineID = intent.getIntExtra("LineID", 0);
StationID = intent.getIntExtra("StationID", 0);
Sequence = intent.getIntExtra("Sequence", 0);
mDataBaseManager = PCDataBaseHelper
.getInstance(BuslineListViewParallel.this);
mUserDataBaseHelper = PCUserDataDBHelper
.getInstance(BuslineListViewParallel.this);
mNetAndGpsUtil = NetAndGpsUtil
.getInstance(this.getApplicationContext());
// offlineParam = new HashMap<Integer, Integer>();
register();
setListener();
mBuslineAdapter = new HorizontalListViewAdapter(this, mStations,
R.layout.horizontallistview_item_parallel, new String[] {
"itemsTitle", "isCurStation" }, new int[] {
R.id.iv_bus, R.id.tv_stationName });
mBuslineListView.setAdapter(mBuslineAdapter);
mHasRtStationList = new HashMap<Integer, Integer>();
mVolleyNetwork = VolleyNetwork.getInstance(this);
mLocationUtil = LocationUtil.getInstance(this.getApplicationContext());
mCoordConventer = new CoordinateConverter();
}
private void updateLineInfo() {
mAbTitleBar.setTitleText(FullName);
mStartTime.setText(formatString(R.string.startTime, startTime));
mEndTime.setText(formatString(R.string.endTime, endTime));
mLocalStation.setText(LineName);
}
private void register() {
mChangeDirecLayout = (LinearLayout) findViewById(R.id.lLayout_changeDirec);
mAlertLayout = (LinearLayout) findViewById(R.id.lLayout_addAlert);
mConcernLayout = (LinearLayout) findViewById(R.id.lLayout_addFav);
mRefreshLayout = (LinearLayout) findViewById(R.id.lLayout_refresh);
mChangeDirecBtn = (ImageView) findViewById(R.id.iv_changeDirec);
mOnOffBtn = (ImageView) findViewById(R.id.iv_onoff);
mOnOff = (TextView) findViewById(R.id.tv_onoff);
mAlertBtn = (ImageView) findViewById(R.id.iv_addAlert);
mConcernBtn = (ImageView) findViewById(R.id.iv_addFav);
mCorrectMistakeLayout = (LinearLayout) findViewById(R.id.lLayout_correct);
mViewInMap = (ImageView) findViewById(R.id.iv_map);
mStartTime = (TextView) findViewById(R.id.tv_startTime);
mEndTime = (TextView) findViewById(R.id.tv_endTime);
mLocalStation = (TextView) findViewById(R.id.tv_localStation);
mRtInfo = (TextView) findViewById(R.id.tv_rtInfo);
mCanversLayout = (RelativeLayout) findViewById(R.id.rlayout_shadow);
mBuslineListView = (ListView) findViewById(R.id.mBuslineListView);
mBuslineListView.setVisibility(View.INVISIBLE);
mRtInfo.setText(Html.fromHtml(loadingInfo));
if (mUserDataBaseHelper.IsFavStation(LineID, StationID))
mConcernBtn.setImageResource(R.drawable.icon_horizon_like);
else
mConcernBtn.setImageResource(R.drawable.icon_horizon_dislike);
if (mUserDataBaseHelper.IsAlertOpenBusline(LineID, StationID))
mAlertBtn.setImageResource(R.drawable.icon_horizon_alarm);
else
mAlertBtn.setImageResource(R.drawable.icon_horizon_disalarm);
if (mVolleyNetwork.lineList == LineID) {
mOnOffBtn.setImageResource(R.drawable.offbus);
mOnOff.setText("下 车");
} else {
mAlertBtn.setImageResource(R.drawable.onbus);
mOnOff.setText("上 车");
}
}
private String formatString(int id, String info) {
return String.format(getResources().getString(id), info);
}
private void setListener() {
mChangeDirecLayout.setOnClickListener(mClickListener);
mAlertLayout.setOnClickListener(mClickListener);
mConcernLayout.setOnClickListener(mClickListener);
mRefreshLayout.setOnClickListener(mClickListener);
mCorrectMistakeLayout.setOnClickListener(mClickListener);
mViewInMap.setOnClickListener(mClickListener);
mBuslineListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
// TODO Auto-generated method stub
showLoading();
rtInfo = "???";
mRtInfo.setText(Html.fromHtml(loadingInfo));
mBuslineAdapter.setSelectIndex(position);
mBuslineAdapter.notifyDataSetChanged();
mHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if (position < 2)
mBuslineListView.setSelection(0);
else
mBuslineListView.setSelection(position - 2);
}
});
Sequence = position + 1;
StationID = mStations.get(position).getStationID();
StationName = mStations.get(position).getStationName();
if (mUserDataBaseHelper.IsFavStation(LineID, StationID))
mConcernBtn.setImageResource(R.drawable.icon_horizon_like);
else
mConcernBtn
.setImageResource(R.drawable.icon_horizon_dislike);
if (mUserDataBaseHelper.IsAlertOpenBusline(LineID, StationID))
mAlertBtn.setImageResource(R.drawable.icon_horizon_alarm);
else
mAlertBtn
.setImageResource(R.drawable.icon_horizon_disalarm);
// getRtParam();
getSeverInfo();
}
});
}
private void showSelectPopWindow(Child child) {
menuWindow = new SelectPicPopupWindow(BuslineListViewParallel.this,
child, mPopItemListener);
menuWindow.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {// 点击消失
mCanversLayout.setVisibility(View.GONE);
}
});
menuWindow.showAtLocation(
BuslineListViewParallel.this.findViewById(R.id.rLayout),
Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
menuWindow.setFocusable(true);
menuWindow.setOutsideTouchable(false);
menuWindow.update();
mCanversLayout.setVisibility(View.VISIBLE);
}
private OnClickListener mClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.lLayout_addAlert:
if (mStations == null || Sequence > mStations.size())
return;
mSelectedChild = mStations.get(Sequence - 1);
if (mUserDataBaseHelper.IsAlertOpenBusline(LineID, StationID)) {
mUserDataBaseHelper.closeAlertBusline(mSelectedChild);
mAlertBtn
.setImageResource(R.drawable.icon_horizon_disalarm);
} else {
mUserDataBaseHelper.openAlertBusline(mSelectedChild);
mAlertBtn.setImageResource(R.drawable.icon_horizon_alarm);
}
// Toast.makeText(getApplicationContext(),
// "添加 " + mSelectedChild.getStationName() + " 为提醒站点",
// Toast.LENGTH_SHORT).show();
break;
case R.id.lLayout_addFav:
if (mStations == null || Sequence > mStations.size())
return;
mSelectedChild = mStations.get(Sequence - 1);
int Type = PCUserDataDBHelper.getInstance(
BuslineListViewParallel.this).IsWhichKindFavInfo(
LineID, StationID);
mSelectedChild.setType(Type);
showSelectPopWindow(mSelectedChild);
break;
case R.id.lLayout_changeDirec:
Log.i(TAG, "mChangeDirec");
changeDirection();
break;
case R.id.iv_map:
Log.i(TAG, "mViewInMap");
Intent intent = new Intent(BuslineListViewParallel.this,
BuslineMapView.class);
intent.putExtra("LineName", LineName);
intent.putExtra("StartStation", StartStation);
intent.putExtra("EndStation", EndStation);
intent.putExtra("LineID", LineID);
intent.putExtra("OfflineID", OfflineID);
startActivity(intent);
AnimationUtil
.activityZoomAnimation(BuslineListViewParallel.this);
break;
case R.id.lLayout_correct:
Intent corrIntent = new Intent(BuslineListViewParallel.this,
CorrectMistakeActivity.class);
startActivity(corrIntent);
AnimationUtil
.activityZoomAnimation(BuslineListViewParallel.this);
break;
case R.id.lLayout_refresh:
// showLoading();
// getSeverInfo();
if (mOnOff.getText().toString().equalsIgnoreCase("上 车")) {
mOnOff.setText("下 车");
mOnOffBtn.setImageResource(R.drawable.offbus);
mVolleyNetwork.lineList = LineID;
mVolleyNetwork.startPostMessage();
} else {
mOnOff.setText("上 车");
mOnOffBtn.setImageResource(R.drawable.onbus);
mVolleyNetwork.lineList = 0;
mVolleyNetwork.stopPostMessage();
}
default:
break;
}
}
};
// // 为弹出窗口实现监听类
// private OnClickListener mPopItemListener = new OnClickListener() {
//
// public void onClick(View v) {
// // Map<String, Object> record = new HashMap<String, Object>();
// Child child = mSelectedChild;
// int LineID = child.getLineID();
// int StationID = child.getStationID();
// switch (v.getId()) {
// case R.id.iv_work:
// child.setType(Constants.TYPE_WORK);
// mUserDataBaseHelper.addFavRecord(child);
// break;
// case R.id.iv_home:
// child.setType(Constants.TYPE_HOME);
// mUserDataBaseHelper.addFavRecord(child);
// break;
// case R.id.iv_other:
// child.setType(Constants.TYPE_OTHER);
// mUserDataBaseHelper.addFavRecord(child);
// break;
// case R.id.iv_del:
// mUserDataBaseHelper.cancelFav(LineID, StationID);
// child.setType(Constants.TYPE_NONE);
// break;
// case R.id.btn_cancel:
// break;
// default:
// break;
// }
// menuWindow.dismiss();
// if (mUserDataBaseHelper.IsFavStation(LineID, StationID))
// mConcernBtn.setImageResource(R.drawable.icon_horizon_like);
// else
// mConcernBtn.setImageResource(R.drawable.icon_horizon_dislike);
//
// }
// };
// private void getRtParam() {
// mHasRtStationList.clear();
// mBuslineAdapter.notifyDataSetChanged();
//
// if (!mNetAndGpsUtil.isNetworkAvailable()) {
// Log.i(TAG, "getRtParam !isNetworkConnected(this)");
// rtInfo = "暂无信息";
// Log.i(TAG, "暂无信息 " + 403);
// mRtInfo.setText(Html.fromHtml(rtInfo));
// dismissLoading();
// return;
// }
//
// Log.i(TAG, "getRtParam");
// if (OfflineID > 0) {
// try {
// getRtInfo(OfflineID, Sequence);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// Log.i(TAG, "getRtParam: " + e.getMessage());
// e.printStackTrace();
// }
// } else {
// Log.i(TAG, "未开通");
// rtInfo = "未开通";
// mRtInfo.setText(Html.fromHtml(rtInfo));
// dismissLoading();
// }
// }
//
// private void getSeverInfo() {
// mHasRtStationList.clear();
// mBuslineAdapter.notifyDataSetChanged();
// if (!mNetAndGpsUtil.isNetworkAvailable()) {
// rtInfo = "暂无信息";
// Log.i(TAG, "暂无信息 " + 431);
// mRtInfo.setText(Html.fromHtml(rtInfo));
// dismissLoading();
// return;
// }
// Log.i(TAG, "getSeverInfo");
// mVolleyNetwork.getAllBusesWithLineAndOneStation(LineID, StationID,
// new requestListener() {
//
// @Override
// public void onSuccess(JSONObject data) {
// // TODO Auto-generated method stub
// try {
// JSONArray arr = data.getJSONArray("data");
// if (arr != null) {
// Log.i(TAG, "ARR!=NULL");
// int size = arr.length();
// for (int i = 0; i < size; i++) {
// JSONObject json = arr.getJSONObject(i);
// int nextStationNum = json
// .getInt("NextStationNum");
// int nextStationDistance = json
// .getInt("NextStationDistance");
// if (mHasRtStationList
// .containsKey(nextStationNum - 1)) {
// int amount = mHasRtStationList
// .get(nextStationNum - 1);
// mHasRtStationList.put(
// nextStationNum - 1, ++amount);
// } else {
// mHasRtStationList.put(
// nextStationNum - 1, 1);
// }
// }
// }
// JSONObject latest = data.getJSONObject("latest");
// if (latest != null) {
// Log.i(TAG, "latest!=NULL");
// double StationDistance = latest
// .getInt("StationDistance") / 1000.0;
// int StationArrivingTime = latest
// .getInt("StationArrivingTime");
// int StationArrivingNum = latest
// .getInt("NextStationNum");
// String distance = "<font color=\"red\">"
// + StationDistance + "</font>" + "公里";
// String stationNum = "<font color=\"red\">"
// + (Sequence - StationArrivingNum + 1)
// + "</font>" + "站";
// String stationName = "<font color=\"red\">"
// + StationName + "</font>";
// if (StationArrivingTime <= 10) {
//
// rtInfo = "即将到站,请注意上车!";
//
// } else {
// int tmp = StationArrivingTime / 60;
// String time = "";
// if (tmp <= 0)
// time = "<font color=\"red\">"
// + StationArrivingTime
// + "</font>" + "秒钟";
// else
// time = "<font color=\"red\">" + tmp
// + "</font>" + "分钟";
// rtInfo = "距" + stationName + " "
// + stationNum + " " + distance
// + " " + time;
// }
// } else {
// rtInfo = "暂无信息";
// Log.i(TAG, "暂无信息 " + 500);
// }
// } catch (JSONException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// rtInfo = "暂无信息";
// Log.i(TAG, "暂无信息 " + 506);
// } finally {
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mBuslineAdapter
// .updateBusAmount(mHasRtStationList);
// mRtInfo.setText(Html.fromHtml(rtInfo));
// mBuslineAdapter.notifyDataSetChanged();
// dismissLoading();
// }
// });
// }
// }
//
// @Override
// public void onNotAccess() {
// // TODO Auto-generated method stub
// rtInfo = "未开通";
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mRtInfo.setText(Html.fromHtml(rtInfo));
// mBuslineAdapter.notifyDataSetChanged();
// dismissLoading();
// }
// });
// // getRtParam();
// }
//
// @Override
// public void onFormatError() {
// // TODO Auto-generated method stub
// getRtParam();
// }
//
// @Override
// public void onDataNA(String url) {
// // TODO Auto-generated method stub
// try {
// getRtInfo(url, Sequence);
// } catch (UnsupportedEncodingException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (JSONException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// @Override
// public void onNetError() {
// // TODO Auto-generated method stub
// rtInfo = "网络不佳";
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mBuslineAdapter
// .updateBusAmount(mHasRtStationList);
// mRtInfo.setText(Html.fromHtml(rtInfo));
// mBuslineAdapter.notifyDataSetChanged();
// dismissLoading();
// }
// });
// }
// });
// }
//
// // private void getRtInfo(final int offlineID, final int sequence)
// // throws JSONException, UnsupportedEncodingException {
// // RequestQueue mQueue = Volley.newRequestQueue(this);
// // String Url = "http://bjgj.aibang.com:8899/bus.php?city="
// // + URLEncoder.encode("北京", "utf-8") + "&id=" + offlineID
// // + "&no=" + sequence + "&type=2&encrypt=1&versionid=2";
// // Log.i("Volley", "url " + Url);
// // StringRequest jsonObjectRequest = new StringRequest(Url,
// // new Response.Listener<String>() {
// //
// // @Override
// // public void onResponse(String response) {
// // try {
// // Log.i("Volley", "response " + response);
// // JSONObject responseJson = XML
// // .toJSONObject(response);
// // JSONObject rootJson = responseJson
// // .getJSONObject("root");
// // int status = rootJson.getInt("status");
// // if (status != 200) {
// // // Log.i(TAG, child.getBuslineFullName()
// // // + " 暂无实时公交信息");
// // rtInfo = "暂无信息";
// // Log.i(TAG, "暂无信息 " + 585);
// // mHandler.post(new Runnable() {
// //
// // @Override
// // public void run() {
// // // TODO Auto-generated method stub
// // mRtInfo.setText(Html.fromHtml(rtInfo));
// // mBuslineAdapter.notifyDataSetChanged();
// // dismissLoading();
// // }
// // });
// // return;
// // }
// // JSONObject dataJson = rootJson
// // .getJSONObject("data");
// // JSONArray busJsonArray = null;
// // if (dataJson.toString().indexOf("[") > 0) {
// // busJsonArray = (JSONArray) dataJson.get("bus");
// // busJsonArray = dataJson.getJSONArray("bus");
// // } else {
// // JSONObject busJsonObject = dataJson
// // .getJSONObject("bus");
// // busJsonArray = new JSONArray("["
// // + busJsonObject.toString() + "]");
// // }
// // dealRtInfo(busJsonArray, sequence);
// //
// // } catch (JSONException e) {
// // // TODO Auto-generated catch block
// // Log.i("Volley", "JSONException: " + e.getMessage());
// //
// // rtInfo = "暂无信息";
// // Log.i(TAG, "暂无信息 " + 617);
// // mHandler.post(new Runnable() {
// //
// // @Override
// // public void run() {
// // // TODO Auto-generated method stub
// // mRtInfo.setText(Html.fromHtml(rtInfo));
// // dismissLoading();
// // }
// // });
// // e.printStackTrace();
// // }
// //
// // }
// //
// // }, new Response.ErrorListener() {
// //
// // @Override
// // public void onErrorResponse(VolleyError error) {
// // // TODO Auto-generated method stub
// // Log.d("Volley", "VolleyError: " + error);
// // rtInfo = "暂无信息";
// // Log.i(TAG, "暂无信息 " + 639);
// // mHandler.post(new Runnable() {
// //
// // @Override
// // public void run() {
// // // TODO Auto-generated method stub
// // mRtInfo.setText(Html.fromHtml(rtInfo));
// // dismissLoading();
// // }
// // });
// // }
// //
// // }) {
// //
// // @Override
// // public Map<String, String> getHeaders() {
// // HashMap<String, String> headers = new HashMap<String, String>();
// // headers.put("Accept", "application/json");
// // headers.put("Content-Type", "application/json; charset=UTF-8");
// // return headers;
// // }
// //
// // };
// // //
// //
// MyVolley.sharedVolley(getApplicationContext()).getRequestQueue().add(jsonObjectRequest);
// // jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
// // DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
// // DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
// // DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// // jsonObjectRequest.setShouldCache(false);
// // mQueue.add(jsonObjectRequest);
// // }
// //
// // private void getRtInfo(String Url, final int sequence)
// // throws JSONException, UnsupportedEncodingException {
// // RequestQueue mQueue = Volley.newRequestQueue(this);
// // Log.i("Volley", "url " + Url);
// // StringRequest jsonObjectRequest = new StringRequest(Url,
// // new Response.Listener<String>() {
// //
// // @Override
// // public void onResponse(String response) {
// // try {
// // Log.i("Volley", "response " + response);
// // JSONObject responseJson = XML
// // .toJSONObject(response);
// // JSONObject rootJson = responseJson
// // .getJSONObject("root");
// // int status = rootJson.getInt("status");
// // if (status != 200) {
// // // Log.i(TAG, child.getBuslineFullName()
// // // + " 暂无实时公交信息");
// // rtInfo = "暂无信息";
// // Log.i(TAG, "暂无信息 " + 691);
// // mHandler.post(new Runnable() {
// //
// // @Override
// // public void run() {
// // // TODO Auto-generated method stub
// // mRtInfo.setText(Html.fromHtml(rtInfo));
// // mBuslineAdapter.notifyDataSetChanged();
// // dismissLoading();
// // }
// // });
// // return;
// // }
// // JSONObject dataJson = rootJson
// // .getJSONObject("data");
// // JSONArray busJsonArray = null;
// // if (dataJson.toString().indexOf("[") > 0) {
// // busJsonArray = (JSONArray) dataJson.get("bus");
// // busJsonArray = dataJson.getJSONArray("bus");
// // } else {
// // JSONObject busJsonObject = dataJson
// // .getJSONObject("bus");
// // busJsonArray = new JSONArray("["
// // + busJsonObject.toString() + "]");
// // }
// // dealRtInfo(busJsonArray, sequence);
// //
// // } catch (JSONException e) {
// // // TODO Auto-generated catch block
// // Log.i("Volley", "JSONException: " + e.getMessage());
// //
// // rtInfo = "暂无信息";
// // Log.i(TAG, "暂无信息 " + 723);
// // mHandler.post(new Runnable() {
// //
// // @Override
// // public void run() {
// // // TODO Auto-generated method stub
// // mRtInfo.setText(Html.fromHtml(rtInfo));
// // dismissLoading();
// // }
// // });
// // e.printStackTrace();
// // }
// //
// // }
// //
// // }, new Response.ErrorListener() {
// //
// // @Override
// // public void onErrorResponse(VolleyError error) {
// // // TODO Auto-generated method stub
// // Log.d("Volley", "VolleyError: " + error);
// // rtInfo = "暂无信息";
// // Log.i(TAG, "暂无信息 " + 745);
// // mHandler.post(new Runnable() {
// //
// // @Override
// // public void run() {
// // // TODO Auto-generated method stub
// // mRtInfo.setText(Html.fromHtml(rtInfo));
// // dismissLoading();
// // }
// // });
// // }
// //
// // }) {
// //
// // @Override
// // public Map<String, String> getHeaders() {
// // HashMap<String, String> headers = new HashMap<String, String>();
// // headers.put("Accept", "application/json");
// // headers.put("Content-Type", "application/json; charset=UTF-8");
// // return headers;
// // }
// //
// // };
// // //
// //
// MyVolley.sharedVolley(getApplicationContext()).getRequestQueue().add(jsonObjectRequest);
// // jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
// // DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
// // DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
// // DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// // jsonObjectRequest.setShouldCache(false);
// // mQueue.add(jsonObjectRequest);
// // }
// private void getRtInfo(final int offlineID, final int sequence)
// throws JSONException, UnsupportedEncodingException {
// String Url = "http://bjgj.aibang.com:8899/bus.php?city="
// + URLEncoder.encode("北京", "utf-8") + "&id=" + offlineID
// + "&no=" + sequence + "&type=2&encrypt=1&versionid=2";
// Log.i("Volley", "url " + Url);
// // 创建okHttpClient对象
// OkHttpClient mOkHttpClient = new OkHttpClient();
// // 创建一个Request
// final com.squareup.okhttp.Request request = new
// com.squareup.okhttp.Request.Builder()
// .url(Url).build();
// // new call
// Call call = mOkHttpClient.newCall(request);
// // 请求加入调度
// call.enqueue(new Callback() {
//
// @Override
// public void onFailure(com.squareup.okhttp.Request arg0,
// IOException arg1) {
// // TODO Auto-generated method stub
// Log.i(TAG, "onFailure: " + arg0.body().toString());
// Log.d("OKHTTP", "VolleyError: " + arg0.body().toString());
// rtInfo = "暂无信息";
// Log.i(TAG, "暂无信息 " + 639);
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mRtInfo.setText(Html.fromHtml(rtInfo));
// dismissLoading();
// }
// });
// }
//
// @Override
// public void onResponse(com.squareup.okhttp.Response arg0)
// throws IOException {
// // TODO Auto-generated method stub
// Log.i(TAG, "onResponse: " + arg0.body().string());
// try {
// String response = arg0.body().string();
// Log.i("OKHTTP", "response " + response);
// JSONObject responseJson = XML.toJSONObject(response);
// JSONObject rootJson = responseJson.getJSONObject("root");
// int status = rootJson.getInt("status");
// if (status != 200) {
// // Log.i(TAG, child.getBuslineFullName()
// // + " 暂无实时公交信息");
// rtInfo = "暂无信息";
// Log.i(TAG, "暂无信息 " + 585);
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mRtInfo.setText(Html.fromHtml(rtInfo));
// mBuslineAdapter.notifyDataSetChanged();
// dismissLoading();
// }
// });
// return;
// }
// JSONObject dataJson = rootJson.getJSONObject("data");
// JSONArray busJsonArray = null;
// if (dataJson.toString().indexOf("[") > 0) {
// busJsonArray = (JSONArray) dataJson.get("bus");
// busJsonArray = dataJson.getJSONArray("bus");
// } else {
// JSONObject busJsonObject = dataJson
// .getJSONObject("bus");
// busJsonArray = new JSONArray("["
// + busJsonObject.toString() + "]");
// }
// dealRtInfo(busJsonArray, sequence);
//
// } catch (JSONException e) {
// // TODO Auto-generated catch block
// Log.i("Volley", "JSONException: " + e.getMessage());
//
// rtInfo = "暂无信息";
// Log.i(TAG, "暂无信息 " + 617);
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mRtInfo.setText(Html.fromHtml(rtInfo));
// dismissLoading();
// }
// });
// e.printStackTrace();
// }
//
// }
//
// });
// }
//
// private void getRtInfo(String Url, final int sequence)
// throws JSONException, UnsupportedEncodingException {
// // 创建okHttpClient对象
// OkHttpClient mOkHttpClient = new OkHttpClient();
// // 创建一个Request
// final com.squareup.okhttp.Request request = new
// com.squareup.okhttp.Request.Builder()
// .url(Url).build();
// // new call
// Call call = mOkHttpClient.newCall(request);
// // 请求加入调度
// call.enqueue(new Callback() {
//
// @Override
// public void onFailure(com.squareup.okhttp.Request arg0,
// IOException arg1) {
// // TODO Auto-generated method stub
// Log.i(TAG, "onFailure: " + arg0.body().toString());
// Log.d("Volley", "VolleyError: " + arg0.body().toString());
// rtInfo = "网络不佳";
// Log.i(TAG, "网络不佳 " + 745);
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mRtInfo.setText(Html.fromHtml(rtInfo));
// dismissLoading();
// }
// });
// }
//
// @Override
// public void onResponse(com.squareup.okhttp.Response arg0)
// throws IOException {
// // TODO Auto-generated method stub
// Log.i(TAG, "onResponse: " + arg0.body().string());
// try {
// String response = arg0.body().string();
// Log.i("Volley", "response " + response);
// JSONObject responseJson = XML.toJSONObject(response);
// JSONObject rootJson = responseJson.getJSONObject("root");
// int status = rootJson.getInt("status");
// if (status != 200) {
// // Log.i(TAG, child.getBuslineFullName()
// // + " 暂无实时公交信息");
// rtInfo = "网络不佳";
// Log.i(TAG, "网络不佳 " + 691);
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mRtInfo.setText(Html.fromHtml(rtInfo));
// mBuslineAdapter.notifyDataSetChanged();
// dismissLoading();
// }
// });
// return;
// }
// JSONObject dataJson = rootJson.getJSONObject("data");
// JSONArray busJsonArray = null;
// if (dataJson.toString().indexOf("[") > 0) {
// busJsonArray = (JSONArray) dataJson.get("bus");
// busJsonArray = dataJson.getJSONArray("bus");
// } else {
// JSONObject busJsonObject = dataJson
// .getJSONObject("bus");
// busJsonArray = new JSONArray("["
// + busJsonObject.toString() + "]");
// }
// dealRtInfo(busJsonArray, sequence);
//
// } catch (JSONException e) {
// // TODO Auto-generated catch block
// Log.i("Volley", "JSONException: " + e.getMessage());
//
// rtInfo = "网络不佳";
// Log.i(TAG, "暂无信息 " + 723);
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mRtInfo.setText(Html.fromHtml(rtInfo));
// dismissLoading();
// }
// });
// e.printStackTrace();
// }
// }
// });
// }
//
// private void dealRtInfo(JSONArray json, int sequence) {
// try {
// try {
// rtInfo = "暂无信息";
// Log.i(TAG, "暂无信息 " + 781);
// int count = json.length();
// Log.i(TAG, "busJsonArray_count: " + count);
// JSONObject uploadJson = new JSONObject();
// JSONArray uploadData = new JSONArray();
// uploadJson.put("c", "beijing");
// uploadJson.put("dt", uploadData);
// int max = 0;
// Map<String, Object> map = new HashMap<String, Object>();
// for (int j = 0; j < count; j++) {
// JSONObject busJson = (JSONObject) json.get(j);
// JSONObject uplodaItem = new JSONObject();
// MyCipher mCiper = new MyCipher("aibang"
// + busJson.getString("gt"));
//
// String nextStationName = mCiper.decrypt(busJson
// .getString("ns"));// nextStationName
// int nextStationNum = Integer.parseInt(mCiper
// .decrypt(busJson.getString("nsn")));// nextStationNum
// int id = busJson.getInt("id");
// String nextStationDistance = busJson.getString("nsd");//
// nextStationDistance
// String nextStationTime = busJson.getString("nst");// nextStationTime
//
// String stationDistance = mCiper.decrypt(busJson
// .getString("sd"));// stationDistance
// String stationArrivingTime = mCiper.decrypt(busJson
// .getString("st"));
// String st_c = null;
// if (isNumeric(stationArrivingTime))
// // st_c = TimeStampToDate(Long.parseLong(st),
// // "HH:mm");// station_arriving_time
// st_c = String.valueOf(TimeStampToDelTime(Long
// .parseLong(stationArrivingTime)));// station_arriving_time
// else
// st_c = "-1";
// String x = mCiper.decrypt(busJson.getString("x"));
// String y = mCiper.decrypt(busJson.getString("y"));
// Log.i(TAG,
// "next_station_name: " + nextStationName + "\n"
// + "next_station_num: " + nextStationNum
// + "\n" + "next_station_distance: "
// + nextStationDistance + "\n"
// + "next_station_arriving_time: "
// + nextStationTime + "\n"
// + "station_distance: " + stationDistance
// + "\n" + "station_arriving_time: "
// + stationArrivingTime + " " + st_c + "\n"
// + " currentTime "
// + System.currentTimeMillis());
// if (nextStationNum <= sequence && nextStationNum > max) {
// map.clear();
// map.put("nextStationNum", nextStationNum);
// map.put("stationArrivingTime", stationArrivingTime);
// map.put("stationDistance", stationDistance);
// max = nextStationNum;
// }
// uplodaItem.put("LID", LineID);
// uplodaItem
// .put("BID", LineID + String.format("%02d", j + 1));
// uplodaItem.put("Nsn", nextStationNum);
// uplodaItem.put("Nsd", nextStationDistance);
// uplodaItem.put("Lat", x);
// uplodaItem.put("Lon", y);
// uplodaItem.put("T", System.currentTimeMillis() / 1000);
// uploadData.put(uplodaItem);
//
// if (mHasRtStationList.containsKey(nextStationNum - 1)) {
// int amount = mHasRtStationList.get(nextStationNum - 1);
// mHasRtStationList.put(nextStationNum - 1, ++amount);
// } else {
// mHasRtStationList.put(nextStationNum - 1, 1);
// }
// }
// mVolleyNetwork.upLoadRtInfo(uploadJson, new upLoadListener() {
//
// @Override
// public void onSuccess() {
// // TODO Auto-generated method stub
// Log.i(TAG, " 上传成功");
// }
//
// @Override
// public void onFail() {
// // TODO Auto-generated method stub
// Log.i(TAG, " 上传失败");
// }
// });
// if (map.size() > 0) {
// int nextStationNum = (Integer) map.get("nextStationNum");
// String stationArrivingTime = map.get("stationArrivingTime")
// .toString();
// String stationDistance = map.get("stationDistance")
// .toString();
// Log.e(TAG, "nextStationNum: " + nextStationNum
// + " stationArrivingTime: " + stationArrivingTime
// + " stationDistance: " + stationDistance);
// // 未开通
// if (stationArrivingTime == null || nextStationNum == 0) {
// rtInfo = "未发车";
// }
// // 起点站
// else if (sequence == 1) {
// rtInfo = "起点站";
// }
// // 到站
// else if (nextStationNum <= sequence) {
// if (isNumeric(stationArrivingTime)) {
// if (nextStationNum == sequence) {
// // 已到站
// if (Integer.parseInt(stationArrivingTime) < 10) {
// rtInfo = "已到站,请抓紧上车!";
// }
// // 即将到站
// else if (Integer.parseInt(stationDistance) < 10) {
// rtInfo = "即将到站,请注意上车!";
// } else {
// int nstime = TimeStampToDelTime(Long
// .parseLong(stationArrivingTime));// 计算还有几分钟
// String distance = "<font color=\"red\">"
// + Integer.parseInt(stationDistance)
// / 1000.0 + "</font>" + "公里";
// String time = "<font color=\"red\">"
// + nstime + "</font>" + "分钟";
// String stationNum = "<font color=\"red\">"
// + (sequence - nextStationNum + 1)
// + "</font>" + "站";
// String stationName = "<font color=\"red\">"
// + StationName + "</font>";
// if (nstime <= 0) {
// rtInfo = "即将到站,请注意上车!";
//
// } else {
// rtInfo = "距" + stationName + " "
// + stationNum + " "
// + distance + " " + time;
// }
// }
// } else {
// int nstime = TimeStampToDelTime(Long
// .parseLong(stationArrivingTime));// 计算还有几分钟
// String distance = "<font color=\"red\">"
// + Integer.parseInt(stationDistance)
// / 1000.0 + "</font>" + "公里";
// String time = "<font color=\"red\">" + nstime
// + "</font>" + "分钟";
// String stationNum = "<font color=\"red\">"
// + (sequence - nextStationNum + 1)
// + "</font>" + "站";
// String stationName = "<font color=\"red\">"
// + StationName + "</font>";
// if (nstime <= 0) {
// rtInfo = "距" + stationName + " "
// + stationNum + " " + distance;
// } else {
// rtInfo = "距" + stationName + " "
// + stationNum + " " + distance
// + " " + time;
// }
// }
// }
// } else {
// rtInfo = "未发车";
// }
// }
// } catch (SQLException sqle) {
// throw sqle;
// }
//
// } catch (JSONException e) {
// Log.e("JSON exception", e.getMessage());
// e.printStackTrace();
// } finally {
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mBuslineAdapter.updateBusAmount(mHasRtStationList);
// mRtInfo.setText(Html.fromHtml(rtInfo));
// mBuslineAdapter.notifyDataSetChanged();
// dismissLoading();
// }
// });
// }
// }
//
// public String TimeStampToDate(Long timestampString, String formats) {
// if (timestampString < 0)
// return "0";
// String date = new java.text.SimpleDateFormat(formats)
// .format(new java.util.Date(timestampString * 1000));
// return date;
// }
//
// public boolean isNumeric(String str) {
// Pattern pattern = Pattern.compile("-?[0-9]+.*[0-9]*");
//
// Matcher isNum = pattern.matcher(str);
// if (!isNum.matches()) {
// return false;
// }
// return true;
// }
//
// public int TimeStampToDelTime(Long timestampString) {
// if (timestampString < 0)
// return (int) 0;
// double delTime = (timestampString * 1000 - System.currentTimeMillis()) /
// 1000 / 60;
// return (int) Math.ceil(delTime);
// }
//
// public void onResume() {
// super.onResume();
// MobclickAgent.onPageStart("SplashScreen"); // ͳ��ҳ��
// MobclickAgent.onResume(this); // ͳ��ʱ��
// exeuteTask();
//
// }
//
// @Override
// public void onPause() {
// super.onPause();
// MobclickAgent.onPageEnd("SplashScreen");
// MobclickAgent.onPause(this);
// // task.cancel();
// // timer.cancel();
// if (mTask != null)
// mTask.cancel(true);
// }
//
// @Override
// public void onStop() {
// super.onStop();
// mHandler.removeCallbacksAndMessages(null);
// }
//
// @Override
// public void onRestart() {
// super.onRestart();
// }
//
// public void onDestroy() {
// super.onDestroy();
// }
//
// private List<Child> loadBuslineData(int LineID) {
//
// if (mStations == null)
// mStations = new ArrayList<Child>();
// List<Child> tmp = mDataBaseManager.acquireStationsWithBuslineID(LineID);
// if (tmp.size() > 0) {
// mStations = tmp;
// if (Sequence > mStations.size())
// Sequence = 1;
// StationID = mStations.get(Sequence - 1).getStationID();
// LineName = mStations.get(Sequence - 1).getLineName();
// StationName = mStations.get(Sequence - 1).getStationName();
// Map<String, Object> LineInfo = mDataBaseManager
// .acquireLineInfoWithLineID(LineID);
// if (LineInfo != null && LineInfo.size() > 0) {
// startTime = LineInfo.get("StartTime").toString();
// endTime = LineInfo.get("EndTime").toString();
// StartStation = LineInfo.get("StartStation").toString();
// EndStation = LineInfo.get("EndStation").toString();
// FullName = LineInfo.get("LineName").toString() + " ("
// + LineInfo.get("StartStation").toString() + " - "
// + LineInfo.get("EndStation").toString() + ")";
// OfflineID = Integer.parseInt(LineInfo.get("OfflineID")
// .toString());
// }
// return mStations;
// } else
// return null;
// }
//
// private void changeDirection() {
// if (LineID % 10 == 0)
// LineID += 2;
// else
// LineID -= 2;
// OfflineID = 0;
// exeuteTask();
// }
//
// private loadDataBaseTask mTask = null;
//
// private void exeuteTask() {
// if (mTask != null)
// mTask.cancel(true);
// mTask = new loadDataBaseTask(this);
// mTask.execute();
//
// }
//
// class loadDataBaseTask extends AsyncTask<Integer, Integer, List<Child>> {
// // 后面尖括号内分别是参数(线程休息时间),进度(publishProgress用到),返回值 类型
//
// private Context mContext = null;
//
// public loadDataBaseTask(Context context) {
// this.mContext = context;
// }
//
// /*
// * 第一个执行的方法 执行时机:在执行实际的后台操作前,被UI 线程调用
// * 作用:可以在该方法中做一些准备工作,如在界面上显示一个进度条,或者一些控件的实例化,这个方法可以不用实现。
// *
// * @see android.os.AsyncTask#onPreExecute()
// */
// @Override
// protected void onPreExecute() {
// // TODO Auto-generated method stub
// Log.d(TAG, "onPreExecute");
// super.onPreExecute();
// }
//
// /*
// * 执行时机:在onPreExecute 方法执行后马上执行,该方法运行在后台线程中 作用:主要负责执行那些很耗时的后台处理工作。可以调用
// * publishProgress方法来更新实时的任务进度。该方法是抽象方法,子类必须实现。
// *
// * @see android.os.AsyncTask#doInBackground(Params[])
// */
// @Override
// protected List<Child> doInBackground(Integer... params) {
// // TODO Auto-generated method stub
// Log.d(TAG, "doInBackground");
// // for (int i = 0; i <= 100; i++) {
// // mProgressBar.setProgress(i);
// publishProgress();
//
// // try {
// // Thread.sleep(params[0]);
// // } catch (InterruptedException e) {
// // // TODO Auto-generated catch block
// // e.printStackTrace();
// // }
// // }
// return loadBuslineData(LineID);
// }
//
// /*
// * 执行时机:这个函数在doInBackground调用publishProgress时被调用后,UI
// * 线程将调用这个方法.虽然此方法只有一个参数,但此参数是一个数组,可以用values[i]来调用
// * 作用:在界面上展示任务的进展情况,例如通过一个进度条进行展示。此实例中,该方法会被执行100次
// *
// * @see android.os.AsyncTask#onProgressUpdate(Progress[])
// */
// @Override
// protected void onProgressUpdate(Integer... values) {
// // TODO Auto-generated method stub
// Log.d(TAG, "onProgressUpdate");
// // mTextView.setText(values[0] + "%");
// showLoading();
// super.onProgressUpdate(values);
// }
//
// /*
// * 执行时机:在doInBackground 执行完成后,将被UI 线程调用 作用:后台的计算结果将通过该方法传递到UI
// * 线程,并且在界面上展示给用户 result:上面doInBackground执行后的返回值,所以这里是"执行完毕"
// *
// * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
// */
// @Override
// protected void onPostExecute(List<Child> result) {
// // TODO Auto-generated method stub
// Log.d(TAG, "onPostExecute");
// if (result == null) {
// Toast.makeText(BuslineListViewParallel.this, "对不起,没有反方向线路!",
// Toast.LENGTH_SHORT).show();
// dismissLoading();
// return;
// }
// updateLineInfo();
// rtInfo = "???";
// mBuslineListView.setVisibility(View.VISIBLE);
// mRtInfo.setText(Html.fromHtml(loadingInfo));
// mBuslineAdapter.updateData(mStations);
// mBuslineAdapter.setSelectIndex(Sequence - 1);
// mBuslineAdapter.notifyDataSetChanged();
// getSeverInfo();
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// if ((Sequence - 1) < 1)
// mBuslineListView.setSelection(0);
// else
// mBuslineListView.setSelection(Sequence - 3);
// }
// });
// if (mUserDataBaseHelper.IsFavStation(LineID, StationID))
// mConcernBtn.setImageResource(R.drawable.icon_horizon_like);
// else
// mConcernBtn.setImageResource(R.drawable.icon_horizon_dislike);
// if (mUserDataBaseHelper.IsAlertOpenBusline(LineID, StationID))
// mAlertBtn.setImageResource(R.drawable.icon_horizon_alarm);
// else
// mAlertBtn.setImageResource(R.drawable.icon_horizon_disalarm);
// }
//
// }
// 为弹出窗口实现监听类
private OnClickListener mPopItemListener = new OnClickListener() {
public void onClick(View v) {
// Map<String, Object> record = new HashMap<String, Object>();
Child child = mSelectedChild;
child.setEndStation(EndStation);
int LineID = child.getLineID();
int StationID = child.getStationID();
switch (v.getId()) {
case R.id.iv_work:
child.setType(Constants.TYPE_WORK);
mUserDataBaseHelper.addFavRecord(child);
break;
case R.id.iv_home:
child.setType(Constants.TYPE_HOME);
mUserDataBaseHelper.addFavRecord(child);
break;
case R.id.iv_other:
child.setType(Constants.TYPE_OTHER);
mUserDataBaseHelper.addFavRecord(child);
break;
case R.id.iv_del:
mUserDataBaseHelper.cancelFav(LineID, StationID);
child.setType(Constants.TYPE_NONE);
break;
case R.id.btn_cancel:
break;
default:
break;
}
menuWindow.dismiss();
if (mUserDataBaseHelper.IsFavStation(LineID, StationID))
mConcernBtn.setImageResource(R.drawable.icon_horizon_like);
else
mConcernBtn.setImageResource(R.drawable.icon_horizon_dislike);
}
};
private void getRtParam() {
mHasRtStationList.clear();
mBuslineAdapter.notifyDataSetChanged();
if (!mNetAndGpsUtil.isNetworkAvailable()) {
Log.i(TAG, "getRtParam !isNetworkConnected(this)");
rtInfo = "暂无网络";
Log.i(TAG, "暂无信息 " + 403);
mRtInfo.setText(Html.fromHtml(rtInfo));
dismissLoading();
return;
}
Log.i(TAG, "getRtParam");
if (OfflineID > 0) {
try {
getRtInfo(OfflineID, Sequence);
} catch (Exception e) {
// TODO Auto-generated catch block
// Log.i(TAG, "getRtParam: " + e.getMessage());
e.printStackTrace();
}
} else {
Log.i(TAG, "未开通");
rtInfo = "未开通";
mRtInfo.setText(Html.fromHtml(rtInfo));
dismissLoading();
}
}
private void getSeverInfo() {
mHasRtStationList.clear();
mBuslineAdapter.notifyDataSetChanged();
if (!mNetAndGpsUtil.isNetworkAvailable()) {
rtInfo = "暂无网络";
Log.i(TAG, "暂无信息 " + 431);
mRtInfo.setText(Html.fromHtml(rtInfo));
dismissLoading();
return;
}
Log.i(TAG, "getSeverInfo");
mVolleyNetwork.getAllBusesWithLineAndOneStation(LineID, StationID,
new requestListener() {
@Override
public void onSuccess(JSONObject data) {
// TODO Auto-generated method stub
try {
JSONArray arr = data.getJSONArray("dt");
if (arr != null) {
Log.i(TAG, "ARR!=NULL: " + arr.toString());
int size = arr.length();
for (int i = 0; i < size; i++) {
JSONObject json = arr.getJSONObject(i);
int nextStationNum = json.getInt("Nsn");
int nextStationDistance = json
.getInt("Nsd");
if (mHasRtStationList
.containsKey(nextStationNum - 1)) {
int amount = mHasRtStationList
.get(nextStationNum - 1);
mHasRtStationList.put(
nextStationNum - 1, ++amount);
} else {
mHasRtStationList.put(
nextStationNum - 1, 1);
}
}
}
JSONObject latest = data.getJSONObject("lt");
if (latest != null) {
Log.i(TAG, "latest!=NULL");
double StationDistance = latest.getInt("Sd") / 1000.0;
int StationArrivingTime = latest.getInt("St");
int StationArrivingNum = latest.getInt("Nsn");
String distance = "<font color=\"red\">"
+ StationDistance + "</font>" + "公里";
String stationNum = "<font color=\"red\">"
+ (Sequence - StationArrivingNum + 1)
+ "</font>" + "站";
String stationName = "<font color=\"red\">"
+ StationName + "</font>";
if (StationArrivingTime <= 10) {
rtInfo = "即将到站,请注意上车!";
} else {
int tmp = StationArrivingTime / 60;
String time = "";
if (tmp <= 0)
time = "<font color=\"red\">"
+ StationArrivingTime
+ "</font>" + "秒钟";
else
time = "<font color=\"red\">" + tmp
+ "</font>" + "分钟";
rtInfo = "距" + stationName + " "
+ stationNum + " " + distance
+ " " + time;
}
} else {
if (Sequence == 1)
rtInfo = "起始站";
else
rtInfo = "暂无信息";
Log.i(TAG, "暂无信息 " + 500);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if (Sequence == 1)
rtInfo = "起始站";
else
rtInfo = "暂无信息";
Log.i(TAG, "暂无信息 " + 506);
} finally {
mHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mBuslineAdapter
.updateBusAmount(mHasRtStationList);
mRtInfo.setText(Html.fromHtml(rtInfo));
mBuslineAdapter.notifyDataSetChanged();
dismissLoading();
}
});
}
}
@Override
public void onNotAccess() {
// TODO Auto-generated method stub
rtInfo = "未开通";
mHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mRtInfo.setText(Html.fromHtml(rtInfo));
mBuslineAdapter.notifyDataSetChanged();
dismissLoading();
}
});
// getRtParam();
}
@Override
public void onFormatError() {
// TODO Auto-generated method stub
getRtParam();
}
@Override
public void onDataNA(String url) {
// TODO Auto-generated method stub
try {
getRtInfo(url, Sequence);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onNetError() {
// TODO Auto-generated method stub
getRtParam();
}
});
}
private void getRtInfo(final int offlineID, final int sequence)
throws JSONException, UnsupportedEncodingException {
String Url = "http://bjgj.aibang.com:8899/bus.php?city="
+ URLEncoder.encode("北京", "utf-8") + "&id=" + offlineID
+ "&no=" + sequence + "&type=2&encrypt=1&versionid=2";
// Log.i("Volley", "url " + Url);
// 创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
// 创建一个Request
final com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
.url(Url).build();
// new call
Call call = mOkHttpClient.newCall(request);
// 请求加入调度
call.enqueue(new Callback() {
@Override
public void onFailure(com.squareup.okhttp.Request arg0,
IOException arg1) {
// TODO Auto-generated method stub
// Log.i(TAG, "onFailure: " + arg0.body().toString());
// Log.d("OKHTTP", "VolleyError: " + arg0.body().toString());
if (sequence == 1)
rtInfo = "起始站";
else
rtInfo = "暂无信息";
Log.i(TAG, "暂无信息 " + 639);
mHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mRtInfo.setText(Html.fromHtml(rtInfo));
dismissLoading();
}
});
}
@Override
public void onResponse(com.squareup.okhttp.Response arg0)
throws IOException {
// TODO Auto-generated method stub
// Log.i(TAG, "onResponse: " + arg0.body().string());
try {
String response = arg0.body().string();
// Log.i("OKHTTP", "response " + response);
JSONObject responseJson = XML.toJSONObject(response);
JSONObject rootJson = responseJson.getJSONObject("root");
int status = rootJson.getInt("status");
if (status != 200) {
// Log.i(TAG, child.getBuslineFullName()
// + " 暂无实时公交信息");
if (sequence == 1)
rtInfo = "起始站";
else
rtInfo = "暂无信息";
Log.i(TAG, "暂无信息 " + 585);
mHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mRtInfo.setText(Html.fromHtml(rtInfo));
mBuslineAdapter.notifyDataSetChanged();
dismissLoading();
}
});
return;
}
JSONObject dataJson = rootJson.getJSONObject("data");
JSONArray busJsonArray = null;
if (dataJson.toString().indexOf("[") > 0) {
busJsonArray = (JSONArray) dataJson.get("bus");
busJsonArray = dataJson.getJSONArray("bus");
} else {
JSONObject busJsonObject = dataJson
.getJSONObject("bus");
busJsonArray = new JSONArray("["
+ busJsonObject.toString() + "]");
}
dealRtInfo(busJsonArray, sequence);
} catch (Exception e) {
// TODO Auto-generated catch block
// Log.i("OKHTTP", "JSONException: " + e.getMessage());
if (sequence == 1)
rtInfo = "起始站";
else
rtInfo = "暂无信息";
Log.i(TAG, "暂无信息 " + 617);
mHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mRtInfo.setText(Html.fromHtml(rtInfo));
dismissLoading();
}
});
e.printStackTrace();
}
}
});
}
private void getRtInfo(String Url, final int sequence)
throws JSONException, UnsupportedEncodingException {
// 创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
// 创建一个Request
final com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
.url(Url).build();
// new call
Call call = mOkHttpClient.newCall(request);
// 请求加入调度
call.enqueue(new Callback() {
@Override
public void onFailure(com.squareup.okhttp.Request arg0,
IOException arg1) {
// TODO Auto-generated method stub
// Log.i(TAG, "onFailure: " + arg0.body().toString());
if (sequence == 1) {
rtInfo = "起始站";
} else
rtInfo = "暂无信息";
Log.i(TAG, "暂无信息 " + 745);
mHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mRtInfo.setText(Html.fromHtml(rtInfo));
dismissLoading();
}
});
}
@Override
public void onResponse(com.squareup.okhttp.Response arg0)
throws IOException {
// TODO Auto-generated method stub
// Log.i(TAG, "onResponse: " + arg0.body().string());
try {
String response = arg0.body().string();
// Log.i("OKHTTP", "response " + response);
JSONObject responseJson = XML.toJSONObject(response);
JSONObject rootJson = responseJson.getJSONObject("root");
int status = rootJson.getInt("status");
if (status != 200) {
// Log.i(TAG, child.getBuslineFullName()
// + " 暂无实时公交信息");
if (sequence == 1) {
rtInfo = "起始站";
} else
rtInfo = "暂无信息";
Log.i(TAG, "暂无信息 " + 691);
mHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mRtInfo.setText(Html.fromHtml(rtInfo));
mBuslineAdapter.notifyDataSetChanged();
dismissLoading();
}
});
return;
}
JSONObject dataJson = rootJson.getJSONObject("data");
JSONArray busJsonArray = null;
if (dataJson.toString().indexOf("[") > 0) {
busJsonArray = (JSONArray) dataJson.get("bus");
busJsonArray = dataJson.getJSONArray("bus");
} else {
JSONObject busJsonObject = dataJson
.getJSONObject("bus");
busJsonArray = new JSONArray("["
+ busJsonObject.toString() + "]");
}
dealRtInfo(busJsonArray, sequence);
} catch (Exception e) {
// TODO Auto-generated catch block
if (sequence == 1) {
rtInfo = "起始站";
} else
rtInfo = "暂无信息";
Log.i(TAG, "暂无信息 " + 723);
mHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mRtInfo.setText(Html.fromHtml(rtInfo));
dismissLoading();
}
});
e.printStackTrace();
}
}
});
}
// private void getRtInfo(final int offlineID, final int sequence)
// throws JSONException, UnsupportedEncodingException {
// RequestQueue mQueue = Volley.newRequestQueue(this);
// String Url = "http://bjgj.aibang.com:8899/bus.php?city="
// + URLEncoder.encode("北京", "utf-8") + "&id=" + offlineID
// + "&no=" + sequence + "&type=2&encrypt=1&versionid=2";
// Log.i("Volley", "url " + Url);
// StringRequest jsonObjectRequest = new StringRequest(Url,
// new Response.Listener<String>() {
//
// @Override
// public void onResponse(String response) {
// try {
// Log.i("Volley", "response " + response);
// JSONObject responseJson = XML
// .toJSONObject(response);
// JSONObject rootJson = responseJson
// .getJSONObject("root");
// int status = rootJson.getInt("status");
// if (status != 200) {
// // Log.i(TAG, child.getBuslineFullName()
// // + " 暂无实时公交信息");
// rtInfo = "暂无信息";
// Log.i(TAG, "暂无信息 " + 585);
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mRtInfo.setText(Html.fromHtml(rtInfo));
// mBuslineAdapter.notifyDataSetChanged();
// dismissLoading();
// }
// });
// return;
// }
// JSONObject dataJson = rootJson
// .getJSONObject("data");
// JSONArray busJsonArray = null;
// if (dataJson.toString().indexOf("[") > 0) {
// busJsonArray = (JSONArray) dataJson.get("bus");
// busJsonArray = dataJson.getJSONArray("bus");
// } else {
// JSONObject busJsonObject = dataJson
// .getJSONObject("bus");
// busJsonArray = new JSONArray("["
// + busJsonObject.toString() + "]");
// }
// dealRtInfo(busJsonArray, sequence);
//
// } catch (JSONException e) {
// // TODO Auto-generated catch block
// Log.i("Volley", "JSONException: " + e.getMessage());
//
// rtInfo = "暂无信息";
// Log.i(TAG, "暂无信息 " + 617);
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mRtInfo.setText(Html.fromHtml(rtInfo));
// dismissLoading();
// }
// });
// e.printStackTrace();
// }
//
// }
//
// }, new Response.ErrorListener() {
//
// @Override
// public void onErrorResponse(VolleyError error) {
// // TODO Auto-generated method stub
// Log.d("Volley", "VolleyError: " + error);
// rtInfo = "暂无信息";
// Log.i(TAG, "暂无信息 " + 639);
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mRtInfo.setText(Html.fromHtml(rtInfo));
// dismissLoading();
// }
// });
// }
//
// }) {
//
// @Override
// public Map<String, String> getHeaders() {
// HashMap<String, String> headers = new HashMap<String, String>();
// headers.put("Accept", "application/json");
// headers.put("Content-Type", "application/json; charset=UTF-8");
// return headers;
// }
//
// };
// //
// MyVolley.sharedVolley(getApplicationContext()).getRequestQueue().add(jsonObjectRequest);
// jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
// DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
// DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
// DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// jsonObjectRequest.setShouldCache(false);
// mQueue.add(jsonObjectRequest);
// }
//
// private void getRtInfo(String Url, final int sequence)
// throws JSONException, UnsupportedEncodingException {
// RequestQueue mQueue = Volley.newRequestQueue(this);
// Log.i("Volley", "url " + Url);
// StringRequest jsonObjectRequest = new StringRequest(Url,
// new Response.Listener<String>() {
//
// @Override
// public void onResponse(String response) {
// try {
// Log.i("Volley", "response " + response);
// JSONObject responseJson = XML
// .toJSONObject(response);
// JSONObject rootJson = responseJson
// .getJSONObject("root");
// int status = rootJson.getInt("status");
// if (status != 200) {
// // Log.i(TAG, child.getBuslineFullName()
// // + " 暂无实时公交信息");
// rtInfo = "暂无信息";
// Log.i(TAG, "暂无信息 " + 691);
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mRtInfo.setText(Html.fromHtml(rtInfo));
// mBuslineAdapter.notifyDataSetChanged();
// dismissLoading();
// }
// });
// return;
// }
// JSONObject dataJson = rootJson
// .getJSONObject("data");
// JSONArray busJsonArray = null;
// if (dataJson.toString().indexOf("[") > 0) {
// busJsonArray = (JSONArray) dataJson.get("bus");
// busJsonArray = dataJson.getJSONArray("bus");
// } else {
// JSONObject busJsonObject = dataJson
// .getJSONObject("bus");
// busJsonArray = new JSONArray("["
// + busJsonObject.toString() + "]");
// }
// dealRtInfo(busJsonArray, sequence);
//
// } catch (JSONException e) {
// // TODO Auto-generated catch block
// Log.i("Volley", "JSONException: " + e.getMessage());
//
// rtInfo = "暂无信息";
// Log.i(TAG, "暂无信息 " + 723);
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mRtInfo.setText(Html.fromHtml(rtInfo));
// dismissLoading();
// }
// });
// e.printStackTrace();
// }
//
// }
//
// }, new Response.ErrorListener() {
//
// @Override
// public void onErrorResponse(VolleyError error) {
// // TODO Auto-generated method stub
// Log.d("Volley", "VolleyError: " + error);
// rtInfo = "暂无信息";
// Log.i(TAG, "暂无信息 " + 745);
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// mRtInfo.setText(Html.fromHtml(rtInfo));
// dismissLoading();
// }
// });
// }
//
// }) {
//
// @Override
// public Map<String, String> getHeaders() {
// HashMap<String, String> headers = new HashMap<String, String>();
// headers.put("Accept", "application/json");
// headers.put("Content-Type", "application/json; charset=UTF-8");
// return headers;
// }
//
// };
// //
// MyVolley.sharedVolley(getApplicationContext()).getRequestQueue().add(jsonObjectRequest);
// jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
// DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
// DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
// DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// jsonObjectRequest.setShouldCache(false);
// mQueue.add(jsonObjectRequest);
// }
private void dealRtInfo(JSONArray json, int sequence) {
try {
try {
rtInfo = "暂无信息";
Log.i(TAG, "暂无信息 " + 781);
int count = json.length();
Log.i(TAG, "busJsonArray_count: " + count);
JSONObject uploadJson = new JSONObject();
JSONArray uploadData = new JSONArray();
uploadJson.put("c", "beijing");
uploadJson.put("dt", uploadData);
int max = 0;
Map<String, Object> map = new HashMap<String, Object>();
for (int j = 0; j < count; j++) {
JSONObject busJson = (JSONObject) json.get(j);
JSONObject uplodaItem = new JSONObject();
MyCipher mCiper = new MyCipher("aibang"
+ busJson.getString("gt"));
String nextStationName = mCiper.decrypt(busJson
.getString("ns"));// nextStationName
int nextStationNum = Integer.parseInt(mCiper
.decrypt(busJson.getString("nsn")));// nextStationNum
int id = busJson.getInt("id");
String nextStationDistance = busJson.getString("nsd");// nextStationDistance
String nextStationTime = busJson.getString("nst");// nextStationTime
String stationDistance = mCiper.decrypt(busJson
.getString("sd"));// stationDistance
String stationArrivingTime = mCiper.decrypt(busJson
.getString("st"));
String st_c = null;
if (isNumeric(stationArrivingTime))
// st_c = TimeStampToDate(Long.parseLong(st),
// "HH:mm");// station_arriving_time
st_c = String.valueOf(TimeStampToDelTime(Long
.parseLong(stationArrivingTime)));// station_arriving_time
else
st_c = "-1";
String x = mCiper.decrypt(busJson.getString("x"));
String y = mCiper.decrypt(busJson.getString("y"));
Log.i(TAG,
"next_station_name: " + nextStationName + "\n"
+ "next_station_num: " + nextStationNum
+ "\n" + "next_station_distance: "
+ nextStationDistance + "\n"
+ "next_station_arriving_time: "
+ nextStationTime + "\n"
+ "station_distance: " + stationDistance
+ "\n" + "station_arriving_time: "
+ stationArrivingTime + " " + st_c + "\n"
+ " currentTime "
+ System.currentTimeMillis());
if (nextStationNum <= sequence && nextStationNum > max) {
map.clear();
map.put("nextStationNum", nextStationNum);
map.put("stationArrivingTime", stationArrivingTime);
map.put("stationDistance", stationDistance);
max = nextStationNum;
}
uplodaItem.put("LID", LineID);
uplodaItem
.put("BID", LineID + String.format("%02d", j + 1));
uplodaItem.put("Nsn", nextStationNum);
uplodaItem.put("Nsd", nextStationDistance);
LatLng latLngBaidu = mCoordConventer
.from(CoordinateConverter.CoordType.COMMON)
.coord(new LatLng(Double.parseDouble(y), Double
.parseDouble(x))).convert();
uplodaItem.put("Lat", latLngBaidu.latitude);
uplodaItem.put("Lon", latLngBaidu.longitude);
uplodaItem.put("T", System.currentTimeMillis() / 1000);
uploadData.put(uplodaItem);
if (mHasRtStationList.containsKey(nextStationNum - 1)) {
int amount = mHasRtStationList.get(nextStationNum - 1);
mHasRtStationList.put(nextStationNum - 1, ++amount);
} else {
mHasRtStationList.put(nextStationNum - 1, 1);
}
}
mVolleyNetwork.upLoadRtInfo(uploadJson, new upLoadListener() {
@Override
public void onSuccess() {
// TODO Auto-generated method stub
Log.i(TAG, " 上传成功");
}
@Override
public void onFail() {
// TODO Auto-generated method stub
Log.i(TAG, " 上传失败");
}
});
if (map.size() > 0) {
int nextStationNum = (Integer) map.get("nextStationNum");
String stationArrivingTime = map.get("stationArrivingTime")
.toString();
String stationDistance = map.get("stationDistance")
.toString();
Log.e(TAG, "nextStationNum: " + nextStationNum
+ " stationArrivingTime: " + stationArrivingTime
+ " stationDistance: " + stationDistance);
// 未开通
if (stationArrivingTime == null || nextStationNum == 0) {
rtInfo = "未发车";
}
// 起点站
else if (sequence == 1) {
rtInfo = "起点站";
}
// 到站
else if (nextStationNum <= sequence) {
if (isNumeric(stationArrivingTime)) {
if (nextStationNum == sequence) {
// 已到站
if (Integer.parseInt(stationArrivingTime) < 10) {
rtInfo = "已到站,请抓紧上车!";
}
// 即将到站
else if (Integer.parseInt(stationDistance) < 10) {
rtInfo = "即将到站,请注意上车!";
} else {
int nstime = TimeStampToDelTime(Long
.parseLong(stationArrivingTime));// 计算还有几分钟
String distance = "<font color=\"red\">"
+ Integer.parseInt(stationDistance)
/ 1000.0 + "</font>" + "公里";
String time = "<font color=\"red\">"
+ nstime + "</font>" + "分钟";
String stationNum = "<font color=\"red\">"
+ (sequence - nextStationNum + 1)
+ "</font>" + "站";
String stationName = "<font color=\"red\">"
+ StationName + "</font>";
if (nstime <= 0) {
rtInfo = "即将到站,请注意上车!";
} else {
rtInfo = "距" + stationName + " "
+ stationNum + " "
+ distance + " " + time;
}
}
} else {
int nstime = TimeStampToDelTime(Long
.parseLong(stationArrivingTime));// 计算还有几分钟
String distance = "<font color=\"red\">"
+ Integer.parseInt(stationDistance)
/ 1000.0 + "</font>" + "公里";
String time = "<font color=\"red\">" + nstime
+ "</font>" + "分钟";
String stationNum = "<font color=\"red\">"
+ (sequence - nextStationNum + 1)
+ "</font>" + "站";
String stationName = "<font color=\"red\">"
+ StationName + "</font>";
if (nstime <= 0) {
rtInfo = "距" + stationName + " "
+ stationNum + " " + distance;
} else {
rtInfo = "距" + stationName + " "
+ stationNum + " " + distance
+ " " + time;
}
}
}
} else {
rtInfo = "未发车";
}
}
} catch (SQLException sqle) {
throw sqle;
}
} catch (JSONException e) {
// Log.e("JSON exception", e.getMessage());
e.printStackTrace();
} finally {
mHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mBuslineAdapter.updateBusAmount(mHasRtStationList);
mRtInfo.setText(Html.fromHtml(rtInfo));
mBuslineAdapter.notifyDataSetChanged();
dismissLoading();
}
});
}
}
public String TimeStampToDate(Long timestampString, String formats) {
if (timestampString < 0)
return "0";
String date = new java.text.SimpleDateFormat(formats)
.format(new java.util.Date(timestampString * 1000));
return date;
}
public boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("-?[0-9]+.*[0-9]*");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
public int TimeStampToDelTime(Long timestampString) {
if (timestampString < 0)
return (int) 0;
double delTime = (timestampString * 1000 - System.currentTimeMillis()) / 1000 / 60.0;
return (int) Math.ceil(delTime);
}
public void onResume() {
super.onResume();
MobclickAgent.onPageStart("SplashScreen"); // ͳ��ҳ��
MobclickAgent.onResume(this); // ͳ��ʱ��
exeuteTask();
}
@Override
public void onPause() {
super.onPause();
MobclickAgent.onPageEnd("SplashScreen");
MobclickAgent.onPause(this);
// task.cancel();
// timer.cancel();
if (mTask != null)
mTask.cancel(true);
}
@Override
public void onStop() {
super.onStop();
mHandler.removeCallbacksAndMessages(null);
}
@Override
public void onRestart() {
super.onRestart();
}
public void onDestroy() {
super.onDestroy();
}
private List<Child> loadBuslineData(int LineID) {
if (mStations == null)
mStations = new ArrayList<Child>();
List<Child> tmp = mDataBaseManager.acquireStationsWithBuslineID(LineID);
if (tmp.size() > 0) {
mStations = tmp;
if (Sequence > mStations.size())
Sequence = 1;
StationID = mStations.get(Sequence - 1).getStationID();
LineName = mStations.get(Sequence - 1).getLineName();
StationName = mStations.get(Sequence - 1).getStationName();
Map<String, Object> LineInfo = mDataBaseManager
.acquireLineInfoWithLineID(LineID);
if (LineInfo != null && LineInfo.size() > 0) {
startTime = LineInfo.get("StartTime").toString();
endTime = LineInfo.get("EndTime").toString();
StartStation = LineInfo.get("StartStation").toString();
EndStation = LineInfo.get("EndStation").toString();
FullName = LineInfo.get("LineName").toString() + " ("
+ LineInfo.get("StartStation").toString() + " - "
+ LineInfo.get("EndStation").toString() + ")";
OfflineID = Integer.parseInt(LineInfo.get("OfflineID")
.toString());
}
return mStations;
} else
return null;
}
private void changeDirection() {
if (LineID % 10 == 0)
LineID += 2;
else
LineID -= 2;
OfflineID = 0;
exeuteTask();
}
private loadDataBaseTask mTask = null;
private void exeuteTask() {
if (mTask != null)
mTask.cancel(true);
mTask = new loadDataBaseTask(this);
mTask.execute();
}
class loadDataBaseTask extends AsyncTask<Integer, Integer, List<Child>> {
// 后面尖括号内分别是参数(线程休息时间),进度(publishProgress用到),返回值 类型
private Context mContext = null;
public loadDataBaseTask(Context context) {
this.mContext = context;
}
/*
* 第一个执行的方法 执行时机:在执行实际的后台操作前,被UI 线程调用
* 作用:可以在该方法中做一些准备工作,如在界面上显示一个进度条,或者一些控件的实例化,这个方法可以不用实现。
*
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Log.d(TAG, "onPreExecute");
super.onPreExecute();
}
/*
* 执行时机:在onPreExecute 方法执行后马上执行,该方法运行在后台线程中 作用:主要负责执行那些很耗时的后台处理工作。可以调用
* publishProgress方法来更新实时的任务进度。该方法是抽象方法,子类必须实现。
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected List<Child> doInBackground(Integer... params) {
// TODO Auto-generated method stub
Log.d(TAG, "doInBackground");
// for (int i = 0; i <= 100; i++) {
// mProgressBar.setProgress(i);
publishProgress();
// try {
// Thread.sleep(params[0]);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
return loadBuslineData(LineID);
}
/*
* 执行时机:这个函数在doInBackground调用publishProgress时被调用后,UI
* 线程将调用这个方法.虽然此方法只有一个参数,但此参数是一个数组,可以用values[i]来调用
* 作用:在界面上展示任务的进展情况,例如通过一个进度条进行展示。此实例中,该方法会被执行100次
*
* @see android.os.AsyncTask#onProgressUpdate(Progress[])
*/
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
Log.d(TAG, "onProgressUpdate");
// mTextView.setText(values[0] + "%");
showLoading();
super.onProgressUpdate(values);
}
/*
* 执行时机:在doInBackground 执行完成后,将被UI 线程调用 作用:后台的计算结果将通过该方法传递到UI
* 线程,并且在界面上展示给用户 result:上面doInBackground执行后的返回值,所以这里是"执行完毕"
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(List<Child> result) {
// TODO Auto-generated method stub
Log.d(TAG, "onPostExecute");
if (result == null) {
Toast.makeText(BuslineListViewParallel.this, "对不起,没有反方向线路!",
Toast.LENGTH_SHORT).show();
dismissLoading();
return;
}
updateLineInfo();
rtInfo = "???";
mBuslineListView.setVisibility(View.VISIBLE);
mRtInfo.setText(Html.fromHtml(loadingInfo));
mBuslineAdapter.updateData(mStations);
mBuslineAdapter.setSelectIndex(Sequence - 1);
mBuslineAdapter.notifyDataSetChanged();
getSeverInfo();
mHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if ((Sequence - 1) < 1)
mBuslineListView.setSelection(0);
else
mBuslineListView.setSelection(Sequence - 3);
}
});
if (mUserDataBaseHelper.IsFavStation(LineID, StationID))
mConcernBtn.setImageResource(R.drawable.icon_horizon_like);
else
mConcernBtn.setImageResource(R.drawable.icon_horizon_dislike);
if (mUserDataBaseHelper.IsAlertOpenBusline(LineID, StationID))
mAlertBtn.setImageResource(R.drawable.icon_horizon_alarm);
else
mAlertBtn.setImageResource(R.drawable.icon_horizon_disalarm);
}
}
}
|
package com.example.myapplication22;
public class Lesson {
public String name;
public String no;
public String teacher;
public String classroom;
public Time time=new Time();
public String credit;
public String note;
}
class Time{
public int[] during=new int[2]; //起始周,终止周
public int isOddWeek; //1是单周,0是双周,3是单双周
public int[]begin=new int[7]; //下标是星期,0是周日,1是周一;值是课程开始时间,如34课程开始时间为3
public int last; //课程连续节数,如34为2
public int count; //课程的时间数,比如周一、周二都有课,就是2
}
|
/*
* Copyright (c) 2013-2014, Neuro4j.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.neuro4j.studio.core.diagram.edit.parts.actions;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeNodeEditPart;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.FilteredResourcesSelectionDialog;
import org.eclipse.ui.ide.IDE;
public abstract class OpenNodeAction implements IObjectActionDelegate {
public final static String ID = "org.neuro4j.studio.core.diagram.edit.parts.actions.CallNodeOpenAction1";
protected ShapeNodeEditPart selectedElement;
public void run(IAction action) {
String name = getStringParameter();
if (name == null || "".equals(name.trim()))
{
return;
}
searchFile(name);
}
public void selectionChanged(IAction action, ISelection selection) {
selectedElement = null;
if (selection instanceof IStructuredSelection) {
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
if (structuredSelection.getFirstElement() instanceof ShapeNodeEditPart) {
selectedElement = (ShapeNodeEditPart) structuredSelection.getFirstElement();
}
}
}
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
}
protected void openResource(final IFile file) {
final IWorkbenchPage activePage = JavaPlugin.getActivePage();
if (activePage != null) {
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
try {
IDE.openEditor(activePage, file, true);
} catch (PartInitException e) {
JavaPlugin.log(e);
}
}
});
}
}
private void searchFile(String name)
{
FilteredResourcesSelectionDialog dialog = new FilteredResourcesSelectionDialog(
PlatformUI.getWorkbench().getDisplay().getActiveShell(), false,
ResourcesPlugin.getWorkspace().getRoot(), IResource.FILE);
dialog.setTitle(getTitle());
dialog.setInitialPattern(getResourcePattern(name));
int result = dialog.open();
if (result == Window.OK) {
Object[] files = dialog.getResult();
if (files != null && files.length == 1)
{
if (files[0] instanceof IFile)
{
IFile file = (IFile) files[0];
openResource(file);
}
}
}
}
protected abstract String getResourcePattern(String name);
protected abstract String getTitle();
protected abstract String getStringParameter();
}
|
/*
* 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 games.Board;
import games.Interfaces.IPiece;
/**
*
* @author gpalomox
*/
public class BoardPosition {
int x;
int y;
IPiece piece;
public BoardPosition(int x, int y) {
super();
this.x = x;
this.y = y;
piece = null;
}
public void occupySpot(IPiece piece){
//if piece already here, delete it, i. e. set it dead
if(this.piece != null)
this.piece.isAvailable();
//place piece here
this.piece = piece;
}
public boolean isOccupied() {
return piece != null;
}
public IPiece releaseSpot() {
IPiece releasedPiece = this.piece;
this.piece = null;
return releasedPiece;
}
}
|
package org.foolip.mushup;
public class WikipediaException extends Exception {
WikipediaException() {}
WikipediaException(String message) {super(message);}
WikipediaException(Throwable cause) {super(cause);}
}
|
package cn.codecoach.irest.impl;
import cn.codecoach.irest.IRestAction;
import cn.codecoach.irest.impl.action.IRestActionParamDefault;
/**
* 默认action分类<br>
* 含义参数和返回结果
*
* @author yanchangyou@gmail.com
*
*/
public class IRestActionDefault implements IRestAction {
IRestActionParamDefault iRestActionParamDefault;
IRestResultDefault iRestResultDefault;
IRestActionParamDefault getiRestActionParamDefault() {
return iRestActionParamDefault;
}
void setiRestActionParamDefault(IRestActionParamDefault iRestActionParamDefault) {
this.iRestActionParamDefault = iRestActionParamDefault;
}
IRestResultDefault getiRestResultDefault() {
return iRestResultDefault;
}
void setiRestResultDefault(IRestResultDefault iRestResultDefault) {
this.iRestResultDefault = iRestResultDefault;
}
public void addValue(String name, String value) {
iRestResultDefault.addValue(name, value);
}
public void addComplextValue(String name, Object value) {
iRestResultDefault.addComplextValue(name, value);
}
}
|
package com.nisum.webflux.controller;
import com.nisum.webflux.model.Fruit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.reactive.function.BodyInserters;
@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureWebTestClient
//@ContextConfiguration(classes = TestConfig.class)
public class FruitControllerComponentTest {
@Autowired
WebTestClient webTestClient;
@Test
public void save_UsingWebTestClient() {
Fruit fruit=new Fruit("1","apple","300");
webTestClient.post().uri("/fruit").contentType(MediaType.APPLICATION_JSON_UTF8).body(BodyInserters.fromObject(fruit))
.exchange()
.expectStatus().isOk().expectBody().jsonPath("$.id").isEqualTo("1");
// .jsonPath("$.description").isEqualTo("xx").jsonPath("$.price").isEqualTo(34.4);
}
}
|
package com.ag.service;
import com.ag.dto.Data;
import com.ag.entity.ProductInfo;
import javax.servlet.http.HttpSession;
import java.util.List;
public interface ProductServcie {
List<Data> queryProduct11(Integer id, HttpSession session);
//根据id查
ProductInfo queryByIdProduct(String id);
//根据id修改库存
void updateStock(Integer quantity,String id);
}
|
/*
Owner: Nidhi Agrawal
Problem Statement:
Given an array of integers nums.
A pair (i,j) is called good if nums[i] == nums[j] and i < j.
Return the number of good pairs.
Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100*/
import java.util.Scanner;
public class GoodPair {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array:");
int length=sc.nextInt();
System.out.println("Enter array elements:");
int[] nums = new int[length];
for(int i=0;i<length;i++)
{
nums[i]=sc.nextInt();
}
GoodPair obj = new GoodPair();
int sum = obj.solution(nums);
System.out.print("No of Good Pair:"+sum);
sc.close();
}
private int solution(int[] nums)
{
int[] freq = new int[101];
for(int i=0;i<nums.length;i++)
freq[nums[i]]++;
int sum = 0;
for(int i=0;i<freq.length;i++)
{
if(freq[i] !=0)
sum +=(freq[i]*(freq[i]-1))/2;
}
return sum;
}
}
|
/*
* Zachary Snydar
* 10/11/16
* Subsets.java
* This file converts data files of employees to teams
*/
package edu.greenriver.it.subset;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import edu.greenriver.it.employee.Employee;
/**
* A class with a main method that takes a data file of employees and prints out possible teams with a score over 20.
* @author Zachary Snydar
*
*/
public class Subsets
{
//Fields
private ArrayList<Employee> employees;
private static final int MINIMUM_SCORE = 19;
private static final int EMPLOYEE_STRING_SIZE=3;
private static final int BASE_TEN_RADIX=10;
//Main Method
/**
* Main method that prints out teams of employees given a data file
* @param args Its a main method
*/
public static void main(String[] args)
{
//Initiate employees and run saveTeams()
employees = new ArrayList<Employee>();
saveTeams();
}
//Helper Methods
/**
* This method loads all employees, finds all possible teams, then prints them to the console if they
* have a combined rating of over 20
*/
public static void saveTeams()
{
//load employee objects and instantiate temporary variables
ArrayList<Employee> employees = loadEmployees();
ArrayList<Employee> tempTeam = new ArrayList<Employee>();
int teamsFound=0;
//Find all possible teams using a nested for loop and an and function, 2^n -1 loops.
for (int i = 0; i<(1<<employees.size());i++)
{
for(int j = 0; j<employees.size();j++)
{
if((i & (1 << j)) >0)
{
tempTeam.add(employees.get(j));
}
}
//Find the total team rating
int teamRating=0;
for (Employee toRate : tempTeam)
{
teamRating+=toRate.getRating();
}
//If the team has a higher score than 20
if ( teamRating>MINIMUM_SCORE)
{
//Increment teamsFound and print out the team.
teamsFound++;
System.out.println("Team Found (Score: "+teamRating+")\n"+tempTeam.toString()+"\n");
}
//Empty the tempTeam for reuse
tempTeam.clear();
}
//Print the total number of teams found
System.out.println("Total number of teams found: "+teamsFound);
}
/**
* A method that reads a data file and converts individual lines into employee objects
* @return an ArrayList<Employee> that contains all employees in the loaded file
*/
public static ArrayList<Employee> loadEmployees()
{
//Try/Catch for IO manipulation
try
{
//Make the file and the scanner.
File data = new File("src/even_more_employees.dat");
Scanner eScanner = new Scanner(data);
//run parseEmployee on each line of the file
while(eScanner.hasNextLine())
{
employees.add(parseEmployee(eScanner.nextLine()));
}
//Close dat scanna
eScanner.close();
}
//In case we fudged up
catch (FileNotFoundException e)
{
System.out.println("Error: " + Thread.currentThread().getStackTrace());
}
//Return
return employees;
}
/**
* A method that takes a string and converts it into an Employee object to return
* @param employeeText A single string containing the attributes of the employee
* @return The employee object created from our input string
*/
public static Employee parseEmployee(String employeeText)
{
//String array for using .Split
String[] employeeData = new String[EMPLOYEE_STRING_SIZE];
//Splitting
employeeData = employeeText.split(",");
//Assigning Variables
String name=employeeData[EMPLOYEE_STRING_SIZE-EMPLOYEE_STRING_SIZE];
int rating = Integer.parseInt(employeeData[(EMPLOYEE_STRING_SIZE-EMPLOYEE_STRING_SIZE+)+1].trim(),BASE_TEN_RADIX);
String hireDate = employeeData[EMPLOYEE_STRING_SIZE-1];
//Making a new employee object and returning it
Employee temp = new Employee(name,rating,hireDate);
return temp;
}
}
|
/**
* A type of RuntimeException which occurs when a file is not shared. Possible
* scenarios include a peer which does not exist or a peer which exists but
* is not sharing a given file.
*
* @author Oloff Biermann
*/
package org.biermann.tme3.p2pindex.exception;
public class FileNotSharedException extends RuntimeException
{
/**
*
*/
private static final long serialVersionUID = -4623639569874811482L;
public FileNotSharedException(String message)
{
super(message);
}
}
|
package macro;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class macro2 {
public static void main(String[] args) throws IOException {
MNT[] mntab = new MNT[2];
mntab[0] = new MNT("M1",2,2,1,0);
mntab[1] = new MNT("M2",2,2,6,2);
KPDTAB[] kpdtab = new KPDTAB[4];
kpdtab[0] = new KPDTAB("&A", "AREG");
kpdtab[1] = new KPDTAB("&B", "-");
kpdtab[2] = new KPDTAB("&U", "CREG");
kpdtab[3] = new KPDTAB("&V", "DREG");
HashMap<Integer,String>alptab = new HashMap<>();
int alp=1;
BufferedReader br = new BufferedReader(new FileReader("call.txt"));
BufferedReader ic = new BufferedReader(new FileReader("ic.txt"));
String currBr,currIc;
String[] mdt = new String[20];
String[] strArray = new String[6];
while((currBr=br.readLine())!=null){
int m=0;
StringTokenizer st = new StringTokenizer(currBr);
while(st.hasMoreTokens()){
strArray[m] = st.nextToken();
System.out.print(strArray[m]+" ");
m++;
}
System.out.println();
for(int i=0;i<2;i++){
if(strArray[0].equals(mntab[i].name))
{
if(m-1 < (mntab[i].kp+mntab[i].pp)) //no. of parameters are less
{
for(int j=1;j<(mntab[i].kp+mntab[i].pp);j++){
if(j==3){
alptab.put(j, kpdtab[0].value);
if(strArray[j].contains("=")){
String[] keyp = strArray[j].split("=");
alptab.put(j+1,keyp[1]);
}
}
else
{
alptab.put(j,strArray[j]);
}
}
}
else
{
for(int j=1;j<=(mntab[i].kp+mntab[i].pp);j++){
if(strArray[j].contains("=")){
String[] keyp = strArray[j].split("=");
alptab.put(j,keyp[1]);
}
else
{
alptab.put(j,strArray[j]);
}
}
}
currIc="";
while(!currIc.equals("MEND")){
currIc=ic.readLine();
int mic=0;
StringTokenizer stic = new StringTokenizer(currIc);
while(stic.hasMoreTokens()){
strArray[mic] = stic.nextToken();
// System.out.print(strArray[mic]+" ");
mic++;
}
// System.out.println();
//replace #num with alptab values
if(strArray[1].contains("#") && strArray[2].contains("#") )
{
String[] key = strArray[1].split("#");
String[] key1 = strArray[2].split("#");
System.out.println(strArray[0]+" "+ alptab.get(Integer.parseInt(key[1])) + " " + alptab.get(Integer.parseInt(key1[1])));
}
else if(strArray[1].contains("#") && !strArray[0].equals("MEND")){
String[] key = strArray[1].split("#");
//key[1] contains number
System.out.println(strArray[0]+" "+ alptab.get(Integer.parseInt(key[1])) +" "+strArray[2]);
}
}
}
}
}
}
}
|
package org.shazhi.businessEnglishMicroCourse.service;
import org.shazhi.businessEnglishMicroCourse.entity.CommentEntity;
import org.shazhi.businessEnglishMicroCourse.util.Result;
import java.util.List;
public interface CommentService {
Result mark(CommentEntity comment);
List<CommentEntity> load(CommentEntity comment, Integer start);
}
|
package com.hellofresh.challenge.tests;
import com.hellofresh.challenge.pages.pageObjects.*;
import com.hellofresh.challenge.utils.TestDataProvider;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.assertj.core.api.SoftAssertions;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
public class CheckoutTests extends BaseTest {
private static final Logger logger = LogManager.getLogger(CheckoutTests.class);
/**
* Test: Checkout Scenario
* Receives data from Data provider class as parameter
* @param authData existing User Data as HashMap
* @param product Product data to use in test as String
* All assertions are executed in Tests and not in Pages.
*/
@Test(dataProvider = "product-data-provider",
dataProviderClass = TestDataProvider.class,
description = "Validate that existing user can place an order successfully.")
public void checkoutTest(Map<String, String> authData, String product, HashMap<String, String> expectedValues) {
SoftAssertions softly = new SoftAssertions();
HomePage homePage = new HomePage(getDriver());
homePage.clickLogin();
LoginPage loginPage = new LoginPage(getDriver());
loginPage.loginAsExistingUser(authData.get("email"), authData.get("password"));
MyAccountPage myAccountPage = new MyAccountPage(getDriver());
myAccountPage.selectCategory("Women");
CategoryItemsPage categoryItemsPage = new CategoryItemsPage(getDriver());
categoryItemsPage.selectProduct(product);
ProductPage productPage = new ProductPage(getDriver());
productPage.addProductToCart();
productPage.proceedToCart();
OrderPage orderPage = new OrderPage(getDriver());
softly.assertThat(orderPage.getUrl()).contains(orderPage.getPageUrlFragment());
orderPage.confirmProductCheckout();
orderPage.confirmAddress();
orderPage.confirmShipping();
orderPage.selectPaymentType();
OrderConfirmationPage orderConfirmationPage = new OrderConfirmationPage(getDriver());
softly.assertThat(orderConfirmationPage.getOrderConfirmationHeading().getText()).isEqualTo(expectedValues.get("orderConfirmationTitle"));
softly.assertThat(orderConfirmationPage.getShippingDoneTab().isDisplayed()).isTrue();
softly.assertThat(orderConfirmationPage.getPaymentTab().isDisplayed()).isTrue();
softly.assertThat(orderConfirmationPage.getOrderConfirmationLabel().getText()).contains(expectedValues.get("orderConfirmationMessage"));
softly.assertThat(orderConfirmationPage.getUrl()).contains(orderConfirmationPage.getPageUrlFragment());
softly.assertAll();
}
}
|
/*
* 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.ut.healthelink.model;
import com.ut.healthelink.validator.NoHtml;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
/**
*
* @author chadmccue
*/
@Entity
@Table(name = "NEWSARTICLES")
public class newsArticle {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID", nullable = false)
private int id;
@NotEmpty
@NoHtml
@Column(name = "TITLE", nullable = false)
private String title;
@NoHtml
@Column(name = "SHORTDESC", nullable = false)
private String shortDesc;
@NotEmpty
@Column(name = "LONGDESC", nullable = false)
private String longDesc;
@Column(name = "STATUS", nullable = false)
private boolean status = false;
@DateTimeFormat(pattern = "dd/MM/yyyy hh:mm:ss")
@Column(name = "DATECREATED", nullable = true)
private Date dateCreated = new Date();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getShortDesc() {
return shortDesc;
}
public void setShortDesc(String shortDesc) {
this.shortDesc = shortDesc;
}
public String getLongDesc() {
return longDesc;
}
public void setLongDesc(String longDesc) {
this.longDesc = longDesc;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
}
|
package com.gestion.service.impression;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import com.gestion.entity.Bonlivraison;
import com.gestion.entity.Intervenant;
import com.gestion.entity.Intervention;
import com.gestion.entity.Livraison;
import com.gestion.service.ServiceBonLivraison;
import com.gestion.service.ServiceInterveant;
import com.gestion.service.ServiceIntervention;
import com.gestion.service.ServiceLivraison;
import com.gestion.service.date.Formatter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfNumber;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import fr.cortex2i.utils.HibernateUtils;
/**
* Servlet implementation class ImprimerIntervention
*/
@WebServlet("/ServletImprimerIntervention")
public class ServletImprimerIntervention extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ServletImprimerIntervention() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Session s = HibernateUtils.getSession();
String num = request.getParameter("numinterpdf");
Intervention inter = new Intervention();
inter.setNumIntervention(num);
inter = ServiceIntervention.rechercheInterventionByNum(s, inter);
// Create a reader to extract info
PdfReader reader;
try {
reader = new PdfReader(request.getSession().getServletContext().getRealPath("/intervention.pdf"));
PdfStamper stamper = new PdfStamper(reader , response.getOutputStream());
stamper.getAcroFields().setField("numinter", inter.getNumIntervention());
stamper.getAcroFields().setField("nomclient", inter.getClient().getNom());
stamper.getAcroFields().setField("contact", inter.getClient().getContact());
stamper.getAcroFields().setField("dateinter", Formatter.converteDateStr(inter.getDateIntervention(), new SimpleDateFormat("dd-MM-yyyy") ));
stamper.getAcroFields().setField("ha", Formatter.converteDateStr(inter.getHeure_A() , new SimpleDateFormat("H:mm")));
stamper.getAcroFields().setField("hd", Formatter.converteDateStr(inter.getHeure_D() , new SimpleDateFormat("H:mm")));
stamper.getAcroFields().setField("intervenant", inter.getIntervenant().getNom());
stamper.getAcroFields().setField("objet", inter.getObjetmission());
stamper.getAcroFields().setField("observation", inter.getBilan());
//stamper.getAcroFields().setField("titre", "INTERVENTION INFORMATIQUE");
switch (inter.getForfait())
{
case "HORS FORFAIT" :stamper.getAcroFields().setField("HORS", "Yes");
break;
case "JOURNNEE FORFAIT" :stamper.getAcroFields().setField("FOR", "Yes");
break;
}
switch (inter.getMateriel())
{
case "PC FIXE" :stamper.getAcroFields().setField("pc", "Yes");
break;
case "PORTABLE" :stamper.getAcroFields().setField("portable", "Yes");
break;
case "SERVEUR" :stamper.getAcroFields().setField("serveur", "Yes");
break;
default :stamper.getAcroFields().setField("autre", "Yes");
stamper.getAcroFields().setField("textautre", inter.getMateriel());
break;
}
//stamper.getAcroFields().
stamper.setViewerPreferences(PdfWriter.CenterWindow | PdfWriter.FitWindow);
stamper.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
stamper.addViewerPreference(PdfName.NUMCOPIES, new PdfNumber(3));
response.addHeader("Expires", "0");
response.addHeader("Content-Disposition", "attachment");
response.setContentType("application/pdf");
reader.close();
stamper.close();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
s.close();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import org.springframework.lang.Nullable;
/**
* Adapts a given {@link Map} to the {@link MultiValueMap} contract.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @since 5.3
* @param <K> the key type
* @param <V> the value element type
* @see CollectionUtils#toMultiValueMap
* @see LinkedMultiValueMap
*/
@SuppressWarnings("serial")
public class MultiValueMapAdapter<K, V> implements MultiValueMap<K, V>, Serializable {
private final Map<K, List<V>> targetMap;
/**
* Wrap the given target {@link Map} as a {@link MultiValueMap} adapter.
* @param targetMap the plain target {@code Map}
*/
public MultiValueMapAdapter(Map<K, List<V>> targetMap) {
Assert.notNull(targetMap, "'targetMap' must not be null");
this.targetMap = targetMap;
}
// MultiValueMap implementation
@Override
@Nullable
public V getFirst(K key) {
List<V> values = this.targetMap.get(key);
return (values != null && !values.isEmpty() ? values.get(0) : null);
}
@Override
public void add(K key, @Nullable V value) {
List<V> values = this.targetMap.computeIfAbsent(key, k -> new ArrayList<>(1));
values.add(value);
}
@Override
public void addAll(K key, List<? extends V> values) {
List<V> currentValues = this.targetMap.computeIfAbsent(key, k -> new ArrayList<>(values.size()));
currentValues.addAll(values);
}
@Override
public void addAll(MultiValueMap<K, V> values) {
values.forEach(this::addAll);
}
@Override
public void set(K key, @Nullable V value) {
List<V> values = new ArrayList<>(1);
values.add(value);
this.targetMap.put(key, values);
}
@Override
public void setAll(Map<K, V> values) {
values.forEach(this::set);
}
@Override
public Map<K, V> toSingleValueMap() {
Map<K, V> singleValueMap = CollectionUtils.newLinkedHashMap(this.targetMap.size());
this.targetMap.forEach((key, values) -> {
if (values != null && !values.isEmpty()) {
singleValueMap.put(key, values.get(0));
}
});
return singleValueMap;
}
// Map implementation
@Override
public int size() {
return this.targetMap.size();
}
@Override
public boolean isEmpty() {
return this.targetMap.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return this.targetMap.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return this.targetMap.containsValue(value);
}
@Override
@Nullable
public List<V> get(Object key) {
return this.targetMap.get(key);
}
@Override
@Nullable
public List<V> put(K key, List<V> value) {
return this.targetMap.put(key, value);
}
@Override
@Nullable
public List<V> putIfAbsent(K key, List<V> value) {
return this.targetMap.putIfAbsent(key, value);
}
@Override
@Nullable
public List<V> remove(Object key) {
return this.targetMap.remove(key);
}
@Override
public void putAll(Map<? extends K, ? extends List<V>> map) {
this.targetMap.putAll(map);
}
@Override
public void clear() {
this.targetMap.clear();
}
@Override
public Set<K> keySet() {
return this.targetMap.keySet();
}
@Override
public Collection<List<V>> values() {
return this.targetMap.values();
}
@Override
public Set<Entry<K, List<V>>> entrySet() {
return this.targetMap.entrySet();
}
@Override
public void forEach(BiConsumer<? super K, ? super List<V>> action) {
this.targetMap.forEach(action);
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || this.targetMap.equals(other));
}
@Override
public int hashCode() {
return this.targetMap.hashCode();
}
@Override
public String toString() {
return this.targetMap.toString();
}
}
|
package data.concretes;
import java.util.ArrayList;
import java.util.List;
import data.abstracts.UserDao;
import entities.concretes.User;
public class HibernateUserDao implements UserDao {
List<User> users;
public HibernateUserDao() {
users=new ArrayList<User>();
}
@Override
public void Add(User user) {
users.add(user);
System.out.println("user Eklendi");
}
@Override
public void Delete(User user) {
User deleteUser=users.stream().filter(u->u.getId()==user.getId()).findFirst().get();
users.remove(deleteUser);
System.out.println("user deleted:"+user.getName());
}
@Override
public void Update(User user) {
User updateUser=users.stream().filter(u->u.getId()==user.getId()).findFirst().get();
updateUser.setId(user.getId());
updateUser.setName(user.getName());
updateUser.setLastName(user.getLastName());
updateUser.setMail(user.getMail());
updateUser.setPassword(user.getPassword());
users.remove(user);
users.add(updateUser);
}
@Override
public User GetUser(int id) {
User user=users.stream().filter(u->u.getId()==id).findFirst().get();
return user;
}
@Override
public List<User> GetAll() {
return users;
}
@Override
public List<String> GetAllEmails() {
List<String> mailsList=new ArrayList<String>();
for(User user:users) {
mailsList.add(user.getMail());
}
return mailsList;
}
@Override
public List<String> GetAllPassword() {
List<String> passList=new ArrayList<String>();
for(User user:users) {
passList.add(user.getPassword());
}
return passList;
}
}
|
package DAO;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
class ClienteDAO extends AbstractDAO<Cliente>{
private Connection connection;
public ClienteDAO() {
this.connection = Conexao.getConexao();
}
@Override
public boolean adicionar(Cliente objeto) {
boolean transacaoConcluida = true;
Statement preparedStatement = null;
try {
String query = "INSERT INTO clientes(cpf, nome, email, rua, numero, bairro) VALUES(";
query += "'" + objeto.getCpf() + "','"
+ objeto.getNome() + "','"
+ objeto.getEmail() + "','"
+ objeto.getEndereco().getRua() + "','"
+ objeto.getEndereco().getNumero() + "','"
+ objeto.getEndereco().getBairro() + "')";
preparedStatement = this.connection.createStatement();
preparedStatement.execute(query);
}
catch (SQLException e) {
e.printStackTrace();
transacaoConcluida = false;
}
return transacaoConcluida;
}
@Override
public Cliente encontrarPorId(int id) {
Cliente cliente = new Cliente();
Statement preparedStatement = null;
try {
String query = "SELECT id, cpf, nome , email, rua, numero, bairro FROM clientes WHERE id = " + id;
preparedStatement = this.connection.createStatement();
ResultSet respostaBanco = preparedStatement.executeQuery(query);
if(respostaBanco.next()) {
cliente.setId(respostaBanco.getInt("id"));
cliente.setNome(respostaBanco.getString("nome"));
cliente.setCpf(respostaBanco.getString("cpf"));
cliente.setEmail(respostaBanco.getString("email"));
Endereco endereco = new Endereco();
endereco.setRua(respostaBanco.getString("rua"));
endereco.setNumero(respostaBanco.getString("numero"));
endereco.setBairro(respostaBanco.getString("bairro"));
cliente.setEndereco(endereco);
}
}
catch (SQLException e) {
e.printStackTrace();
}
return cliente;
}
@Override
public boolean remover(int id) {
boolean naoRemoveu = true;
Statement preparedStatement = null;
try {
String query = "DELETE FROM clientes WHERE id = " + id;
preparedStatement = this.connection.createStatement();
naoRemoveu = preparedStatement.execute(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return naoRemoveu;
}
@Override
public boolean atualizar(Cliente objeto) {
boolean atualizou = true;
Statement preparedStatement = null;
try {
String query = "UPDATE clientes SET";
query += " nome = '" + objeto.getNome() + "',";
query += " cpf = '" + objeto.getCpf() + "',";
query += " email = '" + objeto.getEmail() + "',";
query += " rua = '" + objeto.getEndereco().getRua() + "',";
query += " numero = '" + objeto.getEndereco().getNumero() + "',";
query += " bairro = '" + objeto.getEndereco().getBairro() + "'";
query += " WHERE id = " + objeto.getId();
preparedStatement = this.connection.createStatement();
preparedStatement.execute(query);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
atualizou = false;
}
return atualizou;
}
@Override
public ArrayList<Cliente> pegarTodos() {
return null;
}
}
|
package com.flyue.xiaomy.forward.initializer;
import com.flyue.xiaomy.forward.handler.ForwardChannelHandler;
import com.flyue.xiaomy.starter.BaseClientStarter;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
/**
* @Author: Liu Yuefei
* @Date: Created in 2020/2/19 9:50
* @Description:
*/
public class ForwardChannelInitializer extends ChannelInitializer<SocketChannel> {
private final BaseClientStarter forwardClient;
public ForwardChannelInitializer(BaseClientStarter forwardClient) {
this.forwardClient = forwardClient;
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ForwardChannelHandler forwardChannelHandler = new ForwardChannelHandler();
forwardChannelHandler.setForwardClient(forwardClient);
ch.pipeline().addLast(forwardChannelHandler);
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.client;
import java.io.Closeable;
import java.io.IOException;
import java.net.URI;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpHead;
import org.apache.hc.client5.http.classic.methods.HttpOptions;
import org.apache.hc.client5.http.classic.methods.HttpPatch;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.classic.methods.HttpTrace;
import org.apache.hc.client5.http.config.Configurable;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.io.SocketConfig;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.http.HttpMethod;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* {@link org.springframework.http.client.ClientHttpRequestFactory} implementation that
* uses <a href="https://hc.apache.org/httpcomponents-client-ga/">Apache HttpComponents
* HttpClient</a> to create requests.
*
* <p>Allows to use a pre-configured {@link HttpClient} instance -
* potentially with authentication, HTTP connection pooling, etc.
*
* <p><b>NOTE:</b> Requires Apache HttpComponents 5.1 or higher, as of Spring 6.0.
*
* @author Oleg Kalnichevski
* @author Arjen Poutsma
* @author Stephane Nicoll
* @author Juergen Hoeller
* @since 3.1
*/
public class HttpComponentsClientHttpRequestFactory implements ClientHttpRequestFactory, DisposableBean {
private HttpClient httpClient;
@Nullable
private BiFunction<HttpMethod, URI, HttpContext> httpContextFactory;
private long connectTimeout = -1;
private long connectionRequestTimeout = -1;
/**
* Create a new instance of the {@code HttpComponentsClientHttpRequestFactory}
* with a default {@link HttpClient} based on system properties.
*/
public HttpComponentsClientHttpRequestFactory() {
this.httpClient = HttpClients.createSystem();
}
/**
* Create a new instance of the {@code HttpComponentsClientHttpRequestFactory}
* with the given {@link HttpClient} instance.
* @param httpClient the HttpClient instance to use for this request factory
*/
public HttpComponentsClientHttpRequestFactory(HttpClient httpClient) {
this.httpClient = httpClient;
}
/**
* Set the {@code HttpClient} used for
* {@linkplain #createRequest(URI, HttpMethod) synchronous execution}.
*/
public void setHttpClient(HttpClient httpClient) {
Assert.notNull(httpClient, "HttpClient must not be null");
this.httpClient = httpClient;
}
/**
* Return the {@code HttpClient} used for
* {@linkplain #createRequest(URI, HttpMethod) synchronous execution}.
*/
public HttpClient getHttpClient() {
return this.httpClient;
}
/**
* Set the connection timeout for the underlying {@link RequestConfig}.
* A timeout value of 0 specifies an infinite timeout.
* <p>Additional properties can be configured by specifying a
* {@link RequestConfig} instance on a custom {@link HttpClient}.
* <p>This options does not affect connection timeouts for SSL
* handshakes or CONNECT requests; for that, it is required to
* use the {@link SocketConfig} on the
* {@link HttpClient} itself.
* @param connectTimeout the timeout value in milliseconds
* @see RequestConfig#getConnectTimeout()
* @see SocketConfig#getSoTimeout
*/
public void setConnectTimeout(int connectTimeout) {
Assert.isTrue(connectTimeout >= 0, "Timeout must be a non-negative value");
this.connectTimeout = connectTimeout;
}
/**
* Set the connection timeout for the underlying {@link RequestConfig}.
* A timeout value of 0 specifies an infinite timeout.
* <p>Additional properties can be configured by specifying a
* {@link RequestConfig} instance on a custom {@link HttpClient}.
* <p>This options does not affect connection timeouts for SSL
* handshakes or CONNECT requests; for that, it is required to
* use the {@link SocketConfig} on the
* {@link HttpClient} itself.
* @param connectTimeout the timeout value in milliseconds
* @since 6.1
* @see RequestConfig#getConnectTimeout()
* @see SocketConfig#getSoTimeout
*/
public void setConnectTimeout(Duration connectTimeout) {
Assert.notNull(connectTimeout, "ConnectTimeout must not be null");
Assert.isTrue(!connectTimeout.isNegative(), "Timeout must be a non-negative value");
this.connectTimeout = connectTimeout.toMillis();
}
/**
* Set the timeout in milliseconds used when requesting a connection
* from the connection manager using the underlying {@link RequestConfig}.
* A timeout value of 0 specifies an infinite timeout.
* <p>Additional properties can be configured by specifying a
* {@link RequestConfig} instance on a custom {@link HttpClient}.
* @param connectionRequestTimeout the timeout value to request a connection in milliseconds
* @see RequestConfig#getConnectionRequestTimeout()
*/
public void setConnectionRequestTimeout(int connectionRequestTimeout) {
Assert.isTrue(connectionRequestTimeout >= 0, "Timeout must be a non-negative value");
this.connectionRequestTimeout = connectionRequestTimeout;
}
/**
* Set the timeout in milliseconds used when requesting a connection
* from the connection manager using the underlying {@link RequestConfig}.
* A timeout value of 0 specifies an infinite timeout.
* <p>Additional properties can be configured by specifying a
* {@link RequestConfig} instance on a custom {@link HttpClient}.
* @param connectionRequestTimeout the timeout value to request a connection in milliseconds
* @since 6.1
* @see RequestConfig#getConnectionRequestTimeout()
*/
public void setConnectionRequestTimeout(Duration connectionRequestTimeout) {
Assert.notNull(connectionRequestTimeout, "ConnectionRequestTimeout must not be null");
Assert.isTrue(!connectionRequestTimeout.isNegative(), "Timeout must be a non-negative value");
this.connectionRequestTimeout = connectionRequestTimeout.toMillis();
}
/**
* Indicates whether this request factory should buffer the request body internally.
* <p>Default is {@code true}. When sending large amounts of data via POST or PUT, it is
* recommended to change this property to {@code false}, so as not to run out of memory.
* @since 4.0
* @deprecated since 6.1 requests are never buffered, as if this property is {@code false}
*/
@Deprecated(since = "6.1", forRemoval = true)
public void setBufferRequestBody(boolean bufferRequestBody) {
// no-op
}
/**
* Configure a factory to pre-create the {@link HttpContext} for each request.
* <p>This may be useful for example in mutual TLS authentication where a
* different {@code RestTemplate} for each client certificate such that
* all calls made through a given {@code RestTemplate} instance as associated
* for the same client identity. {@link HttpClientContext#setUserToken(Object)}
* can be used to specify a fixed user token for all requests.
* @param httpContextFactory the context factory to use
* @since 5.2.7
*/
public void setHttpContextFactory(BiFunction<HttpMethod, URI, HttpContext> httpContextFactory) {
this.httpContextFactory = httpContextFactory;
}
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
HttpClient client = getHttpClient();
ClassicHttpRequest httpRequest = createHttpUriRequest(httpMethod, uri);
postProcessHttpRequest(httpRequest);
HttpContext context = createHttpContext(httpMethod, uri);
if (context == null) {
context = HttpClientContext.create();
}
// Request configuration not set in the context
if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
// Use request configuration given by the user, when available
RequestConfig config = null;
if (httpRequest instanceof Configurable configurable) {
config = configurable.getConfig();
}
if (config == null) {
config = createRequestConfig(client);
}
if (config != null) {
context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
}
}
return new HttpComponentsClientHttpRequest(client, httpRequest, context);
}
/**
* Create a default {@link RequestConfig} to use with the given client.
* Can return {@code null} to indicate that no custom request config should
* be set and the defaults of the {@link HttpClient} should be used.
* <p>The default implementation tries to merge the defaults of the client
* with the local customizations of this factory instance, if any.
* @param client the {@link HttpClient} (or {@code HttpAsyncClient}) to check
* @return the actual RequestConfig to use (may be {@code null})
* @since 4.2
* @see #mergeRequestConfig(RequestConfig)
*/
@Nullable
protected RequestConfig createRequestConfig(Object client) {
if (client instanceof Configurable configurableClient) {
RequestConfig clientRequestConfig = configurableClient.getConfig();
return mergeRequestConfig(clientRequestConfig);
}
return mergeRequestConfig(RequestConfig.DEFAULT);
}
/**
* Merge the given {@link HttpClient}-level {@link RequestConfig} with
* the factory-level configuration, if necessary.
* @param clientConfig the config held by the current
* @return the merged request config
* @since 4.2
*/
@SuppressWarnings("deprecation") // setConnectTimeout
protected RequestConfig mergeRequestConfig(RequestConfig clientConfig) {
if (this.connectTimeout == -1 && this.connectionRequestTimeout == -1) { // nothing to merge
return clientConfig;
}
RequestConfig.Builder builder = RequestConfig.copy(clientConfig);
if (this.connectTimeout >= 0) {
builder.setConnectTimeout(this.connectTimeout, TimeUnit.MILLISECONDS);
}
if (this.connectionRequestTimeout >= 0) {
builder.setConnectionRequestTimeout(this.connectionRequestTimeout, TimeUnit.MILLISECONDS);
}
return builder.build();
}
/**
* Create a Commons HttpMethodBase object for the given HTTP method and URI specification.
* @param httpMethod the HTTP method
* @param uri the URI
* @return the Commons HttpMethodBase object
*/
protected ClassicHttpRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
if (HttpMethod.GET.equals(httpMethod)) {
return new HttpGet(uri);
}
else if (HttpMethod.HEAD.equals(httpMethod)) {
return new HttpHead(uri);
}
else if (HttpMethod.POST.equals(httpMethod)) {
return new HttpPost(uri);
}
else if (HttpMethod.PUT.equals(httpMethod)) {
return new HttpPut(uri);
}
else if (HttpMethod.PATCH.equals(httpMethod)) {
return new HttpPatch(uri);
}
else if (HttpMethod.DELETE.equals(httpMethod)) {
return new HttpDelete(uri);
}
else if (HttpMethod.OPTIONS.equals(httpMethod)) {
return new HttpOptions(uri);
}
else if (HttpMethod.TRACE.equals(httpMethod)) {
return new HttpTrace(uri);
}
throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
}
/**
* Template method that allows for manipulating the {@link ClassicHttpRequest} before it is
* returned as part of a {@link HttpComponentsClientHttpRequest}.
* <p>The default implementation is empty.
* @param request the request to process
*/
protected void postProcessHttpRequest(ClassicHttpRequest request) {
}
/**
* Template methods that creates a {@link HttpContext} for the given HTTP method and URI.
* <p>The default implementation returns {@code null}.
* @param httpMethod the HTTP method
* @param uri the URI
* @return the http context
*/
@Nullable
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
return (this.httpContextFactory != null ? this.httpContextFactory.apply(httpMethod, uri) : null);
}
/**
* Shutdown hook that closes the underlying
* {@link HttpClientConnectionManager ClientConnectionManager}'s
* connection pool, if any.
*/
@Override
public void destroy() throws Exception {
HttpClient httpClient = getHttpClient();
if (httpClient instanceof Closeable closeable) {
closeable.close();
}
}
}
|
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static Scanner in = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int n = in.nextInt();
in.nextLine();
for (int i = 0; i < n; i++) {
String input = in.nextLine();
char[] inputChar = input.toCharArray();
Arrays.sort(inputChar);
boolean diverse = true;
for (int j = 0; j < inputChar.length - 1 && diverse; j++) {
// out.println("inputChar: " + (int)inputChar[j] + " & " + ((int)inputChar[j + 1] - 1));
if ((int)inputChar[j] == ((int)inputChar[j + 1] - 1)) continue;
diverse = false;
}
out.println(diverse ? "Yes" : "No");
}
in.close();
out.close();
}
} |
package com.example.onenprofessor.activity;
import java.lang.reflect.Constructor;
import com.example.onenprofessor.ConstantValue;
import com.example.onenprofessor.R;
import com.example.onenprofessor.adapter.MyClientDrawListAdapter;
import com.example.onenprofessor.adapter.MyServerClientInfoListAdapter;
import com.example.onenprofessor.control.ClientSetNameControl;
import com.example.onenprofessor.control.EndControl;
import com.example.onenprofessor.dialog.SetNameDialog;
import com.example.onenprofessor.socket.MyClientSocketController;
import com.example.onenprofessor.utils.OpenSocketUtils;
import com.example.onenprofessor.utils.StringUtils;
import com.example.onenprofessor.utils.WifiConnectUtil;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ClientActivity extends Activity implements OnItemClickListener {
private ListView drawerList;
private SharedPreferences sp;
private FragmentTransaction transaction ;
private WifiConnectUtil wifiConnectUtil;
private MyClientSocketController myClientSocketController;
private OpenSocketUtils openSocketUtils;
private FragmentManager fm;
private MyClientDrawListAdapter myClientDrawListAdapter;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case ConstantValue.UPDATA_CLIENT_DRAWER:
//更新用户名,并且将新用户名发送到服务器
myClientDrawListAdapter.notifyDataSetChanged(sp);
String name = sp.getString("clientname", "未设置");
ClientSetNameControl.sendNameToServer(myClientSocketController,name);
break;
case ConstantValue.CONN_SERVER_SOCKET:
Log.i("1", "CONN_SERVER_SOCKET");
handler.sendEmptyMessage(ConstantValue.UPDATA_CLIENT_DRAWER);
break;
case ConstantValue.CLIENT_CONN_WIFI:
myClientSocketController.startSocketConn();
break;
case ConstantValue.SERVER_END:
Toast.makeText(ClientActivity.this, "服务器关闭", 1000).show();
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
fm = getFragmentManager();
transaction = fm.beginTransaction();
wifiConnectUtil = WifiConnectUtil.getInstance(this);
myClientSocketController = new MyClientSocketController(handler);
openSocketUtils = new OpenSocketUtils(this,handler, myClientSocketController, null);
sp = getSharedPreferences("onen.config", MODE_PRIVATE);
drawerList = (ListView) findViewById(R.id.left_client_drawer);
myClientDrawListAdapter = new MyClientDrawListAdapter(this,sp);
drawerList.setAdapter(myClientDrawListAdapter);
SetNameDialog.showSetNameDialog(false,this, sp,handler);
drawerList.setOnItemClickListener(this);
openSocketUtils.openClientSocket();
selectFragment(3);
}
/**
* drawlist点击回调函数
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
if(position==0){
//点击用户名
SetNameDialog.showSetNameDialog(true,this, sp,handler);
}
}
public void selectFragment(int position){
// 开启Fragment事务
String clazzName = myClientDrawListAdapter.itemClass[position];
try {
Class targetClazz = Class.forName(clazzName);
Constructor constructor = targetClazz.getConstructor(Context.class);
Fragment targetFragment = (Fragment) constructor.newInstance(ClientActivity.this);
transaction.replace(R.id.content_client_frame, targetFragment);
transaction.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void end(){
EndControl.sendToServer(myClientSocketController);
wifiConnectUtil.setWifiEnabled(false);
myClientSocketController.end();
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
end();
super.onBackPressed();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
end();
super.onDestroy();
}
}
|
package com.example.iglsmac.login.test;
import android.app.Activity;
import android.content.Intent;
import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.rule.ActivityTestRule;
import android.widget.EditText;
import android.widget.TextView;
import com.example.iglsmac.login.MainActivity;
import com.example.iglsmac.login.R;
import cucumber.api.java.Before;
import cucumber.api.java.After;
import org.junit.Rule;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.action.ViewActions.click;
import static org.junit.Assert.*;
public class MainActivitySteps {
public ActivityTestRule mActivityRule = new ActivityTestRule<>(MainActivity.class, false, true);
private Activity activity = null;
@Before
public void launchActivity() throws Exception {
mActivityRule.launchActivity(null);
this.activity = mActivityRule.getActivity();
}
@After
public void finishActivity() throws Exception {
mActivityRule.getActivity().finish();
}
@Given("I enter email and password \"([^\"]*)\" \"([^\"]*)\"$")
public void i_enter_email_and_password(String email, String password) {
onView(ViewMatchers.withId(R.id.editEmail)).perform(typeText(email), closeSoftKeyboard());
onView(ViewMatchers.withId(R.id.editPassword)).perform(typeText(password), closeSoftKeyboard());
}
@When("I press button login")
public void i_press_button_login() {
onView(ViewMatchers.withId(R.id.btnLogin)).perform(click());
}
@Then("I should be told \"([^\"]*)\"$")
public void i_should_be_told(String expectedAnswer) {
TextView announce = (TextView)this.activity.findViewById(R.id.announceText);
String result = announce.getText().toString();
assertEquals(expectedAnswer, result);
}
// @Given("I have a LoginActivity")
// public void I_have_a_LoginActivity() {
// if(mActivityRule.getActivity() != null){
// assertNotNull(mActivityRule.getActivity());
// }
// }
//
// @When("I enter email {string}")
// public void i_enter_email(String email) {
// onView(ViewMatchers.withId(com.example.iglsmac.login.R.id.editEmail)).perform(typeText(email), closeSoftKeyboard());
// }
//
// @When("I enter password {string}")
// public void i_enter_password(String password){
// onView(ViewMatchers.withId(com.example.iglsmac.login.R.id.editPassword)).perform(typeText(password), closeSoftKeyboard());
// }
//
// @When(("I press button login"))
// public void i_press_button_login(){
// onView(ViewMatchers.withId(R.id.btnLogin)).perform(click());
// }
//
// @Then("I should be told {string}")
// public void i_should_be_told(String expectedAnswer){
// TextView announce = (TextView)this.activity.findViewById(R.id.announceText);
// String result = announce.getText().toString();
//
// assertEquals(expectedAnswer, result);
// }
}
|
public class BubbleSort {
public static void bubble(int[]array)
{
int i,k,j,n=array.length;
for(int m=n;m>=0;m--)
{
for(i=0;i<n-1;i++)
{
k=i+1;
if(array[i]>array[k])
{
swap(i,k,array);
}
}
}
}
public static void print(int [] array)
{
int n=array.length;
for(int i=0;i<n;i++)
{
System.out.print(array[i]+ " , ");
}
System.out.println("\n");
}
public static void swap(int i,int j,int [] array)
{
int temp;
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
public static void main(String [] args)
{
int [] array={4,78,9,1,5,6,1,3,0};
bubble(array);
print(array);
}
}
|
package mobi.app.redis.transcoders;
/**
* User: thor
* Date: 12-12-21
* Time: 下午3:40
*/
public class LongTranscoder implements Transcoder<Long>{
@Override
public byte[] encode(Long v) {
return String.valueOf(v).getBytes();
}
@Override
public Long decode(byte[] v) {
if(v == null) return null;
return Long.parseLong(new String(v));
}
}
|
package com.github.bot.curiosone.core.refinement;
public class Sentence {
private ClauseMain main;
private SentenceType type;
/**
* Sentence constructor.
* @param type type of sentence
* @param main main clause
*/
public Sentence(SentenceType type, ClauseMain main) {
this.type = type;
this.main = main;
}
/**
* Returns the main clause.
* @return clause
*/
public ClauseMain getMainClause() {
return main;
}
/**
* Refinement entry point.
*/
@Override
public String toString() {
String temp = main.toString() + type.getMark();
return temp.substring(0, 1).toUpperCase() + temp.substring(1);
}
}
|
package com.mabang.android.okhttp.loadimg;
import android.graphics.Bitmap;
import android.util.LruCache;
/**
* Created by walke.Z on 2018/3/12.
*/
public class BitmapCache {
private LruCache<String, Bitmap> bitmapLruCache;
private static BitmapCache instance;
private BitmapCache() {
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int cacheSize = maxMemory / 6;
bitmapLruCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getRowBytes()* bitmap.getHeight();//单位 B
}
};
}
public static BitmapCache getInstance() {
if (instance==null)
instance=new BitmapCache();
return instance;
}
public void putBitmap(String key, Bitmap bitmap) {
bitmapLruCache.put(key, bitmap);
}
public Bitmap getBitmap(String key) {
return bitmapLruCache.get(key);
}
}
|
package com.example.ips.model;
import java.util.Date;
public class ServerplanIDealNew {
private Integer id;
private String serverApplication;
private String dev;
private String st1;
private String st2;
private String st3;
private String st4;
private String uat1;
private String uat2;
private String uat3;
private String uat4;
private String uat5;
private String uat6;
private String train;
private String mem1;
private String simulationDataA;
private String nationalSimulationExerciseN;
private String simulationExercise;
private String simulationA;
private String produce;
private Date createTime;
private Date updateTime;
private Integer createUser;
private Integer updateUser;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getServerApplication() {
return serverApplication;
}
public void setServerApplication(String serverApplication) {
this.serverApplication = serverApplication == null ? null : serverApplication.trim();
}
public String getDev() {
return dev;
}
public void setDev(String dev) {
this.dev = dev == null ? null : dev.trim();
}
public String getSt1() {
return st1;
}
public void setSt1(String st1) {
this.st1 = st1 == null ? null : st1.trim();
}
public String getSt2() {
return st2;
}
public void setSt2(String st2) {
this.st2 = st2 == null ? null : st2.trim();
}
public String getSt3() {
return st3;
}
public void setSt3(String st3) {
this.st3 = st3 == null ? null : st3.trim();
}
public String getSt4() {
return st4;
}
public void setSt4(String st4) {
this.st4 = st4 == null ? null : st4.trim();
}
public String getUat1() {
return uat1;
}
public void setUat1(String uat1) {
this.uat1 = uat1 == null ? null : uat1.trim();
}
public String getUat2() {
return uat2;
}
public void setUat2(String uat2) {
this.uat2 = uat2 == null ? null : uat2.trim();
}
public String getUat3() {
return uat3;
}
public void setUat3(String uat3) {
this.uat3 = uat3 == null ? null : uat3.trim();
}
public String getUat4() {
return uat4;
}
public void setUat4(String uat4) {
this.uat4 = uat4 == null ? null : uat4.trim();
}
public String getUat5() {
return uat5;
}
public void setUat5(String uat5) {
this.uat5 = uat5 == null ? null : uat5.trim();
}
public String getUat6() {
return uat6;
}
public void setUat6(String uat6) {
this.uat6 = uat6 == null ? null : uat6.trim();
}
public String getTrain() {
return train;
}
public void setTrain(String train) {
this.train = train == null ? null : train.trim();
}
public String getMem1() {
return mem1;
}
public void setMem1(String mem1) {
this.mem1 = mem1 == null ? null : mem1.trim();
}
public String getSimulationDataA() {
return simulationDataA;
}
public void setSimulationDataA(String simulationDataA) {
this.simulationDataA = simulationDataA == null ? null : simulationDataA.trim();
}
public String getNationalSimulationExerciseN() {
return nationalSimulationExerciseN;
}
public void setNationalSimulationExerciseN(String nationalSimulationExerciseN) {
this.nationalSimulationExerciseN = nationalSimulationExerciseN == null ? null : nationalSimulationExerciseN.trim();
}
public String getSimulationExercise() {
return simulationExercise;
}
public void setSimulationExercise(String simulationExercise) {
this.simulationExercise = simulationExercise == null ? null : simulationExercise.trim();
}
public String getSimulationA() {
return simulationA;
}
public void setSimulationA(String simulationA) {
this.simulationA = simulationA == null ? null : simulationA.trim();
}
public String getProduce() {
return produce;
}
public void setProduce(String produce) {
this.produce = produce == null ? null : produce.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getCreateUser() {
return createUser;
}
public void setCreateUser(Integer createUser) {
this.createUser = createUser;
}
public Integer getUpdateUser() {
return updateUser;
}
public void setUpdateUser(Integer updateUser) {
this.updateUser = updateUser;
}
} |
package com.thoughtworks.a70mm;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by shawast on 6/3/2017.
*/
public class MoviesAdapter extends ArrayAdapter<Movie> {
public MoviesAdapter(Context context, List<Movie> movies) {
super(context, 0, movies);
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.movie_row, parent, false);
}
Movie movie = getItem(position);
((TextView) convertView.findViewById(R.id.movie_name)).setText(movie.getMovieName());
((TextView) convertView.findViewById(R.id.movie_description)).setText(movie.getMovieDescription());
((TextView) convertView.findViewById(R.id.schedule_detail)).setText(movie.getMovieSchedule());
return convertView;
}
}
|
/*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.ml.project.mgt;
public class SQLQueries {
public static final String CREATE_PROJECT = "INSERT INTO ML_PROJECT(PROJECT_ID, NAME," +
"DESCRIPTION, CREATED_TIME) VALUES(?,?,?, CURRENT_TIMESTAMP())";
public static final String DELETE_PROJECT = "DELETE FROM ML_PROJECT WHERE PROJECT_ID=?";
public static final String ADD_TENANT_TO_PROJECT = "INSERT INTO ML_TENANT_PROJECTS" +
"(TENANT_ID, PROJECT_ID) VALUES(?,?)";
public static final String GET_TENANT_PROJECTS = "SELECT PROJECT_ID, NAME, CREATED_TIME FROM " +
"ML_PROJECT WHERE PROJECT_ID IN (SELECT PROJECT_ID FROM ML_TENANT_PROJECTS WHERE " +
"TENANT_ID=?)";
public static final String GET_DATASET_ID = "SELECT DATASET_ID FROM ML_DATASET WHERE PROJECT_ID=?";
public static final String CREATE_NEW_WORKFLOW = "INSERT INTO ML_WORKFLOW (WORKFLOW_ID, " +
"PARENT_WORKFLOW_ID, PROJECT_ID, DATASET_ID,NAME) VALUES(?,?,?,?,?)";
public static final String DELETE_WORKFLOW = "DELETE FROM ML_WORKFLOW WHERE WORKFLOW_ID = ?";
public static final String GET_PROJECT_WORKFLOWS = "SELECT WORKFLOW_ID,NAME FROM ML_WORKFLOW" +
" WHERE PROJECT_ID=?";
public static final String GET_DEFAULT_FEATURE_SETTINGS = "SELECT FEATURE_NAME, FEATURE_INDEX, " +
"TYPE, IMPUTE_METHOD, INCLUDE FROM ML_FEATURE_DEFAULTS WHERE DATASET_ID=?";
public static final String INSERT_FEATURE_SETTINGS = "INSERT INTO ML_FEATURE_SETTINGS " +
"(WORKFLOW_ID, FEATURE_NAME, FEATURE_INDEX, TYPE, IMPUTE_METHOD, INCLUDE) " +
"VALUES(?,?,?,?,?,?)";
//private Constructor to prevent class from instantiating.
private SQLQueries() {
}
}
|
package app.akeorcist.deviceinformation.utility;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import app.akeorcist.deviceinformation.constants.Constants;
/**
* Created by Ake on 2/25/2015.
*/
public class AppPreferences {
private final static String PREFERENCE_APP = "app_pref";
private final static String KEY_APP_VALIDATED = "is_validated";
private final static String KEY_APP_STARTED = "just_started";
private static void setAppPreference(Context context, String key, String value) {
SharedPreferences.Editor editor = getAppPreference(context).edit();
editor.putString(key, value);
editor.commit();
}
private static void setAppPreference(Context context, String key, int value) {
SharedPreferences.Editor editor = getAppPreference(context).edit();
editor.putInt(key, value);
editor.commit();
}
private static void setAppPreference(Context context, String key, boolean value) {
SharedPreferences.Editor editor = getAppPreference(context).edit();
editor.putBoolean(key, value);
editor.commit();
}
public static SharedPreferences getAppPreference(Context context) {
return context.getSharedPreferences(PREFERENCE_APP, Context.MODE_PRIVATE);
}
public static boolean isValidated(Context context) {
return getAppPreference(context).getBoolean(KEY_APP_VALIDATED, false);
}
public static void setValidated(Context context) {
setAppPreference(context, KEY_APP_VALIDATED, true);
}
public static boolean isJustStarted(Context context) {
boolean justStarted = getAppPreference(context).getBoolean(KEY_APP_STARTED, true);
if(justStarted)
setAppPreference(context, KEY_APP_STARTED, false);
return justStarted;
}
public static void clearJustStarted(Context context) {
setAppPreference(context, KEY_APP_STARTED, true);
}
}
|
package com.facade.common.example;
public class ClassA {
public void doSomethingA() {
System.out.println("业务逻辑A");
}
}
|
package pl.basistam.soa.parkometr.dto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.ws.rs.ext.MessageBodyWriter;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class TicketDTO implements Serializable {
private Integer parkingSpotId;
private Long parkingMeterId;
@JsonSerialize(using = ToStringSerializer.class)
private LocalDateTime timeOfPurchase;
@JsonSerialize(using = ToStringSerializer.class)
private LocalDateTime timeOfExpiration;
public String toJson() throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(this);
}
}
|
package org.itst.service;
import java.util.List;
import org.itst.domain.ClubActivity;
public interface ClubActivityService {
public ClubActivity getClubActivityById(String id);
public String getClubActivitiesJsonByPage(int pageSize ,int pageNow);
public int getClubActivitiesCount();
public int getKeySearchCount(String key);
public String getClubActivityJsonByKeyWord(String key,int pageSize ,int pageNow);
public void addClubActivity(ClubActivity clubActivity);
public void updateClubActivity(ClubActivity clubActivity);
public void deleteClubActivityById(String id);
public String getActivityFormJson();
}
|
/*
* 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 dto;
import java.util.Date;
import java.util.List;
/**
*
* @author hienl
*/
public class QuizDTO {
private String subject;
private Date startTime;
private Date endTime;
private List<QuestDTO> questList;
public QuizDTO() {
}
public QuizDTO(String subject, Date startTime, Date endTime, List<QuestDTO> questList) {
this.subject = subject;
this.startTime = startTime;
this.endTime = endTime;
this.questList = questList;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public List<QuestDTO> getQuestList() {
return questList;
}
public void setQuestList(List<QuestDTO> questList) {
this.questList = questList;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
|
package com.teaboot.context.entity;
import java.lang.reflect.Method;
import com.teaboot.context.beans.BeansType;
public class MethodType{
public MethodType() {
}
Method method;
String dataType;
BeansType beansType;
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public BeansType getBeansType() {
return beansType;
}
public void setBeansType(BeansType beansType) {
this.beansType = beansType;
}
}
|
package es.mithrandircraft.disablesuffocation;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.plugin.java.JavaPlugin;
public final class DisableSuffocation extends JavaPlugin implements Listener {
double overworldWorldborderRadius;
double netherWorldborderRadius;
double endWorldborderRadius;
@Override
public void onEnable() {
//Events:
getServer().getPluginManager().registerEvents(this, this);
overworldWorldborderRadius = Bukkit.getWorlds().get(0).getWorldBorder().getSize() / 2d;
netherWorldborderRadius = Bukkit.getWorlds().get(1).getWorldBorder().getSize() / 2d;
endWorldborderRadius = Bukkit.getWorlds().get(2).getWorldBorder().getSize() / 2d;
}
//Block suffocation
@EventHandler
public void EntityDamageEvent(EntityDamageEvent ev)
{ //Outside border exclusion
if(ev.getEntityType() == EntityType.PLAYER && ev.getCause() == EntityDamageEvent.DamageCause.SUFFOCATION && CheckWithinWorldborder(ev.getEntity().getWorld(), ev.getEntity().getLocation()))
{
ev.setCancelled(true);
}
}
public Boolean CheckWithinWorldborder(World world, Location location)
{
switch(world.getEnvironment())
{
case NORMAL:
{
return CheckWithinRadius(overworldWorldborderRadius, location);
}
case NETHER:
{
return CheckWithinRadius(netherWorldborderRadius, location);
}
case THE_END:
{
return CheckWithinRadius(endWorldborderRadius, location);
}
default:
{
return true;
}
}
}
public Boolean CheckWithinRadius(double radius, Location location)
{
return !(location.getBlockX() > radius) && !(location.getBlockZ() > radius) && !(location.getBlockX() < -radius) && !(location.getBlockZ() < -radius);
}
} |
/* ComponentDefinitionMap.java
Purpose:
Description:
History:
Mon Sep 4 20:20:36 2006, Created by tomyeh
Copyright (C) 2006 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.zk.ui.metainfo;
import java.util.Map;
import java.util.HashMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
/**
* A map of component definitions.
* Used with {@link PageDefinition#getComponentDefinitionMap}
* and {@link LanguageDefinition}.
*
* <p>It is thread-safe (since it is used in {@link LanguageDefinition}).
*
* @author tomyeh
*/
public class ComponentDefinitionMap
implements Cloneable, java.io.Serializable {
/** A map of component definition defined in this page. */
private transient Map _compdefs;
/** Map(String clsnm, ComponentDefinition compdef). */
private transient Map _compdefsByClass;
/** Whether the element name is case-insensitive. */
private final boolean _ignoreCase;
/** Constructor.
*/
public ComponentDefinitionMap(boolean ignoreCase) {
_ignoreCase = ignoreCase;
}
/** Returns whether the component names are case-insensitive.
*/
public boolean isCaseInsensitive() {
return _ignoreCase;
}
/** Returns a readonly collection of the names (String)
* of component definitions defined in this map.
*/
public Collection getNames() {
return _compdefs != null ?
_compdefs.keySet(): (Collection)Collections.EMPTY_LIST;
}
/** Returns a readonly collection of component definitions
* ({@link ComponentDefinition}) defined in this map.
* @since 3.6.3
*/
public Collection getDefinitions() {
return _compdefs != null ?
_compdefs.values(): (Collection)Collections.EMPTY_LIST;
}
/** Adds a component definition to this map.
*
* <p>Thread safe.
*/
public void add(ComponentDefinition compdef) {
if (compdef == null)
throw new IllegalArgumentException("null");
String name = compdef.getName();
if (isCaseInsensitive())
name = name.toLowerCase();
Object implcls = compdef.getImplementationClass();
if (implcls instanceof Class)
implcls = ((Class)implcls).getName();
synchronized (this) {
if (_compdefs == null) {
_compdefsByClass =
Collections.synchronizedMap(new HashMap(3));
_compdefs =
Collections.synchronizedMap(new HashMap(3));
}
_compdefs.put(name, compdef);
_compdefsByClass.put(implcls, compdef);
}
}
/** Returns whether the specified component exists.
*/
public boolean contains(String name) {
return _compdefs != null
&& _compdefs.containsKey(
isCaseInsensitive() ? name.toLowerCase(): name);
}
/** Returns the component definition of the specified name, or null if not
* not found.
*
* <p>Note: unlike {@link LanguageDefinition#getComponentDefinition},
* this method doesn't throw ComponentNotFoundException if not found.
* It just returns null.
*/
public ComponentDefinition get(String name) {
return _compdefs != null ?
(ComponentDefinition)_compdefs.get(
isCaseInsensitive() ? name.toLowerCase(): name):
null;
}
/** Returns the component definition of the specified class, or null if not
* found.
*
* <p>Note: unlike {@link LanguageDefinition#getComponentDefinition},
* this method doesn't throw ComponentNotFoundException if not found.
* It just returns null.
*/
public ComponentDefinition get(Class cls) {
if (_compdefsByClass != null) {
for (; cls != null; cls = cls.getSuperclass()) {
final ComponentDefinition compdef =
(ComponentDefinition)_compdefsByClass.get(cls.getName());
if (compdef != null)
return compdef;
}
}
return null;
}
//Serializable//
//NOTE: they must be declared as private
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject();
if (_compdefs != null) {
synchronized (_compdefs) {
s.writeInt(_compdefs.size());
for (Iterator it = _compdefs.values().iterator(); it.hasNext();)
s.writeObject(it.next());
}
} else {
s.writeInt(0);
}
}
private synchronized void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
int cnt = s.readInt();
while (--cnt >= 0)
add((ComponentDefinition)s.readObject());
}
//Cloneable//
public Object clone() {
final ComponentDefinitionMap clone;
try {
clone = (ComponentDefinitionMap)super.clone();
clone._compdefs =
Collections.synchronizedMap(new HashMap(_compdefs));
clone._compdefsByClass =
Collections.synchronizedMap(new HashMap(_compdefsByClass));
} catch (CloneNotSupportedException ex) {
throw new InternalError();
}
return clone;
}
}
|
package de.cuuky.varo.team;
import java.util.ArrayList;
import de.cuuky.varo.Main;
import de.cuuky.varo.config.config.ConfigEntry;
import de.cuuky.varo.logger.logger.EventLogger.LogType;
import de.cuuky.varo.player.VaroPlayer;
import de.cuuky.varo.player.stats.stat.PlayerState;
import de.cuuky.varo.player.stats.stat.inventory.VaroSaveable;
import de.cuuky.varo.scoreboard.nametag.Nametag;
import de.cuuky.varo.serialize.identifier.VaroSerializeField;
import de.cuuky.varo.serialize.identifier.VaroSerializeable;
public class Team implements VaroSerializeable {
private static ArrayList<Team> teams;
private static int highestNumber;
static {
teams = new ArrayList<>();
highestNumber = 1;
}
@VaroSerializeField(path = "name")
private String name;
@VaroSerializeField(path = "colorCode")
private String colorCode;
@VaroSerializeField(path = "id")
private int id;
@VaroSerializeField(path = "lifes")
private double lifes;
@VaroSerializeField(path = "memberid")
private ArrayList<Integer> memberid = new ArrayList<Integer>();
private ArrayList<VaroPlayer> member = new ArrayList<>();
public Team() {
teams.add(this);
}
public Team(String name) {
this.name = name;
this.id = generateId();
loadDefaults();
teams.add(this);
Nametag.refreshAll();
if(this.id > highestNumber)
highestNumber = id;
}
public void loadDefaults() {
this.lifes = ConfigEntry.TEAM_LIFES.getValueAsInt();
}
public double getLifes() {
return lifes;
}
public void setLifes(double lifes) {
this.lifes = lifes;
}
public void addMember(VaroPlayer vp) {
if(this.isMember(vp))
return;
this.member.add(vp);
vp.setTeam(this);
}
public void removeMember(VaroPlayer vp) {
this.member.remove(vp);
vp.setTeam(null);
if(member.size() == 0)
teams.remove(this);
}
public boolean isOnline() {
for(VaroPlayer vp : member)
if(!vp.isOnline())
return false;
return true;
}
public ArrayList<VaroSaveable> getSaveables() {
ArrayList<VaroSaveable> save = new ArrayList<VaroSaveable>();
for(VaroPlayer vp : member)
save.addAll(vp.getStats().getSaveablesRaw());
return save;
}
public void removeSaveable(VaroSaveable saveable) {
for(VaroPlayer vp : member)
if(vp.getStats().getSaveables().contains(saveable))
vp.getStats().removeSaveable(saveable);
}
public int getKills() {
int kills = 0;
for(VaroPlayer player : member)
kills += player.getStats().getKills();
return kills;
}
public void delete() {
this.member.forEach(member -> member.setTeam(null));
teams.remove(this);
}
public void statChanged() {
this.member.forEach(member -> member.update());
}
public boolean isMember(VaroPlayer vp) {
return this.member.contains(vp);
}
public ArrayList<VaroPlayer> getMember() {
return member;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
statChanged();
}
public void setColorCode(String colorCode) {
this.colorCode = colorCode;
statChanged();
}
public String getColorCode() {
return colorCode == null ? Main.getColorCode() : colorCode;
}
public String getDisplay() {
return getColorCode() + "#" + name;
}
public int getId() {
return id;
}
public boolean isDead() {
for(VaroPlayer player : member) {
if(player.getStats().getState() != PlayerState.ALIVE)
continue;
return false;
}
return true;
}
private int generateId() {
int i = teams.size() + 1;
while(getTeam(i) != null)
i++;
return i;
}
public static Team getTeam(int id) {
for(Team team : teams) {
if(team.getId() != id)
continue;
return team;
}
return null;
}
public static ArrayList<Team> getAliveTeams() {
ArrayList<Team> alive = new ArrayList<Team>();
for(Team team : teams)
if(!team.isDead())
alive.add(team);
return alive;
}
public static ArrayList<Team> getDeadTeams() {
ArrayList<Team> dead = new ArrayList<Team>();
for(Team team : teams)
if(team.isDead())
dead.add(team);
return dead;
}
public static ArrayList<Team> getOnlineTeams() {
ArrayList<Team> online = new ArrayList<Team>();
for(Team team : teams)
if(team.isOnline())
online.add(team);
return online;
}
public static Team getTeam(String name) {
for(Team team : teams) {
if(!team.getName().equals(name) && !String.valueOf(team.getId()).equals(name))
continue;
return team;
}
return null;
}
public static ArrayList<Team> getTeams() {
return teams;
}
@Override
public void onDeserializeEnd() {
for(int id : memberid) {
VaroPlayer vp = VaroPlayer.getPlayer(id);
if(vp == null) {
Main.getLoggerMaster().getEventLogger().println(LogType.LOG, id + " has been removed without reason - please report this to the creator of this plugin");
continue;
}
addMember(vp);
}
if(id > highestNumber)
highestNumber = id;
memberid.clear();
}
@Override
public void onSerializeStart() {
for(VaroPlayer member : member)
memberid.add(member.getId());
}
public static int getHighestNumber() {
return highestNumber;
}
}
|
package br.com.microservices.payment.processor.service;
import org.springframework.kafka.annotation.KafkaListener;
import java.io.IOException;
public interface PaymentService {
@KafkaListener(topics = "requested-payments", groupId = "ticket-group-id")
void requestedPaymentsListener(String message) throws IOException;
}
|
package com.teste.southsystem.person.model.DTO;
import lombok.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Builder
public class PersonDTO {
private Long personId;
private String name;
private String type;
private String document;
private int score;
}
|
package com.sha.springbootmongo.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
/**
* @author sa
* @date 1/9/21
* @time 10:34 PM
*/
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Address
{
private String city;
private int postCode;
}
|
package com.trump.auction.account.enums;
/**
* Created by dingxp on 2017-12-27 0027.
* 开心币状态
*/
public enum EnumBuyCoinStatus {
STATUS_UNUSED(1, "未使用"), STATUS_SUR_USED(2, "部分使用"), STATUS_ALL_USED(3, "已使用"), STATUS_OVER(4, "已过期"),
STATUS_DELETE(-1, "已删除"),//开心币多次使用,当执行取消订单时,删除最新开心币记录
BUY_COIN_USING(5, "待使用")
;
private final Integer status;
private final String value;
public Integer getStatus() {
return status;
}
public String getValue() {
return value;
}
EnumBuyCoinStatus(Integer status, String value) {
this.status = status;
this.value = value;
}
public static String getEnumBuyCoinStatusValue(Integer status) {
String name = null;
for (EnumBuyCoinStatus enumBuyCoinStatus : values()) {
if (status.intValue() == enumBuyCoinStatus.getStatus().intValue()) {
name = enumBuyCoinStatus.getValue();
break;
}
}
return name;
}
}
|
package com.cjkj.insurance.mapper;
import com.cjkj.insurance.entity.InsureSupplys;
import java.util.List;
public interface InsureSupplysMapper {
/**
*
* @mbggenerated
*/
int deleteByPrimaryKey(Integer insureSupplysId);
/**
*
* @mbggenerated
*/
int insert(InsureSupplys record);
/**
*
* @mbggenerated
*/
int insertSelective(InsureSupplys record);
/**
*
* @mbggenerated
*/
InsureSupplys selectByPrimaryKey(Integer insureSupplysId);
/**
*
* @mbggenerated
*/
int updateByPrimaryKeySelective(InsureSupplys record);
/**
*
* @mbggenerated
*/
int updateByPrimaryKey(InsureSupplys record);
/**
* 批量添加
*/
public int addInsureSupplys(List<InsureSupplys> insureSupplys);
/**
* 根据任务号查询
*/
public List<InsureSupplys> findAllInsureSupplysByTaskId(String taskId);
} |
import java.io.*;
public class CopyModifile {
public void copyModifile(File modiFile, String position) {
//读取数据时需要的数组
byte[] bytes = new byte[1024];
int count = 0;
//只要能进来就创建文件夹
String oldName = modiFile.getAbsolutePath();
String newName = position + "\\" + oldName.split(":")[1];
System.out.println(newName);
//创建一个新的对象来对应要复制的文件夹
File newFile = new File(newName);
//创建input和output管道
FileInputStream fis = null;
FileOutputStream fos = null;
//获取到所有的子文件
File[] files = modiFile.listFiles();
//只要文件夹有元素就继续递归查看并且创建对应的文件夹
if (files != null) {
newFile.mkdir();
System.out.println(newFile.getName());
if (files.length != 0) {
for (File f : files) {
this.copyModifile(f, position);
}
}
} else {
//能走到这里就说明是文件
try {
fis = new FileInputStream(modiFile);
fos = new FileOutputStream(newFile);
count = fis.read(bytes);
while (count != -1) {
fos.write(bytes,0,count);
count = fis.read(bytes);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void superCopyFile(File file,String newPath){
//获取file的绝对路径 拼串的方式获取新文件的名字
String oldFilePath = file.getAbsolutePath();// C://aaa//bbb文件夹--->D://test//aaa//bbb
String newFilePath = newPath+oldFilePath.split(":")[1];
//创建一个新的file对象
File newFile = new File(newFilePath);
//判断当前传递进来的file是个文件还是文件夹 isFile isDirectory listFiles
File[] files = file.listFiles();//获取当前传递进来的file对象所有子元素
if(files!=null){//file是一个文件夹 才有数组对象
//通过新的file对象操作 在硬盘上创建一个文件夹
newFile.mkdir();
System.out.println(newFile.getName()+"文件夹复制完毕");
//里面的元素
if(files.length!=0){
for(File f:files){
this.superCopyFile(f,newPath);
}
}
}else{//file是一个文件 没有子元素 不需要数组对象
//创建两个文件流 分别读取旧的file和写入新的newFile
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(file);
fos = new FileOutputStream(newFile);
byte[] b = new byte[1024];
int count = fis.read(b);
while(count!=-1){
fos.write(b,0,count);
fos.flush();
count = fis.read(b);//别忘了再读一遍
}
System.out.println(newFile.getName()+"文件复制完毕");
} catch (IOException e) {
e.printStackTrace();
}
// finally {
// try {
// if(fis!=null) {
// fis.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// try {
// if(fos!=null) {
// fos.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
}
}
}
|
import p1.report;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
class hair_dressing extends JFrame implements ActionListener
{
JCheckBox cb1,cb2,cb3,cb4,cb5;
JRadioButton rb1,rb2;
JLabel l1,l2;
JTextField tf1,tf2;
JButton b1,b2,b3;
ButtonGroup bg;
Container c;
int i,j,n,l,m,cust=0;
Double amt=0.0,dis=0.0,t_amt=0.0,t_dues=0.0,paid=0.0,tot_amt=0.0;
String str;
hair_dressing( )
{
c = this.getContentPane( );
c.setLayout(null);
bg = new ButtonGroup( );
cb1 = new JCheckBox("MakeOver(125/-)");
cb2 = new JCheckBox("Hair Styling(60/-)");
cb3 = new JCheckBox("Maincure(35/-)");
cb4 = new JCheckBox("Permanent Makeup(200)");
cb5 = new JCheckBox("Regular Sevice");
cb1.setBounds(485,60,150,30);
cb2.setBounds(485,120,180,30);
cb3.setBounds(485,180,140,30);
cb4.setBounds(485,240,210,30);
cb5.setBounds(485,300,150,30);
c.add(cb1);
c.add(cb2);
c.add(cb3);
c.add(cb4);
c.add(cb5);
rb1 = new JRadioButton("10 percent");
rb2 = new JRadioButton("20 percent");
rb1.setBounds(515,330,110,30);
rb2.setBounds(625,330,110,30);
rb1.setSelected(true);
c.add(rb1);
c.add(rb2);
bg.add(rb1);
bg.add(rb2);
rb1.addActionListener(this);
rb2.addActionListener(this);
l1 = new JLabel("Total Price");
l2 = new JLabel("Paid Amount");
l1.setBounds(485,390,66,30);
l2.setBounds(485,450,77,30);
c.add(l1);
c.add(l2);
tf1 = new JTextField("0.0");
tf2 = new JTextField("0.0");
tf1.setBounds(592,390,150,30);
tf2.setBounds(592,450,150,30);
c.add(tf1);
c.add(tf2);
b1 = new JButton("Ok");
b2 = new JButton("Exit");
//b3 = new JButton("Exit");
b1.setBounds(485,550,120,30);
b2.setBounds(635,550,120,30);
//b3.setBounds(775,550,120,30);
c.add(b1);
c.add(b2);
//c.add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
//b3.addActionListener(this);
cb1.addActionListener(this);
cb2.addActionListener(this);
cb3.addActionListener(this);
cb4.addActionListener(this);
cb5.addActionListener(this);
rb1.setVisible(false);
rb2.setVisible(false);
tf1.setEnabled(false);
}
public void actionPerformed(ActionEvent ae)
{
str = new String( );
if(j==0)
if(cb1.isSelected( )==true)
{
amt = amt+125.0;
t_amt = amt;
j = 1;
}
if(cb1.isSelected( )== false)
if(j==1)
{
amt = amt - 125;
t_amt = amt;
j=0;
}
if(l == 0)
if(cb2.isSelected( )==true)
{
amt = amt + 60;
t_amt = amt;
l = 1;
}
if(cb2.isSelected( )==false)
if(l==1)
{
amt = amt - 60.0;
t_amt = amt;
l = 0;
}
if(cb3.isSelected( )==true)
if(m == 0)
{
amt = amt+35.0;
t_amt = amt;
m = 1;
}
if(cb3.isSelected( )== false)
if(m==1)
{
amt = amt -35;
t_amt = amt;
m = 0;
}
if(cb4.isSelected( )==true)
if(n==0)
{
amt = amt+200.0;
t_amt = amt;
n =1;
}
if(cb4.isSelected( )==false)
if(n == 1)
{
amt = amt - 200.0;
t_amt = amt;
n = 0;
}
if(cb5.isSelected( )==true)
{
rb1.setVisible(true);
rb2.setVisible(true);
if(rb1.isSelected( )==true)
dis = amt * 0.1;
if(rb2.isSelected( )==true)
dis = amt * 0.2;
i=1;
t_amt = amt - dis;
}
if(i==1)
if(cb5.isSelected( )==false)
{
rb1.setVisible(false);
rb2.setVisible(false);
rb1.setSelected(true);
if(i == 1)
t_amt = t_amt + dis;
i =0;
}
str = String.valueOf(t_amt);
tf1.setText(str);
if(ae.getSource( )==b1)
{
tot_amt = tot_amt + t_amt;
i = 0;
j = 0;
l = 0;
m = 0;
n = 0;
str = tf2.getText( );
paid = Double.valueOf(str);
t_dues = t_dues + t_amt - paid;
cb1.setSelected(false);
cb2.setSelected(false);
cb3.setSelected(false);
cb4.setSelected(false);
cb5.setSelected(false);
rb1.setVisible(false);
rb2.setVisible(false);
rb1.setSelected(true);
tf1.setText("0.0");
tf2.setText("0.0");
amt = 0.0;
cust = cust+1;
}
if(ae.getSource( )==b2)
Exit( );
}
public void Exit( )
{
this.dispose( );
tf1.setText("0.0");
report r = new report(cust,tot_amt,t_dues);
r.setVisible(true);
r.setBounds(0,0,1445,860);
r.setTitle("Hair Dressing");
}
public static void main(String args[ ])
{
hair_dressing h = new hair_dressing( );
h.setVisible(true);
h.setBounds(0,0,1445,865);
h.setTitle("Hair Dressing");
h.setBackground(Color.cyan);
}
}
|
package com.letscrawl.base.db.mongodb;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Component;
import com.letscrawl.base.bean.AbstractObject;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
@Component
public class MongoDBMethods extends AbstractObject {
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private GridFsTemplate gridTemplate;
private static final String ID_KEY = "_id";
public GridFSFile saveFile(String contentType, byte[] content) {
return gridTemplate.store(new ByteArrayInputStream(content), UUID
.randomUUID().toString(), contentType);
}
@EnableReturnNullRetryOnMongoDB
public GridFSDBFile findFileById(ObjectId id) {
return gridTemplate.findOne(new Query(Criteria.where(ID_KEY).is(id)));
}
public byte[] getContentFromFile(GridFSDBFile fileToGet) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
try {
fileToGet.writeTo(baos);
return baos.toByteArray();
} catch (IOException e) {
logger.error("读取GridFSDBFile失败", e);
} finally {
try {
baos.close();
} catch (IOException e) {
logger.error("关闭ByteArrayOutputStream失败", e);
}
}
return null;
}
public <T> void save(String collectionName, T objectToSave) {
mongoTemplate.insert(objectToSave, collectionName);
}
public <T> T findById(String collectionName, ObjectId id,
Class<T> requiredType) {
return mongoTemplate.findById(id, requiredType, collectionName);
}
public <T> T increaseValueById(String collectionName, ObjectId id,
String keyToIncrease, long delta, Class<T> requiredType) {
return mongoTemplate.findAndModify(
new Query(Criteria.where(ID_KEY).is(id)),
new Update().inc(keyToIncrease, delta), requiredType,
collectionName);
}
public <T> T increaseValuesById(String collectionName, ObjectId id,
String[] keyArrayToIncrease, long[] deltaArray,
Class<T> requiredType) {
Update update = new Update();
for (int i = 0; i < keyArrayToIncrease.length && i < deltaArray.length; i++) {
update.inc(keyArrayToIncrease[i], deltaArray[i]);
}
return mongoTemplate.findAndModify(
new Query(Criteria.where(ID_KEY).is(id)), update, requiredType,
collectionName);
}
public <T> void updateValueById(String collectionName, ObjectId id,
String keyToUpdate, T value) {
mongoTemplate.updateFirst(new Query(Criteria.where(ID_KEY).is(id)),
new Update().set(keyToUpdate, value), collectionName);
}
public <T> List<T> findByQuery(String collectionName, Query query,
Class<T> requiredType) {
return mongoTemplate.find(query, requiredType, collectionName);
}
public <T> T findOneByQuery(String collectionName, Query query,
Class<T> requiredType) {
return mongoTemplate.findOne(query, requiredType, collectionName);
}
}
|
package view;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
public class Contenedor {
private JFrame frame;
private JPanel actualPanel;
public Contenedor() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 721, 540);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
}
public void setVisible(boolean ver) {
this.frame.setVisible(ver);
}
public JPanel getPanel() {
return this.actualPanel;
}
public void changeWindow(JPanel newWindow) {
frame.getContentPane().removeAll();
this.actualPanel = newWindow;
frame.getContentPane().add(this.actualPanel);
frame.getContentPane().repaint();
}
}
|
package com.zooma.plugins.cameraoverlay;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import com.zooma.peacemaker.R;
import com.zooma.peacemaker.R.id;
public class CameraActivity extends Activity {
protected static final String TAG = "Debug";
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Camera mCamera;
private CameraPreview mPreview;
private String state = "";
public static final int CAMERA_ACTIVITY_RESULT = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("SnapCamera plugin","Camera activity onCreate");
setContentView(R.layout.camerapreview);
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
final PictureCallback mPicture = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions");
return;
}
try {
byte[] pictureBytes;
Bitmap thePicture = BitmapFactory.decodeByteArray(data, 0, data.length);
Log.d("Debug", "Picture height: "+thePicture.getHeight());
Log.d("Debug", "Picture width: "+thePicture.getWidth());
Matrix m = new Matrix();
if(thePicture.getWidth() > thePicture.getHeight()){
m.postRotate(90);
}else{
m.postRotate(0);
}
thePicture = Bitmap.createBitmap(thePicture, 0, 0, thePicture.getWidth(), thePicture.getHeight(), m, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
thePicture.compress(CompressFormat.JPEG, 100, bos);
pictureBytes = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(pictureBytes);
Log.d(TAG, pictureBytes.length+ " written");
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
Intent resultIntent = new Intent();
Log.d(TAG, "URI : " + "file://" + pictureFile.getPath());
resultIntent.putExtra("ImageURI", "file://" + pictureFile.getPath());
resultIntent.putExtra("ImageFile", pictureFile.getPath());
resultIntent.putExtra("State", CameraActivity.this.state);
setResult(Activity.RESULT_OK, resultIntent);
Log.d(TAG, "file size = " + pictureFile.length());
finish();
}
};
ImageButton imokButton = (ImageButton) findViewById(id.button_noworries);
ImageButton closeButton = (ImageButton) findViewById(id.button_close);
ImageButton helpButton = (ImageButton) findViewById(id.button_help);
imokButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
// get an image from the camera
CameraActivity.this.state = "OK";
mCamera.takePicture(null, null, mPicture);
}
}
);
closeButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
// return immediately
setResult(Activity.RESULT_CANCELED);
finish();
}
}
);
helpButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
CameraActivity.this.state = "HELP";
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
}
private static int exifToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; }
else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180; }
else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270; }
return 0;
}
//Release camera, else it will crash or get stuck.
@Override
protected void onDestroy() {
releaseCamera();
super.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
};
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
releaseCamera();
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "HelpImOK-App");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
} else {
Log.i("SnapCamera Plugin", "Media storage exists");
}
Log.d(TAG, "(mediaStorageDir.getPath() = " + (mediaStorageDir.getPath()));
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
Parameters params = c.getParameters();
List <Camera.Size> sizes = params.getSupportedPictureSizes();
int w = 0;
int h = 0;
for (int i=0;i<sizes.size();i++){
if (w == 0 || w > 1000) {
w = sizes.get(i).width;
h = sizes.get(i).height;
}
Log.i("PictureSize", "Supported Size: " +sizes.get(i).width + "height : " + sizes.get(i).height);
}
params.set("jpeg-quality", 50);
params.setPictureFormat(PixelFormat.JPEG);
params.setPictureSize(w, h);
params.setRotation(90);
c.setParameters(params);
}
catch (Exception e){
// Camera is not available (in use or does not exist)
Log.d("Debug", "CameraActivity : error "+e);
}
Log.d("Debug", "CameraActivity : Returning "+c);
return c; // returns null if camera is unavailable
}
private void releaseCamera(){
if (mCamera != null){
mCamera.stopPreview();
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
} |
//
// Decompiled by Procyon v0.5.36
//
package com.davivienda.sara.tablas.binentidad.session;
import javax.annotation.PostConstruct;
import com.davivienda.sara.tablas.binentidad.servicio.BinEntidadServicio;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.ejb.Stateless;
import com.davivienda.sara.entitys.BinEntidad;
import com.davivienda.sara.base.BaseAdministracionTablas;
@Stateless
public class BinEntidadSessionBean extends BaseAdministracionTablas<BinEntidad> implements BinEntidadSessionLocal
{
@PersistenceContext
private EntityManager em;
private BinEntidadServicio binEntidadServicio;
@PostConstruct
public void postConstructor() {
this.binEntidadServicio = new BinEntidadServicio(this.em);
super.servicio = this.binEntidadServicio;
}
@Override
public BinEntidad getEntidadXBin(final String bin) throws Exception {
return this.binEntidadServicio.getEntidadXBin(bin);
}
}
|
import java.util.LinkedList;
import java.util.Queue;
class BinaryTree {
static class Node {
int key;
Node left, right;
Node(int item){
this.key = item;
left = right = null;
}
}
static Node root;
static Node current = root;
static void inorder(Node current) {
if (current == null)
return;
inorder(current.left);
System.out.print(current.key+" ");
inorder(current.right);
}
static void postorder(Node current) {
if (current == null)
return;
postorder(current.left);
postorder(current.right);
System.out.print(current.key+" ");
}
static void preorder(Node current) {
if (current == null)
return;
preorder(current.right);
preorder(current.left);
System.out.print(current.key+" ");
}
//Insert using queue
static void insert(Node current,int key){
Queue <Node> queue = new LinkedList<Node>();
queue.add(current);
while (!queue.isEmpty()) {
current = queue.peek();
queue.remove();
if (current.left == null) {
current.left = new Node(key);
break;
} else {
queue.add(current.left);
}
if (current.right == null) {
current.right = new Node(key);
break;
} else {
queue.add(current.right);
}
}
}
static void delete(Node current, int key){
Queue <Node> queue = new LinkedList<Node>();
queue.add(current);
Node delete_node = null;
while (!queue.isEmpty()) {
current = queue.peek();
System.out.println("Element removed = "+current.key);
queue.remove();
if (current.key==key) {
delete_node = current;
}
if (current.left!=null) {
queue.add(current.left);
System.out.println("Left Added = "+current.left.key);
}
if (current.right!=null) {
queue.add(current.right);
System.out.println("Right added = "+current.right.key);
}
}
Node last_node = current;
System.out.println("Last element is = "+last_node.key);
System.out.println("Node to be deleted = "+delete_node.key);
delete_node = current;
while (!queue.isEmpty()) {
current = queue.peek();
queue.remove();
if (current.key==key) {
current.key = last_node.key;
break;
}
if (current.left!=null) {
queue.add(current.left);
}
if (current.right!=null) {
queue.add(current.right);
}
}
// Create a method to replace the node needed to be deleted with the last node
// Replace that node and return
// then delete the last node
}
public static void main(String[] args) {
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
System.out.println("Inorder traversal before insertion: ");
inorder(root);
insert(root,5);
System.out.println();
System.out.println("Inorder traversal after insertion: ");
inorder(root);
System.out.println();
delete(root,3);
System.out.println("After Deletion");
inorder(root);
}
} |
package com.hwy.study01.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
//@Aspect
//@Order(-1)
@Component
public class Log2Aspect {
@Pointcut("execution(* com.hwy.study01.controller.*.*(..))")
public void pcut1(){}
@Before("LogAspect.pcut1()")
public void beforeController(JoinPoint point) {
System.out.println("================ pcut after =================");
System.out.println(point.getSignature().getDeclaringType());
System.out.println("================ pcut after =================");
}
}
|
package slimeknights.tconstruct.plugin.jei;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import mezz.jei.api.IGuiHelper;
import mezz.jei.api.IJeiHelpers;
import mezz.jei.api.IJeiRuntime;
import mezz.jei.api.IModPlugin;
import mezz.jei.api.IModRegistry;
import mezz.jei.api.IRecipeRegistry;
import mezz.jei.api.ISubtypeRegistry;
import mezz.jei.api.gui.IAdvancedGuiHandler;
import mezz.jei.api.gui.ICraftingGridHelper;
import mezz.jei.api.recipe.VanillaRecipeCategoryUid;
import mezz.jei.api.recipe.IRecipeCategoryRegistration;
import slimeknights.tconstruct.TConstruct;
import slimeknights.tconstruct.gadgets.TinkerGadgets;
import slimeknights.tconstruct.library.DryingRecipe;
import slimeknights.tconstruct.library.TinkerRegistry;
import slimeknights.tconstruct.library.smeltery.AlloyRecipe;
import slimeknights.tconstruct.library.smeltery.MeltingRecipe;
import slimeknights.tconstruct.library.tools.IToolPart;
import slimeknights.tconstruct.library.tools.ToolCore;
import slimeknights.tconstruct.plugin.jei.alloy.AlloyRecipeCategory;
import slimeknights.tconstruct.plugin.jei.alloy.AlloyRecipeChecker;
import slimeknights.tconstruct.plugin.jei.alloy.AlloyRecipeHandler;
import slimeknights.tconstruct.plugin.jei.casting.CastingRecipeCategory;
import slimeknights.tconstruct.plugin.jei.casting.CastingRecipeChecker;
import slimeknights.tconstruct.plugin.jei.casting.CastingRecipeHandler;
import slimeknights.tconstruct.plugin.jei.casting.CastingRecipeWrapper;
import slimeknights.tconstruct.plugin.jei.drying.DryingRecipeCategory;
import slimeknights.tconstruct.plugin.jei.drying.DryingRecipeChecker;
import slimeknights.tconstruct.plugin.jei.drying.DryingRecipeHandler;
import slimeknights.tconstruct.plugin.jei.interpreter.PatternSubtypeInterpreter;
import slimeknights.tconstruct.plugin.jei.interpreter.TableSubtypeInterpreter;
import slimeknights.tconstruct.plugin.jei.interpreter.ToolPartSubtypeInterpreter;
import slimeknights.tconstruct.plugin.jei.interpreter.ToolSubtypeInterpreter;
import slimeknights.tconstruct.plugin.jei.smelting.SmeltingRecipeCategory;
import slimeknights.tconstruct.plugin.jei.smelting.SmeltingRecipeChecker;
import slimeknights.tconstruct.plugin.jei.smelting.SmeltingRecipeHandler;
import slimeknights.tconstruct.plugin.jei.table.TableRecipeHandler;
import slimeknights.tconstruct.shared.block.BlockTable;
import slimeknights.tconstruct.smeltery.TinkerSmeltery;
import slimeknights.tconstruct.smeltery.block.BlockCasting;
import slimeknights.tconstruct.smeltery.client.GuiSmeltery;
import slimeknights.tconstruct.smeltery.client.GuiTinkerTank;
import slimeknights.tconstruct.smeltery.client.IGuiLiquidTank;
import slimeknights.tconstruct.tools.TinkerTools;
import slimeknights.tconstruct.tools.common.TableRecipeFactory.TableRecipe;
import slimeknights.tconstruct.tools.common.block.BlockToolTable;
@mezz.jei.api.JEIPlugin
public class JEIPlugin implements IModPlugin {
public static IJeiHelpers jeiHelpers;
// crafting grid slots, integer constants from the default crafting grid implementation
private static final int craftOutputSlot = 0;
private static final int craftInputSlot1 = 1;
public static ICraftingGridHelper craftingGridHelper;
public static IRecipeRegistry recipeRegistry;
public static CastingRecipeCategory castingCategory;
@Override
public void registerItemSubtypes(ISubtypeRegistry registry) {
TableSubtypeInterpreter tableInterpreter = new TableSubtypeInterpreter();
PatternSubtypeInterpreter patternInterpreter = new PatternSubtypeInterpreter();
// drying racks and item racks
if(TConstruct.pulseManager.isPulseLoaded(TinkerGadgets.PulseId)) {
registry.registerSubtypeInterpreter(Item.getItemFromBlock(TinkerGadgets.rack), tableInterpreter);
}
// tools
if(TConstruct.pulseManager.isPulseLoaded(TinkerTools.PulseId)) {
// tool tables
registry.registerSubtypeInterpreter(Item.getItemFromBlock(TinkerTools.toolTables), tableInterpreter);
registry.registerSubtypeInterpreter(Item.getItemFromBlock(TinkerTools.toolForge), tableInterpreter);
// tool parts
ToolPartSubtypeInterpreter toolPartInterpreter = new ToolPartSubtypeInterpreter();
for(IToolPart part : TinkerRegistry.getToolParts()) {
if(part instanceof Item) {
registry.registerSubtypeInterpreter((Item)part, toolPartInterpreter);
}
}
// tool
ToolSubtypeInterpreter toolInterpreter = new ToolSubtypeInterpreter();
for(ToolCore tool : TinkerRegistry.getTools()) {
registry.registerSubtypeInterpreter(tool, toolInterpreter);
}
// tool patterns
registry.registerSubtypeInterpreter(TinkerTools.pattern, patternInterpreter);
}
// casts
if(TConstruct.pulseManager.isPulseLoaded(TinkerSmeltery.PulseId)) {
registry.registerSubtypeInterpreter(TinkerSmeltery.cast, patternInterpreter);
registry.registerSubtypeInterpreter(TinkerSmeltery.clayCast, patternInterpreter);
}
}
@Override
public void registerCategories(IRecipeCategoryRegistration registry) {
final IJeiHelpers jeiHelpers = registry.getJeiHelpers();
final IGuiHelper guiHelper = jeiHelpers.getGuiHelper();
// Smeltery
if(TConstruct.pulseManager.isPulseLoaded(TinkerSmeltery.PulseId)) {
castingCategory = new CastingRecipeCategory(guiHelper);
registry.addRecipeCategories(new SmeltingRecipeCategory(guiHelper), new AlloyRecipeCategory(guiHelper), castingCategory);
}
if(TConstruct.pulseManager.isPulseLoaded(TinkerGadgets.PulseId)) {
registry.addRecipeCategories(new DryingRecipeCategory(guiHelper));
}
}
@Override
public void register(@Nonnull IModRegistry registry) {
jeiHelpers = registry.getJeiHelpers();
IGuiHelper guiHelper = jeiHelpers.getGuiHelper();
// crafting helper used by the shaped table wrapper
craftingGridHelper = guiHelper.createCraftingGridHelper(craftInputSlot1, craftOutputSlot);
if(TConstruct.pulseManager.isPulseLoaded(TinkerTools.PulseId)) {
registry.handleRecipes(TableRecipe.class, new TableRecipeHandler(), VanillaRecipeCategoryUid.CRAFTING);
// crafting table shiftclicking
registry.getRecipeTransferRegistry().addRecipeTransferHandler(new CraftingStationRecipeTransferInfo());
// add our crafting table to the list with the vanilla crafting table
registry.addRecipeCatalyst(new ItemStack(TinkerTools.toolTables, 1, BlockToolTable.TableTypes.CraftingStation.meta), VanillaRecipeCategoryUid.CRAFTING);
}
// Smeltery
if(TConstruct.pulseManager.isPulseLoaded(TinkerSmeltery.PulseId)) {
registry.handleRecipes(AlloyRecipe.class, new AlloyRecipeHandler(), AlloyRecipeCategory.CATEGORY);
registry.handleRecipes(MeltingRecipe.class, new SmeltingRecipeHandler(), SmeltingRecipeCategory.CATEGORY);
registry.handleRecipes(CastingRecipeWrapper.class, new CastingRecipeHandler(), CastingRecipeCategory.CATEGORY);
registry.addRecipeCatalyst(new ItemStack(TinkerSmeltery.smelteryController), SmeltingRecipeCategory.CATEGORY, AlloyRecipeCategory.CATEGORY);
registry.addRecipeCatalyst(new ItemStack(TinkerSmeltery.castingBlock, 1, BlockCasting.CastingType.TABLE.meta), CastingRecipeCategory.CATEGORY);
registry.addRecipeCatalyst(new ItemStack(TinkerSmeltery.castingBlock, 1, BlockCasting.CastingType.BASIN.meta), CastingRecipeCategory.CATEGORY);
// add the seared furnace to the list with the vanilla furnace
// note that this is just the smelting one, fuel is not relevant
registry.addRecipeCatalyst(new ItemStack(TinkerSmeltery.searedFurnaceController), VanillaRecipeCategoryUid.SMELTING);
// melting recipes
registry.addRecipes(SmeltingRecipeChecker.getSmeltingRecipes(), SmeltingRecipeCategory.CATEGORY);
// alloys
registry.addRecipes(AlloyRecipeChecker.getAlloyRecipes(), AlloyRecipeCategory.CATEGORY);
// casting
registry.addRecipes(CastingRecipeChecker.getCastingRecipes(), CastingRecipeCategory.CATEGORY);
// liquid recipe lookup for smeltery and tinker tank
registry.addAdvancedGuiHandlers(new TinkerGuiTankHandler<>(GuiTinkerTank.class), new TinkerGuiTankHandler<>(GuiSmeltery.class));
}
// drying rack
if(TConstruct.pulseManager.isPulseLoaded(TinkerGadgets.PulseId)) {
registry.handleRecipes(DryingRecipe.class, new DryingRecipeHandler(), DryingRecipeCategory.CATEGORY);
registry.addRecipes(DryingRecipeChecker.getDryingRecipes(), DryingRecipeCategory.CATEGORY);
registry.addRecipeCatalyst(BlockTable.createItemstack(TinkerGadgets.rack, 1, Blocks.WOODEN_SLAB, 0), DryingRecipeCategory.CATEGORY);
}
}
@Override
public void onRuntimeAvailable(@Nonnull IJeiRuntime jeiRuntime) {
recipeRegistry = jeiRuntime.getRecipeRegistry();
}
private static class TinkerGuiTankHandler<T extends GuiContainer & IGuiLiquidTank> implements IAdvancedGuiHandler<T> {
private Class<T> clazz;
public TinkerGuiTankHandler(Class<T> clazz) {
this.clazz = clazz;
}
@Nonnull
@Override
public Class<T> getGuiContainerClass() {
return clazz;
}
@Nullable
@Override
public Object getIngredientUnderMouse(T guiContainer, int mouseX, int mouseY) {
return guiContainer.getFluidStackAtPosition(mouseX, mouseY);
}
}
}
|
package com.example.api.erro;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.validation.ConstraintViolationException;
import java.util.List;
@ControllerAdvice
public class TratamentoErro extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
ex.printStackTrace();
return super.handleHttpRequestMethodNotSupported(ex, headers, status, request);
}
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
ex.printStackTrace();
ErroBean erroBean = new ErroBean(HttpStatus.NOT_FOUND, "URI nao encontrada", ex);
return new ResponseEntity<>(erroBean, erroBean.getStatus());
}
@ExceptionHandler(HttpClientErrorException.class)
public ResponseEntity<Object> tratarNotFound(HttpClientErrorException ex){
ex.printStackTrace();
ErroBean erroBean = new ErroBean(HttpStatus.NOT_FOUND, "URI nao encontrada", ex);
return new ResponseEntity<>(erroBean, erroBean.getStatus());
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Object> tratarObjetoIncorreto(IllegalArgumentException ex){
ex.printStackTrace();
ErroBean erroBean = new ErroBean(HttpStatus.BAD_REQUEST, "Objeto contém dados incompletos ou incorretos", ex);
return new ResponseEntity<>(erroBean, erroBean.getStatus());
}
@ExceptionHandler(TransactionSystemException.class)
public ResponseEntity<Object> tratarCampoInvalido(TransactionSystemException ex) {
ErroBean erroBean;
Throwable rootCause = ex.getRootCause();
if(rootCause instanceof ConstraintViolationException){
erroBean = new ErroBean(HttpStatus.BAD_REQUEST, "JSON mal formatado", rootCause);
}else
erroBean = new ErroBean(HttpStatus.BAD_REQUEST, "JSON mal formatado", ex);
return new ResponseEntity<>(erroBean, erroBean.getStatus());
}
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
ErroBean erroBean = new ErroBean(HttpStatus.BAD_REQUEST, "JSON mal formatado", ex);
return new ResponseEntity<>(erroBean, erroBean.getStatus());
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
ex.printStackTrace();
BindingResult result = ex.getBindingResult();
StringBuilder builder = new StringBuilder();
final List<FieldError> fieldErrors = result.getFieldErrors();
for (FieldError error : fieldErrors) {
builder.append(error.getField() + " : " + error.getDefaultMessage() + "|");
}
ErroBean erroEntity = new ErroBean(HttpStatus.BAD_REQUEST, "Parametro recebido inválido", new Throwable(builder.toString()));
return new ResponseEntity<>(erroEntity, erroEntity.getStatus());
}
}
|
package com.wrathOfLoD.Models.Skill;
/**
* Created by luluding on 4/7/16.
*/
public class SummonerSkillManager extends SkillManager {
private Skill enchantment;
private Skill boon;
private Skill bane;
private Skill staff;
public SummonerSkillManager(){
super();
enchantment = new Skill(getDefaultSkillLevel());
boon = new Skill(getDefaultSkillLevel());
bane = new Skill(getDefaultSkillLevel());
staff = new Skill(getDefaultSkillLevel());
}
public SummonerSkillManager(int bindWoundsLevel, int bargainLevel, int observationLevel, int enchantmentLevel, int boonLevel, int baneLevel, int staffLevel){
super(bindWoundsLevel, bargainLevel, observationLevel);
enchantment = new Skill(enchantmentLevel);
boon = new Skill(boonLevel);
bane = new Skill(baneLevel);
staff = new Skill(staffLevel);
}
/***** getter & setter for skills *******/
public int getEnchantmentLevel(){
return enchantment.getSkillLevel();
}
public int getBoonLevel(){
return boon.getSkillLevel();
}
public int getBaneLevel(){
return bane.getSkillLevel();
}
public int getStaffLevel(){
return staff.getSkillLevel();
}
public boolean updateEnchantmentLevel(int level){
if(!updateAvailableSkillPoints(level))
return false;
enchantment.updateSkillLevel(level);
return true;
}
public boolean updateBoonLevel(int level){
if(!updateAvailableSkillPoints(level))
return false;
boon.updateSkillLevel(level);
return true;
}
public boolean updateBaneLevel(int level){
if(!updateAvailableSkillPoints(level))
return false;
bane.updateSkillLevel(level);
return true;
}
public boolean updateStaffLevel(int level){
if(!updateAvailableSkillPoints(level))
return false;
staff.updateSkillLevel(level);
return true;
}
/****************************************/
}
|
package com.stk123.entity;
import javax.persistence.*;
import java.sql.Time;
import java.util.Objects;
//@Entity
@Table(name = "STK_LABEL_TEXT")
public class StkLabelTextEntity {
private long id;
private Long labelId;
private Long textId;
private Time insertTime;
private Time updateTime;
private StkLabelEntity stkLabelByLabelId;
@Id
@Column(name = "ID", nullable = false, precision = 0)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Basic
@Column(name = "LABEL_ID", nullable = true, precision = 0)
public Long getLabelId() {
return labelId;
}
public void setLabelId(Long labelId) {
this.labelId = labelId;
}
@Basic
@Column(name = "TEXT_ID", nullable = true, precision = 0)
public Long getTextId() {
return textId;
}
public void setTextId(Long textId) {
this.textId = textId;
}
@Basic
@Column(name = "INSERT_TIME", nullable = true)
public Time getInsertTime() {
return insertTime;
}
public void setInsertTime(Time insertTime) {
this.insertTime = insertTime;
}
@Basic
@Column(name = "UPDATE_TIME", nullable = true)
public Time getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Time updateTime) {
this.updateTime = updateTime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StkLabelTextEntity that = (StkLabelTextEntity) o;
return id == that.id &&
Objects.equals(labelId, that.labelId) &&
Objects.equals(textId, that.textId) &&
Objects.equals(insertTime, that.insertTime) &&
Objects.equals(updateTime, that.updateTime);
}
@Override
public int hashCode() {
return Objects.hash(id, labelId, textId, insertTime, updateTime);
}
@ManyToOne
@JoinColumn(name = "LABEL_ID", referencedColumnName = "ID")
public StkLabelEntity getStkLabelByLabelId() {
return stkLabelByLabelId;
}
public void setStkLabelByLabelId(StkLabelEntity stkLabelByLabelId) {
this.stkLabelByLabelId = stkLabelByLabelId;
}
}
|
package com.example.jaya.itday;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import java.util.ArrayList;
public class Main7Activity extends AppCompatActivity {
CardView c,d;
//String[] arr={"City Palace","Dudh Talai","Jag Mandir","FatahSagar" };
ArrayList<String> s=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main7);
c=(CardView)findViewById(R.id.c1);
//d=(CardView)findViewById(R.id.c2);
s.add("City Palace");
s.add("Dudh Talai");
s.add("Jag Mandir");
s.add("FatahSagar");
c.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(Main7Activity.this,Main3Activity.class);
i.putExtra("list",s);
startActivity(i);
}
});
}
}
|
package net.mv.grub;
public interface Food {
public void getEaten();
public void rot();
public void tasteDelicious();
public void setPlate();
public void printSize();
}
|
package com.cyx.dbtools.dbhelper.table;
import com.cyx.dbtools.bean.TableField;
import java.util.List;
public interface ITableDescribe {
List<TableField> getTableDescribe(String tableName);
String getTableFields(String tableName);
}
|
import android.app.Activity;
import android.os.Bundle;
/**
* Created with IntelliJ IDEA.
* User: mrcc
* Date: 10/2/14
* Time: 12:06 PM
* To change this template use File | Settings | File Templates.
*/
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
} |
package eight.person;
import eight.animal.Animal;
import eight.animal.Snake;
public class PersonTester {
public static void main(String[] args) {
Person p1 = new Student();
p1.setName("Amar");
p1.setSurname("Šabić");
p1.printNameOfAnimal();
Animal snake = new Snake("Zmijica");
p1.setAnimal(snake);
p1.printNameOfAnimal();
}
}
|
package WebApi;
import DBApi.ChatMessage;
import DBApi.PrivateMessage;
import managers.ServiceManager;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Date;
import java.util.List;
@Path("/messages/{userId : \\d+}")
public class MessageService {
@PathParam("userId")int userId;
@POST
@Path("/sendChatMessage/{chatId : \\d+}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response sendChatMessage(ChatMessage m,@PathParam("chatId")int chatId,@HeaderParam("token")String key){
if(ServiceManager.autentificationManager.identity(userId,key)
&&ServiceManager.messageManager.sendMessageToChat(m))
return Response.status(201).entity(true).build();
return Response.status(200).entity(false).build();
}
@GET
@Path("/getNewChatMessage/{chatId}/{date}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getChatMessage(@PathParam("chatId")int chatId,@PathParam("date")long date,@HeaderParam("token")String token){
if(ServiceManager.autentificationManager.identity(userId,token))
{
List<ChatMessage> messages=ServiceManager.messageManager.getLastChatMessages(chatId,date);
return Response.status(201).entity(messages).build();
}
return Response.status(201).build();
}
@GET
@Path("/getChatMessage/{chatId}/{date}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getChatMessage(@PathParam("date")long date,@HeaderParam("token")String token,@PathParam("chatId")int chatId){
if(ServiceManager.autentificationManager.identity(userId,token))
{
List<ChatMessage> messages=ServiceManager.messageManager.getChatMessages(chatId,date);
return Response.status(201).entity(messages).build();
}
return Response.status(201).build();
}
@POST
@Path("/sendMessage")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response sendMessage(PrivateMessage m,@HeaderParam("token")String token){
if(ServiceManager.autentificationManager.identity(userId,token)
&&ServiceManager.messageManager.sendPrivateMessage(m))
return Response.status(201).entity(true).build();
return Response.status(200).entity(false).build();
}
@GET
@Path("/getMessage")
@Produces(MediaType.APPLICATION_JSON)
public Response getNewMessage(@HeaderParam("token")String key){
if(ServiceManager.autentificationManager.identity(userId,key))
{
List<PrivateMessage>messages=ServiceManager.messageManager.getNewPrivateMessages(userId);
return Response.status(201).entity(messages).build();
}
return Response.status(201).build();
}
@GET
@Path("/getDialog/{userWith}/{offset}")
@Produces(MediaType.APPLICATION_JSON)
public Response getDialog(@HeaderParam("token")String key,@PathParam("userWith")int userWithId,@PathParam("offset")long dateOffset){
if(ServiceManager.autentificationManager.identity(userId,key))
{
List<PrivateMessage>messages=ServiceManager.messageManager.getDialogMessages(userId,userWithId,dateOffset);
return Response.status(201).entity(messages).build();
}
return Response.status(201).build();
}
}
|
/**
*
*/
package PLAZA;
/**
* @author sreekanth
*
*/
public final class PlazaC {
public static final String siteURL="https://facebook.com";
//public String ChromeDriverLocation="";
//public String FirefoxDriverLocation="";
// public String IeDriverLocation="";
}
|
package resourcehierarchy;
import java.util.ListResourceBundle;
public class Hierarchy_fr_FR extends ListResourceBundle {
@Override
protected Object[][] getContents() {
return new Object[][] {
{"x", "Class Hierarchy_fr_FR"}
};
}
}
|
package com.example.zack.retro;
import java.util.Locale;
public class DadJoke {
public String id;
public String joke;
public int status;
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
return String.format(Locale.getDefault(), "id: %s\njoke:%s\nstatus:%d", id, joke, status);
}
}
|
package oops;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Input1
{
public static void main(String[] args) {
Scanner sc=new Scanner((System.in));
System.out.println("enter first value:");
Float i=sc.nextFloat();
System.out.println("enter second value:");
Integer j=sc.nextInt();
System.out.println("sum is "+(i+j));
}
}
|
package pl.dms.dmsbackend.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.web.bind.annotation.*;
import pl.dms.dmsbackend.utils.dataOutput.AuthenticationResponseDTO;
import pl.dms.dmsbackend.utils.dataInput.CredentialsDTO;
import pl.dms.dmsbackend.utils.dataOutput.MessageDTO;
import pl.dms.dmsbackend.utils.dataInput.PasswordChangeDTO;
import pl.dms.dmsbackend.model.users.Inhabitant;
import pl.dms.dmsbackend.model.users.User;
import pl.dms.dmsbackend.model.users.Worker;
import pl.dms.dmsbackend.repositories.InhabitantRepository;
import pl.dms.dmsbackend.repositories.UserRepository;
import pl.dms.dmsbackend.repositories.WorkerRepository;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.HashMap;
@RestController
@RequestMapping(value = "api")
@Transactional
public class LogInAndLogOutController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private InhabitantRepository inhabitantRepository;
@Autowired
private WorkerRepository workerRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@PostMapping(value = "/login")
public ResponseEntity login(@RequestBody CredentialsDTO credentialsDTO, HttpServletRequest request) {
final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentialsDTO.getEmail(), credentialsDTO.getPassword());
final Authentication authentication = this.authenticationManager.authenticate(token);
SecurityContextHolder.getContext()
.setAuthentication(authentication);
final HttpSession httpSession = request.getSession(true);
httpSession.setAttribute(
HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
SecurityContextHolder.getContext()
);
return ResponseEntity.ok().body(new AuthenticationResponseDTO(httpSession.getId()));
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public ResponseEntity logout(HttpSession session) {
session.invalidate();
return ResponseEntity.ok().build();
}
@GetMapping(value = "/info")
public ResponseEntity info() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentEmail = authentication.getName();
User user = userRepository.findByEmail(currentEmail);
if(user==null) {
return ResponseEntity.badRequest().body(new MessageDTO("Nie znaleziono takie użytkownika"));
}
else {
Inhabitant inhabitant = inhabitantRepository.findByEmail(currentEmail);
if(inhabitant == null) {
Worker worker = workerRepository.findByEmail(currentEmail);
HashMap<String,Object> workerToReturn = new HashMap<>();
workerToReturn.put("firstname",worker.getFirstName());
workerToReturn.put("lastname",worker.getLastName());
workerToReturn.put("email",worker.getEmail());
workerToReturn.put("roles",worker.getUserRoles());
workerToReturn.put("phoneNumber",worker.getPhoneNumber());
return ResponseEntity.ok().body(workerToReturn);
}
HashMap<String,Object> inhabitantToReturn = new HashMap<>();
inhabitantToReturn.put("firstname",inhabitant.getFirstName());
inhabitantToReturn.put("lastname",inhabitant.getLastName());
inhabitantToReturn.put("email",inhabitant.getEmail());
inhabitantToReturn.put("roles",inhabitant.getUserRoles());
inhabitantToReturn.put("roomnumber",inhabitant.getRoomNumber());
return ResponseEntity.ok().body(inhabitantToReturn);
}
}
@PutMapping(value = "/password")
public ResponseEntity changePassword(@RequestBody PasswordChangeDTO passwordChangeDTO) {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentEmail = authentication.getName();
User currentUser = userRepository.findByEmail(currentEmail);
if (currentUser == null && passwordChangeDTO.getOldPassword().length()>0 && passwordChangeDTO.getNewPassword().length()>0) {
return ResponseEntity.badRequest().build();
}
if( passwordEncoder.matches(passwordChangeDTO.getOldPassword(),currentUser.getPassword())) {
currentUser.setPassword(passwordEncoder.encode(passwordChangeDTO.getNewPassword()));
userRepository.save(currentUser);
return ResponseEntity.ok().body(new MessageDTO("Hasło zostało poprawnie zmienione"));
}
else {
return ResponseEntity.badRequest().body(new MessageDTO("Obecne hasło nie jest poprawne"));
}
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().build();
}
}
}
|
package com.zaiou.datamodel.redis.subscribe;
import com.zaiou.common.redis.constant.RedisKey;
import com.zaiou.common.redis.service.JedisService;
import com.zaiou.datamodel.redis.listener.RequestMsgListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @Description: redis消息订阅
* @auther: LB 2018/10/31 15:49
* @modify: LB 2018/10/31 15:49
*/
@Service
@Slf4j
public class SubscribeService {
public ExecutorService threadPool = Executors.newFixedThreadPool(5);
@Autowired
private JedisService jedisService;
@Resource
private RequestMsgListener listener;
public void subscribe() {
threadPool.execute(new Runnable() {
public void run() {
log.info("业务-服务已订阅频道:{}", RedisKey.getMMmodelNormal());
jedisService.subscribe(listener, RedisKey.getMsgModelNormal());
}
});
}
}
|
package at.fhv.teama.easyticket.server.program;
import org.springframework.stereotype.Service;
import javax.annotation.security.RolesAllowed;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@Service
public class ProgramService {
private ProgramRepository programRepo;
private ProgramMapper programMapper;
private EntityManager em;
public ProgramService(ProgramRepository programRepo, ProgramMapper programMapper, EntityManager em) {
this.programRepo = programRepo;
this.programMapper = programMapper;
this.em = em;
}
public Program saveProgram(Program program) {
return programRepo.save(program);
}
@RolesAllowed({"USER"})
public List<Program> getAllPrograms() {
return StreamSupport.stream(programRepo.findAll().spliterator(), false)
.collect(Collectors.toList());
}
public List<String> getAllGenrse(){
return StreamSupport.stream(programRepo.getAllGenres().spliterator(),false).collect(Collectors.toList());
}
}
|
/**
* All rights Reserved, Designed By www.tydic.com
* @Title: TestFtp.java
* @Package com.taotao.test
* @Description: TODO(用一句话描述该文件做什么)
* @author: axin
* @date: 2018年12月5日 下午11:35:45
* @version V1.0
* @Copyright: 2018 www.hao456.top Inc. All rights reserved.
*/
package com.taotao.test;
import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.junit.Test;
/**
* @ClassName: TestFtp
* @Description:测试ftp上传文件
* @author: Axin
* @date: 2018年12月5日 下午11:35:45
* @Copyright: 2018 www.hao456.top Inc. All rights reserved.
*/
public class TestFtp {
@Test
public void testFtpClient() throws Exception{
//创建一个FtpClient对象
FTPClient ftpClient = new FTPClient();
//创建Ftp连接
ftpClient.connect("47.104.228.117",21);
//登录
ftpClient.login("ftpuser", "123456");
//上传文件
//第一个参数:服务器端文件名
//上传文档的inputStream
FileInputStream fis = new FileInputStream(new File("E:\\Pictures\\Saved Pictures\\002.jpg"));
//默认格式为文档格式,图片上传后会出现花屏,设置文件格式为二进制格式
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//改变文件路径
ftpClient.changeWorkingDirectory("/home/ftpuser/files");
ftpClient.storeFile("hello2.jpg", fis);
//退出
ftpClient.logout();
}
}
|
package org.xplan.manager.web.shared;
import java.io.Serializable;
public class Plan implements Serializable, Comparable<Plan> {
/**
*
*/
private static final long serialVersionUID = 573099017461370301L;
private String name;
private String id;
private String type;
private Boolean loaded = false;
private Boolean validated = false;
public Plan() {
this.name = "N/A";
this.id = "-";
this.type = "NO TYPE";
}
public Plan( String name, String id, String type ) {
this.name = name;
this.id = id;
this.type = type;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public String getType() {
return type;
}
public Boolean isLoaded() {
return loaded;
}
public void setLoaded( Boolean loaded ) {
this.loaded = loaded;
}
public Boolean isValidated() {
return validated;
}
public void setValidated( Boolean validated ) {
this.validated = validated;
}
@Override
public int compareTo( Plan o ) {
return ( o == null || o.name == null ) ? -1 : -o.name.compareTo( name );
}
} |
/*
* Created by Angel Leon (@gubatron), Alden Torres (aldenml)
* Copyright (c) 2011-2014, FrostWire(R). All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.frostwire.gui.bittorrent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;
import org.gudy.azureus2.core3.download.DownloadManager;
import org.gudy.azureus2.core3.torrent.TOTorrent;
import org.gudy.azureus2.core3.torrent.TOTorrentException;
import org.gudy.azureus2.core3.torrentdownloader.TorrentDownloader;
import org.gudy.azureus2.core3.torrentdownloader.TorrentDownloaderCallBackInterface;
import org.gudy.azureus2.core3.torrentdownloader.TorrentDownloaderFactory;
import org.gudy.azureus2.core3.util.TorrentUtils;
import org.gudy.azureus2.core3.util.UrlUtils;
import com.limegroup.gnutella.gui.GUIMediator;
import com.limegroup.gnutella.gui.I18n;
import com.limegroup.gnutella.gui.util.BackgroundExecutorService;
import com.limegroup.gnutella.settings.SharingSettings;
/**
*
* @author gubatron
* @author aldenml
*
*/
public class TorrentFetcherDownload implements BTDownload {
private static final String STATE_DOWNLOADING = I18n.tr("Downloading Torrent");
private static final String STATE_ERROR = I18n.tr("Error");
private static final String STATE_CANCELED = I18n.tr("Canceled");
private String _uri;
private final String _torrentSaveDir;
private TorrentDownloader _torrentDownloader;
private final String _displayName;
private final String _hash;
private final long _size;
private final boolean _partialDownload;
private final ActionListener _postPartialDownloadAction;
private final Date dateCreated;
private String _state;
private boolean _removed;
private BTDownload _delegate;
private String relativePath;
private boolean[] filesSelection;
public TorrentFetcherDownload(String uri, String referrer, String displayName, String hash, long size, boolean partialDownload, ActionListener postPartialDownloadAction, final String relativePath) {
_uri = uri;
_torrentSaveDir = SharingSettings.TORRENTS_DIR_SETTING.getValue().getAbsolutePath();
_torrentDownloader = TorrentDownloaderFactory.create(new TorrentDownloaderListener(), _uri, referrer, _torrentSaveDir);
_displayName = displayName;
_hash = hash != null ? hash : "";
_size = size;
_partialDownload = partialDownload;
_postPartialDownloadAction = postPartialDownloadAction;
this.dateCreated = new Date();
this.relativePath = relativePath;
_state = STATE_DOWNLOADING;
if (_hash.length() > 0 && relativePath != null) {
if (!isDownloadingTorrent(_hash)) {
_torrentDownloader.start();
} else {
BackgroundExecutorService.schedule(new WaitForTorrentReady());
}
} else { // best effort
_torrentDownloader.start();
}
}
private boolean isDownloadingTorrent(String hash) {
for (BTDownload d : BTDownloadMediator.instance().getDownloads()) {
if (d != this && d.getHash() != null && d.getHash().equals(_hash)) {
return true;
}
}
return false;
}
private boolean isDownloadingTorrentReady(String hash) {
for (BTDownload d : BTDownloadMediator.instance().getDownloads()) {
if (d != this && d.getHash() != null && d.getHash().equals(_hash)) {
DownloadManager dm = d.getDownloadManager();
if (dm != null) {
return true;
}
}
}
return false;
}
public TorrentFetcherDownload(String uri, boolean partialDownload, ActionListener postPartialDownloadAction) {
this(uri, null, getDownloadNameFromMagnetURI(uri), "", -1, partialDownload, postPartialDownloadAction, null);
}
public TorrentFetcherDownload(String uri, String relativePath, ActionListener postPartialDownloadAction) {
this(uri, null, getDownloadNameFromMagnetURI(uri), "", -1, true, postPartialDownloadAction, relativePath);
}
public TorrentFetcherDownload(String uri, String referrer, String relativePath, String hash, ActionListener postPartialDownloadAction) {
this(uri, referrer, getDownloadNameFromMagnetURI(uri), hash, -1, true, postPartialDownloadAction, relativePath);
}
private static String getDownloadNameFromMagnetURI(String uri) {
if (!uri.startsWith("magnet:")) {
return uri;
}
if (uri.contains("dn=")) {
String[] split = uri.split("&");
for (String s : split) {
if (s.toLowerCase().startsWith("dn=") && s.length() > 3) {
return UrlUtils.decode(s.split("=")[1]);
}
}
}
return uri;
}
public long getSize() {
return _delegate != null ? _delegate.getSize() : _size;
}
public String getDisplayName() {
return _delegate != null ? _delegate.getDisplayName() : _displayName;
}
public boolean isResumable() {
return _delegate != null ? _delegate.isResumable() : false;
}
public boolean isPausable() {
return _delegate != null ? _delegate.isPausable() : false;
}
public boolean isCompleted() {
return _delegate != null ? _delegate.isCompleted() : false;
}
public int getState() {
return _delegate != null ? _delegate.getState() : -1;
}
public void remove() {
if (_delegate != null) {
_delegate.remove();
} else {
_removed = true;
try {
_torrentDownloader.cancel();
} catch (Throwable e) {
// ignore, I can't do anything
//e.printStackTrace();
}
try {
_torrentDownloader.getFile().delete();
} catch (Throwable e) {
// ignore, I can't do anything
//e.printStackTrace();
}
}
}
public void pause() {
if (_delegate != null) {
_delegate.pause();
}
}
public void resume() {
if (_delegate != null) {
_delegate.resume();
}
}
public File getSaveLocation() {
return _delegate != null ? _delegate.getSaveLocation() : null;
}
public int getProgress() {
return _delegate != null ? _delegate.getProgress() : 0;
}
public String getStateString() {
return _delegate != null ? _delegate.getStateString() : _state;
}
public long getBytesReceived() {
return _delegate != null ? _delegate.getBytesReceived() : 0;
}
public long getBytesSent() {
return _delegate != null ? _delegate.getBytesSent() : 0;
}
public double getDownloadSpeed() {
return _delegate != null ? _delegate.getDownloadSpeed() : 0;
}
public double getUploadSpeed() {
return _delegate != null ? _delegate.getUploadSpeed() : 0;
}
public long getETA() {
return _delegate != null ? _delegate.getETA() : 0;
}
public DownloadManager getDownloadManager() {
return _delegate != null ? _delegate.getDownloadManager() : null;
}
public String getPeersString() {
return _delegate != null ? _delegate.getPeersString() : "";
}
public String getSeedsString() {
return _delegate != null ? _delegate.getSeedsString() : "";
}
public boolean isDeleteTorrentWhenRemove() {
return _delegate != null ? _delegate.isDeleteTorrentWhenRemove() : false;
}
public void setDeleteTorrentWhenRemove(boolean deleteTorrentWhenRemove) {
if (_delegate != null) {
_delegate.setDeleteTorrentWhenRemove(deleteTorrentWhenRemove);
}
}
public boolean isDeleteDataWhenRemove() {
return _delegate != null ? _delegate.isDeleteDataWhenRemove() : false;
}
public void setDeleteDataWhenRemove(boolean deleteDataWhenRemove) {
if (_delegate != null) {
_delegate.setDeleteDataWhenRemove(deleteDataWhenRemove);
}
}
public String getHash() {
return _delegate != null ? _delegate.getHash() : _hash;
}
public String getSeedToPeerRatio() {
return _delegate != null ? _delegate.getSeedToPeerRatio() : "";
}
public String getShareRatio() {
return _delegate != null ? _delegate.getShareRatio() : "";
}
public Date getDateCreated() {
return _delegate != null ? _delegate.getDateCreated() : dateCreated;
}
public boolean isPartialDownload() {
return _delegate != null ? _delegate.isPartialDownload() : _partialDownload;
}
private final class TorrentDownloaderListener implements TorrentDownloaderCallBackInterface {
private AtomicBoolean finished = new AtomicBoolean(false);
public void TorrentDownloaderEvent(int state, final TorrentDownloader inf) {
if (_removed) {
return;
}
if (state == TorrentDownloader.STATE_FINISHED && finished.compareAndSet(false, true)) {
onTorrentDownloaderFinished(inf.getFile());
} else if (state == TorrentDownloader.STATE_ERROR) {
if (_hash != null && _hash.trim() != "" && (_uri.toLowerCase().startsWith("http://") || _uri.toLowerCase().startsWith("https://"))) {
_uri = TorrentUtil.getMagnet(_hash);
_torrentDownloader = TorrentDownloaderFactory.create(new TorrentDownloaderListener(), _uri, null, _torrentSaveDir);
_state = STATE_DOWNLOADING;
_torrentDownloader.start();
} else {
_state = STATE_ERROR;
}
}
}
}
private void cancelDownload() {
_state = STATE_CANCELED;
GUIMediator.safeInvokeLater(new Runnable() {
public void run() {
BTDownloadMediator.instance().remove(TorrentFetcherDownload.this);
}
});
}
@Override
public long getSize(boolean update) {
return _delegate != null ? _delegate.getSize(update) : _size;
}
@Override
public void updateDownloadManager(DownloadManager downloadManager) {
if (_delegate != null) {
_delegate.updateDownloadManager(downloadManager);
}
}
private void onTorrentDownloaderFinished(final File torrentFile) {
try {
//single file download straight from a torrent deep search.
if (relativePath != null) {
TOTorrent torrent = TorrentUtils.readFromFile(torrentFile, false);
filesSelection = new boolean[torrent.getFiles().length];
for (int i = 0; i < filesSelection.length; i++) {
filesSelection[i] = torrent.getFiles()[i].getRelativePath().equals(relativePath);
}
} else if (_partialDownload) {
GUIMediator.safeInvokeAndWait(new Runnable() {
public void run() {
try {
PartialFilesDialog dlg = new PartialFilesDialog(GUIMediator.getAppFrame(), torrentFile);
dlg.setVisible(true);
filesSelection = dlg.getFilesSelection();
} catch (TOTorrentException e) {
System.out.println("Error reading torrent:" + e.getMessage());
filesSelection = null;
}
}
});
if (filesSelection == null) {
cancelDownload();
return;
} else {
if (_postPartialDownloadAction != null) {
try {
_postPartialDownloadAction.actionPerformed(null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
BTDownloadCreator creator = new BTDownloadCreator(torrentFile, filesSelection);
_delegate = creator.createDownload();
if (_delegate instanceof DuplicateDownload) {
cancelDownload();
GUIMediator.safeInvokeLater(new Runnable() {
@Override
public void run() {
BTDownloadMediator.instance().selectRowByDownload(_delegate);
}
});
}
} catch (Exception e) {
_state = STATE_ERROR;
e.printStackTrace();
}
}
private final class WaitForTorrentReady implements Runnable {
@Override
public void run() {
do {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
} while (!isDownloadingTorrentReady(_hash));
try {
BTDownloadCreator creator = new BTDownloadCreator(_hash, relativePath);
_delegate = creator.createDownload();
if (_delegate instanceof DuplicateDownload) {
cancelDownload();
GUIMediator.safeInvokeLater(new Runnable() {
@Override
public void run() {
BTDownloadMediator.instance().selectRowByDownload(_delegate);
}
});
}
} catch (Throwable e) {
_state = STATE_ERROR;
e.printStackTrace();
}
}
}
}
|
package com.niko.restbooks;
import com.niko.restbooks.dto.FilterRequestDto;
import com.niko.restbooks.dto.BooksResponseDto;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequiredArgsConstructor
public class BookListRestController {
private final BookService bookService;
@ResponseBody
@GetMapping("books")
public ResponseEntity<BooksResponseDto> bookList() {
return ResponseEntity.status(HttpStatus.OK).body(BooksResponseDto.of(bookService.getAllBooks()));
}
@ResponseBody
@PostMapping("filter-books")
public ResponseEntity<BooksResponseDto> findBook(@RequestBody FilterRequestDto dto) {
String filterInput = dto.getFilterInput();
String filterCriteria = dto.getFilterCriteria();
List<BookEntity> books;
if (filterInput.equals("")) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(BooksResponseDto.of(null));
}
switch (filterCriteria) {
case "title": {
books = bookService.getBooksByTitle(filterInput);
break;
}
case "isbn": {
BookEntity book = bookService.getBookByISBN(filterInput);
books = new ArrayList<>();
books.add(book);
break;
}
default:
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(BooksResponseDto.of(null));
}
return ResponseEntity.status(HttpStatus.OK).body(BooksResponseDto.of(books));
}
@ResponseBody
@PostMapping("add-book")
public ResponseEntity<BooksResponseDto> addBook(@RequestBody BookEntity book) {
if (!book.getAuthor().isEmpty() && !book.getTitle().isEmpty() && !book.getIsbn().isEmpty()) {
bookService.addNewBook(book);
return ResponseEntity.status(HttpStatus.OK).body(BooksResponseDto.of(bookService.getAllBooks()));
} else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(BooksResponseDto.of(null));
}
}
}
|
package com.pawelpiechowiak.library;
import com.google.gson.Gson;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestController
public class BookController {
private BookDeserializer bookDeserializer = new BookDeserializer();
private BookProvider book = new BookProvider(bookDeserializer);
public BookController() {
bookDeserializer.readBooksFromJson();
}
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
@GetMapping(value = "/books/{isbn}")
@ResponseBody
public String getBook(@PathVariable("isbn") String isbn) {
if (book.findBookByISBN(isbn) != null) {
Gson gson = new Gson();
return gson.toJson(book.findBookByISBN(isbn));
} else {
throw new ResourceNotFoundException("The book does not exist.");
}
}
@GetMapping(value = "/books/categories/{category}")
@ResponseBody
public String getCategory(@PathVariable("category") String category) {
Gson gson = new Gson();
return gson.toJson(book.findBookByCategory(category));
}
@GetMapping(value = "/authors")
@ResponseBody
public String getRating() {
AuthorProvider author = new AuthorProvider(bookDeserializer);
Gson gson = new Gson();
return gson.toJson(author.getSortedAuthors());
}
}
|
package ru.mcfr.oxygen.framework.filters;
import org.apache.log4j.Logger;
import ro.sync.ecss.extensions.api.*;
import ro.sync.ecss.extensions.api.node.AttrValue;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;
import ro.sync.ecss.extensions.api.node.AuthorElement;
import ro.sync.ecss.extensions.api.node.AuthorNode;
import javax.swing.text.BadLocationException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.*;
/**
* Simple Documentation Framework document filter used to restrict insertion and deletion of
* different nodes from the document when the strict mode is activated.
*/
public class MOFDocumentFilter extends AuthorDocumentFilter {
private final AuthorAccess authorAccess;
private final AuthorDocumentController controller;
private static Logger logger = Logger.getLogger(MOFDocumentFilter.class.getName());
private ArrayList<String> IdInDocument;
private ArrayList<String> IdWasInDocument;
private int maxIdValue = 0;
private List<String> lostElements;
private class SortByIntValue implements Comparator<String>{
public int compare(String o1, String o2) {
Integer i1 = Integer.valueOf(o1);
Integer i2 = Integer.valueOf(o2);
return o1.compareTo(o2);
}
}
public MOFDocumentFilter(AuthorAccess access) {
this.authorAccess = access;
this.controller = access.getDocumentController();
this.IdInDocument = new ArrayList<String>();
this.lostElements = new ArrayList<String>();
this.lostElements.add("метаданные");
this.lostElements.add("редакции");
this.lostElements.add("ссылки");
try{
AuthorNode[] nodes = authorAccess.getDocumentController().findNodesByXPath("//*[@id and not(ancestor::метаданные) and not(self::редакции) and not(self::ссылки)]", true, true, true);
for (AuthorNode node : nodes){
try{
if (node.getType() == AuthorNode.NODE_TYPE_ELEMENT){
AuthorElement ae = (AuthorElement) node;
String texValue = ae.getAttribute("id").getValue();
int id = Integer.valueOf(texValue);
IdInDocument.add(texValue);
if (id > maxIdValue)
maxIdValue = id;
}
} catch (Exception e){
// do nothing
}
}
} catch (Exception e){
authorAccess.getWorkspaceAccess().showErrorMessage("error:" + e.getMessage());
}
Collections.sort(IdInDocument, new SortByIntValue());
// String currentItem = IdInDocument.get(0);
// String items = "";
// for (int i = 1; i < IdInDocument.size(); i++){
// if (currentItem == IdInDocument.get(i))
// items += currentItem + ",";
// currentItem = IdInDocument.get(i);
// }
// authorAccess.getWorkspaceAccess().showErrorMessage("doubled id's: " + items);
this.IdWasInDocument = new ArrayList<String>(this.IdInDocument);
Collections.copy(this.IdWasInDocument, this.IdInDocument);
}
private boolean isStrictModeActivated() {
String strictMode = authorAccess.getOptionsStorage().getOption("strictMode", "false");
return "true".equals(strictMode);
}
public boolean delete(AuthorDocumentFilterBypass filterBypass, int startOffset, int endOffset, boolean withBackspace){
try {
AuthorDocumentFragment fragment = controller.createDocumentFragment(startOffset, endOffset);
String xmlFragment = controller.serializeFragmentToXML(fragment);
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = factory.createXMLStreamReader(new StringReader("<root>" + xmlFragment + "</root>"));
while(streamReader.hasNext()){
streamReader.next();
if (streamReader.getEventType() == XMLStreamReader.START_ELEMENT) {
for (int i = 0; i < streamReader.getAttributeCount(); i++) {
String name = streamReader.getAttributeName(i).toString();
if (name.equalsIgnoreCase("id")) {
String value = streamReader.getAttributeValue(i);
this.IdInDocument.remove(value);
}
}
}
}
filterBypass.delete(startOffset,endOffset,withBackspace);
} catch (BadLocationException e) {
return false;
} catch (Exception e){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
e.printStackTrace(ps);
try {
String content = baos.toString("UTF8");
authorAccess.getWorkspaceAccess().showErrorMessage(e.getLocalizedMessage() + "\n\n" + content);
return false;
} catch (UnsupportedEncodingException e1) {
authorAccess.getWorkspaceAccess().showErrorMessage(e1.getMessage());
}
}
return true;
}
public boolean deleteNode(AuthorDocumentFilterBypass filterBypass, AuthorNode node){
try {
AuthorDocumentFragment fragment = controller.createDocumentFragment(node, true);
unUseAllId(fragment.getContentNodes());
filterBypass.deleteNode(node);
} catch (BadLocationException e) {
authorAccess.getWorkspaceAccess().showErrorMessage(e.getLocalizedMessage());
return false;
}
return true;
}
public boolean insertNode(AuthorDocumentFilterBypass filterBypass,
int caretOffset, AuthorNode element) {
try {
AuthorDocumentFragment fragment = controller.createDocumentFragment(element, true);
fillID(fragment.getContentNodes());
filterBypass.insertNode(caretOffset,fragment.getContentNodes().get(0));
} catch (BadLocationException e) {
authorAccess.getWorkspaceAccess().showErrorMessage(e.getLocalizedMessage());
}
return super.insertNode(filterBypass, caretOffset, element);
}
public void insertText(AuthorDocumentFilterBypass filterBypass, int caretOffset,
String toInsert) {
super.insertText(filterBypass, caretOffset, toInsert);
}
public void insertFragment(AuthorDocumentFilterBypass arg0, int arg1,
AuthorDocumentFragment arg2) {
fillID(arg2.getContentNodes());
super.insertFragment(arg0, arg1, arg2);
}
private String getIdValue(){
this.maxIdValue++;
String value = "" + this.maxIdValue;
this.IdInDocument.add(value);
return value;
}
private void fillID(List<AuthorNode> nodes){
for (AuthorNode node : nodes){
if (!lostElements.contains(node.getName())){
AuthorElement ae = (AuthorElement) node;
if (!node.getName().equals("документ"))
try {
String idValue = ae.getAttribute("id").getValue();
if (!this.IdWasInDocument.contains(idValue) || this.IdInDocument.contains(idValue))
ae.setAttribute("id", new AttrValue("" + getIdValue()));
} catch (Exception e) {
ae.setAttribute("id", new AttrValue("" + getIdValue()));
}
fillID(ae.getContentNodes());
}
}
}
private void unUseAllId(List<AuthorNode> nodes){
for (AuthorNode currentNode : nodes){
AuthorElement ae = (AuthorElement) currentNode;
try{
String idValue = ae.getAttribute("id").getValue();
this.IdInDocument.remove(idValue);
} catch (Exception e){
}
unUseAllId(ae.getContentNodes());
}
}
}
|
package me.libme.baidu.mapdata.searchindex.keyword;
import me.libme.baidu.mapdata.searchindex.point.Point;
import me.libme.kernel._c.pubsub.Produce;
import me.libme.kernel._c.pubsub.Publisher;
import me.libme.xstream.Compositer;
import me.libme.xstream.ConsumerMeta;
import me.libme.xstream.EntryTupe;
import me.libme.xstream.Tupe;
import java.util.Iterator;
import java.util.List;
/**
* Created by J on 2018/2/27.
*/
public class KeywordConsumer extends Compositer {
private final KeywordSearch keywordSearch;
private final Publisher publisher;
private final Produce produce;
public KeywordConsumer(ConsumerMeta consumerMeta,KeywordSearch keywordSearch,Publisher publisher) {
super(consumerMeta);
this.keywordSearch=keywordSearch;
this.publisher=publisher;
this.produce=publisher.produce();
}
@Override
protected void doConsume(Tupe tupe) throws Exception {
Iterator iterator= tupe.iterator();
SearchParam searchParam= (SearchParam) ((EntryTupe.Entry)iterator.next()).getValue();
List<Point> points=keywordSearch.search(searchParam);
points.forEach(point -> produce.produce(point));
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}
|
package com.mhframework.gameplay.tilemap.io;
import com.mhframework.gameplay.actor.MHActor;
/********************************************************************
* This interface is to be implemented by the class in your game that
* is responsible for taking a tile ID and returning a special
* non-static actor.
* @author Michael Henson
*/
public interface MHActorFactory
{
/****************************************************************
* Accepts tile identifiers, instantiates a special
* object indicated by them, and returns a reference to it. If
* there is no special object for a given identifier, this
* method should return <tt>null</tt>.
*
* @return An actor to be spawned onto the map.
*/
public abstract MHActor spawnActor(int id, int spawnRow, int spawnColumn);
}
|
package cagen.project.repositories;
import org.springframework.data.repository.CrudRepository;
import cagen.project.security.Role;
public interface RoleRepository extends CrudRepository<Role, Integer> {
}
|
/**
*
*/
package com.imooc.security.filter;
import javax.servlet.http.HttpServletRequest;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.stereotype.Component;
import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.RateLimitUtils;
import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.properties.RateLimitProperties;
import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.properties.RateLimitProperties.Policy;
import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.support.DefaultRateLimitKeyGenerator;
/**
* @author jojo
*
*/
@Component
public class MyKeyGen extends DefaultRateLimitKeyGenerator {
public MyKeyGen(RateLimitProperties properties,
RateLimitUtils rateLimitUtils) {
super(properties, rateLimitUtils);
}
@Override
public String key(HttpServletRequest request, Route route, Policy policy) {
// TODO Auto-generated method stub
return super.key(request, route, policy);
}
}
|
/*
* Copyright (c) 2016 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.webadmin.tprofile;
import pl.edu.icm.unity.Constants;
import pl.edu.icm.unity.server.utils.UnityMessageSource;
import pl.edu.icm.unity.types.I18nString;
import pl.edu.icm.unity.types.translation.ActionParameterDefinition;
import pl.edu.icm.unity.webui.common.i18n.I18nTextField;
import com.fasterxml.jackson.core.JsonProcessingException;
public class I18nTextActionParameterComponent extends I18nTextField implements ActionParameterComponent
{
public I18nTextActionParameterComponent(ActionParameterDefinition desc, UnityMessageSource msg)
{
super(msg, desc.getName() + ":");
setDescription(msg.getMessage(desc.getDescriptionKey()));
}
@Override
public String getActionValue()
{
try
{
return Constants.MAPPER.writeValueAsString(getValue().toJson());
} catch (JsonProcessingException e)
{
throw new IllegalStateException("Can't serialize I18nString to JSON", e);
}
}
@Override
public void setActionValue(String value)
{
try
{
setValue(Constants.MAPPER.readValue(value, I18nString.class));
} catch (Exception e)
{
throw new IllegalStateException("Can't deserialize I18nString from JSON", e);
}
}
}
|
package com.target.interview.poc.commentmoderator.data.dboperations;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.UUID;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonPropertyOrder({
"noiseId",
"type",
"noise"
})
public class NoiseBlackListResponse {
@JsonProperty("noisetId")
private UUID noiseId;
@JsonProperty("type")
private String type;
@JsonProperty("noise")
private String noise;
@JsonProperty("error")
private String error;
@JsonProperty("noisetId")
public UUID getNoiseId() {
return noiseId;
}
@JsonProperty("noisetId")
public void setNoiseId(UUID noiseId) {
this.noiseId = noiseId;
}
@JsonProperty("type")
public String getType() {
return type;
}
@JsonProperty("type")
public void setType(String type) {
this.type = type;
}
@JsonProperty("noise")
public String getNoise() {
return noise;
}
@JsonProperty("noise")
public void setNoise(String noise) {
this.noise = noise;
}
@JsonProperty("error")
public String getError(String error) {
return this.error;
}
@JsonProperty("error")
public void setError(String error) {
this.error = error;
}
}
|
package com.gaoshin.coupon.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import com.gaoshin.coupon.dao.impl.CommonDaoImpl;
import com.gaoshin.coupon.service.ServiceBase;
public class ServiceBaseImpl implements ServiceBase {
@Autowired private CommonDaoImpl dao;
@Override
public <T> T getEntity(Class<T> class1, String id) {
return dao.getEntity(class1, id, "*");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.