text stringlengths 10 2.72M |
|---|
package com.git.cloud.iaas.openstack.model;
public class VmRestModel {
private String azName;
private String flavorId;
private String networkId;
private String serverIp;
private String serverName;
private String hostName; // 所属主机名称
private String volumeId; // 系统盘ID(虚拟机需要此属性)
private String imageId; // 镜像ID(物理服务器需要此属性)
private String portId;//虚拟机端口ID,6.3绑定、解绑弹性IP必传参数;6.3添加移除vm安全组必传参数
private String serverId;//2.06绑定、解绑弹性IP必传参数;添加移除vm安全组必传参数
private String securityGroupIdInfo;//6.3添加移除vm安全组必传参数,格式"/"123234345/",/"234325345/""。
private String securityGroupId;//2.06添加移除vm安全组必传参数
private String floatingIpId;
private String floatingIp;
private String floatingIpPoolId;//6.3创建浮动IP使用
private String floatingIpPoolName;//2.06创建浮动IP使用
private String vmGroupId; //虚拟机组ID
//6.3裸金属需要
private String routerId;
private String subnetId;
public String getRouterId() {
return routerId;
}
public void setRouterId(String routerId) {
this.routerId = routerId;
}
public String getSubnetId() {
return subnetId;
}
public void setSubnetId(String subnetId) {
this.subnetId = subnetId;
}
public String getFloatingIpId() {
return floatingIpId;
}
public void setFloatingIpId(String floatingIpId) {
this.floatingIpId = floatingIpId;
}
public String getFloatingIp() {
return floatingIp;
}
public void setFloatingIp(String floatingIp) {
this.floatingIp = floatingIp;
}
public String getFloatingIpPoolId() {
return floatingIpPoolId;
}
public void setFloatingIpPoolId(String floatingIpPoolId) {
this.floatingIpPoolId = floatingIpPoolId;
}
public String getFloatingIpPoolName() {
return floatingIpPoolName;
}
public void setFloatingIpPoolName(String floatingIpPoolName) {
this.floatingIpPoolName = floatingIpPoolName;
}
public String getSecurityGroupIdInfo() {
return securityGroupIdInfo;
}
public void setSecurityGroupIdInfo(String securityGroupIdInfo) {
this.securityGroupIdInfo = securityGroupIdInfo;
}
public String getSecurityGroupId() {
return securityGroupId;
}
public void setSecurityGroupId(String securityGroupId) {
this.securityGroupId = securityGroupId;
}
public String getPortId() {
return portId;
}
public void setPortId(String portId) {
this.portId = portId;
}
public String getServerId() {
return serverId;
}
public void setServerId(String serverId) {
this.serverId = serverId;
}
public String getAzName() {
return azName;
}
public void setAzName(String azName) {
this.azName = azName;
}
public String getFlavorId() {
return flavorId;
}
public void setFlavorId(String flavorId) {
this.flavorId = flavorId;
}
public String getNetworkId() {
return networkId;
}
public void setNetworkId(String networkId) {
this.networkId = networkId;
}
public String getServerIp() {
return serverIp;
}
public void setServerIp(String serverIp) {
this.serverIp = serverIp;
}
public String getServerName() {
return serverName;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getVolumeId() {
return volumeId;
}
public void setVolumeId(String volumeId) {
this.volumeId = volumeId;
}
public String getImageId() {
return imageId;
}
public void setImageId(String imageId) {
this.imageId = imageId;
}
public String getVmGroupId() {
return vmGroupId;
}
public void setVmGroupId(String vmGroupId) {
this.vmGroupId = vmGroupId;
}
@Override
public String toString() {
return "VmRestModel [azName=" + azName + ", flavorId=" + flavorId + ", networkId=" + networkId + ", serverIp="
+ serverIp + ", serverName=" + serverName + ", hostName=" + hostName + ", volumeId=" + volumeId
+ ", imageId=" + imageId + ", portId=" + portId + ", serverId=" + serverId + ", securityGroupIdInfo="
+ securityGroupIdInfo + ", securityGroupId=" + securityGroupId + ", floatingIpId=" + floatingIpId
+ ", floatingIp=" + floatingIp + ", floatingIpPoolId=" + floatingIpPoolId + ", floatingIpPoolName="
+ floatingIpPoolName + ", vmGroupId=" + vmGroupId + "]";
}
}
|
package shapes.textures;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import tuples.Color3f;
import tuples.TexCoord2f;
public class Texture {
protected BufferedImage image;
private String src;
public Texture(String src) {
this.src = src;
File file = new File(src);
try {
image = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
}
public int getHeight() {
return image.getHeight();
}
public int getWidth() {
return image.getWidth();
}
protected int getPx(float u) {
if(u < 0) u++;
if(u >= 1) u--; //1 -> 0
int px = (int) (getWidth()*u);
return px;
}
protected int getPy(float v) {
if(v < 0) v++;
if(v >= 1) v--;
int py = (int) (getHeight()*v);
return py;
}
public Color3f getColor(TexCoord2f texCoord)
{
return getColorByPixel(getPx(texCoord.x), getPy(texCoord.y));
}
/**
* Returns the color of the given pixel in the source image.
*/
protected Color3f getColorByPixel(int px, int py) {
try {
//py = getHeight()-py-1;
int pixel = image.getRGB(px, py);
//int alpha = (pixel >> 24) & 0xff;
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
return new Color3f(red, green, blue);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Height: " + getHeight());
System.out.println("Width: " + getWidth());
System.out.println("Out of bounds: " + new TexCoord2f(px, py));
}
return new Color3f(1, 0, 0); //mark errors red
}
@Override
public String toString() {
return src;
}
}
|
package cs414.a5.bawitt.common;
import cs414.a5.bawitt.server.SignStatusImpl;
public interface Sign extends java.rmi.Remote{
void refreshSign(Spaces s) throws java.rmi.RemoteException;;
SignStatusImpl getSignStatus() throws java.rmi.RemoteException;;
void setSignStatus(SignStatusImpl s) throws java.rmi.RemoteException;;
} |
package com.mygdx.game.tetris;
public class BrickType4 extends Brick
{
private static int[][] a = { { 0, 0, 0, 0 }, { 1, 1, 0, 0 },
{ 1, 1, 0, 0 }, { 0, 0, 0, 0 } };
public BrickType4()
{
super(1);
this.array[0] = a;
}
@Override
public Brick Clone()
{
return new BrickType4();
}
}
|
package com.questionanswer.questionanswer.data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "questions")
public class Question {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(nullable = false, name = "question")
private String question;
@Column(nullable = false, name = "weight")
private int weight;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
|
package io.github.satr.aws.lambda.bookstore.strategies.intenthandler;
// Copyright © 2020, github.com/satr, MIT License
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import io.github.satr.aws.lambda.bookstore.constants.IntentSlotName;
import io.github.satr.aws.lambda.bookstore.request.Request;
import io.github.satr.aws.lambda.bookstore.respond.Response;
import io.github.satr.aws.lambda.bookstore.strategies.selectbook.NotSelectedBookStrategy;
import io.github.satr.aws.lambda.bookstore.strategies.selectbook.SelectBookStrategy;
public abstract class AbstractSelectBookIntentHandlerStrategy extends AbstractIntentHandlerStrategy {
protected SelectBookStrategy notSelectedBookStrategy = new NotSelectedBookStrategy();;
@Override
public Response handle(Request request, LambdaLogger logger) {
String itemNumber = request.getSlot(IntentSlotName.ItemNumber);
String positionInSequence = request.getSlot(IntentSlotName.PositionInSequence);
return customHandle(request, getCloseFulfilledLexRespond(request, "Undefined message"), itemNumber, positionInSequence);
}
protected abstract Response customHandle(Request request, Response respond, String itemNumber, String positionInSequence);
protected SelectBookStrategy selectBookBy(SelectBookStrategy selectBookStrategy, String itemNumber, String positionInSequence, String selectedBookIsbnInSession) {
Integer itemNumberParsed;
if (itemNumber != null && (itemNumberParsed = Integer.valueOf(itemNumber)) != null && itemNumberParsed > 0) {
selectBookStrategy.selectBookByNumberInSequence(itemNumberParsed);
return selectBookStrategy;
}
if(positionInSequence != null) {
selectBookStrategy.selectBookByPositionInList(positionInSequence);
return selectBookStrategy;
}
if(selectedBookIsbnInSession != null && !selectedBookIsbnInSession.isEmpty()) {
selectBookStrategy.selectBookByIsbn(selectedBookIsbnInSession);
return selectBookStrategy;
}
return notSelectedBookStrategy;
}
}
|
package com.example.words.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import java.io.ByteArrayOutputStream;
/**
* Created by 展鹏 on 2017/7/24.
*/
public class BitmapByte {
//【工具函数】Bytes2Bitmap
public Bitmap Bytes2Bitmap(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
} else {
return null;
}
}
//【工具函数】drawable2Bitmap
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
//canvas.setBitmap(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
//byte[] 转换 Bitmap
public Bitmap Bytes2Bimap(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
} else {
return null;
}
}
byte[] Bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
public byte[] drawable2byte(Drawable drawable) {
Bitmap tempBitmap = drawableToBitmap(drawable);
return Bitmap2Bytes(tempBitmap);
}
}
|
package org.wxy.weibo.cosmos.ui.base;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.header.MaterialHeader;
import in.srain.cube.views.ptr.util.PtrLocalDisplay;
/**
* Created by wxy on 2018/4/21.
*/
public abstract class BaseFragment extends Fragment {
View view;
ProgressDialog progressDialog;
private boolean isDestroyed=false;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view=inflater.inflate(getLayoutID(),null);
getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);//恢复状态栏白色字体
initView(view);
init();
initdata();
return view;
}
protected abstract int getLayoutID();
protected void initView(View view){
this.view=view;
}
protected void init(){}
protected void initdata(){}
public void Ptr(PtrClassicFrameLayout mPtrClassicFrameLayout){
// 头部阻尼系数
mPtrClassicFrameLayout.setResistanceHeader(1.7f);
// 底部阻尼系数
mPtrClassicFrameLayout.setResistanceFooter(1.7f);
// 默认1.2f,移动达到头部高度1.2倍时触发刷新操作
mPtrClassicFrameLayout.setRatioOfHeaderHeightToRefresh(1.2f);
// 头部回弹时间
mPtrClassicFrameLayout.setDurationToCloseHeader(1000);
// 底部回弹时间
mPtrClassicFrameLayout.setDurationToCloseFooter(1000);
// 释放刷新
mPtrClassicFrameLayout.setPullToRefresh(false);
// 释放时恢复到刷新状态的时间
mPtrClassicFrameLayout.setDurationToBackHeader(200);
mPtrClassicFrameLayout.setDurationToBackFooter(200);
// Matrial风格头部的实现
final MaterialHeader header = new MaterialHeader(getActivity());
header.setPadding(0, PtrLocalDisplay.dp2px(15),0,0);
mPtrClassicFrameLayout.setHeaderView(header);
mPtrClassicFrameLayout.addPtrUIHandler(header);
}
public void Ptr(PtrFrameLayout mPtrClassicFrameLayout){
// 头部阻尼系数
mPtrClassicFrameLayout.setResistanceHeader(1.7f);
// 底部阻尼系数
mPtrClassicFrameLayout.setResistanceFooter(1.7f);
// 默认1.2f,移动达到头部高度1.2倍时触发刷新操作
mPtrClassicFrameLayout.setRatioOfHeaderHeightToRefresh(1.2f);
// 头部回弹时间
mPtrClassicFrameLayout.setDurationToCloseHeader(1000);
// 底部回弹时间
mPtrClassicFrameLayout.setDurationToCloseFooter(1000);
// 释放刷新
mPtrClassicFrameLayout.setPullToRefresh(false);
// 释放时恢复到刷新状态的时间
mPtrClassicFrameLayout.setDurationToBackHeader(200);
mPtrClassicFrameLayout.setDurationToBackFooter(200);
// Matrial风格头部的实现
final MaterialHeader header = new MaterialHeader(getActivity());
header.setPadding(0, PtrLocalDisplay.dp2px(15),0,0);
mPtrClassicFrameLayout.setHeaderView(header);
mPtrClassicFrameLayout.addPtrUIHandler(header);
}
public void showToast(String msg){
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
}
public void showToast(@StringRes int context){
Toast.makeText(getActivity(), context, Toast.LENGTH_SHORT).show();
}
public void showProgressDialog(){
if (progressDialog==null)
{
progressDialog=new ProgressDialog(getActivity()).show(getActivity(),"","正在加载",true,false);
return;
}
else
{
progressDialog.setTitle("");
progressDialog.setMessage("正在加载");
progressDialog.show();
return;
}
}
public void closeprogress(){
if (null!=progressDialog&&progressDialog.isShowing()){
progressDialog.dismiss();
}
}
public void showProgressDialog(String mag){
showProgressDialog();
progressDialog.setMessage(mag);
}
public void starActivity(Class<?extends Activity> cls)
{
Intent intent=new Intent(getActivity(),cls);
startActivity(intent);
}
public void starActivityofRul(Class<?extends Activity> cls, int Result)
{
Intent intent=new Intent();
intent.setClass(getContext(),cls);
startActivityForResult(intent,Result);
}
protected void initRecycler(RecyclerView recyclerView, RecyclerView.LayoutManager layoutManager){
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(layoutManager);
}
@Override
public void onDestroy() {
super.onDestroy();
closeprogress();
isDestroyed=true;
}
}
|
package com.swm.wechat.controller;
import java.io.IOException;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.swm.user.bean.User;
import com.swm.user.service.IUserService;
import com.swm.wechat.config.WeChatConfiguration;
import com.swm.wechat.core.WeChatOauth;
/**
* 微信请求处理类
* @Title: WeChatController.java
* @Package com.swm.wechat.controller
* @Description: TODO(用一句话描述该文件做什么)
* @author fyy
* @date 2017-3-23 上午10:38:48
* @version V1.0
*/
@Controller //类似Struts的Action
@RequestMapping("/weChat")
public class WeChatController {
public static Logger logger = LogManager.getLogger(WeChatController.class);
/**
* 用户业务对象
*/
@Resource(name="userService")
private IUserService userService;
/**
* 获取微信用户CODE
* @param request
* @param response
* @throws IOException
*/
@RequestMapping(value="/oauth.do")
public void oauth(HttpServletRequest request,HttpServletResponse response) throws IOException{
//请求获取用户CODE
response.sendRedirect(WeChatOauth.code(WeChatConfiguration.SNSAPI_BASE));
}
/**
* 微信回调地址,通过微信CODE获取openid
* @param request
* @param response
*/
@RequestMapping(value="/callback.do")
public void callback(HttpServletRequest request,HttpServletResponse response){
logger.info("回调成功");
//根据微信返回的CODE查询openid信息
try{
String ip = this.getIpAddr(request);
JSONObject result = JSONObject.fromObject(WeChatOauth.accessToken(request.getParameter("code")));
//获取用户的OPENID 还是获取用户的基本信息
String scope = result.getString("scope");
//根据openid查找用户对象
User user = userService.queryUserByOpenId(result.getString("openid"));
if(WeChatConfiguration.SNSAPI_BASE.equals(scope) && null == user){//如果用户不在,再次调用微信获取用户的基本信息
logger.info("通过openid未查询到相关用户信息,重定向获取用户SNSAPI_USER_INFO信息");
response.sendRedirect(WeChatOauth.code(WeChatConfiguration.SNSAPI_USER_INFO));
}else if(WeChatConfiguration.SNSAPI_USER_INFO.equals(scope) && null == user){//如果用户不存在,获取到了用户信息,保存
logger.info("开始获取微信用户信息");
JSONObject userInfo = JSONObject.fromObject(WeChatOauth.snsapiUserinfo(result.getString("access_token"), result.getString("openid")));
user = new User();
user.setOpenId(userInfo.getString("openid"));
user.setGender(userInfo.getString("sex"));
user.setNick(userInfo.getString("nickname"));
user.setLastLoginIP(ip);
userService.addUser(user);
request.getSession().setAttribute("user", user);
response.sendRedirect("/map/index.jsp");
}else{
logger.info("用户信息已存在,跳转页面!");
user.setLastLoginIP(ip);
userService.editUserByLoginIp(user);
request.getSession().setAttribute("user", user);
response.sendRedirect("/map/index.jsp");
}
}catch(Exception e){
logger.error("出现异常-->"+e.getMessage());
}
}
public static String getIpAddr(HttpServletRequest request) throws Exception {
String ip = request.getHeader("X-Real-IP");
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
ip = request.getHeader("X-Forwarded-For");
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个IP值,第一个为真实IP。
int index = ip.indexOf(',');
if (index != -1) {
return ip.substring(0, index);
} else {
return ip;
}
} else {
return request.getRemoteAddr();
}
}
} |
package it.unical.dimes.processmining.ui;
/**
* @author frank
*
* Created on 2013-05-12, 11:51:29 AM
*/
public class Settings {
private String constr_file_name = "Constraints.xml";
private boolean constraintsEnabled;
private double sigma_log_noise;
private double fallFactor;
private String logName;
private double rtb;
public boolean isConstraintsEnabled() {
return constraintsEnabled;
}
public void setConstraintsEnabled(boolean constraintsEnabled) {
this.constraintsEnabled = constraintsEnabled;
}
public double getSigmaLogNoise() {
return sigma_log_noise;
}
public void setSigmaLogNoise(double sigmaLogNoise) {
this.sigma_log_noise = sigmaLogNoise;
}
public String getConstr_file_name() {
return constr_file_name;
}
public void setLogName(String log) {
this.logName = log;
}
public String getLogName() {
return logName;
}
public void setFallFactor(double fallFactor) {
// TODO Auto-generated method stub
this.fallFactor = fallFactor;
}
public void setRelativeToBest(double rtb) {
// TODO Auto-generated method stub
this.rtb = rtb;
}
public double getFallFactor() {
return fallFactor;
}
public double getRelativeToBest() {
// TODO Auto-generated method stub
return rtb;
}
} |
package com.itheima.controller;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.RoleService;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@RequestMapping("/findAll")
public ModelAndView list() {
List<User> userList = userService.list();
ModelAndView mv = new ModelAndView();
mv.addObject("userList", userList);
mv.setViewName("user-list");
return mv;
}
@RequestMapping("/saveUI")
public ModelAndView saveUI() {
ModelAndView mv = new ModelAndView();
List<Role> roleList = roleService.list();
mv.addObject("roleList", roleList);
mv.setViewName("user-add");
return mv;
}
@RequestMapping("/save")
public String save(User user, Long[] roleIds) {
userService.save(user, roleIds);
return "redirect:/user/findAll";
}
@RequestMapping("/delete/{userId}")
public String delete(@PathVariable("userId") Long userId) {
userService.delete(userId);
return "redirect:/user/findAll";
}
}
|
package edu.uci.ics.fabflixmobile;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.time.Year;
import java.util.ArrayList;
import java.util.List;
public class MovieListViewAdapter extends ArrayAdapter<Movie> {
private ArrayList<Movie> movies;
public MovieListViewAdapter(@NonNull Context context, int resource, @NonNull List<Movie> objects) {
super(context, resource, objects);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
String title = getItem(position).getName();
String year = getItem(position).getYear();
String director = getItem(position).getDirector();
String all_gens = getItem(position).all_gens;
String all_stars = getItem(position).all_stars;
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.row, parent, false);
TextView txTitle = view.findViewById(R.id.txTitle);
TextView txYear = view.findViewById(R.id.txYear);
TextView txDirector = view.findViewById(R.id.txDirector);
TextView txGens = view.findViewById(R.id.txGens);
TextView txStars = view.findViewById(R.id.txStars);
txTitle.setText(title);
txYear.setText(year);
txDirector.setText(director);
txGens.setText(all_gens);
txStars.setText(all_stars);
return view;
}
} |
package com.example.archer.amadeus;
import android.*;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.provider.ContactsContract;;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSIONS_ASKED_FOR = 2;
private int userId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
boolean hasHadFirstLogin = sharedPref.getBoolean(getString(R.string.pref_has_had_first_login), false);
String firebaseToken = sharedPref.getString(getString(R.string.firebase_token_key), "No Firebase Token currently exists.");
userId = sharedPref.getInt(getString(R.string.pref_user_id), -1);
if (!hasHadFirstLogin) {
sendRegistrationTokenToServer(firebaseToken);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(getString(R.string.pref_has_had_first_login), true);
editor.commit();
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
startRequestPermissions();
} else {
new Thread(new Runnable() {
@Override
public void run() {
JSONArray contacts = getContacts();
transmitContacts(contacts);
}
}).start();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_ASKED_FOR: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Thanks for granting that permission!", Toast.LENGTH_SHORT).show();
} else {
}
}
}
}
public void goToLogActivity(View view) {
Intent goToLogIntent = new Intent(this, ViewLogActivity.class);
startActivity(goToLogIntent);
}
public void goToErrorLogActivity(View view) {
Intent goToErrorLogIntent = new Intent(this, ErrorLogActivity.class);
startActivity(goToErrorLogIntent);
}
public void startRequestPermissions() {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.READ_SMS,
Manifest.permission.RECEIVE_SMS,
Manifest.permission.SEND_SMS,
Manifest.permission.READ_CONTACTS
}, PERMISSIONS_ASKED_FOR);
}
private JSONArray getContacts() {
ContentResolver cr = getContentResolver();
String [] projections = {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor contactsCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projections, null, null, null);
JSONArray contactsArr = new JSONArray();
int contactIdIndex = contactsCursor.getColumnIndex(ContactsContract.Contacts._ID);
int displayNameIndex = contactsCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int phoneNumberIndex = contactsCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while(contactsCursor.moveToNext()) {
JSONObject contactObj = new JSONObject();
Long contactId = contactsCursor.getLong(contactIdIndex);
String displayName = contactsCursor.getString(displayNameIndex);
String phoneNumber = contactsCursor.getString(phoneNumberIndex);
try {
contactObj.put("contactId", contactId.toString());
contactObj.put("displayName", displayName);
contactObj.put("phoneNumber", phoneNumber);
contactsArr.put(contactObj);
} catch (JSONException e) {
e.printStackTrace();
}
}
return contactsArr;
}
private void transmitContacts(final JSONArray contacts) {
final Context context = this;
String url = AmadeusApplication.AMADEUS_API_URL + "/contacts";
Map<String, String> params = new HashMap();
params.put("contacts", contacts.toString());
params.put("userId", Integer.toString(userId));
JSONObject jsonRequest = new JSONObject(params);
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, jsonRequest,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(context, "Successfully uploaded contacts", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.toString(), Toast.LENGTH_SHORT).show();
}
});
AmadeusApplication.getInstance().getRequestQueue().add(req);
}
private void sendRegistrationTokenToServer(String firebaseToken) {
final Context self = this;
String url = AmadeusApplication.AMADEUS_API_URL + "/users/update-registration-token";
Map<String, String> params = new HashMap();
params.put("registrationToken", firebaseToken);
params.put("userId", Integer.toString(userId));
JSONObject jsonRequest = new JSONObject(params);
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, jsonRequest,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
AmadeusApplication.getInstance().getRequestQueue().add(req);
}
}
|
package com.episen.tp2.application.manager;
import com.episen.tp2.business.dto.DocumentDTO;
import com.episen.tp2.business.model.DocumentStatusEnum;
public interface DocumentManager {
DocumentDTO getDocumentById(Long documentId);
DocumentDTO putDocumentById(Long documentId, DocumentDTO documentDTO);
void putDocumentStatusById(Long documentId, DocumentStatusEnum documentStatusEnum);
}
|
/*
* ### Copyright (C) 2008-2009 Michael Fuchs ###
* ### All Rights Reserved. ###
*
* Author: Michael Fuchs
* E-Mail: michael.fuchs@unico-group.com
* URL: http://www.michael-a-fuchs.de
*/
package org.dbdoclet.tidbit.action;
import java.awt.event.ActionEvent;
import javax.swing.Icon;
import org.dbdoclet.tidbit.application.Application;
import org.dbdoclet.tidbit.application.action.AbstractTidbitAction;
public class ActionExit extends AbstractTidbitAction {
private static final long serialVersionUID = 1L;
public ActionExit(Application application, String name, Icon icon) {
super(application, name, icon);
}
@Override
public void action(ActionEvent event) throws Exception {
application.shutdown();
finished();
System.exit(0);
}
}
|
package CPS261LinkedLists;
import java.util.Iterator;
public class MySingleLinkedList<T> {
private Node head=null;
private Node tail=null;
private int totalSize = 0;
/****** Inner Class *****/
class Node
{
T value;
Node next;
Node(T value)
{
this.value = value;
next = null;
}
}
/******* Inner class Iterator *****/
class MyIterator implements Iterator<T>
{
private Node nextNode = head;
@Override
public boolean hasNext() {
if (nextNode== null)
return false;
return true;
}
@Override
public T next() {
T value = nextNode.value;
nextNode = nextNode.next;
return value;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Iterator.remove not implemented");
}
}
public Iterator<T> iterator()
{
return new MyIterator();
}
public boolean add(T value)
{
Node n = new Node(value);
if (tail == null)
{
// First node to be added to the List
tail = head = n;
}
else
{
tail.next = n;
tail = n;
}
totalSize += 1;
return true;
}
public void addFirst(T value)
{
Node n = new Node(value);
n.next = head;
if (head != null)
{
n.next = head;
head = n;
}
else
{
// First node to be added to the List
head = tail = n;
}
totalSize +=1;
}
public T getFirst()
{
return head.value;
}
public T getlast()
{
return tail.value;
}
void addLast(T value)
{
add(value);
}
T removeFirst()
{
if (head == null)
throw new RuntimeException("MySingleLinkedList.removeFirst call on empty list");
Node n = head;
head = n.next;
totalSize -= 1;
return n.value;
}
T removeLast()
{
throw new UnsupportedOperationException("MySingleLinkedList.removeLast not implemented");
}
public static void main(String[] args) {
MySingleLinkedList<String> ml = new MySingleLinkedList<String>();
ml.add("one");
ml.add("two");
ml.add("three");
ml.add("four");
ml.add("five");
System.out.println("Front = "+ ml.getFirst());
System.out.println("Last = " + ml.getlast());
Iterator<String> iter = ml.iterator();
while (iter.hasNext())
{
String s = iter.next();
System.out.println(s);
}
ml.removeFirst();
System.out.println("After removeFirst");
iter = ml.iterator();
while (iter.hasNext())
{
String s = iter.next();
System.out.println(s);
}
}
} |
package com.sh.base.sort;
/**
* @Auther: bjshaohang
* @Date: 2019/1/24
*/
public class b2QuickSort {
public static void main(String[] args) {
int[] array = {12,20,5,16,15,1,30,45,23,9};
int begin = 0;
int end = array.length-1;
sort(array,begin,end);
for (int i : array) {
System.out.println(i);
}
}
public static void sort(int[] a, int low,int high){
int start = low;
int end = high;
int key = a[start];
while (end >start){
while (end > start && key<a[end]){
end--;
}
if(key >= a[end]){
int temp = a[end];
a[end] = a[start];
a[start] = temp;
}
while (end > start && key > a[start]){
start++;
}
if(key <= a[start]){
int temp = a[start];
a[start] = a[end];
a[end] = temp;
}
}
if (start > low){
sort(a,low,start-1);
}
if (end < high){
sort(a,end+1,high);
}
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* 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.console.windows.security;
import net.datacrow.console.windows.itemforms.ItemForm;
import net.datacrow.core.IconLibrary;
import net.datacrow.core.objects.DcObject;
import net.datacrow.core.objects.ValidationException;
import net.datacrow.core.objects.helpers.Permission;
import net.datacrow.core.objects.helpers.User;
import net.datacrow.core.resources.DcResources;
import net.datacrow.core.wf.requests.CloseWindowRequest;
import net.datacrow.core.wf.requests.CreateUserRequest;
import net.datacrow.core.wf.requests.UpdateUserRequest;
import net.datacrow.util.DcSwingUtilities;
public class UserForm extends ItemForm {
private PluginPermissionPanel pluginPermissionPanel;
private ModulePermissionPanel modulePermissionPanel;
public UserForm(boolean readonly, DcObject dco, boolean update, boolean template) {
super(readonly, update, dco, template);
// needed for saving the permissions
if (dco.getID() == null)
dco.setIDs();
addPluginPermissionPanel();
addModulePermissionPanel();
}
private void addModulePermissionPanel() {
modulePermissionPanel = new ModulePermissionPanel(dco, update);
modulePermissionPanel.setEnabled(!((User) dco).isAdmin());
tabbedPane.addTab(DcResources.getText("lblModulePermission"),
IconLibrary._icoSettings16, modulePermissionPanel);
}
private void addPluginPermissionPanel() {
pluginPermissionPanel = new PluginPermissionPanel(dco, update);
pluginPermissionPanel.setEnabled(!((User) dco).isAdmin());
tabbedPane.addTab(DcResources.getText("lblPluginPermissions"),
IconLibrary._icoSettings16, pluginPermissionPanel);
}
@Override
protected boolean isChanged() {
boolean changed = super.isChanged();
changed = changed ? changed : modulePermissionPanel.isChanged();
changed = changed ? changed : pluginPermissionPanel.isChanged();
return changed;
}
@Override
public void close(boolean afterSave) {
super.close(afterSave);
if (modulePermissionPanel != null) modulePermissionPanel.clear();
modulePermissionPanel = null;
if (pluginPermissionPanel != null) pluginPermissionPanel.clear();
pluginPermissionPanel = null;
}
@Override
protected void addChildrenPanel() {}
@Override
protected void saveValues() {
apply();
dco.addRequest(new CloseWindowRequest(this));
for (Permission permission : modulePermissionPanel.getPermissions())
dco.addChild(permission);
for (Permission permission : pluginPermissionPanel.getPermissions())
dco.addChild(permission);
try {
if (!update) {
dco.addRequest(new CreateUserRequest((User) dco));
dco.saveNew(true);
} else if (isChanged()) {
dco.addRequest(new UpdateUserRequest((User) dco));
dco.saveUpdate(true);
} else {
DcSwingUtilities.displayWarningMessage("msgNoChangesToSave");
}
} catch (ValidationException vExp) {
DcSwingUtilities.displayWarningMessage(vExp.getMessage());
}
}
}
|
package pinno.demo.hackernews.screen.detail;
import android.support.annotation.NonNull;
import java.util.List;
import pinno.demo.hackernews.model.Comment;
import rx.Observable;
public interface CommentRepository {
@NonNull
Observable<Comment> loadItemDetail(final long storyId);
@NonNull
Observable<List<Comment>> loadComments(final List<Long> storyIds);
}
|
package com.hydrophilik.mwrdCsoScraper.executables;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import com.orangewall.bezutils.beztime.BezDate;
public class RunScraper {
public static String mwrdWebPrefix = "http://apps.mwrd.org/CSO/CSOEventSynopsisReport.aspx?passdate=";
public static void main(String[] args) {
String rawScrapingsDir;
// arg0 => directory where the raw scraped html code is placed.
try {
rawScrapingsDir = args[0];
}
catch (Exception e) {
System.out.println("You must specify a directory to place scraped html");
return;
}
System.out.println("Scraping...");
scrapeWebsite(rawScrapingsDir);
System.out.println("Done");
}
private static void scrapeWebsite(String rawScrapingsDir) {
BezDate theDate;
BezDate endDate;
try {
theDate = new BezDate("1/1/2007");
endDate = new BezDate(); // today
}
catch (Exception e) {
System.out.println("Unable to parse dates");
return;
}
System.out.println("Scraper started with start date: " + theDate.convertToString() +
" and end date: " + endDate.convertToString());
while (false == theDate.isSameDayAs(endDate)) {
File file = new File(rawScrapingsDir + "/" + theDate.dateYearFirst() + ".txt");
if (file.exists()) {
// Date has already been scraped. Skip it.
theDate.incrementDays(1);
continue;
}
String date = theDate.convertToString();
BufferedWriter bw = null;
FileWriter fw = null;
try {
file.createNewFile();
String inputLine;
String urlStr = mwrdWebPrefix + date;
URL url = new URL(urlStr);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
fw = new FileWriter(file.getAbsoluteFile());
bw = new BufferedWriter(fw);
while ((inputLine = in.readLine()) != null)
bw.write(inputLine + "\n");
}
catch (Exception e) {
e.printStackTrace();
return;
}
finally {
try {
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
}
theDate.incrementDays(1);
}
}
}
|
public class Main {
String[][] marks =
{
{"I", "V"}, {"X", "L"}, {"C", "D"}, {"M", ""}
};
public String Puzzle(int num) {
int exp = 0;
String res = "";
while(num > 0) {
String nStr = "";
int n = num % 10;
if(n == 9) {
nStr = marks[exp][0] + marks[exp+1][0];
} else if(n == 4) {
nStr = marks[exp][0] + marks[exp][1];
} else {
if(n >= 5) {
n -= 5;
nStr += marks[exp][1];
}
for(int i = 0; i < n; i++)
nStr += marks[exp][0];
}
res = nStr + res;
num /= 10;
exp++;
}
System.out.println(res);
}
}
|
package com.sdz.enumerations;
import com.prive.exercices.Titre;
class MainEnumeration
{
public static void main(String[] args)
{
Titre titre = new Titre();
titre.titre("Test d'énumération des objets de la class enum");
for (Langage langue : Langage.values())
{
if (Langage.JAVA.equals(langue))
System.out.println("------"+langue+"------");
else
System.out.println(langue);
}
titre.titre("Test des méthodes de la class enum");
Langage l1 = Langage.CSS;
Langage l2 = Langage.JAVA;
titre.titre("Contrôle des données avant modification", false);
System.out.println("l1 name = "+l1.getName());
System.out.println("l2 editor = "+l2.getEditor());
System.out.println(l1.toString());
System.out.println(l2.toString());
titre.titre("Modification des données", false);
l1.setName("CSS3");
l2.setEditor("SublimText");
titre.titre("Contrôle des données après modification", false);
System.out.println("l1 name = "+l1.getName());
System.out.println("l2 editor = "+l2.getEditor());
System.out.println(l1.toString());
System.out.println(l2.toString());
}
}
|
package tk.jimmywang.attendance.app.application;
import android.app.Application;
/**
* Created by WangJin on 2014/7/2.
*/
public class BaseApplication extends Application{
private static BaseApplication baseApplication;
@Override
public void onCreate() {
super.onCreate();
if(null == baseApplication){
baseApplication = this;
}
}
public static BaseApplication getInstance(){
return baseApplication;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.vootoo.server.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalChannel;
import io.netty.channel.local.LocalEventLoopGroup;
import io.netty.channel.local.LocalServerChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vootoo.client.netty.NettySolrClient;
import org.vootoo.client.netty.connect.SimpleConnectionPool;
import org.vootoo.server.ExecutorConfig;
import org.vootoo.server.RequestExecutor;
import org.vootoo.server.RequestProcesserTest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* @author chenlb on 2015-05-28 17:23.
*/
public class SolrServerHandlerTest extends RequestProcesserTest {
private static final Logger logger = LoggerFactory.getLogger(SolrServerHandlerTest.class);
static final String PORT = System.getProperty("port", "test_port");
static final LocalAddress addr = new LocalAddress(PORT);
static RequestExecutor queryExecutor;
static RequestExecutor updateExecutor;
static EventLoopGroup serverGroup = new LocalEventLoopGroup();
static EventLoopGroup clientGroup = new NioEventLoopGroup(); // NIO event loops are also OK
static Bootstrap client;
static Channel serverChannel;
@BeforeClass
public static void start_local_netty() throws InterruptedException {
queryExecutor = new RequestExecutor(ExecutorConfig.createDefault().setName("query-executor").setThreadNum(5));
updateExecutor = new RequestExecutor(ExecutorConfig.createDefault().setName("update-executor").setThreadNum(2));
// Note that we can use any event loop to ensure certain local channels
// are handled by the same event loop thread which drives a certain socket channel
// to reduce the communication latency between socket channels and local channels.
ServerBootstrap sb = new ServerBootstrap();
sb.group(serverGroup)
.channel(LocalServerChannel.class)
.handler(new ChannelInitializer<LocalServerChannel>() {
@Override
public void initChannel(LocalServerChannel ch) throws Exception {
ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
}
})
.childHandler(new SolrServerChannelInitializer(h.getCoreContainer(), new ChannelHandlerConfigs(),
queryExecutor,
updateExecutor
));
client = new Bootstrap();
client.group(clientGroup)
.channel(LocalChannel.class)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000);
// Start the server.
ChannelFuture serverFuture = sb.bind(addr).sync();
serverChannel = serverFuture.channel();
}
@AfterClass
public static void close_group() {
if(serverChannel != null) {
logger.info("server channel closing ...");
serverChannel.close();
logger.info("server channel closed");
}
if(serverGroup != null) {
logger.info("server group closing ...");
serverGroup.shutdownGracefully();
logger.info("server group closed");
}
if(clientGroup != null) {
logger.info("client group closing ...");
clientGroup.shutdownGracefully();
logger.info("client group closed");
}
if(queryExecutor != null) {
logger.info("queryExecutor closing ...");
queryExecutor.shutdownAndAwaitTermination(3, TimeUnit.SECONDS);
logger.info("queryExecutor closed");
}
if(updateExecutor != null) {
logger.info("updateExecutor closing ...");
updateExecutor.shutdownAndAwaitTermination(3, TimeUnit.SECONDS);
logger.info("updateExecutor closed");
}
}
NettySolrClient solrClient;
@Before
public void before_test() {
solrClient = createNettysolrClient();
}
protected NettySolrClient createNettysolrClient() {
SimpleConnectionPool connectionPool = new SimpleConnectionPool(client, addr);
NettySolrClient solrClient = new NettySolrClient(connectionPool);
return solrClient;
}
protected SolrQuery createIdQuery(String id) {
SolrQuery query = new SolrQuery("id:\""+id+"\"");
query.set("_timeout_", 1000);
query.set("indent", "on");
return query;
}
@Test
public void test_query() throws InterruptedException, IOException, SolrServerException {
String id = addTestDoc();
QueryResponse queryResponse = solrClient.query("collection1", createIdQuery(id));
assertIdResult(queryResponse, id);
}
@Test
public void test_update_add() throws IOException, SolrServerException {
String id = createDocId();
SolrInputDocument sid = new SolrInputDocument();
sid.addField("id", id);
UpdateResponse addResp = solrClient.add("collection1", sid);
System.out.println(addResp);
assertU(commit());
assertQueryId(id);
}
} |
public class lixt5ex1 {
public static void main(String[] args) throws ParkingException {
cParkingTest t = new cParkingTest();
t.test();
}
}
|
package com.ziaan.cp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Hashtable;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import com.ziaan.library.ConfigSet;
import com.ziaan.library.DBConnectionManager;
import com.ziaan.library.DataBox;
import com.ziaan.library.ErrorManager;
import com.ziaan.library.FormatDate;
import com.ziaan.library.ListSet;
import com.ziaan.library.RequestBox;
import com.ziaan.library.SQLString;
import com.ziaan.library.StringManager;
public class CpOutsourcingBean {
private ConfigSet config;
private int row;
private int adminrow;
private static final String JOBEXETYPE_SUBJ = "SUBJ";
private static final String JOBEXETYPE_PRROPOSE = "PRROPOSE";
private static final String JOBEXETYPE_SCORE = "SCOR";
public CpOutsourcingBean() {
try {
config = new ConfigSet();
row = Integer.parseInt(config.getProperty("page.bulletin.row") ); //이 모듈의 페이지당 row 수를 셋팅한다
adminrow = Integer.parseInt(config.getProperty("page.bulletin.adminrow") ); //이 모듈의 페이지당 row 수를 셋팅한다
} catch( Exception e ) {
e.printStackTrace();
}
}
/**
* JOB APPLICATION INFO
* @param box
* @return
* @throws Exception
*/
public ArrayList selectJobList(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
PreparedStatement pstmt = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
DataBox dbox = null;
int v_pageno = box.getInt("p_pageno");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = " select \n";
sql += " jobnm, \n";
sql += " callprogram, \n";
sql += " jobexetype, \n";
sql += " jobtimetype, \n";
sql += " starttime, \n";
sql += " exectime, \n";
sql += " jobexcuteyn, \n";
sql += " use_yn, \n";
sql += " param \n";
sql += " from tz_cronjobs_t \n";
ls = connMgr.executeQuery(sql);
ls.setPageSize(adminrow); // 페이지당 row 갯수를 세팅한다
ls.setCurrentPage(v_pageno); // 현재페이지번호를 세팅한다.
int total_page_count = ls.getTotalPage(); // 전체 페이지 수를 반환한다
int total_row_count = ls.getTotalCount(); // 전체 row 수를 반환한다
while ( ls.next() ) {
dbox = ls.getDataBox();
dbox.put("d_dispnum", new Integer(total_row_count - ls.getRowNum() + 1));
dbox.put("d_totalpage", new Integer(total_page_count));
dbox.put("d_rowcount", new Integer(adminrow));
list.add(dbox);
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } } // 꼭 닫아준다
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return list;
}
/**
* 위탁과정의 과정/차수정보를 받는다.
* @param box
* @return
* @throws Exception
*/
public String selectListCpSubjSubjseq(RequestBox box) throws Exception {
HttpClient client = new HttpClient();
PostMethod httppost = null;
DBConnectionManager connMgr = null;
PreparedStatement pstmt = null;
ListSet ls = null;
String ls_result;
String ls_param = box.getString("p_execMonth");
String v_year = "";
String v_month = "";
String lsRecvHttp = "";
String sql = "";
String v_enc = box.getStringDefault("p_enc", "A");
try{
connMgr = new DBConnectionManager();
sql = " select \n";
sql += " jobnm, \n";
sql += " callprogram, \n";
sql += " jobexetype, \n";
sql += " jobtimetype, \n";
sql += " starttime, \n";
sql += " exectime, \n";
sql += " jobexcuteyn, \n";
sql += " use_yn, \n";
sql += " param \n";
sql += " from tz_cronjobs_t \n";
sql += " where 1=1 \n";
sql += " and enc = "+StringManager.makeSQL(v_enc)+" \n";
sql += " and jobexetype = '"+JOBEXETYPE_SUBJ+"' \n";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
lsRecvHttp = ls.getString("callprogram");
}
if(ls != null) ls.close();
if (lsRecvHttp == null )
{
return "F";
}
if(ls_param.equals("")){
ls_param = FormatDate.getDate("yyyyMMddHHmmss").substring(0,6);
}
//파라매터 값 지정
v_year = ls_param.substring(0,4);
v_month = ls_param.substring(4,6);
//과정 차수 정보 받아 오는 주소
if(v_enc.equals("A")){ //크레듀는 파라메터 정보를 년도+월
lsRecvHttp = lsRecvHttp +"?p_yyyymm="+ls_param;
}else if(v_enc.equals("Y")||v_enc.equals("W")){
lsRecvHttp = lsRecvHttp +"?p_year="+v_year+"&p_month="+v_month;
}
httppost = new PostMethod(lsRecvHttp);
httppost.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=EUC-KR");
client.executeMethod(httppost);
if (httppost.getStatusCode() == HttpStatus.SC_OK) {
ls_result = httppost.getResponseBodyAsString();
//윈글리쉬은 언어가 asp 이므로 반드시 한글로 인코딩을 해야 한글이 깨지지 않는다. 안깨져서 주석처리함.
if(v_enc !=null && (v_enc.equals("W"))){
ls_result = StringManager.korEncode(ls_result);
}
if(ls_result!=null && ls_result.indexOf("|") > -1){
//HanawProc proc = new HanawProc();
//proc.subjProcess(ls_result,enc, v_year);
//ls_result = _CONFIG._SUCESS;
}
else
{
ls_result ="F"+"[LOG=NO-DATA"+ls_result+"]";
}
} else {
ls_result = "F"+"[LOG="+httppost.getStatusLine().toString()+"]";
}
}
catch(Exception e){
ErrorManager.getErrorStackTrace(e);
throw new Exception("\n e.getMessage() : [\n" + e.getMessage() + "\n]");
}
finally {
httppost.releaseConnection();
}
return ls_result ;
}
/**
* 위탁과정의 과정/차수정보 매칭 조회
* @param box
* @return
* @throws Exception
*/
public ArrayList selectViewSubj(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
StringBuffer strSQL = null;
DataBox dbox = null;
ArrayList list = null;
String v_con_subj = box.getString("p_con_subj");
String v_subj = box.getStringDefault("p_subj", "");
String v_year = box.getString("p_con_year");
String v_edustart = box.getString("p_con_edustart");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
strSQL = new StringBuffer();
strSQL.append(" \n select subj from tz_subj WHERE cpsubj = " + StringManager.makeSQL(v_con_subj));
ls = connMgr.executeQuery(strSQL.toString());
while ( ls.next() ) {
v_subj = ls.getString("subj");
}
if(ls != null){ls.close();}
strSQL.setLength(0);
strSQL.append(" \n select subj, subjnm, year, edustart, cpsubjseq, subjseq") ;
strSQL.append(" \n from tz_subjseq ") ;
strSQL.append(" \n where subj = " + StringManager.makeSQL(v_subj)) ;
strSQL.append(" \n and year = " + StringManager.makeSQL(v_year)) ;
strSQL.append(" \n and edustart = " + StringManager.makeSQL(v_edustart)) ;
strSQL.append(" \n order by subjseq desc ") ;
ls = connMgr.executeQuery(strSQL.toString());
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
}
catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, strSQL.toString());
throw new Exception("sql = " + strSQL.toString() + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { }}
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return list;
}
/**
* CP과정기수와의 동기화
* @param box
* @return
* @throws Exception
*/
public int UpdateCpsubjseqSync(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
PreparedStatement pstmt = null;
String sql = "";
int isOk = 0;
String v_luserid = box.getSession("userid");
String v_con_subjseq = box.getString("p_con_subjseq");
String v_subj = box.getString("p_subj");
String v_con_year = box.getString("p_con_year");
String v_con_edustart = box.getString("p_con_edustart");
try {
connMgr = new DBConnectionManager();
connMgr.setAutoCommit(false);
sql = " UPDATE tz_subjseq SET ";
sql += " cpsubjseq = ?, luserid = ? , ldate = to_char(sysdate,'YYYYMMDDHH24MISS') ";
sql += " WHERE subj = ? AND year = ? AND edustart = ? ";
pstmt = connMgr.prepareStatement(sql);
int index = 0;
pstmt.setString(++index, v_con_subjseq);
pstmt.setString(++index, v_luserid);
pstmt.setString(++index, v_subj);
pstmt.setString(++index, v_con_year);
pstmt.setString(++index, v_con_edustart);
isOk = pstmt.executeUpdate();
if ( isOk > 0) {
connMgr.commit();
} else {
connMgr.rollback();
}
} catch ( Exception ex ) {
connMgr.rollback();
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) try { connMgr.setAutoCommit(true); } catch ( Exception e ) { }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return isOk;
}
/**
* 학습정보(수강신청자 정보)
* @param box
* @return
* @throws Exception
*/
public ArrayList selectListCpSubjPropose(RequestBox box) throws Exception {
HttpClient client = new HttpClient();
PostMethod httppost = null;
DBConnectionManager connMgr = null;
ListSet ls = null;
StringBuffer strSQL = null;
DataBox dbox = null;
ArrayList list = null;
String v_process = box.getString("p_process");
String v_year = "";
String v_month = "";
String sql = "";
String v_owner = "";
String v_enc = box.getStringDefault("p_enc", "A");
String v_con_subj = box.getString("p_con_subj");
String v_con_edustart = box.getString("p_con_edustart");
String v_subj = "";
String v_execMonth = box.getString("p_execMonth");
try{
connMgr = new DBConnectionManager();
strSQL = new StringBuffer();
strSQL.append(" \n select subj from tz_subj WHERE cpsubj = " + StringManager.makeSQL(v_con_subj));
ls = connMgr.executeQuery(strSQL.toString());
while ( ls.next() ) {
v_subj = ls.getString("subj");
}
if(ls != null){ls.close();}
if(v_enc.equals("A")){ //크레듀
v_owner = "00005";
}else if(v_enc.equals("Y")){ //YBM
v_owner = "00011";
}else if(v_enc.equals("W")){ //윈글리쉬
v_owner = "00010";
}
list = new ArrayList();
strSQL.setLength(0);
strSQL.append("\n select a.* ") ;
strSQL.append("\n from ( ") ;
strSQL.append("\n select d.cpsubj subj, a.year, c.cpsubjseq subjseq, ") ;
strSQL.append("\n b.userid, b.name, b.email, b.handphone mobile, b.userid cono, ") ;
strSQL.append("\n b.zip_cd post, b.address, get_compnm(b.comp) compnm, b.position_nm, b.lvl_nm, ") ;
strSQL.append("\n decode(a.stustatus,'Y','1','2') protype, a.ldate, ") ;
strSQL.append("\n a.subj subj2, a.year year2, a.subjseq subjseq2 ") ;
strSQL.append("\n from tz_student a, tz_member b, tz_subjseq c , tz_subj d ") ;
strSQL.append("\n where a.userid = b.userid ") ;
strSQL.append("\n and a.subj = c.subj ") ;
strSQL.append("\n and a.subjseq = c.subjseq ") ;
strSQL.append("\n and a.year = c.year ") ;
strSQL.append("\n and a.subj = d.subj ") ;
strSQL.append("\n and isclosed !='Y' ") ;
strSQL.append("\n and d.owner = " + StringManager.makeSQL(v_owner)) ;
if(v_process.equals("selectViewSubj")){
strSQL.append("\n and c.edustart = " + StringManager.makeSQL(v_con_edustart)) ; //추가
strSQL.append("\n and c.subj = " + StringManager.makeSQL(v_subj)) ; //추가
} else if(v_process.equals("selectCpProposeUser")){
strSQL.append("\n and c.edustart like '" +v_execMonth + "%'") ; //추가
}
//strSQL.append("\n and substr(a.ldate,0,8) = TO_CHAR(SYSDATE,'YYYYMMDD') ") ;
//strSQL.append("\n and a.stdgubun ='0' ") ;
strSQL.append("\n UNION ALL ") ;
strSQL.append("\n select d.cpsubj subj, a.year, c.cpsubjseq subjseq, ") ;
strSQL.append("\n b.userid, b.name, b.email, b.handphone mobile, b.userid cono, ") ;
strSQL.append("\n b.zip_cd post, b.address, get_compnm(b.comp) compnm, b.position_nm, b.lvl_nm, '2' protype, a.ldate, ") ;
strSQL.append("\n a.subj subj2, a.year year2, a.subjseq subjseq2 ") ;
strSQL.append("\n from tz_cancel a, tz_member b, tz_subjseq c , tz_subj d ") ;
strSQL.append("\n where a.userid = b.userid ") ;
strSQL.append("\n and a.subj = c.subj ") ;
strSQL.append("\n and a.subjseq = c.subjseq ") ;
strSQL.append("\n and a.year = c.year ") ;
strSQL.append("\n and a.subj = d.subj ") ;
strSQL.append("\n and isclosed !='Y' ") ;
//strSQL.append("\n and substr(a.ldate,0,8) = TO_CHAR(SYSDATE,'YYYYMMDD') ") ;
strSQL.append("\n and d.owner = " + StringManager.makeSQL(v_owner)) ;
if(v_process.equals("selectViewSubj")){
strSQL.append("\n and c.edustart = " + StringManager.makeSQL(v_con_edustart)) ; //추가
strSQL.append("\n and c.subj = " + StringManager.makeSQL(v_subj)) ; //추가
}else if(v_process.equals("selectCpProposeUser")){
strSQL.append("\n and c.edustart like '" +v_execMonth + "%'") ; //추가
}
strSQL.append("\n ) a ") ;
strSQL.append("\n where subjseq is not null ") ;
strSQL.append("\n order by protype desc, ldate desc ") ;
ls = connMgr.executeQuery(strSQL.toString());
while(ls.next())
{
Hashtable data = new Hashtable();
data.put("p_subj",ls.getString("subj"));
data.put("p_year",ls.getString("year"));
data.put("p_subjseq",ls.getString("subjseq"));
data.put("p_userid",ls.getString("userid"));
data.put("p_name",ls.getString("name"));
data.put("p_email",ls.getString("email")+" ");
data.put("p_mobile",ls.getString("mobile")+" ");
data.put("p_cono",ls.getString("cono"));
data.put("p_post",ls.getString("post")+" ");
data.put("p_address",ls.getString("address")+" ");
data.put("p_protype",ls.getString("protype"));
data.put("p_compnm",ls.getString("compnm")+" ");
data.put("p_position_nm",ls.getString("position_nm")+" ");
data.put("p_lvl_nm",ls.getString("lvl_nm")+" ");
data.put("p_subj2",ls.getString("subj2"));
data.put("p_year2",ls.getString("year2"));
data.put("p_subjseq2",ls.getString("subjseq2"));
list.add(data);
}
}
catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, strSQL.toString());
throw new Exception("sql = " + strSQL.toString() + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { }}
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return list;
}
/**
* 위탁과정 입과자 정보 동기화
* @param box
* @return
* @throws Exception
*/
public int UpdateCpProposeSync(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
StringBuffer strSQL = null;
DataBox dbox = null;
HttpClient client = new HttpClient();
PostMethod httppost = null;
String ls_result = "";
String sql = "";
String v_enc = box.getString("p_enc");
String v_jobexetype = "PROPOSE";
String lsRecvHttp = "";
try{
connMgr = new DBConnectionManager();
sql = " select callprogram \n";
sql += " from tz_cronjobs_t \n";
sql += " where jobexetype = "+ StringManager.makeSQL(v_jobexetype) +" \n";
sql += " and enc = "+ StringManager.makeSQL(v_enc) +" \n";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
lsRecvHttp = ls.getString("callprogram");
}
if(ls != null){ ls.close(); }
if (lsRecvHttp.equals(""))
{
return -99;
}
if(v_enc != null )
{
ArrayList list = (ArrayList) this.selectListCpSubjPropose(box);
int v_result = 0;
int v_success = 0;
int v_fail = 0;
if(list.size()>0){
for(int i = 0; i <= list.size(); i++){
Hashtable data = (Hashtable)list.get(i);
System.out.println("HTTPCallResult_//:"+lsRecvHttp);
httppost = new PostMethod(lsRecvHttp);
httppost.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=EUC-KR");
httppost.setParameter("p_subj", (String)data.get("p_subj"));//과정코드 세팅
httppost.setParameter("p_year", (String)data.get("p_year"));//과정년도 세팅
httppost.setParameter("p_subjseq", (String)data.get("p_subjseq"));//과정차수 세팅
httppost.setParameter("p_userid", (String)data.get("p_userid"));//사용자 아이디 세팅
httppost.setParameter("p_name", (String)data.get("p_name"));//수강생 이름 세팅
httppost.setParameter("p_email", (String)data.get("p_email"));//수강생 이메일 세팅
httppost.setParameter("p_mobile", (String)data.get("p_mobile"));//수강생 휴대폰번호 세팅
httppost.setParameter("p_cono", (String)data.get("p_cono"));//수강생 사번 세팅
httppost.setParameter("p_post", (String)data.get("p_post"));//수강생 우편번호 세팅
httppost.setParameter("p_addr", (String)data.get("p_address"));//수강생 주소 세팅
httppost.setParameter("p_protype", (String)data.get("p_protype"));//수강생 수강정보 세팅
httppost.setParameter("p_division", (String)data.get("p_compnm"));//수강생 회사 세팅
httppost.setParameter("p_depart", (String)data.get("p_position_nm"));//수강생 부서 세팅
httppost.setParameter("p_position", (String)data.get("p_lvl_nm"));//수강생 직급 세팅
String v_url = "";
v_url = lsRecvHttp+"?p_subj="+ (String)data.get("p_subj")
+"&p_year="+ (String)data.get("p_year")
+"&p_subjseq="+ (String)data.get("p_subjseq")
+"&p_userid="+ (String)data.get("p_userid")
+"&p_name="+ (String)data.get("p_name")
+"&p_email="+ (String)data.get("p_email")
+"&p_mobile="+ (String)data.get("p_mobile")
+"&p_cono="+ (String)data.get("p_cono")
+"&p_post="+ (String)data.get("p_post")
+"&p_addr="+ (String)data.get("p_address")
+"&p_protype="+ (String)data.get("p_protype")
+"&p_division="+(String)data.get("p_compnm")
+"&p_depart="+ (String)data.get("p_position_nm")
+"&p_position="+(String)data.get("p_lvl_nm");//값을셋팅
client.executeMethod(httppost);
v_result = httppost.getStatusCode();
if(v_result == 200){
v_success = v_success + 1;
String v_protype = (String)data.get("p_protype");
if(v_protype.equals("1")){
this.proposeSuccessProcess((String)data.get("p_subj2"),(String)data.get("p_year2"),(String)data.get("p_subjseq2"),(String)data.get("p_userid"));
}
}else{
v_fail = v_fail + 1;
}
} // end for
}// end if
ls_result = "RESULT"+"[LOG=SUCCESS="+v_success+";FAIL = "+v_fail+"]";
}
}
catch(Exception e){
e.printStackTrace();
}
finally {
if(httppost != null) httppost.releaseConnection();
}
return 0 ;
}
/**
* 입과자 신청완료처리
* @param p_datas
* @param p_comp
* @param p_uri
*/
public void proposeSuccessProcess(String p_subj, String p_year, String p_subjseq, String p_userid){
DBConnectionManager connMgr = null;
ListSet ls = null;
StringBuffer strSQL = null;
DataBox dbox = null;
PreparedStatement pstmt = null;
String sql = "";
int isOk = 0;
try {
connMgr = new DBConnectionManager();
connMgr.setAutoCommit(false);
sql = "update tz_student set stdgubun ='Y' where subj=? and year=? and subjseq = ? and userid = ?";
pstmt = connMgr.prepareStatement(sql);
pstmt.setString(1, p_subj);
pstmt.setString(2, p_year);
pstmt.setString(3, p_subjseq);
pstmt.setString(4, p_userid);
isOk = pstmt.executeUpdate();
if(pstmt != null) pstmt.close();
if ( isOk > 0) {
connMgr.commit();
} else {
connMgr.rollback();
}
}catch(Exception e) {
e.printStackTrace();
} finally {
if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) try { connMgr.setAutoCommit(true); } catch ( Exception e ) { }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
}
/**
* 위탁과정 수료자정보 리스트
* @param box
* @return
* @throws Exception
*/
public String selectListCpSubjScore(RequestBox box) throws Exception {
HttpClient client = new HttpClient();
PostMethod httppost = null;
DBConnectionManager connMgr = null;
PreparedStatement pstmt = null;
ListSet ls = null;
String ls_result = "";
String ls_param = box.getString("p_execMonth");
String v_year = "";
String v_month = "";
String lsRecvHttp = "";
String sql = "";
String v_enc = box.getString("p_enc");
try{
connMgr = new DBConnectionManager();
sql = " select \n";
sql += " jobnm, \n";
sql += " callprogram, \n";
sql += " jobexetype, \n";
sql += " jobtimetype, \n";
sql += " starttime, \n";
sql += " exectime, \n";
sql += " jobexcuteyn, \n";
sql += " use_yn, \n";
sql += " param \n";
sql += " from tz_cronjobs_t \n";
sql += " where 1=1 \n";
sql += " and enc = "+StringManager.makeSQL(v_enc)+" \n";
sql += " and jobexetype = '"+JOBEXETYPE_SCORE+"' \n";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
lsRecvHttp = ls.getString("callprogram");
}
if(ls != null) ls.close();
if (lsRecvHttp == null )
{
return "F";
}
if(box.getString("p_execMonth").equals("")){
ls_param = FormatDate.getDate("yyyyMMddHHmmss").substring(0,6);
}
//파라매터 값 지정
v_year = ls_param.substring(0,4);
v_month = ls_param.substring(4,6);
if(v_enc != null )
{
if(v_enc.equals("A")){ //크레듀
lsRecvHttp = lsRecvHttp +"?p_yyyymm="+ls_param;
}else if(v_enc.equals("Y")){ //YBM
lsRecvHttp = lsRecvHttp +"?p_year="+v_year+"&p_month="+v_month;
}else if(v_enc.equals("W")){ //윈글리쉬
lsRecvHttp = lsRecvHttp +"?p_ym="+ls_param;
}
}
//lsRecvHttp = lsRecvHttp +ls_param;
System.out.println("HTTPCallResult_//:"+lsRecvHttp);
httppost = new PostMethod(lsRecvHttp);
httppost.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=EUC-KR");
client.executeMethod(httppost);
System.out.println("httppost.getStatusCode()==="+httppost.getStatusCode());
if (httppost.getStatusCode() == HttpStatus.SC_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(httppost.getResponseBodyAsStream()));
StringBuffer buf = new StringBuffer();
String s = null;
while (null != (s = br.readLine())) {
buf.append(s);
}
br.close();
ls_result = buf.toString();
}
}
catch(Exception e){
ErrorManager.getErrorStackTrace(e);
throw new Exception("\n e.getMessage() : [\n" + e.getMessage() + "\n]");
}
finally {
httppost.releaseConnection();
}
return ls_result ;
}
public static String getSubjnm(String cpsubj) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
String sql = "";
String subjnm = "";
try
{
connMgr = new DBConnectionManager();
String s_subj = cpsubj;
sql =
"\n SELECT subjnm FROM tz_subj WHERE cpsubj = " + SQLString.Format( s_subj );
ls = connMgr.executeQuery( sql );
while ( ls.next() )
{
subjnm = ls.getString( "subjnm" );
}
}
catch (Exception ex)
{
ErrorManager.getErrorStackTrace(ex);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage());
}
finally
{
if(ls != null) { try { ls.close(); }catch (Exception e) {} }
if(connMgr != null) { try { connMgr.freeConnection(); }catch (Exception e10) {} }
}
return subjnm;
}
public int getExecuteCommand(String Command) throws Exception {
System.out.println("init getExecuteCommand");
Process p = null;
System.out.println("ls");
try {
p = Runtime.getRuntime().exec("ls");
p.waitFor ();
if (p.exitValue () != 0) {
BufferedReader err = new BufferedReader (new InputStreamReader (p.getErrorStream ()));
while (err.ready())
System.out.println ("ERR"+err.readLine ());
err.close ();
} else {
BufferedReader out = new BufferedReader (new InputStreamReader (p.getInputStream()));
while (out.ready())
System.out.println ("O K"+ out.readLine ());
out.close ();
}
p.destroy ();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
|
/*
* Copyright 2016 CIRDLES.
*
* 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.
*
*
* This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
* See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
* Any modifications to this file will be lost upon recompilation of the source schema.
* Generated on: 2016.03.03 at 09:06:25 AM EST
*/
package org.geosamples.samples;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SedimentaryDetails.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* {@code
* <xml>
* <simpleType name="SedimentaryDetails">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Carbonate"/>
* <enumeration value="ConglomerateAndOrBreccia"/>
* <enumeration value="Evaporite"/>
* <enumeration value="GlacialAndOrPaleosol"/>
* <enumeration value="Hybrid"/>
* <enumeration value="Ironstone"/>
* <enumeration value="MixedCarbAndOrSiliciclastic"/>
* <enumeration value="MnNoduleAndOrCrust"/>
* <enumeration value="SiliceousBiogenic"/>
* <enumeration value="Siliciclastic"/>
* <enumeration value="Volcaniclastic"/>
* </restriction>
* </simpleType>
* </xml>
* }
* </pre>
*
*/
@XmlType(name = "SedimentaryDetails")
@XmlEnum
public enum SedimentaryDetails {
@XmlEnumValue("Carbonate")
CARBONATE("Carbonate"),
@XmlEnumValue("ConglomerateAndOrBreccia")
CONGLOMERATE_AND_OR_BRECCIA("ConglomerateAndOrBreccia"),
@XmlEnumValue("Evaporite")
EVAPORITE("Evaporite"),
@XmlEnumValue("GlacialAndOrPaleosol")
GLACIAL_AND_OR_PALEOSOL("GlacialAndOrPaleosol"),
@XmlEnumValue("Hybrid")
HYBRID("Hybrid"),
@XmlEnumValue("Ironstone")
IRONSTONE("Ironstone"),
@XmlEnumValue("MixedCarbAndOrSiliciclastic")
MIXED_CARB_AND_OR_SILICICLASTIC("MixedCarbAndOrSiliciclastic"),
@XmlEnumValue("MnNoduleAndOrCrust")
MN_NODULE_AND_OR_CRUST("MnNoduleAndOrCrust"),
@XmlEnumValue("SiliceousBiogenic")
SILICEOUS_BIOGENIC("SiliceousBiogenic"),
@XmlEnumValue("Siliciclastic")
SILICICLASTIC("Siliciclastic"),
@XmlEnumValue("Volcaniclastic")
VOLCANICLASTIC("Volcaniclastic");
private final String value;
SedimentaryDetails(String v) {
value = v;
}
public String value() {
return value;
}
public static SedimentaryDetails fromValue(String v) {
for (SedimentaryDetails c: SedimentaryDetails.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
|
package com.energytrade.app.dto;
import java.util.Date;
import java.util.List;
import com.energytrade.app.model.UserDRDevices;
public class CustomerEventMappingDetailsDto extends AbstractBaseDto {
/**
*
*/
private static final long serialVersionUID = 1L;
private int eventCustomerMappingId;
private Date bidTs;
private Double bidPrice;
private Double committedPower;
private Double actualPower;
private int eventCustomerStatus;
private String counterBidFlag;
private Double counterBidAmount;
private Date createdTs;
private List<DRDeviceDto> mappedDevices;
private double customerFine;
private double earnings;
private String isFineApplicable;
public double getEarnings() {
return earnings;
}
public void setEarnings(double earnings) {
this.earnings = earnings;
}
public double getCustomerFine() {
return customerFine;
}
public void setCustomerFine(double customerFine) {
this.customerFine = customerFine;
}
public String getIsFineApplicable() {
return isFineApplicable;
}
public void setIsFineApplicable(String isFineApplicable) {
this.isFineApplicable = isFineApplicable;
}
public int getEventCustomerMappingId() {
return eventCustomerMappingId;
}
public void setEventCustomerMappingId(int eventCustomerMappingId) {
this.eventCustomerMappingId = eventCustomerMappingId;
}
public Date getBidTs() {
return bidTs;
}
public void setBidTs(Date bidTs) {
this.bidTs = bidTs;
}
public Double getBidPrice() {
return bidPrice;
}
public void setBidPrice(Double bidPrice) {
this.bidPrice = bidPrice;
}
public Double getCommittedPower() {
return committedPower;
}
public void setCommittedPower(Double committedPower) {
this.committedPower = committedPower;
}
public Double getActualPower() {
return actualPower;
}
public void setActualPower(Double actualPower) {
this.actualPower = actualPower;
}
public int getEventCustomerStatus() {
return eventCustomerStatus;
}
public void setEventCustomerStatus(int eventCustomerStatus) {
this.eventCustomerStatus = eventCustomerStatus;
}
public String getCounterBidFlag() {
return counterBidFlag;
}
public void setCounterBidFlag(String counterBidFlag) {
this.counterBidFlag = counterBidFlag;
}
public Double getCounterBidAmount() {
return counterBidAmount;
}
public void setCounterBidAmount(Double counterBidAmount) {
this.counterBidAmount = counterBidAmount;
}
public Date getCreatedTs() {
return createdTs;
}
public void setCreatedTs(Date createdTs) {
this.createdTs = createdTs;
}
public List<DRDeviceDto> getMappedDevices() {
return mappedDevices;
}
public void setMappedDevices(List<DRDeviceDto> mappedDevices) {
this.mappedDevices = mappedDevices;
}
}
|
import java.util.Scanner;
public class inVoice {
public static void main(String[] args) {
int orderedShirts, orederdTrousers, points=0;
int priceOfShirt = 300;
int priceofTrouser = 700;
int costOfShirts, costOfTrousers, Totalcost;
double discount, netPay;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of Shirts to order: ");
orderedShirts = input.nextInt();
System.out.println("Enter the number of Trousers to order: ");
orederdTrousers = input.nextInt();
costOfShirts = priceOfShirt * orderedShirts;
costOfTrousers = priceofTrouser * orederdTrousers;
Totalcost = costOfShirts + costOfTrousers;
discount = Totalcost > 3000? Totalcost * 10/100 :0;
netPay = Totalcost - discount;
points = (int) (netPay > 3000? netPay/100 :0);
// Display
System.out.println("\n Item \t\t Quanity \t Price \t Total ");
System.out.println("________________________________________________");
System.out.printf("Shirts \t\t %d\t\t %d\t\t %d\n ", orderedShirts, priceOfShirt, costOfShirts);
System.out.printf("Trouser \t\t %d\t\t %d\t\t %d\n", orederdTrousers, priceofTrouser, costOfTrousers);
System.out.printf("Discout \t \t\t \t\t\t\t %.2f \n", discount);
System.out.println("_________________________________");
System.out.printf("Net total \t \t\t \t\t\t\t %.2f \n", netPay);
System.out.println("_________________________________");
System.out.printf("Points Earned : \t %d \n ", points);
System.out.println("Thanks U!");
}
}
|
package com.futs.model;
import lombok.Data;
import javax.persistence.*;
@Data
@Entity
@Table(schema = "DB_FUTTS", name = "TB_GOL")
public class Gol {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer codigoGol;
@Column(name = "IDJOGO", unique = true, nullable = false)
private Integer idJogo;
@Column(name = "IDTJOGADOR", unique = true, nullable = false)
private String idtJogador;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "IDJOGO", referencedColumnName = "ID", insertable = false, updatable = false)
private Jogo jogo;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "IDTJOGADOR", referencedColumnName = "IDT", insertable = false, updatable = false)
private Jogador jogador;
}
|
package Football;
import java.io.*;
import java.util.*;
import java.util.Random;
class Football{
final static int MAXTEAM = 16;
public static void main (String[] args)
{
// ArrayList<Team> allteams = new ArrayList<Team>();
//getTeams (allteams,"teams.foot.txt");
// getTeams (allteams,"/home/andre/eclipse-workspace/Football/bin/Football/EQUIPAS.EF2");
//Match mtest = new Match (allteams.get(0),allteams.get(1));
//System.out.println(allteams.get(0));
//System.out.println(allteams.get(1));
ArrayList<Team> league1 = new ArrayList<Team>();
ArrayList<Team> league2 = new ArrayList<Team>();
ArrayList<Team> league3 = new ArrayList<Team>();
ArrayList<Team> league4 = new ArrayList<Team>();
TeamLoader loader = new TeamLoader("/home/andre/eclipse-workspace/Football/bin/Football/EQUIPAS.EF2");
loader.getLeague(league1,8);
Tournament t = new Tournament(league1);
t.genGames();
System.out.println(t);
int i = 0;
league1.get(0).setTactics(5 ,1, 3);
System.out.println(league1.get(i)
+ "\n size attack:"+ league1.get(i).attack.size()
+ "\n size middle:"+ league1.get(i).middle.size()
+ "\n size defence:"+ league1.get(i).defence.size()
+ "\n size gk:"+ league1.get(i).gkeaper.size()
+ "\n size bench:"+ league1.get(i).bench.size()
);
/*
loader.getLeagues(league1, league2, league3, league4);
for (int i =0;i< league1.size();i++) {
System.out.println(league1.get(i).name);
for(int j=0;j<league1.get(i).players.size();j++)
System.out.println("pos: " + j + league1.get(i).players.get(j).nationality);
}
int i=0;
System.out.println(league1.get(i)
+ "\n size attack:"+ league1.get(i).attack.size()
+ "\n size middle:"+ league1.get(i).middle.size()
+ "\n size defence:"+ league1.get(i).defence.size()
+ "\n size gk:"+ league1.get(i).gkeaper.size()
+ "\n size bench:"+ league1.get(i).bench.size()
);
*/
// mtest.gameOn();
}
public static void getTeams (ArrayList<Team> allteams, String playersFile)
{
boolean notend = false;
int numberofteams =0;
Team team;
Player player;
String temp1;
int i;
StringTokenizer tokens;
try{
FileInputStream teams = new FileInputStream(playersFile);
BufferedReader f = new BufferedReader (new InputStreamReader(teams));
temp1 = f.readLine();
do{
System.out.println ("OK4");
tokens = new StringTokenizer(temp1);
team = createTeam(tokens);
System.out.println ("OK1");
setColors(team, f);
System.out.println ("OK3");
//temp2 = getTeamName (tokens);
// System.out.println("Team name: " + temp2);
for (i=0;i<16;i++)
{
player = getPlayer(f);
team.addPlayer(player);
}
do
{
notend=false;
temp1 = f.readLine();
System.out.println("Ok5" +temp1+"!");
if(temp1==null)
notend = false;
else if (temp1.equals(""))
notend = true;
}while (notend);
allteams.add(team);
numberofteams ++;
}while (temp1!=null);
System.out.println("Number of teams " + numberofteams);
//System.out.println ("Team1:\n" + allteams[0]); //+ "Team2:\n" + allteams[1]);
//System.out.println(allteams);
}catch (Exception e)
{System.out.println("Exception!" + e);}
}
static Player getPlayer(BufferedReader buf) throws IOException
{
Player player = null;
String name,type, nationality;
StringTokenizer tokens= new StringTokenizer(buf.readLine());
int i, nt = tokens.countTokens();
name = tokens.nextToken();
nt = nt -3;
for(i=0;i<nt;i++)
{
name = " " + tokens.nextToken();
}
type = tokens.nextToken();
nationality = tokens.nextToken();
// for the force, pick up a number between 9 and 13
Random rand = new Random();
int force = rand.nextInt(5)+9;
if (type.equals("gr"))
player = new GKeaper(force,name,nationality);
else if ( type.equals("md"))
player = new Middle(force,name,nationality);
else if ( type.equals("df"))
player = new Defence(force,name,nationality);
else if (type.equals("av"))
player = new Attack(force,name,nationality);
else
System.out.println("AYBABTU: Strange player:" + type + "!");
return player;
}
static String getTeamName(StringTokenizer tokens)
{
String teamName;
int i,noftokens = tokens.countTokens();
teamName = tokens.nextToken();
for(i = 2; i<noftokens; i++)
{
teamName = teamName + " " + tokens.nextToken();
}
return teamName;
}
static void setColors (Team team, BufferedReader buf) throws IOException
{
int color1, color2;
color1 = Integer.parseInt(buf.readLine().trim());
color2 = Integer.parseInt(buf.readLine().trim());
team.setColor1(color1);
team.setColor2(color2);
}
static Team createTeam (StringTokenizer tokens)
{
String teamname;
String nationality;
teamname = getTeamName(tokens);
nationality = tokens.nextToken();
return (new Team(teamname, nationality));
}
}
|
package com.mahang.weather.base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public abstract class MvpBaseActivity extends BaseActivity {
private List<MvpBasePresenter> mPresenterList;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void addPresenter(MvpBasePresenter presenter){
if (mPresenterList == null){
mPresenterList = new ArrayList<>();
}
mPresenterList.add(presenter);
}
@Override
protected void onDestroy() {
if (mPresenterList != null){
for (MvpBasePresenter presenter : mPresenterList){
presenter.onDestroy();
}
}
super.onDestroy();
}
}
|
public class HardException extends Exception implements Red{
String whyred;
String panelty;
HardException(String whyred, String panelty){
super("This exception cannot be ignored");
this.whyred= whyred;
this.panelty = panelty;
}
public String whyred() {
return whyred;
}
@Override
public String penalty() {
return panelty;
}
public String toString (){
try {
throw new Exception("This exception must be addressed because "+whyred()+" and the penalty is '"+penalty()+"'");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// this is dummy, it will never get here.
return "";
}
} |
package oracle.ocp.locale;
import java.util.Locale;
import java.util.ResourceBundle;
public class LocalizedHello {
public static void main(String args[]) {
Locale currentLocale = Locale.getDefault();
ResourceBundle resBundle = ResourceBundle.getBundle("ResourceBundle", currentLocale);
System.out.println(resBundle.getString("Greeting"));
currentLocale = Locale.ITALIAN;
ResourceBundle resourceBundleIt = ResourceBundle.getBundle("ResourceBundle", currentLocale);
System.out.println(resourceBundleIt.getString("Greeting"));
}
}
|
package cn.tedu.date;
import java.text.SimpleDateFormat;
import java.util.Date;
/*本类用于测试SimpleDateFormat*/
public class TestSDF {
public static void main(String[] args) {
Date d=new Date();
//2.创建日期格式转换工具类对象,此时使用的是无参构造
SimpleDateFormat sdf=new SimpleDateFormat();
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String s = sdf2.format(d);
System.out.println(s);
}
}
|
package holderVtwo;
import holder.ListNode;
import holder.TreeNode;
import holder.*;
import java.util.*;
public class SolverPa {
public static void main(String[] args) {
int[] nums = { 5, 7, 10, 4, 2, 7, 8, 1, 3 };
// System.out.println(5/2);
// subsets(nums);
HashMap<Integer, Integer> nMap = new HashMap<>();
// nMap.getOrDefault(key, defaultValue)
// reverseAscendingSubArrays(nums);
Person oneP = Person.getInstance(45);
Person oneTwo = Person.getInstance(20);
oneTwo.weight = 100;
System.out.println(oneP.weight);
System.out.println(oneTwo.weight);
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
int g= 10;
int sd=14;
nMap.put(g,sd);
System.out.println(nMap.get(g));
// System.out.println(migratoryBirds(list));
// .list.co
PriorityQueue<Integer> pQ = new PriorityQueue<>();
// pQ.is
}
}
public static void reverseAscendingSubArrays(int[] items) {
int leftCounter = 0;
int rightCounter = 1;
int totalCounter = 0;
int temp = 0;
int miniLenght = 0;
while (rightCounter < items.length) {
if (items[leftCounter] > items[rightCounter]) {
if (items[leftCounter] > items[rightCounter] && items[leftCounter] < temp) {
leftCounter++;
rightCounter++;
totalCounter++;
continue;
}
int newLenght = items.length - rightCounter;
newLenght = newLenght - totalCounter;
int lengthOfSubArray = items.length - leftCounter;
// int lengthOfSubArray = items.length-totalCounter;
lengthOfSubArray = items.length - lengthOfSubArray + 1;
temp = reverse(items, miniLenght, temp);
rightCounter++;
leftCounter++;
totalCounter = lengthOfSubArray;
} else {
rightCounter++;
miniLenght = (items.length - rightCounter) - (rightCounter - leftCounter + 1);
if (miniLenght < 1)
miniLenght = miniLenght * -1;
leftCounter++;
}
}
}
public static int reverse(int a[], int n, int tempOne) {
int leftCounter = 0;
int rightCounter = n - 1;
tempOne = a[rightCounter];
while (rightCounter > leftCounter) {
int temp = a[leftCounter];
a[leftCounter] = a[rightCounter];
a[rightCounter] = temp;
rightCounter--;
leftCounter++;
}
return tempOne;
}
public static List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> resultList = new ArrayList<>();
subSetsHelper(nums, resultList, new ArrayList<Integer>(), 0);
return resultList;
}
public static void subSetsHelper(int nums[], List<List<Integer>> resultList, ArrayList<Integer> holder, int index) {
// resultList.add(new ArrayList<>(holder));
resultList.add((holder));
if (index > nums.length) {
return;
}
List<Integer> temp = new ArrayList<>();
for (int i = index; i < nums.length; i++) {
holder.add(nums[i]);
subSetsHelper(nums, resultList, holder, i + 1);
holder.remove(holder.size() - 1);
}
}
public static int maxProfit(int[] prices) {
int maxprofit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1])
maxprofit += prices[i] - prices[i - 1];
}
return maxprofit;
}
public static void listFcn(ArrayList<Integer> list, int value) {
if (list.contains(10)) {
// return list;
}
list.add(10);
}
}
|
package com.teaboot.web.manager;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.teaboot.web.server.NettyServiceTemplate;
public class WebManager {
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
private static class WebManagerContainer {
private static WebManager instance = new WebManager();
}
public static WebManager getInstance() {
return WebManagerContainer.instance;
}
public static void addTask(Runnable t) {
getInstance().cachedThreadPool.submit(t);
}
public static void addServer(NettyServiceTemplate server) {
getInstance().cachedThreadPool.submit(new Thread() {
@Override
public void run() {
try {
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
|
package kr.co.magiclms.mypage.controller;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
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 com.oreilly.servlet.MultipartRequest;
import kr.co.magiclms.common.db.MyAppSqlConfig;
import kr.co.magiclms.common.file.MlecFileRenamePolicy;
import kr.co.magiclms.domain.Content;
import kr.co.magiclms.mapper.ContentMapper;
@WebServlet("/mypage/contentRegist")
public class WriteContentController extends HttpServlet{
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ContentMapper mapper = MyAppSqlConfig.getSqlSession().getMapper(ContentMapper.class);
String uploadPath = "c:/java-lec/content_upload";
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/HH");
String datePath = sdf.format(new Date());
File file = new File(uploadPath + datePath);
if(!file.exists()) file.mkdirs();
MultipartRequest mRequest = new MultipartRequest(
request,
uploadPath + datePath,
1024*1024*100,
"utf-8",
new MlecFileRenamePolicy());
Content content = new Content();
content.setContentNo(Integer.parseInt(mRequest.getParameter("contentNo")));
content.setTitle(mRequest.getParameter("title"));
content.setRef(mRequest.getParameter("ref"));
mapper.insertContent(content);
// Save File(s)
Enumeration<String> names = mRequest.getFileNames();
while(names.hasMoreElements()) {
String name = names.nextElement();
File f = mRequest.getFile(name);
if(f!=null) {
String origName = mRequest.getOriginalFileName(name);
String sysName = mRequest.getFilesystemName(name);
Content contFile = new Content();
contFile.setFilePath(datePath);
contFile.setOrigName(origName);
contFile.setSysName(sysName);
mapper.insertContentFile(contFile);
}
}
response.sendRedirect("contentList");
}
}
|
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
/*
* handles the data going through this to find the data between the sql and java for users
*/
/**
*
* @author Admin
*/
public class GCUUser_Data_Handler {
Connection con;
PreparedStatement pst;
public GCUuser getValidUser(GCUuser pUser){
// boolean userExistsInDatabase = false;
DB_Utils.isDatabaseDriversExist(); // check that ucanaccess drivers exist
try
{
ResultSet rs = pst.executeQuery ("SELECT * FROM user WHERE username='" + pUser.getUsername()+ "' AND " + " passcode =" + pUser.getPassCode());
rs.next();//move to first record
pUser.setID(rs.getString("ID"));
pUser.setFirstName(rs.getString("firstname"));
pUser.setLastName(rs.getString("lastname"));
pUser.setPassCode(Integer.parseInt(rs.getString("passcode")));
pUser.setGcuRole(rs.getString("role"));
}
catch(SQLException e)
{
System.out.println("getValidUser : Error");
System.out.println("SQL exception occured" + e);
}
//==========================================================='
return pUser;
}
public boolean checkUserIsValid(GCUuser pUser){
boolean userExistsInDatabase = false;
try
{
Connection con = DB_Utils.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery ("SELECT * FROM user WHERE username='" + pUser.getUsername()+ "' AND " + " passcode=" + pUser.getPassCode());
while (rs.next())
{
userExistsInDatabase=true; // set if at least one record is found
}
}
catch(SQLException ex)
{
System.out.println("checkUserIsValid : Error");
System.out.println("SQL exception occured\n" + ex);
}
//==========================================================='
return (userExistsInDatabase);
}
protected void createDatabase(){
try{
/*This method is essential for creating the database from the localhost if it does
not already exists it provides the necessary means the database and tables required to
be created.
It should be noted that mysql-connector-java file needs to be attached to library
and mysql needs to be running on machine.
*/
String database = "jdbc:mysql://localhost/";
String username = "root";
String password = "Password";
con = DriverManager.getConnection(database, username, password);
String sql = "CREATE DATABASE IF NOT EXISTS GCUBake";
pst = con.prepareStatement(sql);
pst.execute();
con.close();
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
protected void startConnection(){
try{
/* The details below may need to be adjust in order to connect on the local machine.
Mysql database in combination with the mysql-connector-java.jar (added to library) file will be required
in order to provide full functionality to the program and its database.
*/
String mysqlUrl = "jdbc:mysql://localhost/GCUBake";
String username = "root";
String password = "Password";
con = DriverManager.getConnection(mysqlUrl, username, password);
}
catch(Exception e){
System.err.println("Got an exception");
System.err.println(e.getMessage());
}
}
protected void createTables(){
try{
startConnection();
//A backend method which creates the tables on the specified unit if it does not exist
String createQuery1 = "CREATE TABLE IF NOT EXISTS User("
+ "userID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(userID),"
+ "customerStatus TEXT,"
+ "title TEXT,"
+ "firstname TEXT,"
+ "lastname TEXT,"
+ "contactNo TEXT,"
+ "email TEXT,"
+ "username TEXT,"
+ "password TEXT);";
pst = con.prepareStatement(createQuery1);
pst.execute();
String createQuery2 = "CREATE TABLE IF NOT EXISTS Staff("
+ "staffID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(staffID),"
+ "role TEXT,"
+ "firstname TEXT,"
+ "lastname TEXT,"
+ "contactNo TEXT,"
+ "email TEXT,"
+ "username TEXT,"
+ "password TEXT);";
pst = con.prepareStatement(createQuery2);
pst.execute();
String createQuery3 = "CREATE TABLE IF NOT EXISTS Login("
+ "loginID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(loginID),"
+ "username TEXT,"
+ "password TEXT);";
pst = con.prepareStatement(createQuery3);
pst.execute();
String createQuery4 = "CREATE TABLE IF NOT EXISTS Lessons("
+ "lessonID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(lessonID),"
+ "lessonType TEXT,"
+ "lessonSatus TEXT)";
pst = con.prepareStatement(createQuery4);
pst.execute();
con.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
public void DeleteUser()
{
}
}//end of class
|
package com.vmerkotan.quiz.model;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="questions")
public class Question implements Serializable {
private static final long serialVersionUID = -7985996092530054494L;
@Id
private long id;
@Column(name = "question_string")
private String questionString;
@Column(name = "author")
private String author;
@Column(name = "created_date")
private Timestamp createdDate;
@Column(name = "question_type")
private String questionType;
@OneToMany(fetch = FetchType.LAZY,mappedBy="questionId",cascade = CascadeType.ALL)
private List<Answer> answers = new ArrayList<>();
public List<Answer> getAnswers() {
return answers;
}
public Long getId() {
return id;
}
public String getQuestionString() {
return questionString;
}
@Override
public String toString() {
return String.format("Question[id=%d, text='%s', author='%s', createdDate='%s', questionType='%s', answers='%d']",
id, questionString, author, createdDate, questionType, answers.size());
}
}
|
package com.xxzzsoftware.game;
import android.os.Bundle;
import android.view.Menu;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
public class MainActivity extends AndroidApplication {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
cfg.useGL20 = true;
cfg.useAccelerometer = false;
cfg.useCompass = false;
initialize(new Game(), cfg);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
|
package Courier.CourierService.Repositories;
import java.util.List;
import Courier.CourierService.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import CourierModels.Route;
import CourierService.hibernate.HibernateUtil;
public class RouteRepository {
public List<Route> Get()
{
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
List<Route> routes = session.createQuery("from Route").list();
session.close();
return routes;
}
}
|
package com.asm.entities.worker;
import com.asm.entities.worker.salaries.SalaryIteration;
import com.asm.entities.worker.salaries.SalaryType;
import com.asm.entities.worker.workhistory.WorkHistory;
import java.util.ArrayList;
import java.util.List;
public class Employee {
private String id;
private String name;
private String surnames;
private Genre genre;
private String birthDate;
private String rfc;
private String email;
private String phone;
private Address address;
private String position;
private List<String> specialties;
private List<WorkHistory> workHistory;
private SalaryInfo paysheet;
private int qualification;
private String active;
public Employee() {
this.id = "";
this.name = "";
this.surnames = "";
this.genre = Genre.Otro;
this.rfc = "";
this.email = "";
this.phone = "";
this.address = new Address();
this.position = "";
this.workHistory = new ArrayList<>();
this.paysheet = new SalaryInfo(0, SalaryType.NOTSET, SalaryIteration.Sin_Establecer, 5553);
this.qualification = 0;
this.active = "true";
}
public Employee(String id, String name, String surnames) {
this.id = id;
this.name = name;
this.surnames = surnames;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurnames() {
return surnames;
}
public void setSurnames(String surnames) {
this.surnames = surnames;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public Genre getGenre() {
return genre;
}
public void setGenre(Genre genre) {
this.genre = genre;
}
public String getRfc() {
return rfc;
}
public void setRfc(String rfc) {
this.rfc = rfc;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<String> getSpecialities() {
return specialties;
}
public void setSpecialities(List<String> specialities) {
this.specialties = specialities;
}
public int getQualification() {
return qualification;
}
public void setQualification(int qualification) {
this.qualification = qualification;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public List<WorkHistory> getWorkHistory() {
return workHistory;
}
public void setWorkHistory(List<WorkHistory> workHistory) {
this.workHistory = workHistory;
}
public SalaryInfo getPaysheet() {
return paysheet;
}
public void setPaysheet(SalaryInfo paysheet) {
this.paysheet = paysheet;
}
@Override
public String toString() {
return name + " " + surnames;
}
}
|
package pers.mine.scratchpad.base.lambda;
import java.util.UUID;
public class LambdaMan {
Demo d = new Demo("LambdaMan demo");
public void lambdaCaller(FunactionDemoA fd) {
System.out.println("void FunactionDemoA.test()");
fd.test();
// StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
// for (StackTraceElement ste : stackTrace) {
// System.out.println(ste);
// }
return;
}
public void lambdaCaller(FunactionDemoB fd) {
System.out.println("void FunactionDemoB.test(String)");
fd.test(UUID.randomUUID().toString());
return;
}
public void lambdaCaller(FunactionDemoC fd) {
System.out.println("boolean FunactionDemoC.test()");
System.out.println("return:" + fd.test());
return;
}
public void lambdaCaller(FunactionDemoD fd) {
System.out.println("String FunactionDemoD.test()");
System.out.println("return:" + fd.test());
return;
}
public void lambdaCaller(FunactionDemoE fd) {
System.out.println("String FunactionDemoD.test(String)");
System.out.println("return:" + fd.test("我是参数"));
return;
}
public void lambdaCallerF(FunactionDemoF fd) {
System.out.println("String FunactionDemoD.test(String)");
fd.test(d);
return;
}
public static void methodA() {
System.out.println(String.format("%s:验证方法引用", System.nanoTime()));
}
public static void main(String[] args) {
LambdaMan man = new LambdaMan();
// man.lambdaCaller(() -> {
// System.out.println(String.format("%s:输出A", System.nanoTime()));
// });
//
// man.lambdaCaller(s -> {
// System.out.println(String.format("%s:输出B", System.nanoTime(), s));
// });
// man.lambdaCaller(() -> true);// 忽略return写法
// man.lambdaCaller(() -> "叫我返回值");
// man.lambdaCaller(s -> "直接返回 ->" + s);
Demo e = new Demo("123");
man.lambdaCaller(LambdaMan::methodA); //静态方法引用
man.lambdaCaller(e::objectMethodA); //实例方法引用
man.lambdaCallerF(Demo::classMethodF); //类调用实例方法引用
man.lambdaCaller(new FunactionDemoA() {
@Override
public void test() {
System.out.println("123");
}
});
man.lambdaCaller(()->System.out.println("123"));
}
}
|
package com;
import java.time.LocalDate;
import business.abstracts.ScoreService;
import business.concretes.KidsScoreCalculator;
import business.concretes.ManScoreCalculator;
import business.concretes.OldsScoreCalculator;
import business.concretes.WomenScoreCalculator;
import entities.concretes.Game;
import entities.concretes.Gamer;
public class Main {
public static void main(String[] args) {
Gamer gamer1 = new Gamer(1,"1234567832124","İbrahim","Dos",LocalDate.of(1978, 6, 2),1);
Gamer gamer2= new Gamer(2," 2345768768673","Ali","Şimşek",LocalDate.of(2005, 3, 29),1 );
Gamer gamer3 = new Gamer(3,"1234598021321","Cemre","Yıldız",LocalDate.of(1934, 8, 21),2);
Game game1 = new Game(1,"Valorant","FPS",500,50);
Game game2 = new Game(2,"CS-GO","FPS",500,70);
Game game3 = new Game(3,"Call Of Duty","FPS",5000,90);
ScoreService scoreService = new ManScoreCalculator();
scoreService.calculateScore(gamer1, 100);
ScoreService scoreService1 = new KidsScoreCalculator();
scoreService1.calculateScore(gamer2, 100);
ScoreService scoreService2 = new OldsScoreCalculator();
scoreService2.calculateScore(gamer3, 100);
}
}
|
package com.niit.model;
import java.util.ArrayList;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
@Table(name="My_Job", schema="ANGULARDB")
@Entity
public class MyJob {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
private long jobId;
@Size(min=5, max=50, message="Job Title should be 5 - 50 characters.")
private String title;
@Size(min=5, max=300, message="Your description should be between 5 - 300 characters.")
private String description;
private Date dated;
@Size(min=2, max=50, message="Your qualifications should be between 2 - 50 characters.")
private String qualification;
private String status;
@Size(min=3, max=30, message="Your company name should be between 3 - 30 characters.")
private String Companyname;
private Integer userId;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public long getJobId() {
return jobId;
}
public void setJobId(long jobId) {
this.jobId = jobId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getDated() {
return dated;
}
public void setDated(Date dated) {
this.dated = dated;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCompanyname() {
return Companyname;
}
public void setCompanyname(String companyname) {
Companyname = companyname;
}
}
|
/**
*
*/
package com.vinodborole.portal.persistence.model;
import java.io.Serializable;
/**
* @author vinodborole
*
*/
public class PortalAccountProductConfigId implements Serializable {
/**
*
*/
private static final long serialVersionUID = 43577177999231931L;
private long accounts;
private long products;
/**
* @return the accounts
*/
public long getAccounts() {
return accounts;
}
/**
* @param accounts
* the accounts to set
*/
public void setAccounts(long accounts) {
this.accounts = accounts;
}
/**
* @return the products
*/
public long getProducts() {
return products;
}
/**
* @param products
* the products to set
*/
public void setProducts(long products) {
this.products = products;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (accounts ^ (accounts >>> 32));
result = prime * result + (int) (products ^ (products >>> 32));
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PortalAccountProductConfigId other = (PortalAccountProductConfigId) obj;
if (accounts != other.accounts)
return false;
if (products != other.products)
return false;
return true;
}
}
|
package br.com.webscraping.b3.model;
import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class AtivoBovespa {
@Id
private String codigo;
private String acao;
private String tipo;
private BigDecimal quantidadeTeorica;
private BigDecimal participacao;
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getAcao() {
return acao;
}
public void setAcao(String acao) {
this.acao = acao;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public BigDecimal getQuantidadeTeorica() {
return quantidadeTeorica;
}
public void setQuantidadeTeorica(BigDecimal quantidadeTeorica) {
this.quantidadeTeorica = quantidadeTeorica;
}
public BigDecimal getParticipacao() {
return participacao;
}
public void setParticipacao(BigDecimal participacao) {
this.participacao = participacao;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codigo == null) ? 0 : codigo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AtivoBovespa other = (AtivoBovespa) obj;
if (codigo == null) {
if (other.codigo != null)
return false;
} else if (!codigo.equals(other.codigo))
return false;
return true;
}
public void setPorCodigo(Integer codigo, String valor) {
if(codigo == 0) {
this.codigo = valor;
return;
}
if(codigo == 1) {
this.acao = valor;
return;
}
if(codigo == 2) {
this.tipo = valor;
return;
}
if(codigo == 3) {
this.quantidadeTeorica = recuperaString(valor);
return;
}
if(codigo == 4) {
this.participacao = recuperaString(valor);
return;
}
}
public BigDecimal recuperaString(String str)
{
str = str.replace(".","");
str = str.replace(",", ".");
str = str.trim();
return new BigDecimal(str);
}
}
|
package com.joalib.DAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.joalib.DAO.DAO;
import com.joalib.DTO.Board_CommentDTO;
import com.joalib.DTO.member_alarmDTO;
import com.joalib.DTO.memberinfoDTO;
public class memberinfoDAO {
SqlSessionFactory sqlfactory;
//�̱��� ����
private static memberinfoDAO instance;
public static memberinfoDAO getinstance() {
if (instance == null) { // >DAO ��ü ������ �־�?
synchronized (memberinfoDAO.class) {
instance = new memberinfoDAO(); }
}
return instance;
}
public memberinfoDAO(){
try {
Reader reader = Resources.getResourceAsReader("com/joalib/DAO/mybatis_test-config.xml"); //xml ����
sqlfactory = new SqlSessionFactoryBuilder().build(reader); //batis�� �����ϴ� ����.
} catch (IOException e) {
e.printStackTrace();
}
}
//
//insert
public int memberInsert (memberinfoDTO dto) {
SqlSession sqlsession = sqlfactory.openSession();
int i = sqlsession.insert("memberInsert", dto);
sqlsession.commit();
sqlsession.close();
return i;
}
//id üũ�ϰ� pw,name���� �ƿ�
public memberinfoDTO memberIDCheck(String checkID) {
SqlSession sqlsession = sqlfactory.openSession();
memberinfoDTO memberinfo = sqlsession.selectOne("memberLoginCheck", checkID);
sqlsession.commit();
sqlsession.close();
return memberinfo;
}
//ȸ�����Խ� point�߰�
public int pointInsert(String member_id) {
SqlSession sqlsession = sqlfactory.openSession();
int i = sqlsession.insert("newMemberPointInsert", member_id);
sqlsession.commit();
sqlsession.close();
return i;
}
//ȸ��Ż��
public int memberDel (String member_id) {
SqlSession sqlsession = sqlfactory.openSession();
//ȸ�� ������ ������ �ִ� ���͵��� ���켼��
sqlsession.delete("memberDeleteFault", member_id);
sqlsession.delete("memberDeleteBoardcomment", member_id);
sqlsession.delete("memberDeleteBoard", member_id);
sqlsession.delete("memberDeletePoint", member_id);
System.out.println("dao1");
int i = sqlsession.delete("memberDelete", member_id);
sqlsession.commit();
sqlsession.close();
return i;
}
//ȸ�� ���� ����
public memberinfoDTO memberinfoSelectAll(String member_id) {
SqlSession sqlsession = sqlfactory.openSession();
memberinfoDTO dto = sqlsession.selectOne("memberinfoSelectAll", member_id);
sqlsession.commit();
sqlsession.close();
return dto;
}
//ȸ������ ����
public int memberinfoChange(memberinfoDTO dto) {
SqlSession sqlsession = sqlfactory.openSession();
int i = sqlsession.update("memberinfoChange", dto);
sqlsession.commit();
sqlsession.close();
return i;
}
////////////////////// 알림 ///////////////////////
public List<member_alarmDTO> memberAlarmView(String member_id) {
SqlSession sqlsession = sqlfactory.openSession();
List<member_alarmDTO> list = sqlsession.selectList("memberAlarmView", member_id);
sqlsession.commit();
sqlsession.close();
return list;
}
public int AlarmCheck(member_alarmDTO dto) {
SqlSession sqlsession = sqlfactory.openSession();
int i = sqlsession.update("alarmCheckChange", dto );
//System.out.println("DAO 실행 완료");
sqlsession.commit();
sqlsession.close();
return i;
}
}
|
package com.meetingapp.android.activities.contacts;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.widget.TabHost;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.meetingapp.android.R;
import com.meetingapp.android.activities.base.BaseActivity;
import com.meetingapp.android.activities.create_meeting.pick_contacts.PickContactActivity;
import com.meetingapp.android.activities.edit_profile.EditGroupActivity;
import com.meetingapp.android.activities.home.HomeActivity;
import com.meetingapp.android.constants.Constants;
import com.meetingapp.android.firebase.DatabaseManager;
import com.meetingapp.android.fragments.contacts.ContactListAdapter;
import com.meetingapp.android.fragments.contacts.GroupListAdapter;
import com.meetingapp.android.model.Contact;
import com.meetingapp.android.model.UserGroup;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import static com.meetingapp.android.constants.Constants.EDIT_GROUP_PICKER;
import static com.meetingapp.android.constants.Constants.KEY_CONTACTS;
import static com.meetingapp.android.constants.Constants.REQUEST_CONTACTS_PERMISSION;
import static com.meetingapp.android.constants.Constants.URL_GROUPS;
import static com.meetingapp.android.constants.Constants.URL_CONTACTS;
import com.meetingapp.android.model.ContactsModels;
/**
* This activity called for displaying the contacts
*/
public class ContactsActivity extends BaseActivity implements DatabaseManager.OnDatabaseDataChanged,
GroupListAdapter.OnClickListener {
private static final String TAG = ContactsActivity.class.getSimpleName();
@BindView(R.id.contacts_recyclerview)
RecyclerView rvContacts;
@BindView(R.id.groups_recyclerview)
RecyclerView rvGroups;
@BindView(R.id.tabHost)
TabHost tabhost;
@BindView(R.id.contacts_sv)
SearchView mSearchView;
@Inject
DatabaseManager mDatabaseManager;
private Unbinder unbinder;
private ContactListAdapter contactListAdapter;
private GroupListAdapter groupListAdapter;
private HashSet<Contact> mListContactsPhone;
private ArrayList<Contact> mSorted;
private ArrayList<UserGroup> mGroupsList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_contacts);
init();
setupDefaults();
setupEvents();
}
@Override
protected void onDestroy() {
unbinder.unbind();
super.onDestroy();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
@NonNull int[] grantResults) {
if (requestCode == REQUEST_CONTACTS_PERMISSION && grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//reloadWeekView(newYear, newMonth, eventsMonth);
initContactsList();
} else {
setProgressMessage(getString(R.string.permission_denied));
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
/**
* This function return the Edit Group Picker result
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case EDIT_GROUP_PICKER: {
this.setResult(RESULT_OK);
break;
}
}
}
}
@Override
public void menuClicked() {
finish();
}
/**
* This callback is used for getting the existing group from the firebase database
*/
@Override
public void onDataChanged(String url, DataSnapshot dataSnapshot) {
switch (url) {
case URL_GROUPS:
mGroupsList.clear();
mGroupsList.addAll(mDatabaseManager.getListUserGroups());
Log.d(TAG, "onDataChanged: " + mGroupsList.size());
for (int i = 0; i < mGroupsList.size(); i++) {
Log.d(TAG, "onDataChanged: " + mGroupsList.get(i).getName());
Log.d(TAG, "onDataChanged: " + mGroupsList.get(i).getUsers());
if (mGroupsList.get(i).getAvailableTimes() != null) {
Log.d(TAG, "onDataChanged: " + mGroupsList.get(i).getAvailableTimes().get(0).getDayOfWeek());
Log.d(TAG, "onDataChanged: " + mGroupsList.get(i).getAvailableTimes().get(0).getStartTime());
Log.d(TAG, "onDataChanged: " + mGroupsList.get(i).getAvailableTimes().get(0).getEndTime());
}
}
groupListAdapter = new GroupListAdapter(mGroupsList);
rvGroups.setAdapter(groupListAdapter);
groupListAdapter.setOnClickListener(this);
break;
}
}
@Override
public void onCancelled(DatabaseError error) {
}
/**
* This listener is used for creating the group
*/
@OnClick(R.id.create_group_fab)
void createGroup() {
//TODO Uncomment create group -- finish
Intent intent = new Intent(this, PickContactActivity.class);
ArrayList<Contact> pickedList = new ArrayList<>(mSorted);
intent.putParcelableArrayListExtra(Constants.KEY_CONTACTS, pickedList);
startActivity(intent);
}
/**
* This function redirects the Edit Group Screen
*/
@Override
public void onClicked(UserGroup userGroup) {
Bundle bundle = new Bundle();
bundle.putString("groupName", userGroup.getName());
bundle.putParcelableArrayList(KEY_CONTACTS, userGroup.getUsers());
if (userGroup.getAvailableTimes() != null)
bundle.putParcelableArrayList("availableItems", userGroup.getAvailableTimes());
Intent editGroupIntent = new Intent(this, EditGroupActivity.class);
editGroupIntent.putExtras(bundle);
startActivityForResult(editGroupIntent, EDIT_GROUP_PICKER);
}
private void init() {
getApp().getAppComponent().inject(this);
unbinder = ButterKnife.bind(this);
mListContactsPhone = new HashSet<>();
mSorted = new ArrayList<>();
mGroupsList = new ArrayList<>();
LinearLayoutManager contactsLayoutmanager = new LinearLayoutManager(this);
LinearLayoutManager groupsLayoutmanager = new LinearLayoutManager(this);
rvContacts.setLayoutManager(contactsLayoutmanager);
rvGroups.setLayoutManager(groupsLayoutmanager);
tabhost.setup();
//Tab 1
TabHost.TabSpec spec = tabhost.newTabSpec("contactsTab");
spec.setContent(R.id.contacts);
spec.setIndicator("CONTACTS");
tabhost.addTab(spec);
//Tab 2
spec = tabhost.newTabSpec("groupsTab");
spec.setContent(R.id.groups);
spec.setIndicator("GROUPS");
tabhost.addTab(spec);
if (HomeActivity.tabIndex == 0) {
tabhost.setCurrentTab(0);
setTitle(getString(R.string.contacts));
} else {
tabhost.setCurrentTab(1);
setTitle(getString(R.string.groups));
}
setMenuIcon(R.drawable.ic_arrow_back_new);
}
private void setupDefaults() {
mDatabaseManager.setDatabaseManagerListener(this);
mDatabaseManager.subscribeToContactsUpdates(this);
mDatabaseManager.initGroups();
if (!isPermissionGranted()) {
requestPermission(REQUEST_CONTACTS_PERMISSION);
} else {
initContactsList();
}
}
private void setupEvents() {
tabhost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String s) {
if (tabhost.getCurrentTab() == 0) {
setTitle(getString(R.string.contacts));
} else {
setTitle(getString(R.string.groups));
}
}
});
}
/**
* This function is used for checking whether the permission is granted or not for contacts
*/
private boolean isPermissionGranted() {
int permissionCheck = ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.READ_CONTACTS);
return permissionCheck == PackageManager.PERMISSION_GRANTED;
}
/**
* This function is used for request the permission for contacts
*/
private void requestPermission(int permissionCount) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS}, permissionCount);
}
/**
* This function is used to getting the contact list and to display it
*/
public void initContactsList() {
mListContactsPhone.clear();
mSorted.clear();
Cursor phones = this.getContentResolver().query(ContactsContract.CommonDataKinds
.Phone.CONTENT_URI, null, null, null, null);
if (phones == null) {
return;
}
while (phones.moveToNext()) {
String name = phones.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phone = phones.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String photo = phones.getString
(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (photo != null) {
mListContactsPhone.add(new Contact(name, phone, Uri.parse(photo)));
} else {
mListContactsPhone.add(new Contact(name, phone));
}
}
phones.close();
performSort();
}
/**
* This function is used for sorting the contacts
*/
private void performSort() {
mSorted.clear();
mSorted.addAll(mListContactsPhone);
Collections.sort(mSorted, new Comparator<Contact>() {
@Override
public int compare(Contact o1, Contact o2) {
return o1.getName().compareTo(o2.getName());
}
});
contactListAdapter = new ContactListAdapter(mSorted, 1);
rvContacts.setAdapter(contactListAdapter);
}
}
|
package sample;
import javafx.beans.Observable;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.util.Callback;
import javafx.util.StringConverter;
import java.awt.*;
public class Controller{
// @FXML
// private ListView<String> lvwListPeople;
@FXML
private TableView<Info> vwTableView;
@FXML
private TableColumn<Info, String> colEnglish;
@FXML
private TableColumn<Info, String> colJapan;
@FXML
private TableColumn<Info, Boolean> colBoolean;
@FXML
private TableColumn<Info, String> colColor;
static Object[][] rowData = {
{ "1", "ichi -\u4E00", Boolean.TRUE, "red" },
{ "2", "ni -\u4E8C", Boolean.TRUE, "blue" },
{ "3", "san -\u4E09", Boolean.FALSE, "green" },
{ "4", "shi -\u56DB", Boolean.TRUE, "magenta" },
{ "5", "go -\u4E94", Boolean.FALSE, "pink" },
};
static Info []infos = new Info[rowData.length];
static ObservableList<Info> items = FXCollections.observableArrayList();
static ObservableList<String> colorList = FXCollections.observableArrayList();
public void initialize(){
readData();
// lvwListPeople.setEditable(true);
// StringConverter<People> converter;
// Callback<ListView<String>, ListCell<String>> cellFactory = TextFieldListCell.forListView();
// ObservableList<String> items = FXCollections.<String>observableArrayList();
//
// people[0] = new People(10, "Bat");
// people[1] = new People(9, "Dorj");
// for (int i = 0; i < 2; i++) {
// lvwListPeople.getItems().add(people[i].getData());
// items.add(people[i].getData());
// }
// lvwListPeople.setCellFactory(ChoiceBoxListCell.forListView(items));
items.addAll();
vwTableView.setEditable(true);
colEnglish.setCellFactory(TextFieldTableCell.forTableColumn());
colJapan.setCellFactory(TextFieldTableCell.forTableColumn());
colEnglish.setCellValueFactory(new PropertyValueFactory<>("English"));
colJapan.setCellValueFactory(new PropertyValueFactory<>("Japan"));
colColor.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Info, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<Info, String> param) {
Info Info = param.getValue();
String color = Info.getColor();
return new SimpleObjectProperty<String>(color){
private final javafx.scene.shape.Rectangle rectangle;
{
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
rectangle = new Rectangle(10, 10);
}
@Override
protected void updateItem(Color item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setGraphic(null);
} else {
rectangle.setFill(item);
setGraphic(rectangle);
}
}
};;
}
});
colColor.setCellFactory(ComboBoxTableCell.forTableColumn(colorList));
colColor.setOnEditCommit((TableColumn.CellEditEvent<Info, String> event) -> {
TablePosition<Info, String> pos = event.getTablePosition();
String color = event.getNewValue();
int row = pos.getRow();
Info Info = event.getTableView().getItems().get(row);
Info.setColor(color);
});
colBoolean.setEditable(true);
colBoolean.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Info, Boolean>, ObservableValue<Boolean>>() {
@Override
public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<Info, Boolean> param) {
Info info = param.getValue();
SimpleBooleanProperty booleanProp = new SimpleBooleanProperty(info.isBool());
booleanProp.addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
info.setBool(newValue);
}
});
return booleanProp;
}
});
colBoolean.setCellFactory(new Callback<TableColumn<Info, Boolean>, TableCell<Info, Boolean>>() {
@Override
public TableCell<Info, Boolean> call(TableColumn<Info, Boolean> p) {
CheckBoxTableCell<Info, Boolean> cell = new CheckBoxTableCell<Info, Boolean>();
cell.setAlignment(Pos.CENTER);
return cell;
}
});
vwTableView.setItems(items);
}
public static void readData(){
System.out.println(rowData.length);
for (int i = 0; i < rowData.length; i++) {
infos[i] = new Info(rowData[i][3].toString(),rowData[i][0].toString(),rowData[i][1].toString(),rowData[i][2].equals(true));
colorList.add(String.valueOf(rowData[i][3]));
}
items.addAll(infos);
}
}
|
package com.redhat.cloud.notifications.db;
import com.redhat.cloud.notifications.TestLifecycleManager;
import com.redhat.cloud.notifications.models.Application;
import com.redhat.cloud.notifications.models.BehaviorGroup;
import com.redhat.cloud.notifications.models.BehaviorGroupAction;
import com.redhat.cloud.notifications.models.Bundle;
import com.redhat.cloud.notifications.models.Endpoint;
import com.redhat.cloud.notifications.models.EndpointType;
import com.redhat.cloud.notifications.models.EventType;
import com.redhat.cloud.notifications.models.EventTypeBehavior;
import io.quarkus.test.common.QuarkusTestResource;
import io.quarkus.test.junit.QuarkusTest;
import io.vertx.pgclient.PgException;
import org.hibernate.reactive.mutiny.Mutiny;
import org.junit.jupiter.api.Test;
import javax.inject.Inject;
import javax.persistence.PersistenceException;
import javax.validation.ConstraintViolationException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@QuarkusTestResource(TestLifecycleManager.class)
public class BehaviorGroupResourcesTest extends DbIsolatedTest {
private static final String ACCOUNT_ID = "root";
@Inject
Mutiny.Session session;
@Inject
BundleResources bundleResources;
@Inject
ApplicationResources appResources;
@Inject
EndpointResources endpointResources;
@Inject
BehaviorGroupResources behaviorGroupResources;
@Test
public void testCreateAndUpdateAndDeleteBehaviorGroup() {
Bundle bundle = createBundle();
// Create behavior group.
BehaviorGroup behaviorGroup = createBehaviorGroup("displayName", bundle.getId());
List<BehaviorGroup> behaviorGroups = findBehaviorGroupsByBundleId(bundle.getId());
assertEquals(1, behaviorGroups.size());
assertEquals(behaviorGroup, behaviorGroups.get(0));
assertEquals(behaviorGroup.getDisplayName(), behaviorGroups.get(0).getDisplayName());
assertEquals(bundle.getId(), behaviorGroups.get(0).getBundle().getId());
assertNotNull(bundle.getCreated());
// Update behavior group.
String newDisplayName = "newDisplayName";
Boolean updated = updateBehaviorGroup(behaviorGroup.getId(), newDisplayName);
assertTrue(updated);
session.clear(); // We need to clear the session L1 cache before checking the update result.
behaviorGroups = findBehaviorGroupsByBundleId(bundle.getId());
assertEquals(1, behaviorGroups.size());
assertEquals(behaviorGroup.getId(), behaviorGroups.get(0).getId());
assertEquals(newDisplayName, behaviorGroups.get(0).getDisplayName());
assertEquals(bundle.getId(), behaviorGroups.get(0).getBundle().getId());
// Delete behavior group.
Boolean deleted = deleteBehaviorGroup(behaviorGroup.getId());
assertTrue(deleted);
behaviorGroups = findBehaviorGroupsByBundleId(bundle.getId());
assertTrue(behaviorGroups.isEmpty());
}
@Test
public void testCreateBehaviorGroupWithNullDisplayName() {
Bundle bundle = createBundle();
PersistenceException e = assertThrows(PersistenceException.class, () -> {
createBehaviorGroup(null, bundle.getId());
});
assertSame(ConstraintViolationException.class, e.getCause().getCause().getClass());
assertTrue(e.getCause().getCause().getMessage().contains("propertyPath=displayName"));
}
@Test
public void testCreateBehaviorGroupWithNullBundleId() {
PersistenceException e = assertThrows(PersistenceException.class, () -> {
createBehaviorGroup("displayName", null);
});
assertSame(IllegalArgumentException.class, e.getCause().getCause().getClass());
}
@Test
public void testCreateBehaviorGroupWithUnknownBundleId() {
PersistenceException e = assertThrows(PersistenceException.class, () -> {
createBehaviorGroup("displayName", UUID.randomUUID());
});
assertSame(PgException.class, e.getCause().getCause().getClass()); // FK constraint violation
}
@Test
public void testfindByBundleIdOrdering() {
Bundle bundle = createBundle();
BehaviorGroup behaviorGroup1 = createBehaviorGroup("displayName", bundle.getId());
BehaviorGroup behaviorGroup2 = createBehaviorGroup("displayName", bundle.getId());
BehaviorGroup behaviorGroup3 = createBehaviorGroup("displayName", bundle.getId());
List<BehaviorGroup> behaviorGroups = findBehaviorGroupsByBundleId(bundle.getId());
assertEquals(3, behaviorGroups.size());
// Behavior groups should be sorted on descending creation date.
assertSame(behaviorGroup3, behaviorGroups.get(0));
assertSame(behaviorGroup2, behaviorGroups.get(1));
assertSame(behaviorGroup1, behaviorGroups.get(2));
}
@Test
public void testAddAndDeleteEventTypeBehaviorAndMuteEventType() {
Bundle bundle = createBundle();
Application app = createApp(bundle.getId());
EventType eventType = createEventType(app.getId());
// Add behaviorGroup1 to eventType behaviors.
BehaviorGroup behaviorGroup1 = createBehaviorGroup("displayName", bundle.getId());
Boolean added = addEventTypeBehavior(ACCOUNT_ID, eventType.getId(), behaviorGroup1.getId());
assertTrue(added);
// Doing it again should not throw any exception but return false.
added = addEventTypeBehavior(ACCOUNT_ID, eventType.getId(), behaviorGroup1.getId());
assertFalse(added);
// Add behaviorGroup2 to eventType behaviors.
BehaviorGroup behaviorGroup2 = createBehaviorGroup("displayName", bundle.getId());
added = addEventTypeBehavior(ACCOUNT_ID, eventType.getId(), behaviorGroup2.getId());
assertTrue(added);
// Add behaviorGroup3 to eventType behaviors.
BehaviorGroup behaviorGroup3 = createBehaviorGroup("displayName", bundle.getId());
added = addEventTypeBehavior(ACCOUNT_ID, eventType.getId(), behaviorGroup3.getId());
assertTrue(added);
// Check all behaviors were correctly persisted.
List<EventTypeBehavior> behaviors = findEventTypeBehaviorByEventTypeId(eventType.getId());
assertEquals(3, behaviors.size());
assertTrue(behaviors.stream().anyMatch(behavior -> behavior.getId().behaviorGroupId.equals(behaviorGroup1.getId())));
assertTrue(behaviors.stream().anyMatch(behavior -> behavior.getId().behaviorGroupId.equals(behaviorGroup2.getId())));
assertTrue(behaviors.stream().anyMatch(behavior -> behavior.getId().behaviorGroupId.equals(behaviorGroup3.getId())));
// Remove behaviorGroup2 from eventType behaviors.
Boolean deleted = deleteEventTypeBehavior(ACCOUNT_ID, eventType.getId(), behaviorGroup2.getId());
assertTrue(deleted);
behaviors = findEventTypeBehaviorByEventTypeId(eventType.getId());
assertEquals(2, behaviors.size());
assertTrue(behaviors.stream().noneMatch(action -> action.getId().behaviorGroupId.equals(behaviorGroup2.getId())));
// Doing it again should not throw any exception but return false.
deleted = deleteEventTypeBehavior(ACCOUNT_ID, eventType.getId(), behaviorGroup2.getId());
assertFalse(deleted);
behaviors = findEventTypeBehaviorByEventTypeId(eventType.getId());
assertEquals(2, behaviors.size());
// Mute eventType, removing all its behaviors.
Boolean muted = muteEventType(ACCOUNT_ID, eventType.getId());
assertTrue(muted);
behaviors = findEventTypeBehaviorByEventTypeId(eventType.getId());
assertTrue(behaviors.isEmpty());
}
@Test
public void testAddEventTypeBehaviorWithWrongAccountId() {
Bundle bundle = createBundle();
Application app = createApp(bundle.getId());
EventType eventType = createEventType(app.getId());
BehaviorGroup behaviorGroup = createBehaviorGroup("displayName", bundle.getId());
Boolean added = addEventTypeBehavior("unknownAccountId", eventType.getId(), behaviorGroup.getId());
assertFalse(added);
}
@Test
public void testFindEventTypesByBehaviorGroupId() {
Bundle bundle = createBundle();
Application app = createApp(bundle.getId());
EventType eventType = createEventType(app.getId());
BehaviorGroup behaviorGroup = createBehaviorGroup("displayName", bundle.getId());
addEventTypeBehavior(ACCOUNT_ID, eventType.getId(), behaviorGroup.getId());
List<EventType> eventTypes = findEventTypesByBehaviorGroupId(ACCOUNT_ID, behaviorGroup.getId());
assertEquals(1, eventTypes.size());
assertEquals(eventType.getId(), eventTypes.get(0).getId());
}
@Test
public void testFindBehaviorGroupsByEventTypeId() {
Bundle bundle = createBundle();
Application app = createApp(bundle.getId());
EventType eventType = createEventType(app.getId());
BehaviorGroup behaviorGroup = createBehaviorGroup("displayName", bundle.getId());
addEventTypeBehavior(ACCOUNT_ID, eventType.getId(), behaviorGroup.getId());
List<BehaviorGroup> behaviorGroups = findBehaviorGroupsByEventTypeId(ACCOUNT_ID, eventType.getId());
assertEquals(1, behaviorGroups.size());
assertEquals(behaviorGroup.getId(), behaviorGroups.get(0).getId());
}
@Test
public void testAddAndDeleteBehaviorGroupAction() {
Bundle bundle = createBundle();
BehaviorGroup behaviorGroup = createBehaviorGroup("displayName", bundle.getId());
Endpoint endpoint1 = createEndpoint();
Endpoint endpoint2 = createEndpoint();
Endpoint endpoint3 = createEndpoint();
updateAndCheckBehaviorGroupActions(ACCOUNT_ID, bundle.getId(), behaviorGroup.getId(), true, endpoint1.getId());
updateAndCheckBehaviorGroupActions(ACCOUNT_ID, bundle.getId(), behaviorGroup.getId(), true, endpoint1.getId());
updateAndCheckBehaviorGroupActions(ACCOUNT_ID, bundle.getId(), behaviorGroup.getId(), true, endpoint1.getId(), endpoint2.getId());
updateAndCheckBehaviorGroupActions(ACCOUNT_ID, bundle.getId(), behaviorGroup.getId(), true, endpoint2.getId());
updateAndCheckBehaviorGroupActions(ACCOUNT_ID, bundle.getId(), behaviorGroup.getId(), true, endpoint3.getId(), endpoint2.getId(), endpoint1.getId());
updateAndCheckBehaviorGroupActions(ACCOUNT_ID, bundle.getId(), behaviorGroup.getId(), true);
}
@Test
public void testUpdateBehaviorGroupActionsWithWrongAccountId() {
Bundle bundle = createBundle();
BehaviorGroup behaviorGroup = createBehaviorGroup("displayName", bundle.getId());
Endpoint endpoint = createEndpoint();
updateAndCheckBehaviorGroupActions("unknownAccountId", bundle.getId(), behaviorGroup.getId(), false, endpoint.getId());
}
private Bundle createBundle() {
Bundle bundle = new Bundle();
bundle.setName("name");
bundle.setDisplayName("displayName");
return bundleResources.createBundle(bundle).await().indefinitely();
}
private Application createApp(UUID bundleId) {
Application app = new Application();
app.setBundleId(bundleId);
app.setName("name");
app.setDisplayName("displayName");
return appResources.createApp(app).await().indefinitely();
}
private EventType createEventType(UUID appID) {
EventType eventType = new EventType();
eventType.setApplicationId(appID);
eventType.setName("name");
eventType.setDisplayName("displayName");
return session.persist(eventType).call(session::flush).replaceWith(eventType).await().indefinitely();
}
private Endpoint createEndpoint() {
Endpoint endpoint = new Endpoint();
endpoint.setAccountId(ACCOUNT_ID);
endpoint.setName("name");
endpoint.setDescription("description");
endpoint.setType(EndpointType.WEBHOOK);
return endpointResources.createEndpoint(endpoint).await().indefinitely();
}
private BehaviorGroup createBehaviorGroup(String displayName, UUID bundleId) {
BehaviorGroup behaviorGroup = new BehaviorGroup();
behaviorGroup.setDisplayName(displayName);
behaviorGroup.setBundleId(bundleId);
return behaviorGroupResources.create(ACCOUNT_ID, behaviorGroup).await().indefinitely();
}
private Boolean updateBehaviorGroup(UUID behaviorGroupId, String displayName) {
BehaviorGroup behaviorGroup = new BehaviorGroup();
behaviorGroup.setId(behaviorGroupId);
behaviorGroup.setDisplayName(displayName);
behaviorGroup.setBundleId(UUID.randomUUID()); // This should not have any effect, the bundle is not updatable.
return behaviorGroupResources.update(ACCOUNT_ID, behaviorGroup).await().indefinitely();
}
private Boolean deleteBehaviorGroup(UUID behaviorGroupId) {
return behaviorGroupResources.delete(ACCOUNT_ID, behaviorGroupId).await().indefinitely();
}
private List<BehaviorGroup> findBehaviorGroupsByBundleId(UUID bundleId) {
return behaviorGroupResources.findByBundleId(ACCOUNT_ID, bundleId).await().indefinitely();
}
private Boolean addEventTypeBehavior(String accountId, UUID eventTypeId, UUID behaviorGroupId) {
return behaviorGroupResources.addEventTypeBehavior(accountId, eventTypeId, behaviorGroupId).await().indefinitely();
}
private List<EventTypeBehavior> findEventTypeBehaviorByEventTypeId(UUID eventTypeId) {
String query = "FROM EventTypeBehavior WHERE eventType.id = :eventTypeId";
return session.createQuery(query, EventTypeBehavior.class)
.setParameter("eventTypeId", eventTypeId)
.getResultList()
.await().indefinitely();
}
private Boolean deleteEventTypeBehavior(String accountId, UUID eventTypeId, UUID behaviorGroupId) {
return behaviorGroupResources.deleteEventTypeBehavior(accountId, eventTypeId, behaviorGroupId).await().indefinitely();
}
private Boolean muteEventType(String accountId, UUID eventTypeId) {
return behaviorGroupResources.muteEventType(accountId, eventTypeId).await().indefinitely();
}
private List<EventType> findEventTypesByBehaviorGroupId(String accountId, UUID behaviorGroupId) {
return behaviorGroupResources.findEventTypesByBehaviorGroupId(accountId, behaviorGroupId).await().indefinitely();
}
private List<BehaviorGroup> findBehaviorGroupsByEventTypeId(String accountId, UUID eventTypeId) {
return behaviorGroupResources.findBehaviorGroupsByEventTypeId(accountId, eventTypeId, new Query()).await().indefinitely();
}
private void updateAndCheckBehaviorGroupActions(String accountId, UUID bundleId, UUID behaviorGroupId, boolean expectedResult, UUID... endpointIds) {
Boolean updated = behaviorGroupResources.updateBehaviorGroupActions(accountId, behaviorGroupId, Arrays.asList(endpointIds)).await().indefinitely();
// Is the update result the one we expected?
assertEquals(expectedResult, updated);
if (expectedResult) {
session.clear(); // We need to clear the session L1 cache before checking the update result.
// If we expected a success, the behavior group actions should match exactly the given endpoint IDs.
List<BehaviorGroupAction> actions = findBehaviorGroupActions(accountId, bundleId, behaviorGroupId);
assertEquals(endpointIds.length, actions.size());
for (int i = 0; i < endpointIds.length; i++) {
assertEquals(endpointIds[i], actions.get(i).getEndpoint().getId());
}
}
}
private List<BehaviorGroupAction> findBehaviorGroupActions(String accountId, UUID bundleId, UUID behaviorGroupId) {
List<BehaviorGroup> behaviorGroups = behaviorGroupResources.findByBundleId(accountId, bundleId).await().indefinitely();
assertEquals(1, behaviorGroups.size());
return behaviorGroups
.stream().filter(behaviorGroup -> behaviorGroup.getId().equals(behaviorGroupId))
.findFirst().get().getActions();
}
}
|
package org.elevenst.SampleRT;
import static org.junit.Assert.*;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
public class Reg_PCTest {
String id = "nike";
@Test
public void PC_loginTest() throws Exception
{
Reg_PC app = new Reg_PC();
app.ChromeSet();
Reg_PC.PCLogin();
}
@Test
public void PC_Search() throws Exception
{ //주석추
// String id = "나이키";
Reg_PC app = new Reg_PC();
app.ChromeSet();
Reg_PC.PCSearch(id);
}
@Test
public void PC_GnbTest() throws Exception
{
// String id = "나이키";
Reg_PC app = new Reg_PC();
app.ChromeSet();
Reg_PC.PCGnb();
}
}
|
package cn.bakon.domain;
public class Device {
private String host;
public String getHost() {
return this.host;
}
}
|
/**
*
*/
package com.imooc.security.order;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import lombok.extern.slf4j.Slf4j;
/**
* @author jojo
*
*/
@RestController
@RequestMapping("/orders")
@Slf4j
public class OrderController {
@Autowired
private OAuth2RestTemplate restTemplate;
@PostMapping
@PreAuthorize("hasRole('ROLE_ADMIN')")
@SentinelResource("createOrder")
public OrderInfo create(@RequestBody OrderInfo info, @AuthenticationPrincipal String username) throws InterruptedException {
log.info("user is " + username);
restTemplate.getForObject("http://localhost:8080/users/13", String.class);
Thread.sleep(RandomUtils.nextInt(100, 1000));
// throw new RuntimeException("haha, test");
return info;
}
@GetMapping("/{id}")
public OrderInfo getInfo(@PathVariable Long id, @AuthenticationPrincipal String username) {
log.info("user is " + username);
log.info("orderId is " + id);
OrderInfo info = new OrderInfo();
info.setId(id);
info.setProductId(id * 5);
return info;
}
}
|
package com.emg.projectsmanage.dao.emapgoaccount;
import java.util.List;
import com.emg.projectsmanage.pojo.DepartmentModel;
public interface DepartmentModelDao {
List<DepartmentModel> getAllDepartment();
} |
package cn.appInfo.controller;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import cn.appInfo.entity.AppInfo;
import cn.appInfo.entity.App_Category;
import cn.appInfo.entity.App_Version;
import cn.appInfo.entity.Data_Dictionary;
import cn.appInfo.entity.DevUser;
import cn.appInfo.service.DevUserService;
import cn.appInfo.utils.Constants;
import cn.appInfo.utils.PageSupport;
@Controller
public class devUserController {
@Resource
private DevUserService devUserService;
private Logger logger = Logger.getLogger(devUserController.class);
@RequestMapping(value="/sys/appInfolist.html",method=RequestMethod.GET)
public String main(Model model){
PageSupport pages = new PageSupport();
pages.setCurrentPageNo(1);
pages.setPageSize(Constants.pageSize);
pages.setTotalCount(devUserService.findTotalCount(null,null,null,null,null,null,null));
List<Data_Dictionary> list = devUserService.findStatus();
List<Data_Dictionary> list2 = devUserService.findFlatform();
List<App_Category> list3 = devUserService.findLevel1();
List<AppInfo> list4 = devUserService.findAllInfo(pages);
model.addAttribute("pages",pages);
model.addAttribute("status",list);
model.addAttribute("flatform",list2);
model.addAttribute("level1",list3);
model.addAttribute("appInfoList",list4);
return "devjsp/appinfolist";
}
@RequestMapping(value="/list",method=RequestMethod.POST)
public String pages(@RequestParam Integer pageIndex,
@RequestParam(required=false) String querySoftwareName,
@RequestParam(required=false) Integer queryStatus,
@RequestParam(required=false) Integer queryFlatformId,
@RequestParam(required=false) Integer queryCategoryLevel1,
@RequestParam(required=false) Integer queryCategoryLevel2,
@RequestParam(required=false) Integer queryCategoryLevel3,
HttpSession session,
Model model){
DevUser u = (DevUser)session.getAttribute(Constants.USER_SESSION);
int zt = devUserService.findTotalCount(querySoftwareName,queryStatus,queryFlatformId,queryCategoryLevel1,queryCategoryLevel2,queryCategoryLevel3,u.getId());
int zy = zt%Constants.pageSize==0?zt/Constants.pageSize:zt/Constants.pageSize+1;
System.out.println(zt+"\t"+zy);
if(pageIndex<=0){
pageIndex = 1;
}
if(pageIndex>=zy){
pageIndex = zy;
}
System.out.println(zt+"\t"+zy);
List<AppInfo> list4 = null;
if(zt==0){
list4 = null;
}else{
list4 = devUserService.findInfoByCondition(querySoftwareName,
queryStatus,
queryCategoryLevel1,
queryCategoryLevel2,
queryCategoryLevel3,
queryFlatformId,
u.getId(),
pageIndex,
5);
}
PageSupport pages = new PageSupport();
pages.setCurrentPageNo(pageIndex);
pages.setPageSize(Constants.pageSize);
System.out.println(zt);
pages.setTotalCount(zt);
List<Data_Dictionary> list = devUserService.findStatus();
List<Data_Dictionary> list2 = devUserService.findFlatform();
List<App_Category> list3 = devUserService.findLevel1();
if(querySoftwareName!=null || querySoftwareName!=""){
model.addAttribute("querySoftwareName",querySoftwareName);
}
if(queryStatus!=null){
model.addAttribute("queryStatus",queryStatus);
}
if(queryFlatformId!=null){
model.addAttribute("queryFlatformId",queryFlatformId);
}
if(queryCategoryLevel1!=null){
model.addAttribute("queryCategoryLevel1",queryCategoryLevel1);
}
if(queryCategoryLevel2!=null){
List<App_Category> categoryLevel2List = devUserService.findLevel2(queryCategoryLevel1);
model.addAttribute("categoryLevel2List",categoryLevel2List);
model.addAttribute("queryCategoryLevel2",queryCategoryLevel2);
}
if(queryCategoryLevel3!=null){
List<App_Category> categoryLevel3List = devUserService.findLevel3(queryCategoryLevel2);
model.addAttribute("categoryLevel3List",categoryLevel3List);
model.addAttribute("queryCategoryLevel3",queryCategoryLevel3);
}
model.addAttribute("pages",pages);
model.addAttribute("status",list);
model.addAttribute("flatform",list2);
model.addAttribute("level1",list3);
model.addAttribute("appInfoList",list4);
return "devjsp/appinfolist";
}
@RequestMapping(value="/addAppInfo",method=RequestMethod.POST)
public String addAppInfo(AppInfo appInfo,HttpServletRequest request,HttpSession session,@RequestParam(value ="a_logoPicPath", required = false) MultipartFile attach){
DevUser du = (DevUser)session.getAttribute(Constants.USER_SESSION);
String logoLocPath = null;
String logoPicPath = null;
//判断文件是否为空
if(!attach.isEmpty()){
String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
String oldFileName = attach.getOriginalFilename();//原文件名
String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
int filesize = 50000;
if(attach.getSize() > filesize){//上传大小不得超过 500k
request.setAttribute("uploadFileError", " * 上传大小不得超过 50k");
request.setAttribute("addInfoBack", appInfo);
return "devjsp/appinfoadd";
}else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
|| prefix.equalsIgnoreCase("jpeg")){//上传图片格式不正确
Random r = new Random();
int random = r.nextInt(1000000);
String fileName = System.currentTimeMillis()+random+"_Personal.jpg";
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
//保存
try {
attach.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("uploadFileError", " * 上传失败!");
request.setAttribute("addInfoBack", appInfo);
return "devjsp/appinfoadd";
}
logoLocPath = path+File.separator+fileName;
logoPicPath = "statics"+File.separator+"uploadfiles";
}else{
request.setAttribute("uploadFileError", " * 上传图片格式不正确");
request.setAttribute("addInfoBack", appInfo);
return "devjsp/appinfoadd";
}
}
appInfo.setLogoPicPath(logoPicPath);
appInfo.setLogoLocPath(logoLocPath);
appInfo.setCreatedBy(du.getId());
appInfo.setCreationDate(new Date());
appInfo.setDevId(du.getId());
if(devUserService.addAppInfo(appInfo)>0){
return "redirect:/sys/appInfolist.html";
}
return "devjsp/appinfoadd";
}
/**
* 验证唯一性
* @param APKName
* @return
*/
@RequestMapping(value="/APKName",method=RequestMethod.GET)
@ResponseBody
public String APKName(@RequestParam String APKName){
int line = devUserService.findOne(APKName);
if(APKName==null || APKName==""){
return "empty";
}else if(line>0){
return "exist";
}else if(line==0){
return "noexist";
}else{
return "hz";
}
}
@RequestMapping(value="/categorylevellist.json",method=RequestMethod.GET)
@ResponseBody
public List<App_Category> getAppCategoryList (@RequestParam String pid){
logger.debug("getAppCategoryList pid ============ " + pid);
if(pid.equals("")) pid = null;
return getCategoryList(pid);
}
public List<App_Category> getCategoryList (String pid){
List<App_Category> categoryLevelList = null;
try {
categoryLevelList = devUserService.getAppCategoryListByParentId(pid==null?null:Integer.parseInt(pid));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return categoryLevelList;
}
@RequestMapping(value="/flatformInfo",method=RequestMethod.GET)
@ResponseBody
public Object flatform(){
List<Data_Dictionary> list2 = devUserService.findFlatform();
return list2;
}
@RequestMapping(value="/level1",method=RequestMethod.GET)
@ResponseBody
public Object level1(){
List<App_Category> list3 = devUserService.findLevel1();
return list3;
}
@RequestMapping(value="/getLevel2",method=RequestMethod.GET)
@ResponseBody
public Object Getlevel2(@RequestParam Integer pid){
logger.info(pid);
List<App_Category> list = devUserService.findLevel2(pid);
return JSON.toJSON(list);
}
@RequestMapping(value="/getLevel3",method=RequestMethod.GET)
@ResponseBody
public Object Getlevel3(@RequestParam Integer pid){
logger.info(pid);
List<App_Category> list = devUserService.findLevel3(pid);
return JSON.toJSON(list);
}
@RequestMapping(value="/sys/getaddInfo",method=RequestMethod.GET)
public String addGET(){
return "devjsp/appinfoadd";
}
/**
* 显示修改页面
* @param pid
* @return
*/
@RequestMapping(value="/appinfomodify",method=RequestMethod.GET)
public String GETupdate(@RequestParam Integer id,Model model){
System.out.println(id);
AppInfo appInfo = devUserService.findAppInfoById(id);
model.addAttribute("appInfo",appInfo);
return "devjsp/appinfomodify";
}
/**
* 修改及保存及重新上传
* @param appInfo
* @param session
* @param status
* @return
*/
@RequestMapping(value="/appinfomodifysave",method=RequestMethod.POST)
public String POSTupdate(AppInfo appInfo,HttpSession session,@RequestParam(required=false) Integer status){
DevUser du = (DevUser)session.getAttribute(Constants.USER_SESSION);
if(status==null){
appInfo.setModifyBy(du.getId());
appInfo.setModifyDate(new Date());
int line = devUserService.updateModify(appInfo);
if(line>0){
return "redirect:/sys/appInfolist.html";
}else{
return "devjsp/appinfomodify";
}
}else{
appInfo.setStatus(status);
appInfo.setModifyBy(du.getId());
appInfo.setModifyDate(new Date());
int line = devUserService.updateModify(appInfo);
if(line>0){
return "redirect:/sys/appInfolist.html";
}else{
return "devjsp/appinfomodify";
}
}
}
/**
* 显示新增版本信息页
* @param id
* @param model
* @return
*/
@RequestMapping(value="/sys/appversionadd",method=RequestMethod.GET)
public String appversionadd(@RequestParam Integer id,Model model){
List<App_Version> list = devUserService.findVersionInfoById(id);
model.addAttribute("appVersionList",list);
model.addAttribute("appId",id);
return "devjsp/appversionadd";
}
/**
* 保存新增版本的信息
* @param id
* @param model
* @return
*/
@RequestMapping(value="/appversionadd",method=RequestMethod.POST)
public String appversionaddPOST(@RequestParam Integer appId,@RequestParam Integer publishStatus,App_Version appVersion,HttpServletRequest request,HttpSession session,@RequestParam(value ="a_downloadLink", required = false) MultipartFile attach){
DevUser du = (DevUser)session.getAttribute(Constants.USER_SESSION);
String logoLocPath = null;
String logoPicPath = null;
String fileName = null;
//判断文件是否为空
if(!attach.isEmpty()){
String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
String oldFileName = attach.getOriginalFilename();//原文件名
String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
long filesize = 5000000000l;
if(attach.getSize() > filesize){//上传大小不得超过 500MB
request.setAttribute("uploadFileError", " * 上传大小不得超过 500MB");
request.setAttribute("addInfoBack", appVersion);
return "devjsp/appversionadd";
}else if(prefix.equalsIgnoreCase("apk")
|| prefix.equalsIgnoreCase("jpeg")){//上传图片格式不正确
Random r = new Random();
int random = r.nextInt(1000000);
fileName = System.currentTimeMillis()+random+"_Personal.apk";
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
try {
attach.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("uploadFileError", " * 上传失败!");
request.setAttribute("addInfoBack", appVersion);
return "devjsp/appversionadd";
}
logoLocPath = path+File.separator+fileName;
logoPicPath = "statics"+File.separator+"uploadfiles"+File.separator+fileName;
}else{
request.setAttribute("uploadFileError", " * 上传图片格式不正确");
request.setAttribute("addInfoBack", appVersion);
return "devjsp/appversionadd";
}
}
appVersion.setDownloadLink(logoPicPath);
appVersion.setApkFileName(fileName);
appVersion.setApkLocPath(logoLocPath);
appVersion.setAppId(appId);
appVersion.setPublishStatus(publishStatus);
appVersion.setCreatedBy(du.getId());
appVersion.setCreationDate(new Date());
if(devUserService.addVersion(appVersion)>0){
if(devUserService.updateVersionId(appVersion.getId(), appId)>0){
return "redirect:/sys/appInfolist.html";
}
}
request.setAttribute("addInfoBack", appVersion);
return "devjsp/appversionadd";
}
/**
* 显示版本信息修改页面
* @param vid
* @param aid
* @param model
* @return
*/
@RequestMapping(value="/sys/appversionmodify",method=RequestMethod.GET)
public String appversionmodify(@RequestParam Integer vid,@RequestParam Integer aid,Model model){
System.out.println(vid+"\t"+aid);
List<App_Version> list = devUserService.findVersionInfoById(aid);
App_Version appVersion = devUserService.findVersionById(vid);
model.addAttribute("appVersionList",list);
model.addAttribute("appVersion",appVersion);
return "devjsp/appversionmodify";
}
/**
* 删除文件方法
* @param id
* @return
*/
@RequestMapping(value="/delfile.json",method=RequestMethod.GET)
@ResponseBody
public Object appversiondel(@RequestParam Integer id){
HashMap<String,String> resultMap = new HashMap<String,String>();
String fileLocPath = null;
try {
fileLocPath = (devUserService.findVersionById(id)).getApkLocPath();
File file = new File(fileLocPath);
if (file.exists()) {
if (file.delete()) {// 删除服务器存储的物理文件
if (devUserService.updateVersionFile(id)>0) {// 更新表
resultMap.put("result", "success");
}
}
}
} catch (Exception e) {
e.printStackTrace();
resultMap.put("result", "failed");
}
return JSON.toJSON(resultMap);
}
@RequestMapping(value="/appversionmodifysave",method=RequestMethod.POST)
public String appversionmodifysave(App_Version appVersion,@RequestParam(value="attach",required= false) MultipartFile attach,HttpSession session,HttpServletRequest request){
DevUser du = (DevUser)session.getAttribute(Constants.USER_SESSION);
String logoLocPath = null;
String logoPicPath = null;
String fileName = null;
//判断文件是否为空
if(!attach.isEmpty()){
String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
String oldFileName = attach.getOriginalFilename();//原文件名
String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
long filesize = 5000000000l;
if(attach.getSize() > filesize){//上传大小不得超过 500MB
request.setAttribute("uploadFileError", " * 上传大小不得超过 500MB");
request.setAttribute("addInfoBack", appVersion);
return "devjsp/appversionmodify";
}else if(prefix.equalsIgnoreCase("apk")
|| prefix.equalsIgnoreCase("jpeg")){//上传图片格式不正确
Random r = new Random();
int random = r.nextInt(1000000);
fileName = System.currentTimeMillis()+random+"_Personal.apk";
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
try {
attach.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("uploadFileError", " * 上传失败!");
request.setAttribute("addInfoBack", appVersion);
return "devjsp/appversionmodify";
}
logoLocPath = path+File.separator+fileName;
logoPicPath = "statics"+File.separator+"uploadfiles"+File.separator+fileName;
appVersion.setDownloadLink(logoPicPath);
appVersion.setApkFileName(fileName);
appVersion.setApkLocPath(logoLocPath);
}else{
request.setAttribute("uploadFileError", " * 上传图片格式不正确");
request.setAttribute("addInfoBack", appVersion);
return "devjsp/appversionmodify";
}
}
appVersion.setModifyBy(du.getId());
appVersion.setModifyDate(new Date());
if(devUserService.modifyVersion(appVersion)>0){
return "redirect:/sys/appInfolist.html";
}
return "devjsp/appversionmodify";
}
@RequestMapping(value="/sys/appinfoview",method=RequestMethod.GET)
public String appinfoview(@RequestParam Integer appinfoid,Model model){
System.out.println(appinfoid);
List<App_Version> list = devUserService.findVersionInfoById(appinfoid);
AppInfo appInfo = devUserService.findViewInfo(appinfoid);
model.addAttribute("appInfo",appInfo);
model.addAttribute("appVersionList",list);
return "devjsp/appinfoview";
}
/**
* ajax删除APP
* @param id
* @return
*/
@RequestMapping(value="/delapp.json",method=RequestMethod.GET)
@ResponseBody
public Object delapp(@RequestParam Integer id){
HashMap<String,String> result = new HashMap<String,String>();
if(devUserService.delAppInfoVersion(id)>0){
result.put("delResult", "true");
}else{
result.put("delResult", "false");
}
return result;
}
/**
* ajax上架、下架操作
* @param appId
* @return
*/
@RequestMapping(value="/updateStatus",method=RequestMethod.POST)
@ResponseBody
public Object sale(@RequestParam Integer appId,@RequestParam String info){
HashMap<String,String> result = new HashMap<String,String>();
if(info.equals("open")){ //上架
if(devUserService.updateAppInfoStatus(appId, 4)>0){
result.put("resultMsg","success");
}else{
result.put("resultMsg","failed");
}
}else if(info.equals("close")){ //下架
if(devUserService.updateAppInfoStatus(appId, 5)>0){
result.put("resultMsg","success");
}else{
result.put("resultMsg","failed");
}
}
return result;
}
}
|
package services;
import models.*;
import readwrite.write.Writer;
import java.util.Collections;
public class PerformanceService {
private final Writer audit = new Writer();
public void printSeatsAvailable(Performance performance) {
audit.writeData("PerformanceService", "printSeatsAvailable");
Balcony a = new Balcony();
Loge b = new Loge();
Standard c = new Standard();
System.out.println("We have " + countAvailableStandardSeats(performance) + " standard seats available at price " + c.getPrice());
System.out.println("We have " + countAvailableBalcony(performance) + " balcony seats available at price " + a.getPrice());
System.out.println("We have " + countAvailableLoge(performance) + " loge seats available at price " + b.getPrice());
}
int getFirstOfTypeIndex(String s, Performance performance) {
audit.writeData("PerformanceService", "getFirstOfTypeIndex");
int i = 0;
for (Seat x : performance.getAvailableSeats()) {
if (s.equals("Balcony") && x instanceof Balcony) {
return i;
} else if (s.equals("StandardSeat") && x instanceof Standard) {
return i;
} else if (s.equals("Loge") && x instanceof Loge) {
return i;
}
i++;
}
return -1;
}
public void displayAvailableSeats(Performance performance) {
audit.writeData("PerformanceService", "displayAvailableSeats");
sortAvailableSeats(performance);
for (Seat x : performance.getAvailableSeats())
System.out.println(x.toString());
}
private int countAvailableStandardSeats(Performance performance) {
audit.writeData("PerformanceService", "countAvailableStandardSeats");
int count = 0;
for (Seat x : performance.getAvailableSeats())
if (x instanceof Standard)
count++;
return count;
}
private int countAvailableBalcony(Performance performance) {
audit.writeData("PerformanceService", "countAvailableBalcony");
int count = 0;
for (Seat x : performance.getAvailableSeats())
if (x instanceof Balcony)
count++;
return count;
}
private int countAvailableLoge(Performance performance) {
audit.writeData("PerformanceService", "countAvailableLoge");
int count = 0;
for (Seat x : performance.getAvailableSeats())
if (x instanceof Loge)
count++;
return count;
}
public void deleteSeat(int i, Performance performance) {
audit.writeData("PerformanceService", "deleteSeat");
performance.getAvailableSeats().remove(i);
}
public void sortAvailableSeats(Performance performance) {
audit.writeData("PerformanceService", "sortAvailableSeats");
Collections.sort(performance.getAvailableSeats());
}
}
|
package com.edasaki.rpg.particles.custom;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.bukkit.Location;
import org.bukkit.util.Vector;
import de.slikey.effectlib.Effect;
import de.slikey.effectlib.EffectManager;
import de.slikey.effectlib.EffectType;
import de.slikey.effectlib.util.MathUtils;
import de.slikey.effectlib.util.ParticleEffect;
import de.slikey.effectlib.util.VectorUtils;
public class FairyWingsEffect extends Effect {
/**
* Particle to draw the image
*/
public ParticleEffect particle = ParticleEffect.REDSTONE;
/**
* Each stepX pixel will be shown. Saves packets for high resolutions.
*/
public int stepX = 1;
/**
* Each stepY pixel will be shown. Saves packets for high resolutions.
*/
public int stepY = 1;
/**
* Scale the image down
*/
public float size = (float) 1 / 12;
/**
* Image as BufferedImage
*/
protected BufferedImage image = null;
/**
* Step counter
*/
protected int step = 0;
/**
* Delay between steps
*/
protected int delay = 0;
public FairyWingsEffect(EffectManager effectManager) {
super(effectManager);
type = EffectType.REPEATING;
period = 5;
iterations = -1;
}
public void loadFile(File file) {
try {
image = ImageIO.read(file);
} catch (Exception ex) {
ex.printStackTrace();
image = null;
}
}
@Override
public void onRun() {
if (image == null) {
cancel();
return;
}
Location location = getLocation();
Vector dir = location.getDirection().normalize();
dir.setY(0);
location.subtract(dir.multiply(0.4));
{
Location loc_right = location.clone();
Vector shift = dir.getCrossProduct(new Vector(0, 1, 0));
shift = shift.normalize();
loc_right.add(shift.multiply(1.5));
for (int y = 0; y < image.getHeight(); y += stepY) {
for (int x = 0; x < image.getWidth(); x += stepX) {
Vector v = new Vector((float) image.getWidth() / 2 - x, (float) image.getHeight() / 2 - y, 0).multiply(size);
VectorUtils.rotateAroundAxisY(v, -loc_right.getYaw() * MathUtils.degreesToRadians);
int r = (new Color(image.getRGB(x, y))).getRed();
int g = (new Color(image.getRGB(x, y))).getGreen();
int b = (new Color(image.getRGB(x, y))).getBlue();
loc_right.add(v);
if ((r == 0 && g == 0 && b == 0)) {
display(particle, loc_right, org.bukkit.Color.LIME);
}
loc_right.subtract(v);
}
}
}
{
Location loc_left = location.clone();
Vector shift = dir.getCrossProduct(new Vector(0, 1, 0));
shift = shift.normalize();
loc_left.add(shift.multiply(-1.5));
for (int y = 0; y < image.getHeight(); y += stepY) {
for (int x = 0; x < image.getWidth(); x += stepX) {
Vector v = new Vector((float) image.getWidth() / 2 - x, (float) image.getHeight() / 2 - y, 0).multiply(size);
VectorUtils.rotateAroundAxisY(v, -loc_left.getYaw() * MathUtils.degreesToRadians);
int tempX = image.getWidth() - 1 - x;
Color clr = new Color(image.getRGB(tempX, y));
int r = clr.getRed();
int g = clr.getGreen();
int b = clr.getBlue();
loc_left.add(v);
if ((r == 0 && g == 0 && b == 0)) {
display(particle, loc_left, org.bukkit.Color.LIME);
}
loc_left.subtract(v);
}
}
}
}
} |
package com.stackroute.service;
import com.stackroute.domain.Questions;
import com.stackroute.exceptions.QuestionAlreadyExistsException;
public interface QuestionService {
Questions saveQuestion(Questions question) throws QuestionAlreadyExistsException;
}
|
/**
* Kenny Akers
* Mr. Paige
* Homework #15
* 1/22/18
*/
import java.io.Console;
public class BinarySearchTree<T extends Comparable<T>> {
public class Node {
private T data;
private Node left;
private Node right;
private Balance balanceFactor;
public Node(T data, Node left, Node right) {
this.data = data;
this.left = left;
this.right = right;
this.balanceFactor = Balance.EVEN;
}
public Node(T data) {
this(data, null, null); // A leaf node is balanced.
}
public T value() {
return this.data;
}
public Node left() {
return this.left;
}
public Node right() {
return this.right;
}
public Balance balanceFactor() {
return this.balanceFactor;
}
public void value(T data) {
this.data = data;
}
public void left(Node child) {
this.left = child;
}
public void right(Node child) {
this.right = child;
}
public void setBalance(Balance bal) {
this.balanceFactor = bal;
}
}
private static enum Balance {
LEFT('/'),
EVEN('-'),
RIGHT('\\');
private char c;
private Balance(char c) {
this.c = c;
}
@Override
public String toString() {
return Character.toString(c);
}
}
private class RootAndTaller {
public Node root;
public boolean gotTaller;
public RootAndTaller(Node root, boolean gotTaller) {
this.root = root;
this.gotTaller = gotTaller;
}
}
private Node root;
public BinarySearchTree() {
this.root = null;
}
public BinarySearchTree(T[] values) {
for (T value : values) {
add(value);
}
}
// Return the number of nodes in the tree (or in
// the sub-tree rooted at a specified node).
public int size() {
return size(this.root);
}
private int size(Node node) {
if (node == null) {
return 0;
} else {
return size(node.left) + size(node.right) + 1;
}
}
// Returnthe height of a tree (or the height of
// a sub-tree rooted at a specified node).
public int height() {
return height(this.root);
}
private int height(Node node) {
if (node == null) {
return 0;
} else {
return 1 + Math.max(height(node.left), height(node.right));
}
}
// Determine if a tree contains a specified key.
public boolean contains(T item) {
Node rover = this.root;
while (rover != null) {
int compare = item.compareTo(rover.data);
if (compare < 0) {
rover = rover.left;
} else if (compare > 0) {
rover = rover.right;
} else {
return true;
}
}
return false;
}
// Find the node in a tree having a specified key value.
public Node locate(Node node, T item) {
Node rover = node;
while (rover != null) {
int compare = item.compareTo(rover.data);
if (compare < 0) {
rover = rover.left;
} else if (compare > 0) {
rover = rover.right;
} else {
return rover;
}
}
return null;
}
public Node locate(T item) {
return locate(this.root, item);
}
public T find(Node node, T item) {
Node result = locate(node, item);
return (result == null) ? null : result.data;
}
public T find(T item) {
Node result = locate(item);
return (result == null) ? null : result.data;
}
public Node min(Node node) {
if (node == null) {
return null;
}
Node rover = node;
while (rover.left != null) {
rover = rover.left;
}
return rover;
}
public T min() {
Node result = min(this.root);
return (result == null) ? null : result.data;
}
public Node max(Node node) {
// A slightly different version than min:
Node parent = null;
Node rover = node;
while (rover != null) {
parent = rover;
rover = rover.right;
}
return parent;
}
public T max() {
Node result = max(this.root);
return (result == null) ? null : result.data;
}
// Find the item in a tree having the largest value
// that is no greater than a specified key.
public T floor(T item) {
Node floor = null;
Node rover = this.root;
while (rover != null) {
int compare = item.compareTo(rover.data);
if (compare < 0) {
rover = rover.left;
} else if (compare > 0) {
floor = rover;
rover = rover.right;
} else {
return rover.data;
}
}
return (floor == null) ? null : floor.data;
}
// Find the item in a tree having the smallest value
// that is not less than a specified key.
public T ceiling(T item) {
Node ceiling = null;
Node rover = this.root;
while (rover != null) {
int compare = item.compareTo(rover.data);
if (compare < 0) {
ceiling = rover;
rover = rover.left;
} else if (compare > 0) {
rover = rover.right;
} else {
return rover.data;
}
}
return (ceiling == null) ? null : ceiling.data;
}
public int rank(Node node, T item) {
// TODO
return 0;
}
public int rank(T item) {
return rank(this.root, item);
}
public T select(Node node, int rank) {
// TODO
return null;
}
public T select(int rank) {
return select(this.root, rank);
}
private Node balance(Node node) {
if (height(node.left) - height(node.right) > 1) { // Left subtree is 2+ taller than the right subtree.
if (node.left.balanceFactor == Balance.LEFT) { // Need to do a single right rotation.
System.out.println("Rotating right around " + node.data);
node.balanceFactor = Balance.EVEN;
node = rotateRight(node);
node.balanceFactor = Balance.EVEN;
} else { // Left child's right subtree is bigger than the left child's left subtree --> LR
System.out.println("LR: Node is " + node.data);
System.out.println("LR: Rotating left around " + node.left.data);
node.left.balanceFactor = Balance.EVEN; // A
node.left.right.balanceFactor = Balance.LEFT; // B
node.left = rotateLeft(node.left);
System.out.println("LR: Rotating right around " + node.data);
node.balanceFactor = (node.balanceFactor == Balance.LEFT && node.right != null) ? Balance.RIGHT : Balance.EVEN;
node = rotateRight(node);
node.balanceFactor = Balance.EVEN;
}
} else { // Right subtree is 2+ taller than the left subtree.
if (node.right.balanceFactor == Balance.RIGHT) { // Need to do a single left rotation.
System.out.println("Rotating left around " + node.data);
node.balanceFactor = Balance.EVEN;
node = rotateLeft(node);
node.balanceFactor = Balance.EVEN;
} else { // Right child's left subtree is bigger than the right child's right subtree --> RL
System.out.println("RL: Node is " + node.data); // A
System.out.println("RL: Rotating right around " + node.right.data); // C
node.right.balanceFactor = Balance.EVEN; // C
node.right.left.balanceFactor = Balance.RIGHT; // B
node.right = rotateRight(node.right);
System.out.println("RL: Rotating left around " + node.data); // A
node.balanceFactor = (node.balanceFactor == Balance.RIGHT && node.left != null) ? Balance.LEFT : Balance.EVEN;
node = rotateLeft(node);
node.balanceFactor = Balance.EVEN;
}
}
return node;
}
public RootAndTaller add(Node node, T item) {
boolean taller = false;
if (node == null) {
return new RootAndTaller(new Node(item), true);
} else {
int compare = item.compareTo(node.data);
if (compare < 0) {
RootAndTaller left = add(node.left, item);
node.left = left.root;
if (left.gotTaller) {
switch (node.balanceFactor) {
case LEFT:
System.out.println("left balance");
node = this.balance(node);
break;
case EVEN:
node.balanceFactor = Balance.LEFT;
taller = true;
break;
case RIGHT:
node.balanceFactor = Balance.EVEN;
taller = false;
break;
}
} else {
taller = false;
}
} else if (compare > 0) {
RootAndTaller right = add(node.right, item);
node.right = right.root;
if (right.gotTaller) {
switch (node.balanceFactor) {
case LEFT:
node.balanceFactor = Balance.EVEN;
taller = false;
break;
case EVEN:
node.balanceFactor = Balance.RIGHT;
taller = true;
break;
case RIGHT:
System.out.println("right balance");
node = this.balance(node);
break;
}
} else {
taller = false;
}
} else {
node.data = item;
taller = false;
}
return new RootAndTaller(node, taller);
}
/*
TEST DATA FOR DOUBLE ROTATION TREE
cow
bat
ant
bug
dog
then add cat will trigger the double
*/
}
public Node rotateLeft(Node pivot) {
Node right = pivot.right;
pivot.right = pivot.right.left;
right.left = pivot;
return right;
}
public Node rotateRight(Node pivot) {
Node left = pivot.left;
pivot.left = pivot.left.right;
left.right = pivot;
return left;
}
public void add(T item) {
this.root = add(this.root, item).root;
}
public Node remove(Node node, T item) {
if (node == null) {
return null;
}
int compare = item.compareTo(node.data);
if (compare < 0) {
node.left = remove(node.left, item);
return node;
} else if (compare > 0) {
node.right = remove(node.right, item);
return node;
} else if (node.left == null) {
return node.right;
} else if (node.right == null) {
return node.left;
} else {
Node min = min(node.right);
node.data = min.data;
node.right = deleteMin(node.right);
return node;
}
}
public Node deleteMin(Node node) {
Node rover = node;
Node parent = null;
while (rover.left != null) {
parent = rover;
rover = rover.left;
}
if (parent == null) {
return node.right;
} else {
parent.left = rover.right;
return node;
}
}
public void deleteMin() {
this.root = deleteMin(this.root);
}
public Node deleteMax(Node node) {
Node rover = node;
Node parent = null;
while (rover.right != null) {
parent = rover;
rover = rover.right;
}
if (parent == null) {
return node.left;
} else {
parent.right = rover.left;
return node;
}
}
public void deleteMax() {
this.root = deleteMax(this.root);
}
public void remove(T item) {
this.root = remove(this.root, item);
}
public interface Action<T> {
public void visit(T data, int depth, Balance factor);
}
public void traverse(Action<T> action) {
traverse(root, action, 0);
}
public void traverse(Node node, Action<T> action, int depth) {
if (node != null) {
traverse(node.left, action, depth + 1);
action.visit(node.data, depth, node.balanceFactor);
traverse(node.right, action, depth + 1);
}
}
private static String getArgument(String line, int index) {
String[] words = line.split("\\s");
return words.length > index ? words[index] : "";
}
private static String getCommand(String line) {
return getArgument(line, 0);
}
public static void main(String[] args) {
Console console = System.console();
BinarySearchTree<String> tree;
if (console == null) {
System.err.println("No console");
return;
}
if (args.length > 0) {
tree = new BinarySearchTree<String>(args);
} else {
tree = new BinarySearchTree<String>();
}
String line = console.readLine("Command: ").trim();
while (line != null) {
String command = getCommand(line);
String arg = getArgument(line, 1);
switch (command) {
case "size":
System.out.println(tree.size());
break;
case "height":
System.out.println(tree.height());
break;
case "add":
tree.add(arg);
break;
case "contains":
System.out.println(tree.contains(arg));
break;
case "find":
System.out.println(tree.find(arg));
break;
case "floor":
System.out.println(tree.floor(arg));
break;
case "ceiling":
System.out.println(tree.ceiling(arg));
break;
case "min":
System.out.println(tree.min());
break;
case "max":
System.out.println(tree.max());
break;
case "rank":
System.out.println(tree.rank(arg));
break;
case "select":
try {
int rank = Integer.parseInt(arg);
System.out.println(tree.select(rank));
} catch (NumberFormatException e) {
System.out.println("Invalid rank: " + arg);
}
break;
case "remove":
case "delete":
tree.remove(arg);
break;
case "delmin":
case "deletemin":
tree.deleteMin();
break;
case "delmax":
case "deletemax":
tree.deleteMax();
break;
case "clear":
tree = new BinarySearchTree<String>();
break;
case "tree":
case "print":
Action<String> action = new Action<String>() {
@Override
public void visit(String data, int depth, Balance factor) {
int temp = depth;
while (depth-- > 0) {
System.out.print(" ");
}
System.out.println(data + " (" + factor + ")");
}
};
tree.traverse(action);
break;
case "help":
System.out.println("size Size of the tree");
System.out.println("height Height of the tree");
System.out.println("min Smallest item in the tree");
System.out.println("max Largest item in the tree");
System.out.println("add <key> Add an item");
System.out.println("contains <key> Is an item in the tree");
System.out.println("find <key> Finds an item");
System.out.println("floor <key> Finds largest item <= key");
System.out.println("ceiling <key> Finds smallest item >= key");
System.out.println("rank <key> Determines the rank of the key");
System.out.println("select <#> Finds the kth smallest key");
System.out.println("remove <key> Remove an item");
System.out.println("delete <key> Remove an item");
System.out.println("delmin Removes the smallest item");
System.out.println("delmax Removes the largest item");
System.out.println("clear Deletes the entire tree");
System.out.println("print Displays the tree");
System.out.println("exit Exits the program");
break;
case "exit":
case "quit":
return;
default:
System.out.println("Unknown command: " + command);
break;
}
line = console.readLine("Command: ").trim();
}
}
}
|
package test;
import core.BaseTest;
import org.openqa.selenium.Keys;
import org.testng.annotations.Test;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
import java.io.File;
import static com.codeborne.selenide.Selenide.*;
@Features("Selenide + TestNG + Allureのテスト")
public class ExampleTest extends BaseTest {
private final String googleUrl = "http://www.google.com";
@Stories("Googleにアクセスしタイトルを調べる")
@Test
public void testTitle() {
open(googleUrl);
assert title().contains("Google");
}
@Stories("Googleで検索を行う")
@Test
public void searchOnGoogle() throws InterruptedException {
open(googleUrl);
$("[name='q'").setValue("Selenium").sendKeys(Keys.RETURN);
assert title().contains("Selenium - Google");
}
@Stories("スクリーンショットをとる")
@Test
public void takeScreenshot() {
open(googleUrl);
screenshot("screenshot");
File png = new File("build/reports/tests/screenshot.png");
assert png.exists();
}
}
|
package com.productStock.dataproviders.postgrees;
import com.productStock.converter.ProductStockAppConverter;
import com.productStock.dataprovider.ProductStockDataProvider;
import com.productStock.dataproviders.postgrees.model.ProductStockModel;
import com.productStock.dataproviders.postgrees.repository.ProductStockAppDataProviderRepository;
import com.productStock.entity.CustomProductStock;
import com.productStock.entity.ProductStock;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ProductStockDatabaseDataProvider implements ProductStockDataProvider {
private final ProductStockAppConverter productStockAppConverter;
private final ProductStockAppDataProviderRepository productStockAppDataProviderRepository;
@Override
public ProductStock insertProductIntoStock(ProductStock productStock) {
ProductStockModel productStockModel = this.productStockAppConverter.toProductStockModel(productStock);
ProductStockModel productStockSaved = this.productStockAppDataProviderRepository.save(productStockModel);
return this.productStockAppConverter.toProductStockDomain(productStockSaved);
}
@Override
public List<ProductStock> listAllProductsTheStocks() {
return this.productStockAppDataProviderRepository.findAll().stream()
.map(this.productStockAppConverter::toProductStockDomain)
.collect(Collectors.toList());
}
@Override
public List<CustomProductStock> listStocksCustomsByIdStock(int idStock) {
return this.productStockAppDataProviderRepository.listAllStocksWithProductsByIdStock(idStock).stream()
.map(this.productStockAppConverter::toCustomProductStock)
.collect(Collectors.toList());
}
@Override
public List<CustomProductStock> listAllStocksCustoms() {
return this.productStockAppDataProviderRepository.listAllStocksWithProducts().stream()
.map(this.productStockAppConverter::toCustomProductStock)
.collect(Collectors.toList());
}
} |
/*
* 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 algo;
import jdk.nashorn.internal.objects.Global;
import model.Location;
import model.Vehicle;
/**
*
* @author Team Foufou
*/
public class FusionTourInfos {
/**
* Vehicle of the previous tour
*/
private Vehicle vehicleFrom;
/**
* Vehicle of the new tour
*/
private Vehicle vehicleTo;
/**
* position in the new vehicle
*/
protected final int positionTo;
/**
* Delta cost of the change
*/
protected double deltaCost;
protected Location bestLocation;
/**
* Data Constructor
*
* @param vehicleFrom
* @param vehicleTo
* @param positionTo
*/
public FusionTourInfos(Vehicle vehicleFrom, Vehicle vehicleTo, int positionTo) {
this.vehicleFrom = vehicleFrom;
this.vehicleTo = vehicleTo;
this.positionTo = positionTo;
this.deltaCost = Global.Infinity;
this.bestLocation = null;
}
/**
*
* @return vehicleFrom
*/
public Vehicle getVehicleFrom() {
return vehicleFrom;
}
/**
*
* @return vehicleTo
*/
public Vehicle getVehicleTo() {
return vehicleTo;
}
/**
*
* @return deltaCost
*/
public double getDeltaCost() {
return deltaCost;
}
/**
*
* @return bestLocation
*/
public Location getBestLocation() {
return bestLocation;
}
/**
* Launch the check of the location
* @param location
*/
public void checkMovementTime(Location location) {
this.bestLocation = this.vehicleFrom.checkMovementFusionLocation(positionTo, location, vehicleTo);
}
/**
* Launch the calcul of the cost for the bestLocation
*/
public void calculateDeltaCost() {
this.deltaCost = this.vehicleFrom.calculateDeltaMovementFusionCost(positionTo, bestLocation, vehicleTo);
if (this.deltaCost == Double.NEGATIVE_INFINITY)
this.deltaCost = 0.0;
}
/**
* Execute the deplacement from the previous position to the new one
* @return true
*/
public boolean doDeplacementFusionTournee() {
if (!this.vehicleTo.moveFusionLocation(positionTo, bestLocation))
return false;
return true;
}
@Override
public String toString() {
return "FusionTourInfos{" + "vehicleFrom=" + vehicleFrom + ", vehicleTo=" + vehicleTo + ", positionTo=" + positionTo + ", deltaCost=" + deltaCost + ", bestLocation=" + bestLocation + '}';
}
}
|
package diplomski.autoceste.models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.time.LocalDateTime;
@Entity
public class Report {
@Id
@GeneratedValue
private Long id;
private String locationEntry;
private String locationExit;
private LocalDateTime entryTime;
private LocalDateTime exitTime;
private String plate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLocationEntry() {
return locationEntry;
}
public void setLocationEntry(String locationEntry) {
this.locationEntry = locationEntry;
}
public String getLocationExit() {
return locationExit;
}
public void setLocationExit(String locationExit) {
this.locationExit = locationExit;
}
public LocalDateTime getEntryTime() {
return entryTime;
}
public void setEntryTime(LocalDateTime entryTime) {
this.entryTime = entryTime;
}
public LocalDateTime getExitTime() {
return exitTime;
}
public void setExitTime(LocalDateTime exitTime) {
this.exitTime = exitTime;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
}
|
package com.neo.listener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
/**
* ApplicationEnvironmentPreparedEvent is send when the Environment
* to be used in the context is known but before the context is created
*/
@Slf4j
public class ApplicationEnvironmentPreparedEventListener implements
ApplicationListener<ApplicationEnvironmentPreparedEvent> {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
log.info("onApplicationEvent(event={})", event);
}
}
|
package be.openclinic.datacenter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.Debug;
import be.mxs.common.util.system.ScreenHelper;
public class POP3Receiver extends Receiver {
public void receive(){
String host = MedwanQuery.getInstance().getConfigString("datacenterPOP3Host","localhost");
String username = MedwanQuery.getInstance().getConfigString("datacenterPOP3Username","");
String password = MedwanQuery.getInstance().getConfigString("datacenterPOP3Password","");
Properties props=System.getProperties();
Session session = Session.getInstance(props, null);
try {
Store store = session.getStore("pop3");
Debug.println("Log in with user name "+username+" on POP3 server "+host);
store.connect(host, username, password);
Folder folder = store.getFolder("INBOX");
Debug.println("Opening POP3 mailbox INBOX");
folder.open(Folder.READ_WRITE);
Message message[] = folder.getMessages();
Debug.println("Total number of messages: "+message.length);
for (int i=0, n=message.length; i<n; i++) {
Debug.println("Analyzing message "+i);
if(message[i].getSubject().startsWith("datacenter.content")){
Debug.println("Message starts with datacenter.content");
//Store the message in the oc_imports database here and delete it if successful
SAXReader reader = new SAXReader(false);
try{
String ms = new String(message[i].getContent().toString().getBytes("UTF-8"));
if(ms.indexOf("</message>")>-1){
ms=ms.substring(0,ms.indexOf("</message>")+10);
}
Document document = reader.read(new ByteArrayInputStream(ms.getBytes("UTF-8")));
Element root = document.getRootElement();
Iterator msgs = root.elementIterator("data");
Vector ackMessages=new Vector();
while(msgs.hasNext()){
Element data = (Element)msgs.next();
ImportMessage msg = new ImportMessage(data);
msg.setType(root.attributeValue("type"));
Debug.println("Message type = "+root.attributeValue("type")+ " from "+message[i].getFrom()[0]);
msg.setReceiveDateTime(new java.util.Date());
msg.setRef("SMTP:"+message[i].getFrom()[0]);
try {
msg.store();
message[i].setFlag(Flags.Flag.DELETED, true);
ackMessages.add(msg);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Set ackDateTime for all received messages in mail
Debug.println("Sending ACK for received message "+i);
ImportMessage.sendAck(ackMessages);
}
catch(MessagingException e){
e.printStackTrace();
message[i].setFlag(Flags.Flag.DELETED, true);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message[i].setFlag(Flags.Flag.DELETED, true);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message[i].setFlag(Flags.Flag.DELETED, true);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if (message[i].getSubject().startsWith("datacenter.ack")){
SAXReader reader = new SAXReader(false);
try{
Document document = reader.read(new ByteArrayInputStream(message[i].getContent().toString().getBytes("UTF-8")));
Element root = document.getRootElement();
Iterator msgs = root.elementIterator("data");
while(msgs.hasNext()){
Element data = (Element)msgs.next();
AckMessage msg = new AckMessage(data);
if(msg.serverId==MedwanQuery.getInstance().getConfigInt("datacenterServerId",0)){
ExportMessage.updateAckDateTime(msg.getObjectId(), msg.getAckDateTime());
}
else {
//TODO: send warning to system administrator
//ACK received addressed to other server!
if(MedwanQuery.getInstance().getConfigInt("datacenterServerId",0)>=0 && msg.getServerId()>0){
String error="Server "+MedwanQuery.getInstance().getConfigInt("datacenterServerId",0)+" received SMTP ACK message intended for server "+msg.getServerId();
SMTPSender.sendSysadminMessage(error, msg);
}
}
}
message[i].setFlag(Flags.Flag.DELETED, true);
}
catch(MessagingException e){
Debug.println(e.getMessage());
message[i].setFlag(Flags.Flag.DELETED, true);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message[i].setFlag(Flags.Flag.DELETED, true);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message[i].setFlag(Flags.Flag.DELETED, true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if (message[i].getSubject().startsWith("datacenter.importack")){
SAXReader reader = new SAXReader(false);
try{
Document document = reader.read(new ByteArrayInputStream(message[i].getContent().toString().getBytes("UTF-8")));
Element root = document.getRootElement();
Iterator msgs = root.elementIterator("data");
while(msgs.hasNext()){
Element data = (Element)msgs.next();
ImportAckMessage msg = new ImportAckMessage(data);
if(msg.serverId==MedwanQuery.getInstance().getConfigInt("datacenterServerId",0)){
ExportMessage.updateImportAckDateTime(msg.getObjectId(), msg.getImportAckDateTime());
ExportMessage.updateImportDateTime(msg.getObjectId(), msg.getImportDateTime());
ExportMessage.updateErrorCode(msg.getObjectId(), msg.getError());
}
else {
//TODO: send warning to system administrator
//Import ACK received addressed to other server!
if(MedwanQuery.getInstance().getConfigInt("datacenterServerId",0)>=0 && msg.getServerId()>0){
String error="Server "+MedwanQuery.getInstance().getConfigInt("datacenterServerId",0)+" received SMTP ACK message intended for server "+msg.getServerId();
SMTPSender.sendSysadminMessage(error, msg);
}
}
}
message[i].setFlag(Flags.Flag.DELETED, true);
}
catch(MessagingException e){
Debug.println(e.getMessage());
message[i].setFlag(Flags.Flag.DELETED, true);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message[i].setFlag(Flags.Flag.DELETED, true);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message[i].setFlag(Flags.Flag.DELETED, true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
SAXReader reader = new SAXReader(false);
try {
Multipart multipart = (Multipart) message[i].getContent();
for (int o = 0; o < multipart.getCount(); o++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if(!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) &&
ScreenHelper.checkString(bodyPart.getFileName()).length()==0) {
continue; // dealing with attachments only
}
Document document = reader.read(bodyPart.getInputStream());
Element root = document.getRootElement();
if(root.attributeValue("type").equalsIgnoreCase("invoicefollowup")){
}
}
message[i].setFlag(Flags.Flag.DELETED, true);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
message[i].setFlag(Flags.Flag.DELETED, true);
}
}
}
// Close connection
folder.close(true);
store.close();
} catch (MessagingException e1) {
// TODO Auto-generated catch block
if(Debug.enabled) e1.printStackTrace();
}
}
}
|
package com.tqb.mapper;
import com.tqb.pojo.Conten;
import com.tqb.pojo.ContenExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface ContenMapper {
int countByExample(ContenExample example);
int deleteByExample(ContenExample example);
int deleteByPrimaryKey(Integer cId);
int insert(Conten record);
int insertSelective(Conten record);
List<Conten> selectByExample(ContenExample example);
Conten selectByPrimaryKey(Integer cId);
int updateByExampleSelective(@Param("record") Conten record, @Param("example") ContenExample example);
int updateByExample(@Param("record") Conten record, @Param("example") ContenExample example);
int updateByPrimaryKeySelective(Conten record);
int updateByPrimaryKey(Conten record);
} |
package com.example.databindingtest.data;
import android.util.Log;
import androidx.arch.core.util.Function;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;
/**
* @author hy
* @Date 2019/10/21 0021
**/
public class SimpleViewModel extends ViewModel {
public MutableLiveData<String> name = new MutableLiveData<>("Ada");
public MutableLiveData<String> lastName = new MutableLiveData<>("Lovelace");
public MutableLiveData<Integer> likes = new MutableLiveData<>(0);
public LiveData<Popularity> popularity = Transformations.map(likes, new Function<Integer, Popularity>() {
@Override
public Popularity apply(Integer input) {
if (input > 9) {
return Popularity.STAR;
} else if (input > 4) {
return Popularity.POPULAR;
}
return Popularity.NORMAL;
}
});
public MutableLiveData<Integer> getLikes() {
return likes;
}
public void setLikes(Integer likes) {
this.likes.setValue(likes);
}
public void onLike() {
Integer value = likes.getValue();
if (value == null) value = 0;
value = value + 1;
Log.d("SimpleViewModel", "onLike: value = " + value);
likes.setValue(value);
}
public enum Popularity {
NORMAL,
POPULAR,
STAR
}
}
|
package nl.tue.win.dbt.tests;
import nl.tue.win.dbt.data.GraphCreator;
import nl.tue.win.dbt.data.LabeledGraph;
import nl.tue.win.dbt.data.LabeledHistoryGraph;
import nl.tue.win.dbt.data.LabeledVersionGraph;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Objects;
public class LvgTime<V, E, L> {
private final LabeledHistoryGraph<LabeledGraph<V, E, L>, V, E, L> lhg;
private final LabeledVersionGraph<V, E, L> lvg;
private final GraphCreator<LabeledGraph<V, E, L>, V, E> graphCreator;
private final long startLvg;
private final long endLvg;
private final long startWrite;
private final long endWrite;
public LvgTime(LabeledHistoryGraph<LabeledGraph<V, E, L>, V, E, L> lhg) {
Objects.requireNonNull(lhg);
this.lhg = lhg;
this.graphCreator = lhg.getGraphCreator();
this.startLvg = System.currentTimeMillis();
this.lvg = new LabeledVersionGraph<>(this.lhg);
this.endLvg = this.startWrite = System.currentTimeMillis();
// this.writeToFile("data/lvg.ser");
this.endWrite = System.currentTimeMillis();
}
public LabeledHistoryGraph<LabeledGraph<V, E, L>, V, E, L> getLhg() {
return this.lhg;
}
public LabeledVersionGraph<V, E, L> getLvg() {
return this.lvg;
}
public long getStartLvg() {
return this.startLvg;
}
public long getEndLvg() {
return this.endLvg;
}
public long getStartWrite() {
return this.startWrite;
}
public long getEndWrite() {
return this.endWrite;
}
public long calculateLvgDelta() {
return this.endLvg - this.startLvg;
}
public long calculateWriteDelta() {
return this.endWrite - this.startWrite;
}
private void writeToFile(String filename) {
try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename))) {
out.writeObject(this.lvg);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class A7memberaction {
public void memberAppend(String filename,String name,int age)
{
BufferedWriter bw=null;
try{
bw=new BufferedWriter(new FileWriter(filename,true));
bw.write(name+","+age+"\n");
}catch(IOException e){
System.out.println(e);
}finally{
if(bw!=null)try{bw.close();}catch(IOException e){};
}
}
public void memberRead()
{
}
}
|
package com.theshoes.jsp.board.model.dto;
import java.io.Serializable;
import java.sql.Date;
public class BoardAndBoardCategoryDTO implements Serializable{
private static final long serialVersionUID = 2985353657379854092L;
private int boardNo; // 게시글번호
private String boardId; // 아이디
private BoardCategoryDTO boardCategory; // 메뉴:카테고리 = 1:1 (association)
private String boardTitle; // 제목
private String boardContent; // 내용
private Date boardRegDate; // 작성일자
private int boardHit; // 조회수
private int categoryOrder; // (카테고리별) 게시글 '순서'
public BoardAndBoardCategoryDTO() {
}
public BoardAndBoardCategoryDTO(int boardNo, String boardId, BoardCategoryDTO boardCategory, String boardTitle,
String boardContent, Date boardRegDate, int boardHit, int categoryOrder) {
this.boardNo = boardNo;
this.boardId = boardId;
this.boardCategory = boardCategory;
this.boardTitle = boardTitle;
this.boardContent = boardContent;
this.boardRegDate = boardRegDate;
this.boardHit = boardHit;
this.categoryOrder = categoryOrder;
}
public int getBoardNo() {
return boardNo;
}
public void setBoardNo(int boardNo) {
this.boardNo = boardNo;
}
public String getBoardId() {
return boardId;
}
public void setBoardId(String boardId) {
this.boardId = boardId;
}
public BoardCategoryDTO getBoardCategory() {
return boardCategory;
}
public void setBoardCategory(BoardCategoryDTO boardCategory) {
this.boardCategory = boardCategory;
}
public String getBoardTitle() {
return boardTitle;
}
public void setBoardTitle(String boardTitle) {
this.boardTitle = boardTitle;
}
public String getBoardContent() {
return boardContent;
}
public void setBoardContent(String boardContent) {
this.boardContent = boardContent;
}
public Date getBoardRegDate() {
return boardRegDate;
}
public void setBoardRegDate(Date boardRegDate) {
this.boardRegDate = boardRegDate;
}
public int getBoardHit() {
return boardHit;
}
public void setBoardHit(int boardHit) {
this.boardHit = boardHit;
}
public int getCategoryOrder() {
return categoryOrder;
}
public void setCategoryOrder(int categoryOrder) {
this.categoryOrder = categoryOrder;
}
@Override
public String toString() {
return "BoardAndBoardCategoryDTO [boardNo=" + boardNo + ", boardId=" + boardId + ", boardCategory="
+ boardCategory + ", boardTitle=" + boardTitle + ", boardContent=" + boardContent + ", boardRegDate="
+ boardRegDate + ", boardHit=" + boardHit + ", categoryOrder=" + categoryOrder + "]";
}
}
|
package com.developworks.jvmcode;
/**
* <p>Title: d2f</p>
* <p>Description: 将double类型数据转换为float</p>
* <p>Author: ouyp </p>
* <p>Date: 2018-05-19 16:05</p>
*/
public class d2f {
public void d2f(double d, float f) {
f = (float)d;
}
}
/**
* public void d2f(double, float);
* Code:
* 0: dload_1
* 1: d2f
* 2: fstore_3
* 3: return
*/ |
package com.tradesystem.tradesystem.persistence.entity;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name="TRADE_STORE")
public class TradeStore {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
@Column(name="TRADE_ID")
private String tradeId;
@Column(name="COUNTER_PARTY_ID")
private String counterPartyId;
@Column(name="VERSION")
private Integer version;
@Column(name="BOOK_ID")
private String bookingId;
@Column(name="EXPIRED_FLAG")
private String expiredFlag;
@Column(name="MATURITY_ON")
private Date maturityDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTradeId() {
return tradeId;
}
public void setTradeId(String tradeId) {
this.tradeId = tradeId;
}
public String getCounterPartyId() {
return counterPartyId;
}
public void setCounterPartyId(String counterPartyId) {
this.counterPartyId = counterPartyId;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public String getBookingId() {
return bookingId;
}
public void setBookingId(String bookingId) {
this.bookingId = bookingId;
}
public String getExpiredFlag() {
return expiredFlag;
}
public void setExpiredFlag(String expiredFlag) {
this.expiredFlag = expiredFlag;
}
public Date getMaturityDate() {
return maturityDate;
}
public void setMaturityDate(Date maturityDate) {
this.maturityDate = maturityDate;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
@Column(name="CREATED_ON")
private Date createdDate;
}
|
/*
* Copyright 2002-2021 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.test.web.servlet.setup;
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ser.impl.UnknownSerializer;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.springframework.http.converter.json.SpringHandlerInstantiator;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link StandaloneMockMvcBuilder}
*
* @author Rossen Stoyanchev
* @author Rob Winch
* @author Sebastien Deleuze
*/
class StandaloneMockMvcBuilderTests {
@Test // SPR-10825
void placeHoldersInRequestMapping() throws Exception {
TestStandaloneMockMvcBuilder builder = new TestStandaloneMockMvcBuilder(new PlaceholderController());
builder.addPlaceholderValue("sys.login.ajax", "/foo");
builder.build();
RequestMappingHandlerMapping hm = builder.wac.getBean(RequestMappingHandlerMapping.class);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo");
HandlerExecutionChain chain = hm.getHandler(request);
assertThat(chain).isNotNull();
assertThat(((HandlerMethod) chain.getHandler()).getMethod().getName()).isEqualTo("handleWithPlaceholders");
}
@Test // SPR-13637
@SuppressWarnings("deprecation")
void suffixPatternMatch() throws Exception {
TestStandaloneMockMvcBuilder builder = new TestStandaloneMockMvcBuilder(new PersonController());
builder.setUseSuffixPatternMatch(false);
builder.build();
RequestMappingHandlerMapping hm = builder.wac.getBean(RequestMappingHandlerMapping.class);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/persons");
HandlerExecutionChain chain = hm.getHandler(request);
assertThat(chain).isNotNull();
assertThat(((HandlerMethod) chain.getHandler()).getMethod().getName()).isEqualTo("persons");
request = new MockHttpServletRequest("GET", "/persons.xml");
chain = hm.getHandler(request);
assertThat(chain).isNull();
}
@Test // SPR-12553
void applicationContextAttribute() {
TestStandaloneMockMvcBuilder builder = new TestStandaloneMockMvcBuilder(new PlaceholderController());
builder.addPlaceholderValue("sys.login.ajax", "/foo");
WebApplicationContext wac = builder.initWebAppContext();
assertThat(WebApplicationContextUtils.getRequiredWebApplicationContext(wac.getServletContext())).isEqualTo(wac);
}
@Test
void addFiltersFiltersNull() {
StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(new PersonController());
assertThatIllegalArgumentException().isThrownBy(() ->
builder.addFilters((Filter[]) null));
}
@Test
void addFiltersFiltersContainsNull() {
StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(new PersonController());
assertThatIllegalArgumentException().isThrownBy(() ->
builder.addFilters(new ContinueFilter(), null));
}
@Test
void addFilterPatternsNull() {
StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(new PersonController());
assertThatIllegalArgumentException().isThrownBy(() ->
builder.addFilter(new ContinueFilter(), (String[]) null));
}
@Test
void addFilterPatternContainsNull() {
StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(new PersonController());
assertThatIllegalArgumentException().isThrownBy(() ->
builder.addFilter(new ContinueFilter(), (String) null));
}
@Test // SPR-13375
@SuppressWarnings("rawtypes")
void springHandlerInstantiator() {
TestStandaloneMockMvcBuilder builder = new TestStandaloneMockMvcBuilder(new PersonController());
builder.build();
SpringHandlerInstantiator instantiator = new SpringHandlerInstantiator(builder.wac.getAutowireCapableBeanFactory());
JsonSerializer serializer = instantiator.serializerInstance(null, null, UnknownSerializer.class);
assertThat(serializer).isNotNull();
}
@Controller
private static class PlaceholderController {
@RequestMapping(value = "${sys.login.ajax}")
private void handleWithPlaceholders() { }
}
private static class TestStandaloneMockMvcBuilder extends StandaloneMockMvcBuilder {
private WebApplicationContext wac;
private TestStandaloneMockMvcBuilder(Object... controllers) {
super(controllers);
}
@Override
protected WebApplicationContext initWebAppContext() {
this.wac = super.initWebAppContext();
return this.wac;
}
}
@Controller
private static class PersonController {
@RequestMapping(value="/persons")
public String persons() {
return null;
}
@RequestMapping(value="/forward")
public String forward() {
return "forward:/persons";
}
}
private static class ContinueFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
filterChain.doFilter(request, response);
}
}
}
|
package com.example.NFEspring.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Set;
@Entity
@Table(name = "item")
public class Item implements Serializable {
@Id
@Column(name = "it_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "it_label")
@NotEmpty
private String label;
@Column(name = "it_readonly")
@NotNull
private boolean readonly;
@Column(name = "it_required")
@NotNull
private boolean required;
@Column(name = "it_sort")
@NotNull
private Integer sort;
@OneToOne
@JoinColumn(name = "it_tracker")
@NotNull
private Tracker tracker;
@OneToOne
@JoinColumn(name = "it_universal")
@NotNull
private Universal universal;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "item")
@NotNull
@JsonIgnoreProperties("item")
private Set<ItemOption> options;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public boolean isReadonly() {
return readonly;
}
public void setReadonly(boolean readonly) {
this.readonly = readonly;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Tracker getTracker() {
return tracker;
}
public void setTracker(Tracker tracker) {
this.tracker = tracker;
}
public Universal getUniversal() {
return universal;
}
public void setUniversal(Universal universal) {
this.universal = universal;
}
public Set<ItemOption> getOptions() {
return options;
}
public void setOptions(Set<ItemOption> options) {
this.options = options;
}
}
|
package android.example.bakingapp;
import android.content.Context;
import android.content.Intent;
import android.example.bakingapp.Data.Steps;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import static android.example.bakingapp.DetailActivity.isTablet;
public class ShortDescAdapter extends RecyclerView.Adapter<ShortDescAdapter.ItemViewHolder> {
Context context;
ArrayList<Steps> steps;
final static String KEY_STEP="step";
public ShortDescAdapter(Context context, ArrayList<Steps> steps) {
this.context = context;
this.steps=steps;
}
@NonNull
@Override
public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater=LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.item_detail_recycle,viewGroup,false);
return new ShortDescAdapter.ItemViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ItemViewHolder itemViewHolder, int i) {
itemViewHolder.textViewIntro.setText(steps.get(i).getShortDescription());
}
@Override
public int getItemCount() {
return steps.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder{
TextView textViewIntro;
public ItemViewHolder(@NonNull final View itemView) {
super(itemView);
textViewIntro=itemView.findViewById(R.id.text_view_recycle_detail);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (steps!=null){
Bundle bundle=new Bundle();
Steps step=steps.get(getAdapterPosition());
bundle.putParcelable(KEY_STEP,step);
if (isTablet){
DescFragment descFragment =new DescFragment();
VideoFragment videoFragment=new VideoFragment();
videoFragment.setStep(step);
descFragment.setStep(step);
AppCompatActivity activity = (AppCompatActivity) v.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frame_vid,videoFragment).commit();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frame_text,descFragment).commit();
}
else{
Intent intent= new Intent(context, VideoDescActivity.class);
intent.putExtras(bundle);
context.startActivity(intent);
}
}
}
});
}
}
}
|
package pro.likada.service.serviceImpl;
import pro.likada.dao.CustomerDAO;
import pro.likada.model.Customer;
import pro.likada.model.User;
import pro.likada.service.CustomerService;
import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.Transactional;
import java.util.List;
/**
* Created by Yusupov on 12/19/2016.
*/
@Named("customerService")
@Transactional
public class CustomerServiceImpl implements CustomerService {
@Inject
private CustomerDAO customerDAO;
@Override
public Customer findById(long id) {
return customerDAO.findById(id);
}
@Override
public List<Customer> findByTitle(String title) {
return customerDAO.findByTitle(title);
}
@Override
public void save(Customer customer) {
customerDAO.save(customer);
}
@Override
public void deleteById(long id) {
customerDAO.deleteById(id);
}
@Override
public void deleteByTitle(String title) {
customerDAO.deleteByTitle(title);
}
@Override
public List<Customer> findAllCustomers(String searchStringTitle) {
return customerDAO.findAllCustomers(searchStringTitle);
}
@Override
public List<Customer> findAllCustomersBasedOnUserRole(User user, Integer startFrom, Integer maxNumberOfResults) {
return customerDAO.findAllCustomersBasedOnUserRole(user, startFrom, maxNumberOfResults);
}
@Override
public Long countCustomersBasedOnUserRole(User user) {
return customerDAO.countCustomersBasedOnUserRole(user);
}
}
|
package com.example.recyclerview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private UserMessageAdapter mUserWordMessageAdapter;
private EditText mEditTextUserWordMessage;
private List<UserMessage> mUserWordMessageList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditTextUserWordMessage=findViewById(R.id.edittextUserMessage);
mUserWordMessageList=new ArrayList<>();
mRecyclerView=findViewById(R.id.recyclerview);
mUserWordMessageAdapter=new UserMessageAdapter(mUserWordMessageList);
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setAdapter(mUserWordMessageAdapter);
}
/**
* 用户按下消息发送按钮时发送消息
* @param view
*/
public void onButtonSendMessageClick(View view)
{
String content=mEditTextUserWordMessage.getText().toString();
content=content.trim();
if(content.length()==0){
Toast.makeText(this,"文本内容不能为空",Toast.LENGTH_SHORT).show();
return;
}
addSendMessage(content);
/**
* 这里模拟接收对方发送的消息,在实际程序中,应该定时从网络获得相关数据
*/
addReceiveMessage("我接受到"+content);
}
/**
* 增加接收消息
* @param content
*/
private void addReceiveMessage(String content){
UserMessage userWordMessage=new UserMessage(content,UserMessage.TYPE_RECEIVE);
mUserWordMessageList.add(userWordMessage);
mUserWordMessageAdapter.notifyItemInserted(mUserWordMessageList.size()-1);
mRecyclerView.scrollToPosition(mUserWordMessageList.size()-1);
mEditTextUserWordMessage.setText("");
}
/**
* 增加发送消息
* @param content
*/
private void addSendMessage(String content){
UserMessage userWordMessage=new UserMessage(content,UserMessage.TYPE_SEND);
mUserWordMessageList.add(userWordMessage);
mUserWordMessageAdapter.notifyItemInserted(mUserWordMessageList.size()-1);
mRecyclerView.scrollToPosition(mUserWordMessageList.size()-1);
mEditTextUserWordMessage.setText("");
}
} |
package com.demo;
/**
* Created by xu-f1 on 2018/8/17.
*/
public class test {
public static void main(String []args){
String str="<html><h1>sdfsdfsdf</h1><img src=\"1.png\"></img></html>测试</td>测试测试</td>测试</td></p>";
str = str.replaceAll("</td>","@@");
str = str.replaceAll("<[a-zA-Z]+[1-9]?[^><]*>", "").replaceAll("</[a-zA-Z]+[1-9]?>", "");
str = str.replaceAll("@@","<br/>");
System.out.println(str);
}
}
|
package com.cht.training.Lab8d;
import com.cht.training.Lab8.Employee;
public class Customer {
public void foo() {
Employee e1 = new Employee();
System.out.println("a=" + e1.a);
// System.out.println("a=" + e1.b);
// System.out.println("a=" + e1.c);
// System.out.println("a=" + e1.d);
}
}
|
/*
*
* Copyright 2018 EMBL - European Bioinformatics Institute
*
* 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 uk.ac.ebi.ega.accession.file.rest;
import uk.ac.ebi.ega.accession.file.FileModel;
import uk.ac.ebi.ega.accession.file.HashType;
@ValidHash
public class FileDTO implements FileModel {
private HashType hashType;
private String hash;
FileDTO() {
}
public FileDTO(HashType hashType, String hash) {
this.hashType = hashType;
this.hash = hash;
}
public String getHash() {
return hash;
}
public HashType getHashType() {
return hashType;
}
}
|
/*
* 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.innovaciones.reporte.service;
import com.innovaciones.reporte.model.UnidadMedida;
import java.util.List;
/**
*
* @author fyaulema
*/
public interface UnidadMedidaService {
public UnidadMedida addUnidadMedida(UnidadMedida unidadMedida);
public List<UnidadMedida> getUnidadMedidas();
public UnidadMedida getUnidadMedidaById(Integer id);
public UnidadMedida getUnidadMedidaByCodigo(String codigo);
public UnidadMedida getUnidadMedidaByNombre(String codigo);
public List<UnidadMedida> getUnidadMedidasByEstado(Integer estado);
public UnidadMedida saveUnidadMedida(UnidadMedida unidadMedida) ;
}
|
package com.star.entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
/**
* 分类实体类,和博客一对多
*/
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class Type {
private Long id;
private String name;
private List<Blog> blogs = new ArrayList<>();
}
|
package com.hubpan.IslandBooking.api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.Future;
import javax.validation.constraints.FutureOrPresent;
import javax.validation.constraints.NotNull;
import java.time.ZonedDateTime;
@Data
public class BookingUpdateRequestDTO {
@NotNull
@ApiModelProperty(notes = "id of the campsite", name = "campSiteId", required = true)
private final Long campSiteId;
@NotNull
@FutureOrPresent
@ApiModelProperty(notes = "the start of the reservation", name = "from", required = true)
private final ZonedDateTime from;
@NotNull
@Future
@ApiModelProperty(notes = "then end of the reservation", name = "to", required = true)
private final ZonedDateTime to;
} |
package com.lotus.workers;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.lotus.model.TweetDetails;
public class TweetPipeline {
private static TweetPipeline pipeline = null;
public ConcurrentLinkedQueue<TweetDetails> tweetQueue = new ConcurrentLinkedQueue<TweetDetails>();
private TweetPipeline() {}
public static TweetPipeline getInstance() {
if(pipeline == null) {
pipeline = new TweetPipeline();
}
return pipeline;
}
public synchronized void addTweet(TweetDetails tweet) {
tweetQueue.add(tweet);
// tweetQueue.notifyAll();
}
public synchronized TweetDetails getTweet() {
return tweetQueue.poll();
}
}
|
/*
* 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 tp2pbo;
import java.awt.HeadlessException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import net.proteanit.sql.DbUtils;
/**
*
* @author ASUS
*/
public class tp2pbo extends javax.swing.JFrame {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
ArrayList<Mobil> listMobil;
String header[] = new String[]{"No", "Merk", "Plat", "Warna", "Jenis"};
DefaultTableModel dtm;
int row,col;
/**
* Creates new form tp2pbo
*/
public tp2pbo() {
initComponents();
listMobil = new ArrayList<>();
dtm = new DefaultTableModel(header, 0);
jTable1.setModel(dtm);
// this.setLocationRelativeTo(null);
pan1.setVisible(false);
pan2.setVisible(false);
pan3.setVisible(false);
jLabel6.setVisible(true);
jComboBox1.setVisible(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
welcome = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
btn1 = new javax.swing.JButton();
btn2 = new javax.swing.JButton();
btn3 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
pan2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
pan1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
tMerk = new javax.swing.JTextField();
tPlat = new javax.swing.JTextField();
tWarna = new javax.swing.JTextField();
jComboBox1 = new javax.swing.JComboBox<>();
jButton1 = new javax.swing.JButton();
pan3 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
welcome.setFont(new java.awt.Font("Impact", 0, 24)); // NOI18N
welcome.setForeground(new java.awt.Color(0, 51, 51));
welcome.setText("Selamat Datang!");
jPanel1.setBackground(new java.awt.Color(153, 153, 153));
btn1.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
btn1.setText("Form");
btn1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn1MouseClicked(evt);
}
});
btn2.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
btn2.setText("Table");
btn2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn2MouseClicked(evt);
}
});
btn2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn2ActionPerformed(evt);
}
});
btn3.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
btn3.setText("Info");
btn3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn3MouseClicked(evt);
}
});
jLabel1.setFont(new java.awt.Font("Ebrima", 1, 36)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Data Mobil");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(72, 72, 72)
.addComponent(btn1)
.addGap(43, 43, 43)
.addComponent(btn2)
.addGap(44, 44, 44)
.addComponent(btn3))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(96, 96, 96)
.addComponent(jLabel1)))
.addContainerGap(43, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn1)
.addComponent(btn2)
.addComponent(btn3))
.addGap(36, 36, 36))
);
pan2.setBackground(new java.awt.Color(0, 153, 153));
jTable1.setBackground(new java.awt.Color(204, 204, 204));
jTable1.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}
},
new String [] {
"No", "Merk", "Plat", "Warna", "Jenis"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout pan2Layout = new javax.swing.GroupLayout(pan2);
pan2.setLayout(pan2Layout);
pan2Layout.setHorizontalGroup(
pan2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 365, Short.MAX_VALUE)
.addGroup(pan2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pan2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE)
.addContainerGap()))
);
pan2Layout.setVerticalGroup(
pan2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 470, Short.MAX_VALUE)
.addGroup(pan2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pan2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 458, Short.MAX_VALUE)
.addContainerGap()))
);
pan1.setBackground(new java.awt.Color(0, 255, 204));
jLabel2.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
jLabel2.setForeground(new java.awt.Color(0, 0, 0));
jLabel2.setText("Merk");
jLabel3.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
jLabel3.setForeground(new java.awt.Color(0, 0, 0));
jLabel3.setText("Plat");
jLabel4.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
jLabel4.setForeground(new java.awt.Color(0, 0, 0));
jLabel4.setText("Warna");
jLabel6.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
jLabel6.setForeground(new java.awt.Color(0, 0, 0));
jLabel6.setText("Jenis");
tMerk.setBackground(new java.awt.Color(255, 255, 255));
tMerk.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
tPlat.setBackground(new java.awt.Color(255, 255, 255));
tPlat.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
tWarna.setBackground(new java.awt.Color(255, 255, 255));
tWarna.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jComboBox1.setBackground(new java.awt.Color(255, 255, 255));
jComboBox1.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jComboBox1.setForeground(new java.awt.Color(0, 0, 0));
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Biasa", "Balap", "Sport", "Truk" }));
jButton1.setBackground(new java.awt.Color(255, 255, 255));
jButton1.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jButton1.setForeground(new java.awt.Color(0, 0, 0));
jButton1.setText("Submit");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout pan1Layout = new javax.swing.GroupLayout(pan1);
pan1.setLayout(pan1Layout);
pan1Layout.setHorizontalGroup(
pan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pan1Layout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(pan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel6))
.addGap(18, 18, 18)
.addGroup(pan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(tPlat, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE)
.addComponent(tMerk)
.addComponent(tWarna)
.addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pan1Layout.createSequentialGroup()
.addContainerGap(109, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(137, 137, 137))
);
pan1Layout.setVerticalGroup(
pan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pan1Layout.createSequentialGroup()
.addGap(60, 60, 60)
.addGroup(pan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(tMerk, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(47, 47, 47)
.addGroup(pan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(tPlat, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
.addGroup(pan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(tWarna, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(38, 38, 38)
.addGroup(pan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox1))
.addGap(65, 65, 65)
.addComponent(jButton1)
.addGap(47, 47, 47))
);
pan3.setBackground(new java.awt.Color(0, 102, 102));
jLabel5.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Nama : Sekar Andika Putri");
jLabel7.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 255, 255));
jLabel7.setText("NIM : 1903970");
jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/tp2pbo/image/sekar.png"))); // NOI18N
jLabel8.setText("jLabel1");
javax.swing.GroupLayout pan3Layout = new javax.swing.GroupLayout(pan3);
pan3.setLayout(pan3Layout);
pan3Layout.setHorizontalGroup(
pan3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 365, Short.MAX_VALUE)
.addGroup(pan3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pan3Layout.createSequentialGroup()
.addContainerGap(33, Short.MAX_VALUE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(78, Short.MAX_VALUE)))
.addGroup(pan3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pan3Layout.createSequentialGroup()
.addContainerGap(33, Short.MAX_VALUE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(170, Short.MAX_VALUE)))
.addGroup(pan3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pan3Layout.createSequentialGroup()
.addContainerGap(110, Short.MAX_VALUE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(118, Short.MAX_VALUE)))
);
pan3Layout.setVerticalGroup(
pan3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 464, Short.MAX_VALUE)
.addGroup(pan3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pan3Layout.createSequentialGroup()
.addContainerGap(283, Short.MAX_VALUE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(136, Short.MAX_VALUE)))
.addGroup(pan3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pan3Layout.createSequentialGroup()
.addContainerGap(323, Short.MAX_VALUE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(89, Short.MAX_VALUE)))
.addGroup(pan3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pan3Layout.createSequentialGroup()
.addContainerGap(26, Short.MAX_VALUE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(217, Short.MAX_VALUE)))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pan1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pan3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pan2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(129, 129, 129)
.addComponent(welcome, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(53, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pan1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 181, Short.MAX_VALUE)
.addComponent(pan3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 175, Short.MAX_VALUE)
.addComponent(pan2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(283, 283, 283)
.addComponent(welcome, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(253, Short.MAX_VALUE)))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void btn1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn1MouseClicked
// TODO add your handling code here:
pan1.setVisible(true);
pan2.setVisible(false);
pan3.setVisible(false);
}//GEN-LAST:event_btn1MouseClicked
private void btn2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn2MouseClicked
// TODO add your handling code here:
pan1.setVisible(false);
pan2.setVisible(true);
pan3.setVisible(false);
}//GEN-LAST:event_btn2MouseClicked
private void btn3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn3MouseClicked
// TODO add your handling code here:
pan1.setVisible(false);
pan2.setVisible(false);
pan3.setVisible(true);
}//GEN-LAST:event_btn3MouseClicked
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
//Menambahkan data ke Database
try
{
String sql = "insert into mobil (merk, plat, warna, jenis) values (?,?,?,?)";
con = DriverManager.getConnection("jdbc:mysql://localhost/tp2pbo","root","");
pst = con.prepareStatement(sql);
pst.setString(1, tMerk.getText());
pst.setString(2, tPlat.getText());
pst.setString(3, tWarna.getText());
pst.setString(4, (String) jComboBox1.getSelectedItem());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "success");
}
catch(HeadlessException | SQLException e)
{
JOptionPane.showMessageDialog(null, e);
}
tMerk.setText("");
tPlat.setText("");
tWarna.setText("");
jComboBox1.setSelectedIndex(0);
btn2.setVisible(true);
btn3.setVisible(true);
}//GEN-LAST:event_jButton1ActionPerformed
private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn2ActionPerformed
// TODO add your handling code here:
//Menampilkan data di tabel sesuai Database
try
{
String sql = "select * from mobil";
con = DriverManager.getConnection("jdbc:mysql://localhost/tp2pbo","root","");
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}//GEN-LAST:event_btn2ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(tp2pbo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(tp2pbo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(tp2pbo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(tp2pbo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new tp2pbo().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn1;
private javax.swing.JButton btn2;
private javax.swing.JButton btn3;
private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JPanel pan1;
private javax.swing.JPanel pan2;
private javax.swing.JPanel pan3;
private javax.swing.JTextField tMerk;
private javax.swing.JTextField tPlat;
private javax.swing.JTextField tWarna;
private javax.swing.JLabel welcome;
// End of variables declaration//GEN-END:variables
}
|
package ru.vyarus.dropwizard.guice.module.context.unique;
import ru.vyarus.dropwizard.guice.module.context.info.ItemInfo;
import java.util.Collection;
/**
* Configuration items may be registered by class (extension, installer) or by instance (guicey bundle, guice module).
* Duplicates are obvious for class registrations: one class - one extension instance (no matter how much times
* this class was registered). But for instances it's not so obvious. For example, in dropwizard you can
* register multiple instances of the same bundle (and it's often very useful!). But, sometimes,
* there are common bundles (or guice modules), used by multiple other bundles (and so declared by all of them).
* In this case it would be desirable to register common bundle just once (and avoid duplicate).
* <p>
* This is exactly the case why duplicates detector exists: when multiple instances of the same class detected
* (guicey bundle, guice module) detector is asked to decide if multiple instances are allowed.
* Custom implementations may be used to resolve existing duplicates (e.g. registered by different 3rd party modules).
*
* @author Vyacheslav Rusakov
* @see EqualDuplicatesDetector as default implementation
* @see LegacyModeDuplicatesDetector with legacy guicey behaviour implementation (always one instance per class)
* @since 03.07.2019
*/
public interface DuplicateConfigDetector {
/**
* Called every time when configured object (guicey bundle or guice module) of the same type is already registered.
* Used to resolve duplicate registrations: decide to allow another instance or not.
* <p>
* If 3 or more instances of the same type are registered then method would be called for each new configured
* instance (in case of 3 registrations - 2 method calls).
*
* @param info item descriptor
* @param registered already registered items
* @param newItem new item to check
* @return true to prevent item registration, false to allow registration
*/
boolean isDuplicate(ItemInfo info, Collection<Object> registered, Object newItem);
}
|
package com.getroadmap.r2rlib.models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jan on 11/07/16.
*/
public class SurfaceAgency implements Parcelable {
/**
* agency integer Agency (index into agencies array)
* frequency float Estimated feequency (per week) (optional)
* duration float Estimated duration (in minutes) (optional)
* operatingDays DayFlags Days of operation bitmask (optional)
* lineNames SurfaceLineName[] Array of line names (optional) [1]
* lineCodes SurfaceLineCode[] Array of line codes (optional) [1]
* links ExternalLink[] Array of links (optional)
*/
private int agency;
private float frequency;
private float duration;
private DayFlags operatindDays;
private List<SurfaceLineName> lineNames;
private List<SurfaceLineCode> lineCodes;
private List<ExternalLink> links;
public SurfaceAgency() {
}
public int getAgency() {
return agency;
}
public void setAgency(int agency) {
this.agency = agency;
}
public float getFrequency() {
return frequency;
}
public void setFrequency(float frequency) {
this.frequency = frequency;
}
public float getDuration() {
return duration;
}
public void setDuration(float duration) {
this.duration = duration;
}
public DayFlags getOperatindDays() {
return operatindDays;
}
public void setOperatindDays(DayFlags operatindDays) {
this.operatindDays = operatindDays;
}
public List<SurfaceLineName> getLineNames() {
return lineNames;
}
public void setLineNames(List<SurfaceLineName> lineNames) {
this.lineNames = lineNames;
}
public List<SurfaceLineCode> getLineCodes() {
return lineCodes;
}
public void setLineCodes(List<SurfaceLineCode> lineCodes) {
this.lineCodes = lineCodes;
}
public List<ExternalLink> getLinks() {
return links;
}
public void setLinks(List<ExternalLink> links) {
this.links = links;
}
protected SurfaceAgency(Parcel in) {
agency = in.readInt();
frequency = in.readFloat();
duration = in.readFloat();
operatindDays = (DayFlags) in.readValue(DayFlags.class.getClassLoader());
if (in.readByte() == 0x01) {
lineNames = new ArrayList<SurfaceLineName>();
in.readList(lineNames, SurfaceLineName.class.getClassLoader());
} else {
lineNames = null;
}
if (in.readByte() == 0x01) {
lineCodes = new ArrayList<SurfaceLineCode>();
in.readList(lineCodes, SurfaceLineCode.class.getClassLoader());
} else {
lineCodes = null;
}
if (in.readByte() == 0x01) {
links = new ArrayList<ExternalLink>();
in.readList(links, ExternalLink.class.getClassLoader());
} else {
links = null;
}
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(agency);
dest.writeFloat(frequency);
dest.writeFloat(duration);
dest.writeValue(operatindDays);
if (lineNames == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(lineNames);
}
if (lineCodes == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(lineCodes);
}
if (links == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(links);
}
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<SurfaceAgency> CREATOR = new Parcelable.Creator<SurfaceAgency>() {
@Override
public SurfaceAgency createFromParcel(Parcel in) {
return new SurfaceAgency(in);
}
@Override
public SurfaceAgency[] newArray(int size) {
return new SurfaceAgency[size];
}
};
@Override
public String toString() {
return "SurfaceAgency{" +
"agency=" + agency +
", frequency=" + frequency +
", duration=" + duration +
", operatindDays=" + operatindDays +
", lineNames=" + lineNames +
", lineCodes=" + lineCodes +
", links=" + links +
'}';
}
} |
package com.gsccs.sme.center.controller;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gsccs.sme.api.domain.Account;
import com.gsccs.sme.api.domain.Sneed;
import com.gsccs.sme.api.domain.base.Datagrid;
import com.gsccs.sme.api.domain.base.JsonMsg;
import com.gsccs.sme.api.exception.ApiException;
import com.gsccs.sme.api.service.AccountServiceI;
import com.gsccs.sme.api.service.CorpServiceI;
import com.gsccs.sme.api.service.SneedServiceI;
/**
* 企业需求管理
*
* @author x.d zhang
*
*/
@Controller(value="NeedCtl")
@RequestMapping(value = "/cp/sneed")
public class NeedController {
@Autowired
private AccountServiceI accountAPI;
@Autowired
private CorpServiceI corpAPI;
@Autowired
private SneedServiceI sneedAPI;
/**
* 需求列表
*
* @param model
* @param response
* @return
*/
@RequestMapping(value="/list",method = RequestMethod.GET)
public String sneedlist(Model model, HttpServletResponse response) {
return "sneed/sneed-list";
}
/**
* 需求详情
*
* @param model
* @param response
* @return
*/
@RequestMapping(value="/view",method = RequestMethod.GET)
public String view(Long id,Model model, HttpServletResponse response) {
Sneed sneed = null;
try {
sneed = sneedAPI.getSneed(id);
} catch (ApiException e) {
e.printStackTrace();
}
model.addAttribute("sneed", sneed);
return "sneed/sneed-view";
}
/**
* 需求表单
*
* @param model
* @param response
* @return
*/
@RequestMapping(value = "/form", method = RequestMethod.GET)
public String form(Long id,Model model, HttpServletResponse response) {
Subject subject = SecurityUtils.getSubject();
String username = (String) subject.getPrincipal();
Account user = null;
Sneed sneed = null;
try {
user = accountAPI.getAccount(username);
sneed = sneedAPI.getSneed(id);
} catch (ApiException e) {
e.printStackTrace();
}
model.addAttribute("sneed",sneed);
model.addAttribute("user", user);
return "sneed/sneed-form";
}
@ResponseBody
@RequestMapping(value = "/datagrid", method = RequestMethod.POST)
public Datagrid datagrid(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int pagesize, Model model,
HttpServletResponse response) {
Subject subject = SecurityUtils.getSubject();
String username = (String) subject.getPrincipal();
Datagrid datagrid = new Datagrid();
try {
Sneed sneed = new Sneed();
Account user = accountAPI.getAccount(username);
if (null != user) {
sneed.setCorpid(user.getOrgid());
}
List<Sneed> sneedList = sneedAPI.querySneedList(sneed,
"addtime desc", page, pagesize);
datagrid.setRows(sneedList);
datagrid.setTotal(30l);
} catch (ApiException e) {
e.printStackTrace();
}
return datagrid;
}
@ResponseBody
@RequestMapping(value = "/bid/datagrid", method = RequestMethod.POST)
public Datagrid datagrid(
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int pagesize,
Long id,
Model model,
HttpServletResponse response) {
Datagrid datagrid = new Datagrid();
try {
datagrid = sneedAPI.queryBidList(id, "addtime desc", page, pagesize);
} catch (ApiException e) {
e.printStackTrace();
}
return datagrid;
}
@ResponseBody
@RequestMapping(value = "/add", method = RequestMethod.POST)
public JsonMsg add(@RequestBody Sneed sneed, Model model,
HttpServletResponse response) {
JsonMsg jsonMsg = new JsonMsg();
Subject subject = SecurityUtils.getSubject();
String username = (String) subject.getPrincipal();
try {
if (null != sneed) {
Account user = accountAPI.getAccount(username);
if (null != user) {
sneed.setCorpid(user.getOrgid());
}
sneed.setAddtime(new Date());
sneedAPI.addSneed(sneed);
jsonMsg.setSuccess(true);
jsonMsg.setMsg("需求发布成功。");
}
} catch (ApiException e) {
jsonMsg.setSuccess(false);
jsonMsg.setMsg("需求发布失败。");
}
return jsonMsg;
}
/**
* 修改需求
*
* @param model
* @param response
* @return
*/
@RequestMapping(value = "/edit", method = RequestMethod.POST)
@ResponseBody
public JsonMsg edit(@RequestBody Sneed sneed, Model model,
HttpServletResponse response) {
JsonMsg jsonMsg = new JsonMsg();
Subject subject = SecurityUtils.getSubject();
String username = (String) subject.getPrincipal();
try {
if (null != sneed) {
Account user = accountAPI.getAccount(username);
if (null != user) {
sneed.setCorpid(user.getOrgid());
}
sneed.setAddtime(new Date());
sneedAPI.updateSneed(sneed);
jsonMsg.setSuccess(true);
jsonMsg.setMsg("需求信息保存成功。");
}
} catch (ApiException e) {
jsonMsg.setSuccess(false);
jsonMsg.setMsg("需求信息保存失败。");
}
return jsonMsg;
}
/**
* 参与竞标
*
* @param sneedid
* @param remark
* @param model
* @param response
* @return
*/
@ResponseBody
@RequestMapping(value = "/bid", method = RequestMethod.POST)
public JsonMsg SneedBid(Long sneedid, String remark, Model model,
HttpServletResponse response) {
JsonMsg jsonMsg = new JsonMsg();
Subject subject = SecurityUtils.getSubject();
String username = (String) subject.getPrincipal();
try {
if (null == sneedid) {
jsonMsg.setSuccess(false);
jsonMsg.setMsg("竞标失败,需求不存在!");
return jsonMsg;
}
Account user = accountAPI.getAccount(username);
Sneed sneed = sneedAPI.getSneed(sneedid);
if (null == sneed || !sneed.getStatus().equals("0")) {
jsonMsg.setSuccess(false);
jsonMsg.setMsg("竞标失败,需求已关闭");
}
sneedAPI.addSneedBid(sneedid, user.getOrgid(), remark);
jsonMsg.setSuccess(true);
jsonMsg.setMsg("竞标成功。");
} catch (ApiException e) {
jsonMsg.setSuccess(false);
jsonMsg.setMsg("竞标失败。");
}
return jsonMsg;
}
/**
* 指定中标单位
* @param sneedid
* @param model
* @param response
* @return
*/
@ResponseBody
@RequestMapping(value = "/stoned", method = RequestMethod.POST)
public JsonMsg SneedBidStoned(Long id, Model model,
HttpServletResponse response) {
JsonMsg jsonMsg = new JsonMsg();
try{
if (null == id){
jsonMsg.setSuccess(false);
jsonMsg.setMsg("选择失败!数据不存在");
return jsonMsg;
}
sneedAPI.setSneedBidStone(id);
jsonMsg.setSuccess(true);
jsonMsg.setMsg("保存成功!");
}catch(Exception e){
jsonMsg.setSuccess(false);
jsonMsg.setMsg("选择失败!数据不存在");
}
return jsonMsg;
}
}
|
import java.util.*;
public class Solution1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] instructions = scanner.nextLine().split(", ");
System.out.println(blocksAway(instructions));
}
private enum Direction {
NORTH,
EAST,
SOUTH,
WEST;
private Direction left, right;
static {
NORTH.left = WEST;
NORTH.right = EAST;
EAST.left = NORTH;
EAST.right = SOUTH;
SOUTH.left = EAST;
SOUTH.right = WEST;
WEST.left = SOUTH;
WEST.right = NORTH;
}
public Direction getNextDirection(char direction) {
if (direction == 'L') {
return this.left;
} else if (direction == 'R') {
return this.right;
}
return null;
}
}
public static int blocksAway(String[] instructions) {
Direction facing = Direction.NORTH;
int x = 0, y = 0;
for (String instruction : instructions) {
char direction = instruction.charAt(0);
int steps = Integer.parseInt(instruction.substring(1));
facing = facing.getNextDirection(direction);
// Walk in new direction.
switch (facing) {
case NORTH:
y -= steps;
break;
case EAST:
x += steps;
break;
case SOUTH:
y += steps;
break;
case WEST:
x -= steps;
break;
}
}
return Math.abs(x) + Math.abs(y);
}
}
|
package edu.neumont.csc280.lab4.item;
import edu.neumont.csc280.lab4.Money;
import java.util.List;
public interface ItemService {
AuctionItem lookupById(String id);
// String addItem(String title, String description, String imageUrl, String startPrice, String startDate, String endDate);
String addItem(String title, String description, String imageUrl, Money startPrice, long startDate, long endDate);
// String addItemDefault();
void updateItem(String id, String title, String description, String imageUrl, String startPrice, String startDate, String endDate);
void updateItemTitle(String id, String title);
void updateItemDescription(String id, String description);
void updateItemImageUrl(String id, String imageUrl);
void updateItemStartPrice(String id, Money startPrice);
void updateItemStartTime(String id, long startTime);
void updateItemEndTime(String id, long endTime);
void updateItem(String id, String title, String description, String imageUrl, Money startPrice, long startDate, long endDate);
void removeItem(String id);
public List<AuctionItem> listItems();
public void placeBid(String itemId, Bid bid);
}
|
package dfs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class L17 {
public static void main(String[] args) {
String digits = "23";
Solution_1 solution = new Solution_1();
List<String> res1 = solution.letterCombinations(digits);
System.out.println(res1.toString());
Solution_2 solution2 = new Solution_2();
List<String> res2 = solution2.letterCombinations(digits);
System.out.println(res2.toString());
}
/**
* 17. 电话号码的字母组合 方法:1.回溯(DFS); 2.BFS 找出所有组合这种问题注意使用递归
*
*/
static class Solution_1 {
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<String>();
if(digits.length()==0) {
return res;
}
Map<Character, String> map = new HashMap<Character, String>() {
private static final long serialVersionUID = 1L;
{
put('2', "abc");
put('3', "def");
put('4', "ghi");
put('5', "jkl");
put('6', "mno");
put('7', "pqrs");
put('8', "tuv");
put('9', "wxyz");
}
};
recur(digits, map, res, "");
return res;
}
public void recur(String digits, Map<Character, String> map, List<String> res, String zh) {
if (digits.length() == 0) {
res.add(zh);
return;
}
String zm = map.get(digits.charAt(0));
for (int i = 0; i < zm.length(); i++) {
recur(digits.substring(1), map, res, zh + zm.charAt(i));
}
}
}
/**
* 方法2
*
*/
static class Solution_2 {
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if(digits.length()==0) {
return res;
}
Map<Character, String> map = new HashMap<Character, String>() {
private static final long serialVersionUID = 1L;
{
put('2', "abc");
put('3', "def");
put('4', "ghi");
put('5', "jkl");
put('6', "mno");
put('7', "pqrs");
put('8', "tuv");
put('9', "wxyz");
}
};
res.add("");
for (int i = 0; i < digits.length(); i++) {
String dy = map.get(digits.charAt(i));
int size = res.size();
for(int j=0;j<size;j++) {
String old = res.remove(0);
for (int k = 0; k < dy.length(); k++) {
res.add(old+dy.charAt(k));
}
}
}
return res;
}
}
}
|
package com.getkhaki.api.bff.persistence.models.views;
public interface OrganizerStatisticsView {
String getOrganizerId();
Integer getTotalMeetings();
String getOrganizerEmail();
String getOrganizerFirstName();
String getOrganizerLastName();
String getOrganizerAvatarUrl();
Long getTotalSeconds();
Double getTotalCost();
} |
package org.peterkwan.udacity.mysupermarket.viewmodel;
import android.app.Application;
import android.arch.lifecycle.LiveData;
import org.peterkwan.udacity.mysupermarket.data.entity.WishlistItem;
import java.util.List;
public class WishListItemViewModel extends BaseViewModel {
private LiveData<WishlistItem> wishListItemLiveData;
private LiveData<List<WishlistItem>> wishListLiveData;
public WishListItemViewModel(final Application app) {
super(app);
}
public LiveData<WishlistItem> retrieveWishListItem(int itemId) {
if (wishListItemLiveData == null)
wishListItemLiveData = shoppingDao.findWishListItemById(itemId);
return wishListItemLiveData;
}
public LiveData<List<WishlistItem>> retrieveWishListItemList() {
if (wishListLiveData == null)
wishListLiveData = shoppingDao.findAllWishlistItems();
return wishListLiveData;
}
}
|
package webprojectLib;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
public class dbconnection {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class.forName ("com.mysql.jdbc.Driver");
System.out.println("Driver found");
} catch (ClassNotFoundException e) {
System.out.println("Driver not found" +e);
}
String url = "jdbc:mysql://ec2-34-217-41-127.us-west-2.compute.amazonaws.com:3306/myDB2";
String user = "newremoteuser";
String password = "password";
Connection con = null;
//import database
try {
con = (Connection) DriverManager.getConnection(url, user, password);
System.out.println("Connected Successfully!");
} catch (SQLException e) {
System.out.println("Something went wrong in database connection"+e);
}
}
}
; |
package com.jixin;
import lombok.Data;
public @Data class Person {
private Integer hour;
private State state;
public void doSomething() {
if (hour == 7) {
new MState().doSomething();
} else if (hour == 12) {
new LState().doSomething();
} else if (hour == 18) {
new WState().doSomething();
} else {
System.out.println(hour + "未定义");
}
}
}
|
package com.git.support.common;
public final class MesgRetCode {
public final static String SUCCESS = "0000"; //处理成功
public final static String ERR_PROCESS_FAILED = "9997"; //处理失败
public final static String ERR_NOT_SUPPORT_OPT = "9998"; //不支持的操作
public final static String ERR_OTHER = "9999"; //其他错误
public final static String ERR_PARAMETER_WRONG = "9996"; //参数错误
public final static String ERR_SIZE_INSUFFICIENT = "9995"; //存储容量不满足
public final static String ERR_TIMEOUT = "9994"; //处理超时
public final static String ERR_EXISTED = "9993"; //纳管物理机已经存在
public final static String ERR_NOTFOUND = "9992"; //解除纳管物理机不存在
}
|
package Logica;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class conexion {
public String db = "registrosydatos";
public String url = "jdbc:mysql://iotpoligran.mysql.database.azure.com:3306/" + db;
public String user = "rirojasp@iotpoligran";
public String pass = "Bdmsmj2305.";
public Connection conectar;
public conexion() {
}
public Connection conectar() {
Connection link = null;
try {
Class.forName("org.gjt.mm.mysql.Driver");
link = DriverManager.getConnection(this.url, this.user, this.pass);
if (link != null) {
System.out.println("conexion");
}
} catch (ClassNotFoundException | SQLException e) {
JOptionPane.showConfirmDialog(null, e);
}
return link;
}
}
|
package Tasks;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Task59 {
public static void main(String[] args) {
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.