blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
d5e263723b4f52c7a2c3256b233035b491e33e9d | Java | de-jcup/eclipse-commons | /src/main/java/de/jcup/eclipse/commons/ui/CSSProvider.java | UTF-8 | 200 | 1.59375 | 2 | [
"Apache-2.0"
] | permissive | package de.jcup.eclipse.commons.ui;
public interface CSSProvider {
void setBackgroundColor(String backgroundColor);
void setForegroundColor(String foregroundColor);
String getCSS();
} | true |
abb5cf46f21defe7a368e6f3836972e62cdf79c2 | Java | spring-gamal/lucenex | /src/main/java/com/ld/lucenex/plugin/SpringBootPlugin.java | UTF-8 | 606 | 1.742188 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright © 2018LD. All rights reserved.
*
* @Title: SpringBootPlugin.java
* @Prject: lucenex
* @Package: com.ld.lucenex.plugin
* @Description: TODO
* @author: Myzhang
* @date: 2018年5月28日 下午2:40:58
* @version: V1.0
*/
package com.ld.lucenex.plugin;
import com.ld.lucenex.base.BaseConfig;
import com.ld.lucenex.config.LuceneXConfig;
/**
* @ClassName: SpringBootPlugin
* @Description: TODO
* @author: Myzhang
* @date: 2018年5月28日 下午2:40:58
*/
public class SpringBootPlugin {
public void add(LuceneXConfig config) {
BaseConfig.configLuceneX(config);
}
}
| true |
14cfbfa0052ec356a0ded1c719f78713792de133 | Java | Webkova/Covadonga.Diez.SVC | /src/main/java/PIndividual/C21.java | UTF-8 | 253 | 1.992188 | 2 | [] | no_license | package PIndividual;
public class C21 {
public String m1() {
return "C21: m1";
}
public String m2() {
return "C21: m2";
}
public String m3() {
return "C21: m3";
}
}
| true |
b01108261db7e63a4d66232f4f44f18640b7788d | Java | mohamedalighouma/demojenkins | /folder/com/CalculetteTest.java | UTF-8 | 702 | 2.8125 | 3 | [] | no_license | package com;
import org.testng.Assert;
import org.testng.annotations.Test;
public class CalculetteTest {
@Test(groups = { "test-group" })
public void add() {
Calculette calc = new Calculette();
Assert.assertEquals(calc.add(12, 8),20.0);
}
@Test
public void produit() {
Calculette calc = new Calculette();
Assert.assertEquals(calc.produit(12, 8),96.0);
}
@Test(groups = { "test-group" })
public void soustraire() {
Calculette calc = new Calculette();
Assert.assertEquals(calc.soustraire(12, 8),4.0);
}
@Test
public void division() {
Calculette calc = new Calculette();
Assert.assertEquals(calc.diviser(16, 8),2.0);
}
} | true |
462f4a4ff10eec767fd221677172de4bcf93f611 | Java | Hrishikesh-Thakkar/Visa_Training | /oop/src/com/visa/prj/client/FunctionalExample.java | UTF-8 | 871 | 2.90625 | 3 | [] | no_license | package com.visa.prj.client;
@FunctionalInterface
interface Computation{
int compute(int x,int y);
//int cp(int x);
}
public class FunctionalExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
Computation c1= new Computation() {
@Override
public int compute(int x, int y) {
// TODO Auto-Computation c5 = (x,y) -> x*y;
return x+y;
}
};
doTask(c1,4,5);
Computation c2= new Computation() {
@Override
public int compute(int x, int y) {
// TODO Auto-generated method stub
return x-y;
}
};
doTask(c2,4,5);
Computation c3 = (int x,int y) -> {return x*y;};
doTask(c3, 2, 3);
Computation c5 = (x,y) -> x*y;
doTask(c5, 2, 3);
}
private static void doTask(Computation c1, int j, int k) {
// TODO Auto-generated method stub
System.out.println(c1.compute(j,k));
}
}
| true |
44eb0b13f33bdfbf0f76294c8733d9367fc5071a | Java | lvdong218/myProject | /project/src/main/java/com/ld/util/ResponseUtil.java | UTF-8 | 772 | 2.546875 | 3 | [] | no_license | package com.ld.util;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
/**
* 关于response和request的一些公用方法
* @author lvdong
*
*/
public class ResponseUtil {
/**
* 将json通过response输出
* @param request
* @param response
* @param json
*/
public static void outputJson(HttpServletRequest request,HttpServletResponse response,JSONObject json) {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
try {
PrintWriter wr=response.getWriter();
wr.append(json.toString());
wr.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
1b94678bec1be9f290321434fb69e5d16b1a00fc | Java | zxli27/myprojects | /Simple_Language_Compiler/src/Type/Type.java | UTF-8 | 170 | 2.4375 | 2 | [] | no_license | package Type;
public abstract class Type {
public abstract String toString();
public abstract boolean equals(Object o);
public abstract String toChar();
}
| true |
53ac677e56aa5ab0eec98d242c21f7d64de189d7 | Java | dreamer888/zhihuinongmao | /zhnm/zhnm-miniapp/backend/mallweb/src/main/java/com/yq/service/user/impl/ShopUserService.java | UTF-8 | 2,168 | 1.9375 | 2 | [
"Apache-2.0"
] | permissive | package com.yq.service.user.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.yq.dao.DaoSupport;
import org.change.entity.Page;
import org.change.util.PageData;
import com.yq.service.user.ShopUserManager;
/**
* 说明: 会员用户
* 创建人:壹仟科技 qq 357788906
* 创建时间:2016-12-28
* @version
*/
@Service("shopUserService")
public class ShopUserService implements ShopUserManager{
@Resource(name = "daoSupport")
private DaoSupport dao;
/**新增
* @param pd
* @throws Exception
*/
public void save(PageData pd)throws Exception{
dao.save("ShopUserMapper.save", pd);
}
/**删除
* @param pd
* @throws Exception
*/
public void delete(PageData pd)throws Exception{
dao.delete("ShopUserMapper.delete", pd);
}
/**修改
* @param pd
* @throws Exception
*/
public void edit(PageData pd)throws Exception{
dao.update("ShopUserMapper.edit", pd);
}
/**列表
* @param page
* @throws Exception
*/
@SuppressWarnings("unchecked")
public List<PageData> list(Page page)throws Exception{
return (List<PageData>)dao.findForList("ShopUserMapper.datalistPage", page);
}
/**列表(全部)
* @param pd
* @throws Exception
*/
@SuppressWarnings("unchecked")
public List<PageData> listAll(PageData pd)throws Exception{
return (List<PageData>)dao.findForList("ShopUserMapper.listAll", pd);
}
/**通过id获取数据
* @param pd
* @throws Exception
*/
public PageData findById(PageData pd)throws Exception{
return (PageData)dao.findForObject("ShopUserMapper.findById", pd);
}
public int count(PageData pd)throws Exception{
return (int) dao.findForObject("ShopUserMapper.count", pd);
}
public PageData findByPhone(PageData pd)throws Exception{
return (PageData)dao.findForObject("ShopUserMapper.findByPhone", pd);
}
/**批量删除
* @param ArrayDATA_IDS
* @throws Exception
*/
public void deleteAll(String[] ArrayDATA_IDS)throws Exception{
dao.delete("ShopUserMapper.deleteAll", ArrayDATA_IDS);
}
}
| true |
c2057c538bdcd6295e22f527c5156947e8708ab9 | Java | Billwjn/witch | /question/src/main/java/com/wjn/question/service/mapper/QuestionMapper.java | UTF-8 | 301 | 1.554688 | 2 | [] | no_license | package com.wjn.question.service.mapper;
import com.wjn.api.dto.QuestionDto;
import com.wjn.base.mapper.BaseMapper;
import com.wjn.question.entity.Question;
import org.mapstruct.Mapper;
@Mapper(componentModel = "spring")
public interface QuestionMapper extends BaseMapper<Question, QuestionDto> {
}
| true |
e97dd3607655ca6a751fcf2363d4bb43d059dc7f | Java | 13sakshi13/the-lazy-chef-android | /app/src/main/java/com/example/thelazychef/SearchByIngredientsResults.java | UTF-8 | 8,819 | 2.234375 | 2 | [] | no_license | package com.example.thelazychef;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Objects;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class SearchByIngredientsResults extends AppCompatActivity {
ProgressBar loader;
TextView recipeResults1, recipeResults2, recipeResults3, recipeResults4, recipeResults5, recipeResults6;
TextView searchByIngredientsResultsSubheading;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_by_ingredients_results);
// get query from previous find recipes page
final String ingredientsQuery = getIntent().getStringExtra("INGREDIENTS_QUERY");
// initialise the loader
loader = findViewById(R.id.loader);
// initialise the text views for displaying results
recipeResults1 = findViewById(R.id.recipeResult1);
recipeResults2 = findViewById(R.id.recipeResult2);
recipeResults3 = findViewById(R.id.recipeResult3);
recipeResults4 = findViewById(R.id.recipeResult4);
recipeResults5 = findViewById(R.id.recipeResult5);
recipeResults6 = findViewById(R.id.recipeResult6);
searchByIngredientsResultsSubheading = findViewById(R.id.searchByIngredientsResultsSubheading);
// initialise the HTTP client
OkHttpClient client = new OkHttpClient();
// define the API endpoint
String endpoint = "https://api.spoonacular.com/recipes/findByIngredients?ingredients=" + ingredientsQuery + "&number=6&limitLicense=true&ranking=1&ignorePantry=false&apiKey=fc6fef8c0bb04e27ad8da3843fef1602";
// build a request object
Request request = new Request.Builder()
.url(endpoint)
.build();
// make the HTTP call
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
// display network error page on request failure
Intent networkErrorPageOpener = new Intent(SearchByIngredientsResults.this, NetworkError.class);
startActivity(networkErrorPageOpener);
e.printStackTrace();
finish();
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {
// log server response
final String serverResponse = Objects.requireNonNull(response.body()).string();
System.out.println("DEBUG RESPONSE: " + serverResponse);
if (response.isSuccessful()) {
SearchByIngredientsResults.this.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
// parse json response
JSONArray results = new JSONArray(serverResponse);
if (results.length() > 0) {
// remove the loader
loader.setVisibility(View.GONE);
// display the search query
searchByIngredientsResultsSubheading.setText("Search results for " + ingredientsQuery);
// make the text views visible and display the results(from the previously parsed json) for all 6 recipes
// set recipe 1
JSONObject result1 = results.getJSONObject(0);
String recipe1 = result1.getString("title");
// shorten long responses
if (recipe1.length() > 90) recipe1 = recipe1.substring(0, 85) + "...";
recipeResults1.setVisibility(View.VISIBLE);
recipeResults1.setText(recipe1);
// set recipe 2
JSONObject result2 = results.getJSONObject(1);
String recipe2 = result2.getString("title");
// shorten long responses
if (recipe2.length() > 90) recipe2 = recipe2.substring(0, 85) + "...";
recipeResults2.setVisibility(View.VISIBLE);
recipeResults2.setText(recipe2);
// set recipe 3
JSONObject result3 = results.getJSONObject(2);
String recipe3 = result3.getString("title");
// shorten long responses
if (recipe3.length() > 90) recipe3 = recipe3.substring(0, 85) + "...";
recipeResults3.setVisibility(View.VISIBLE);
recipeResults3.setText(recipe3);
// set recipe 4
JSONObject result4 = results.getJSONObject(3);
String recipe4 = result4.getString("title");
// shorten long responses
if (recipe4.length() > 90) recipe4 = recipe4.substring(0, 85) + "...";
recipeResults4.setVisibility(View.VISIBLE);
recipeResults4.setText(recipe4);
// set recipe 5
JSONObject result5 = results.getJSONObject(4);
String recipe5 = result5.getString("title");
// shorten long responses
if (recipe5.length() > 90) recipe5 = recipe5.substring(0, 85) + "...";
recipeResults5.setVisibility(View.VISIBLE);
recipeResults5.setText(recipe5);
// set recipe 6
JSONObject result6 = results.getJSONObject(5);
String recipe6 = result6.getString("title");
// shorten long responses
if (recipe6.length() > 90) recipe6 = recipe6.substring(0, 85) + "...";
recipeResults6.setVisibility(View.VISIBLE);
recipeResults6.setText(recipe6);
} else {
// remove the loader
loader.setVisibility(View.GONE);
// answer was not received from the API, display error to the user
searchByIngredientsResultsSubheading.setText("Oops! We couldn't find any results for " + ingredientsQuery + " :( \n Please try rephrasing your query.");
}
} catch (JSONException e) {
// remove the loader
loader.setVisibility(View.GONE);
// answer was not received from the API, display error to the user
searchByIngredientsResultsSubheading.setText("Oops! That did not work too well :( \n Please try rephrasing your query.");
e.printStackTrace();
}
}
});
} else {
// remove the loader and set the error message
loader.setVisibility(View.GONE);
searchByIngredientsResultsSubheading.setText("An unkown error occurred. Please contact the administrator.");
}
}
});
}
// on click handler for back button
public void backButtonClickHandler(View v) {
finish();
}
} | true |
e2dd15447febc15ddc03f5b0795443bf1bbe836b | Java | hooheohee/Jupiter | /src/main/java/rpc/ItemHistory.java | UTF-8 | 3,285 | 2.46875 | 2 | [] | no_license | package rpc;
import db.MySQLConnection;
import entity.Item;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Set;
public class ItemHistory extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
String userId = request.getParameter("user_id");
if (session == null || !((String) session.getAttribute("user_id")).equalsIgnoreCase(userId)) {
JSONObject object = new JSONObject();
object.put("status", "Invalid Session");
response.setStatus(403);
RpcHelper.writeJsonObject(response, object);
return;
}
MySQLConnection connection = new MySQLConnection();
Set<Item> items = connection.getFavoriteItems(userId);
connection.close();
JSONArray array = new JSONArray();
for (Item item : items) {
JSONObject obj = item.toJSONObject();
obj.put("favorite", true);
array.put(obj);
}
RpcHelper.writeJsonArray(response, array);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
JSONObject input = RpcHelper.readJSONObject(request);
String userId = input.getString("user_id");
if (session == null || !((String) session.getAttribute("user_id")).equalsIgnoreCase(userId)) {
JSONObject object = new JSONObject();
object.put("status", "Invalid Session");
response.setStatus(403);
RpcHelper.writeJsonObject(response, object);
return;
}
MySQLConnection connection = new MySQLConnection();
Item item = RpcHelper.parseFavoriteItem(input.getJSONObject("favorite"));
connection.setFavoriteItems(userId, item);
connection.close();
RpcHelper.writeJsonObject(response, new JSONObject().put("result", "SUCCESS"));
}
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session == null) {
response.sendError(403, "Not Authenticated");
response.setStatus(403);
return;
}
MySQLConnection connection = new MySQLConnection();
JSONObject input = RpcHelper.readJSONObject(request);
String userId = input.getString("user_id");
if (!((String) session.getAttribute("user_id")).equalsIgnoreCase(userId)) {
response.setStatus(403);
return;
}
Item item = RpcHelper.parseFavoriteItem(input.getJSONObject("favorite"));
connection.unsetFavoriteItems(userId, item.getItemId());
connection.close();
RpcHelper.writeJsonObject(response, new JSONObject().put("result", "SUCCESS"));
}
}
| true |
a93896a45be6f1d9fec574ab64852c0a8ca832ed | Java | thb143/cec | /cec.site/src/cn/mopon/cec/site/actions/price/ChannelPolicyAction.java | UTF-8 | 11,604 | 1.976563 | 2 | [] | no_license | package cn.mopon.cec.site.actions.price;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import cn.mopon.cec.core.entity.ChannelPolicy;
import cn.mopon.cec.core.entity.ChannelRuleGroup;
import cn.mopon.cec.core.entity.Cinema;
import cn.mopon.cec.core.entity.Show;
import cn.mopon.cec.core.model.CinemaModel;
import cn.mopon.cec.core.model.ProviceCinemaListModel;
import cn.mopon.cec.core.service.ChannelPolicyService;
import cn.mopon.cec.core.service.ChannelRuleGroupService;
import cn.mopon.cec.core.service.ChannelService;
import cn.mopon.cec.core.service.ChannelShowService;
import cn.mopon.cec.core.service.CinemaService;
import coo.base.model.Page;
import coo.base.util.StringUtils;
import coo.core.message.MessageSource;
import coo.core.model.SearchModel;
import coo.core.security.annotations.Auth;
import coo.mvc.util.DialogResultUtils;
import coo.mvc.util.NavTabResultUtils;
/**
* 渠道策略管理。
*/
@Controller
@RequestMapping("/price")
public class ChannelPolicyAction {
@Resource
private ChannelService channelService;
@Resource
private ChannelPolicyService channelPolicyService;
@Resource
private ChannelRuleGroupService channelRuleGroupService;
@Resource
private CinemaService cinemaService;
@Resource
private ChannelShowService channelShowService;
@Resource
private MessageSource messageSource;
/**
* 查看策略列表。
*
* @param selectedChannelPolicyId
* 选中的策略ID
* @param model
* 数据模型
* @param searchModel
* 搜索条件
*/
@Auth("POLICY_VIEW")
@RequestMapping("channelPolicy-list")
public void list(String selectedChannelPolicyId, Model model,
SearchModel searchModel) {
model.addAttribute(channelPolicyService.searchPolicy(searchModel));
model.addAttribute("searchModel", searchModel);
model.addAttribute("selectedChannelPolicyId", selectedChannelPolicyId);
}
/**
* 查看渠道策略开放的影院列表。
*
* @param channelPolicyId
* 渠道策略ID
* @param selectGroupId
* 已选择的分组ID
* @param model
* 数据模型
* @param searchModel
* 检索条件
*/
@Auth("POLICY_VIEW")
@RequestMapping("channelPolicy-cinema-list")
public void cinemaList(String channelPolicyId, String selectGroupId,
Model model, SearchModel searchModel) {
searchModel.setPageSize(30);
ChannelPolicy channelPolicy = channelPolicyService
.getChannelPolicy(channelPolicyId);
Page<ChannelRuleGroup> groups = channelRuleGroupService
.searchChannelRuleGroup(channelPolicyId, searchModel, null);
model.addAttribute("channelPolicy", channelPolicy);
model.addAttribute("groupCount", channelRuleGroupService
.searchChannelRuleGroupCount(channelPolicyId, null));
model.addAttribute("groupPage", groups);
model.addAttribute("searchModel", searchModel);
model.addAttribute("selectGroupId", selectGroupId);
}
/**
* 查看策略。
*
* @param channelPolicyId
* 策略ID
* @param cinemaId
* 影院ID
* @param model
* 数据模型
*
*/
@Auth("POLICY_VIEW")
@RequestMapping("channelPolicy-view")
public void view(String channelPolicyId, String cinemaId, Model model) {
ChannelPolicy channelPolicy = channelPolicyService.groupChannelPolicy(
channelPolicyId, cinemaId);
model.addAttribute("channelPolicy", channelPolicy);
model.addAttribute("cinemaId", cinemaId);
}
/**
* 新增策略。
*
* @param model
* 数据模型
* @param channelId
* 渠道ID
*/
@Auth("POLICY_MANAGE")
@RequestMapping("channelPolicy-add")
public void add(Model model, String channelId) {
ChannelPolicy channelPolicy = new ChannelPolicy();
channelPolicy.setChannel(channelService.getChannel(channelId));
model.addAttribute(channelPolicy);
}
/**
* 保存策略。
*
* @param channelPolicy
* 策略
* @return 返回提示信息。
*/
@Auth("POLICY_MANAGE")
@RequestMapping("channelPolicy-save")
public ModelAndView save(ChannelPolicy channelPolicy) {
channelPolicyService.createChannelPolicy(channelPolicy);
return DialogResultUtils.closeAndForwardNavTab(
messageSource.get("policy.add.success"),
"/price/channelPolicy-list?selectedChannelPolicyId="
+ channelPolicy.getId());
}
/**
* 编辑策略。
*
* @param model
* 数据模型
* @param channelPolicyId
* 策略ID
*/
@Auth("POLICY_SWITCH")
@RequestMapping("channelPolicy-edit")
public void edit(Model model, String channelPolicyId) {
model.addAttribute(channelPolicyService
.getChannelPolicy(channelPolicyId));
}
/**
* 更新策略。
*
* @param channelPolicy
* 策略
* @return 返回提示信息。
*/
@Auth("POLICY_SWITCH")
@RequestMapping("channelPolicy-update")
public ModelAndView update(ChannelPolicy channelPolicy) {
// 获取渠道 用于记录日志。
channelPolicy.setChannel(channelPolicyService.getChannelPolicy(
channelPolicy.getId()).getChannel());
channelPolicyService.updateChannelPolicy(channelPolicy);
return DialogResultUtils.closeAndReloadNavTab(messageSource
.get("policy.edit.success"));
}
/**
* 删除策略。
*
* @param channelPolicyId
* 策略ID
* @return 返回提示信息。
*/
@Auth("POLICY_MANAGE")
@RequestMapping("channelPolicy-delete")
public ModelAndView delete(String channelPolicyId) {
channelPolicyService.deleteChannelPolicy(channelPolicyService
.getChannelPolicy(channelPolicyId));
return NavTabResultUtils.reload(messageSource
.get("policy.delete.success"));
}
/**
* 启用策略。
*
* @param channelPolicy
* 策略
* @return 返回提示信息。
*/
@Auth("POLICY_SWITCH")
@RequestMapping("channelPolicy-enable")
public ModelAndView enable(ChannelPolicy channelPolicy) {
List<Show> shows = channelPolicyService
.enableChannelPolicy(channelPolicy);
channelShowService.batchGenChannelShows(shows);
return NavTabResultUtils.forward(
messageSource.get("policy.enable.success"),
"/price/channelPolicy-list?selectedChannelPolicyId="
+ channelPolicy.getId());
}
/**
* 停用策略。
*
* @param channelPolicy
* 策略
* @return 返回提示信息。
*/
@Auth("POLICY_SWITCH")
@RequestMapping("channelPolicy-disable")
public ModelAndView disable(ChannelPolicy channelPolicy) {
List<Show> shows = channelPolicyService
.disableChannelPolicy(channelPolicy);
channelShowService.batchGenChannelShows(shows);
return NavTabResultUtils.forward(
messageSource.get("policy.disable.success"),
"/price/channelPolicy-list?selectedChannelPolicyId="
+ channelPolicy.getId());
}
/**
* 上移策略。
*
* @param channelPolicyId
* 策略ID
*/
@Auth("POLICY_MANAGE")
@RequestMapping("channelPolicy-up")
@ResponseBody
public void up(String channelPolicyId) {
channelPolicyService.upChannelPolicy(channelPolicyService
.getChannelPolicy(channelPolicyId));
}
/**
* 下移策略。
*
* @param channelPolicyId
* 策略ID
*/
@Auth("POLICY_MANAGE")
@RequestMapping("channelPolicy-down")
@ResponseBody
public void down(String channelPolicyId) {
channelPolicyService.downChannelPolicy(channelPolicyService
.getChannelPolicy(channelPolicyId));
}
/**
* 弹出复制新增选择策略页面。
*
* @param model
* 数据模型
* @param channelId
* 渠道ID
* @param searchModel
* 搜索条件
*/
@Auth("POLICY_MANAGE")
@RequestMapping("channelPolicy-copy-select")
public void copySelect(Model model, String channelId,
SearchModel searchModel) {
model.addAttribute("channelId", channelId);
model.addAttribute("policyPage",
channelPolicyService.searchChannelPolicy(searchModel));
}
/**
* 复制策略。
*
* @param channelPolicyId
* 待复制的策略ID
* @param channelId
* 渠道ID
* @return 返回提示信息。
*/
@Auth("POLICY_MANAGE")
@RequestMapping("channelPolicy-copy")
public ModelAndView copy(String channelPolicyId, String channelId) {
ChannelPolicy channelPolicy = channelPolicyService.copyChannelPolicy(
channelPolicyService.getChannelPolicy(channelPolicyId),
channelId);
return DialogResultUtils.closeAndForwardNavTab(
messageSource.get("policy.copy.success"),
"/price/channelPolicy-list?selectedChannelPolicyId="
+ channelPolicy.getId());
}
/**
* 弹出新增选择影院页面。
*
* @param model
* 数据模型
* @param channelPolicyId
* 策略ID
* @param cinemaModel
* 搜索条件
*/
@Auth("POLICY_MANAGE")
@RequestMapping("channelPolicy-cinema-select")
public void cinemaSelect(Model model, String channelPolicyId,
CinemaModel cinemaModel) {
ChannelPolicy channelPolicy = channelPolicyService
.getChannelPolicy(channelPolicyId);
List<Cinema> cinemas = cinemaService.filterSelectedCinema(
channelPolicy, cinemaModel);
ProviceCinemaListModel proviceCinemaListModel = new ProviceCinemaListModel();
for (Cinema cinema : cinemas) {
proviceCinemaListModel.addProvinceCinemaModel(cinema);
}
model.addAttribute("cinemaModel", cinemaModel);
model.addAttribute("cinemaListModel", proviceCinemaListModel);
model.addAttribute("channelPolicyId", channelPolicyId);
}
/**
* 弹出影院开放设置页面。
*
* @param model
* 数据模型
* @param channelPolicyId
* 策略ID
* @param cinemaModel
* 搜索条件
*/
@Auth("POLICY_MANAGE")
@RequestMapping("channelPolicy-cinema-set")
public void cinemaSet(Model model, String channelPolicyId,
CinemaModel cinemaModel) {
setCinemaTreeModel(model, channelPolicyId, cinemaModel);
}
/**
* 弹出影院接入费设置页面。
*
* @param model
* 数据模型
* @param channelPolicyId
* 策略ID
* @param cinemaModel
* 搜索条件
*/
@Auth("POLICY_MANAGE")
@RequestMapping("channelPolicy-connectFee-set")
public void connectFeeSet(Model model, String channelPolicyId,
CinemaModel cinemaModel) {
setCinemaTreeModel(model, channelPolicyId, cinemaModel);
}
/**
* 设置影院树形页面。
*
* @param model
* 数据模型
* @param channelPolicyId
* 策略ID
* @param cinemaModel
* 搜索条件
*/
private void setCinemaTreeModel(Model model, String channelPolicyId,
CinemaModel cinemaModel) {
ChannelPolicy channelPolicy = channelPolicyService
.getChannelPolicy(channelPolicyId);
ProviceCinemaListModel proviceCinemaListModel = new ProviceCinemaListModel();
for (ChannelRuleGroup group : channelPolicy.getGroups()) {
if (cinemaModel != null
&& StringUtils.isNotEmpty(cinemaModel.getKeyword())) {
if (group.getCinema().getName()
.contains(cinemaModel.getKeyword().trim())) {
proviceCinemaListModel.addProvinceCinemaModel(group
.getCinema());
}
} else {
proviceCinemaListModel
.addProvinceCinemaModel(group.getCinema());
}
}
model.addAttribute("cinemaModel", cinemaModel);
model.addAttribute("cinemaListModel", proviceCinemaListModel);
model.addAttribute("channelPolicy", channelPolicy);
}
} | true |
c8eefebeed70c8ad513282cec34aa7d633808897 | Java | pftx/api-mono | /common/common-core/src/main/java/com/x/api/common/validation/validator/EnumValidator.java | UTF-8 | 3,199 | 2.21875 | 2 | [
"Apache-2.0"
] | permissive | /**
* EnumValidator.java
*
* Copyright 2017 the original author or authors.
*
* We 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 com.x.api.common.validation.validator;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.validation.ConstraintValidatorContext;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;
import com.google.common.base.Joiner;
import com.x.api.common.validation.annotation.ValidEnum;
/**
* @author <a href="mailto:pftx@live.com">Lex Xie</a>
* @version 1.0.0
* @since Nov 16, 2017
*/
public class EnumValidator extends AllowNullConstraintValidator<ValidEnum, String> {
private List<String> supportedList;
/**
* This is the override of super method.
*
* @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
*/
@Override
public void initialize(ValidEnum constraintAnnotation) {
Class<?> targetType = constraintAnnotation.type();
Enum<?>[] constants = (Enum<?>[]) targetType.getEnumConstants();
if (constants == null) {
supportedList = Arrays.stream(constraintAnnotation.supportedList()).collect(Collectors.toList());
} else {
supportedList = Arrays.stream(constants).map(Enum::name).collect(Collectors.toList());
}
}
/**
* This is the override of super method.
* @see com.x.api.common.validation.validator.AllowNullConstraintValidator#extraErrorContext(org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext)
*/
@Override
protected void extraErrorContext(HibernateConstraintValidatorContext h) {
h.addExpressionVariable("supported_list", Joiner.on(", ").join(supportedList));
}
/**
* This is the override of super method.
*
* @see javax.validation.ConstraintValidator#isValid(java.lang.Object, javax.validation.ConstraintValidatorContext)
*/
@Override
public boolean isValidNonNull(String value, ConstraintValidatorContext context) {
if (supportedList.isEmpty()) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("Enum class not set for validator, value = " + value)
.addConstraintViolation();
return false;
}
Optional<String> optional = supportedList.stream().filter(s -> s.equalsIgnoreCase(value)).findAny();
if (optional.isPresent()) {
return true;
} else {
generateErrorContext(context);
return false;
}
}
}
| true |
0006c685d2d8865c9e4123c000e97a1d47c1f118 | Java | MakcSan/TheBadSunrise | /src/main/java/net/mcreator/badsunrise/MCreatorEntityOnFire.java | UTF-8 | 2,568 | 2.21875 | 2 | [] | no_license | package net.mcreator.badsunrise;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraft.world.World;
import net.minecraft.util.math.BlockPos;
import net.minecraft.entity.Entity;
@Elementsbadsunrise.ModElement.Tag
public class MCreatorEntityOnFire extends Elementsbadsunrise.ModElement {
public MCreatorEntityOnFire(Elementsbadsunrise instance) {
super(instance, 2);
MinecraftForge.EVENT_BUS.register(this);
}
public static void executeProcedure(java.util.HashMap<String, Object> dependencies) {
if (dependencies.get("entity") == null) {
System.err.println("Failed to load dependency entity for procedure MCreatorEntityOnFire!");
return;
}
if (dependencies.get("x") == null) {
System.err.println("Failed to load dependency x for procedure MCreatorEntityOnFire!");
return;
}
if (dependencies.get("y") == null) {
System.err.println("Failed to load dependency y for procedure MCreatorEntityOnFire!");
return;
}
if (dependencies.get("z") == null) {
System.err.println("Failed to load dependency z for procedure MCreatorEntityOnFire!");
return;
}
if (dependencies.get("world") == null) {
System.err.println("Failed to load dependency world for procedure MCreatorEntityOnFire!");
return;
}
Entity entity = (Entity) dependencies.get("entity");
int x = (int) dependencies.get("x");
int y = (int) dependencies.get("y");
int z = (int) dependencies.get("z");
World world = (World) dependencies.get("world");
if (((badsunriseVariables.WorldVariables.get(world).OnFire) || ((world.getDayTime()) > 72000))) {
if ((world.canBlockSeeSky(new BlockPos((int) x, (int) y, (int) z)))) {
if ((!(((!(world.isDaytime())) || (world.isRaining())) || (world.isThundering())))) {
entity.setFire((int) 5);
}
}
}
}
@SubscribeEvent
public void onPlayerTick(TickEvent.PlayerTickEvent event) {
if (event.phase == TickEvent.Phase.END) {
Entity entity = event.player;
World world = entity.world;
int i = (int) entity.posX;
int j = (int) entity.posY;
int k = (int) entity.posZ;
java.util.HashMap<String, Object> dependencies = new java.util.HashMap<>();
dependencies.put("x", i);
dependencies.put("y", j);
dependencies.put("z", k);
dependencies.put("world", world);
dependencies.put("entity", entity);
dependencies.put("event", event);
this.executeProcedure(dependencies);
}
}
}
| true |
5d66df6071d6be5bf945b0323065610e98cd67da | Java | zveno65/Spring-Boot | /src/main/java/ru/plotnikov/repository/UserRepository.java | UTF-8 | 231 | 1.914063 | 2 | [] | no_license | package ru.plotnikov.repository;
import org.springframework.data.repository.CrudRepository;
import ru.plotnikov.model.User;
public interface UserRepository extends CrudRepository<User, Long> {
User findByName(String name);
}
| true |
39f141398a661bdedd1a91001c201e3720a8a380 | Java | Hugo18x/Proyecto-javainicial | /Gym/src/Modelo/EntrenadoresEnum.java | UTF-8 | 95 | 1.726563 | 2 | [] | no_license | package Modelo;
public enum EntrenadoresEnum {
Lucas,
Pepito,
Walter,
Jose
}
| true |
1ca6500eb1ed606e46d7e68c83ebaae49591109a | Java | cappelleMedia/mfa_model | /src/domain/poll/PollItemAnswer.java | UTF-8 | 2,370 | 2.703125 | 3 | [] | no_license | package domain.poll;
import domain.DaoObject;
import domain.DomainException;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Entity;
@Entity
public class PollItemAnswer extends DaoObject implements Serializable{
private String answerText; //TODO add multi langs
private int votes;
public PollItemAnswer(){
}
public PollItemAnswer(String answerText) throws DomainException{
this.setAnswerText(answerText);
}
public String getAnswerText() {
return this.answerText;
}
public int getVotes() {
return this.votes;
}
public void setAnswerText(String answerText) throws DomainException {
if(answerText == null || answerText.trim().isEmpty()) {
throw new DomainException("A poll answer needs text to be useful");
}
this.answerText = answerText;
}
public void addVote() {
this.votes++;
}
public void removeVote() {
if(this.votes > 0){
this.votes--;
}
}
public double getPercentage(int totalVotes) {
double percentage = 0;
if(totalVotes > 0 && this.getVotes() > 0){
double thisVotesD = (double) this.getVotes();
double totalVotesD = (double) totalVotes;
percentage = (thisVotesD/totalVotesD) * 100;
}
return percentage;
}
@Override
public String toString() {
String pollItemAnswer = "";
pollItemAnswer+= "Answer: "+this.getAnswerText();
pollItemAnswer+= "\nVotes: " + this.getVotes();
return pollItemAnswer;
}
@Override
public boolean equals(Object object) {
if(object instanceof PollItemAnswer) {
PollItemAnswer answer = (PollItemAnswer) object;
if(answer.getAnswerText().equalsIgnoreCase(this.getAnswerText())){
return true;
}
}
return false;
}
@Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + Objects.hashCode(this.answerText);
hash = 71 * hash + this.votes;
hash = 71 * hash + (int) (super.getId() ^ (super.getId() >>> 32));
return hash;
}
}
| true |
ebea243cbbb63f811939f59a5718dc0fc61df5e7 | Java | sandychn/LibraryManageSystem | /src/common/util/MyXMLReader.java | UTF-8 | 1,295 | 2.546875 | 3 | [
"MIT"
] | permissive | package common.util;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class MyXMLReader {
public Map<String, String> readXML() {
try {
File f = new File("config/database_server_config.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
String address = doc.getElementsByTagName("address").item(0).getTextContent();
String dbname = doc.getElementsByTagName("dbname").item(0).getTextContent();
String dbusername = doc.getElementsByTagName("dbusername").item(0).getTextContent();
String dbpassword = doc.getElementsByTagName("dbpassword").item(0).getTextContent();
Map<String, String> map = new HashMap<>();
map.put("address", address);
map.put("dbname", dbname);
map.put("dbusername", dbusername);
map.put("dbpassword", dbpassword);
return map;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
} | true |
8c9f502a21c0cf8ab606cf6ddbb7fe299b97cc64 | Java | korrio/SocialKit-VM | /app/src/main/java/co/aquario/socialkit/event/toolbar/ChatSubTitleEvent.java | UTF-8 | 214 | 1.8125 | 2 | [] | no_license | package co.aquario.socialkit.event.toolbar;
/**
* Created by Mac on 3/2/15.
*/
public class ChatSubTitleEvent {
public String str;
public ChatSubTitleEvent(String str) {
this.str = str;
}
}
| true |
40dfccfa4c5092ca652eff2e5e3fa700832438bc | Java | pdibez/trabajos-ia-2017 | /a-estrella/src/a_star/Nodo.java | UTF-8 | 1,305 | 3.515625 | 4 | [] | no_license | package a_star;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Nodo implements Comparable<Nodo> {
private Map<Nodo, Integer> nodosHijos; // Nodo hijo -> Coste desde este nodo hasta nodo hijo
public final String nombre;
public final int h; // Heurística
public int coste = 0; // Coste del camino más corto desde el nodo inicial hasta este nodo
public Nodo padre = null;
private Nodo(String nombre, int h) {
this.nombre = nombre;
this.h = h;
this.nodosHijos = new HashMap<Nodo, Integer>();
}
public static Nodo crearNodo(String nombre, int h) {
return new Nodo(nombre, h);
}
public void addHijo(Nodo nodo, int coste) {
nodosHijos.put(nodo, coste);
}
public Set<Nodo> getHijos() {
return nodosHijos.keySet();
}
public int getCosteHijo(Nodo hijo) {
return nodosHijos.get(hijo);
}
public int getF() {
return this.coste + this.h;
}
@Override
public int compareTo(Nodo otro) {
return this.getF() - otro.getF();
}
@Override
public boolean equals(Object otro) {
if(otro == null || !(otro instanceof Nodo)) {
return false;
}
return ((Nodo) otro).nombre == this.nombre;
}
}
| true |
be66f662c4b0ede4c1af3872ab6e72c46024243d | Java | andreipopov00/Programming-Projects | /CMSC203_Lab6/GradeBookTest.java | UTF-8 | 1,343 | 3.03125 | 3 | [] | no_license | package Lab6;
import static org.junit.Assert.*;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class GradeBookTest {
private GradeBook scores1;
private GradeBook scores2;
@BeforeEach
void setUp() throws Exception {
scores1 = new GradeBook(5);
scores2 = new GradeBook(5);
scores1.addScore(100.0);
scores1.addScore(78.3);
scores1.addScore(92.0);
scores1.addScore(88.6);
scores2.addScore(43.5);
scores2.addScore(87.4);
scores2.addScore(35.0);
}
@AfterEach
void tearDown() throws Exception {
scores1 = null;
scores2 = null;
}
@Test
void testAddScore() {
assertTrue(scores1.toString().equals("100.0 78.3 92.0 88.6 0.0 "));
assertTrue(scores2.toString().equals("43.5 87.4 35.0 0.0 0.0 "));
assertEquals(4, scores1.getScoreSize());
assertEquals(3, scores2.getScoreSize());
}
@Test
void testSum() {
assertEquals(358.9, scores1.sum(), 0.0001);
assertEquals(165.9, scores2.sum(), 0.0001);
}
@Test
void testMinimum() {
assertEquals(78.3, scores1.minimum(), 0.001);
assertEquals(35.0, scores2.minimum(), 0.001);
}
@Test
void testFinalScore() {
assertEquals(280.6, scores1.finalScore(), 0.001);
assertEquals(130.9, scores2.finalScore(), 0.001);
}
}
| true |
61df3b940acecaab6bf67227157a95b10c464199 | Java | GuiTom/showdance | /ShowDanceActivity/src/com/android/app/showdance/ui/oa/FoundNearManActivity.java | UTF-8 | 3,826 | 2.28125 | 2 | [] | no_license | package com.android.app.showdance.ui.oa;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import com.android.app.wumeiniang.R;
import com.android.app.showdance.adapter.FoundNearManAdapter;
import com.android.app.showdance.ui.BaseActivity;
/**
* 发现-【附近舞友】
**/
public class FoundNearManActivity extends BaseActivity {
private ListView found_near_man_lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_found_near_man);
findViewById();
initView();
setOnClickListener();
found_near_man_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent intent = new Intent();
intent.setClass(FoundNearManActivity.this, FoundNearManDetail.class);
startActivity(intent);
}
});
}
@Override
protected void findViewById() {
tvTitle = (TextView) findViewById(R.id.tvTitle);
return_imgbtn = (ImageButton) findViewById(R.id.return_imgbtn);
found_near_man_lv = (ListView) findViewById(R.id.found_near_man_lv);
}
@Override
protected void initView() {
tvTitle.setText("附近舞友");
return_imgbtn.setVisibility(View.VISIBLE);
/**
* // ** ListView列表数据的显示 //
**/
List<Map<String, Object>> listItem = new ArrayList<Map<String, Object>>();
HashMap<String, Object> map1 = new HashMap<String, Object>();
HashMap<String, Object> map2 = new HashMap<String, Object>();
HashMap<String, Object> map3 = new HashMap<String, Object>();
HashMap<String, Object> map4 = new HashMap<String, Object>();
map1.put("letter_sort", "A");
map1.put("dance_man", "阿苏");
map1.put("dance_man_gender", "男");
map1.put("isTeamHeader", "队长");
map1.put("dance_team", "凤凰舞队");
map1.put("team_starLevel", "3星级");
map1.put("dance_man_distance", "100");
map2.put("letter_sort", "B");
map2.put("dance_man", "贝贝");
map2.put("dance_man_gender", "男");
map2.put("isTeamHeader", "");
map2.put("dance_team", "绚丽舞队");
map2.put("team_starLevel", "2星级");
map2.put("dance_man_distance", "200");
map3.put("letter_sort", "X");
map3.put("dance_man", "西西");
map3.put("dance_man_gender", "男");
map3.put("isTeamHeader", "");
map3.put("dance_team", "热火舞队");
map3.put("team_starLevel", "4星级");
map3.put("dance_man_distance", "300");
map4.put("letter_sort", "Z");
map4.put("dance_man", "紫紫");
map4.put("dance_man_gender", "女");
map4.put("isTeamHeader", "队长");
map4.put("dance_team", "七彩舞队");
map4.put("team_starLevel", "5星级");
map4.put("dance_man_distance", "300");
listItem.add(map1);
listItem.add(map2);
listItem.add(map3);
listItem.add(map4);
listItem.add(map1);
listItem.add(map2);
listItem.add(map3);
listItem.add(map4);
// 创建适配器对象
FoundNearManAdapter FoundNearManAdapter = new FoundNearManAdapter(FoundNearManActivity.this,listItem);
found_near_man_lv.setAdapter(FoundNearManAdapter);// 为ListView绑定适配器
}
@Override
protected void setOnClickListener() {
return_imgbtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent mIntent = new Intent();
switch (v.getId()) {
case R.id.return_imgbtn:// 返回
this.finish();
break;
default:
break;
}
}
@Override
public void refresh(Object... param) {
}
@Override
protected boolean validateData() {
return false;
}
}
| true |
eb369ac2135aab200f650099fbee3b77d8ceeca8 | Java | JanaUnbekannt/LerntagebuchOOP | /app/src/main/java/com/example/students/lerntagebuchoop/fragment/Tasks.java | UTF-8 | 7,973 | 1.867188 | 2 | [] | no_license | package com.example.students.lerntagebuchoop.fragment;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.students.lerntagebuchoop.R;
import com.example.students.lerntagebuchoop.adapter.TaskListAdapter;
import com.example.students.lerntagebuchoop.model.IntegrationData;
import com.example.students.lerntagebuchoop.model.TaskItem;
import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link Tasks.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link Tasks#newInstance} factory method to
* create an instance of this fragment.
*/
public class Tasks extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String taskName;
View mView;
String title;
ListView mListView;
TaskListAdapter mAdapter;
ArrayList<TaskItem> taskItems;
JSONObject lectureJSON;
private OnFragmentInteractionListener mListener;
private TextView mtitle;
public Tasks() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Tasks.
*/
// TODO: Rename and change types and number of parameters
public static Tasks newInstance(String param1, String param2) {
Tasks fragment = new Tasks();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(this.getArguments() == null){
try {
this.taskName = findCurrentLecture();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
else {
this.taskName = (String) this.getArguments().get("taskName");
}
taskItems = new ArrayList<>();
lectureJSON = IntegrationData.getInstance().lectureResources.get(taskName);
try {
title = (String)((JSONObject)lectureJSON.get("lecture")).get("topic");
JSONArray ja = (JSONArray)((JSONObject)((JSONObject)lectureJSON.get("lecture")).get("questions")).get("task");
for(int i =0; i<ja.length(); i++){
TaskItem ti = new TaskItem();
JSONObject task = (JSONObject) ja.get(i);
ti.setDescription(task.getString("description"));
ti.setText(task.getString("text"));
taskItems.add(ti);
}
}catch(Exception e){
e.printStackTrace();
}
}
private String findCurrentLecture() throws IllegalAccessException, ParseException {
// Alle XMLs nach DATE-Tag durchsuchen
SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy");
String currentLecture = null;
Date today = sdf.parse(sdf.format(new Date()));
Date currentLectureDate = null;
Date tempDate = null;
Field[] xmlFields = R.xml.class.getFields();
for(int i=0; i<xmlFields.length; i++){
// finde VL mit aktuellem Datum
try {
JSONObject lecture = (JSONObject)(IntegrationData.getInstance().lectureResources.get(xmlFields[i].getName())).get("lecture");
tempDate = sdf.parse(lecture.get("date").toString());
if(i == 0){
currentLectureDate = tempDate;
currentLecture = xmlFields[i].getName();
}
else if(tempDate.after(currentLectureDate) &&
tempDate.before(today)){
currentLectureDate = tempDate;
currentLecture = xmlFields[i].getName();
}
}catch (Exception e) {
e.printStackTrace();
}
}
return currentLecture;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//View leeren
if (container != null) {
container.removeAllViews();
}
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_tasks, container, false);
mtitle = (TextView) mView.findViewById(R.id.lectureTitle);
mtitle.setText(title);
mListView = (ListView) mView.findViewById(R.id.taskList);
mAdapter = new TaskListAdapter(getContext(), taskItems);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
String question = taskItems.get(position).getDescription();
String answer = taskItems.get(position).getText();
EditAnswer edit = new EditAnswer();
Bundle args = new Bundle();
args.putString("question", question);
args.putString("answer", answer);
args.putString("lectureName", taskName);
edit.setArguments(args); // hier wird der Name weitergegebn
ft.replace(R.id.frameLayout, edit).commit();
}
});
return mView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| true |
21dc4e00ef4a4f64207459bacdc7e469bf7ec7d3 | Java | northpl93/NorthPlatform | /Sources/MiniGame/ElytraRace/src/main/java/pl/north93/northplatform/minigame/elytrarace/scoreboard/ScoreScoreboard.java | UTF-8 | 4,615 | 2.40625 | 2 | [] | no_license | package pl.north93.northplatform.minigame.elytrarace.scoreboard;
import static pl.north93.northplatform.api.minigame.server.gamehost.MiniGameApi.getArena;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import pl.north93.northplatform.api.bukkit.player.INorthPlayer;
import pl.north93.northplatform.api.bukkit.scoreboard.ContentBuilder;
import pl.north93.northplatform.api.bukkit.scoreboard.IScoreboardContext;
import pl.north93.northplatform.api.bukkit.scoreboard.IScoreboardLayout;
import pl.north93.northplatform.api.global.component.annotations.bean.Inject;
import pl.north93.northplatform.api.global.messages.Messages;
import pl.north93.northplatform.api.global.messages.MessagesBox;
import pl.north93.northplatform.api.minigame.server.gamehost.arena.LocalArena;
import pl.north93.northplatform.minigame.elytrarace.arena.ElytraRaceArena;
import pl.north93.northplatform.minigame.elytrarace.arena.ElytraRacePlayer;
import pl.north93.northplatform.minigame.elytrarace.arena.ElytraScorePlayer;
public class ScoreScoreboard implements IScoreboardLayout
{
@Inject @Messages("ElytraRace")
private MessagesBox msg;
// Score Attack
//
// Punkty 68
//
// Top3
// 68 NorthPL93
// 67 _Wodzio_
// -1 _Pitbull_
//
// mcpiraci.pl
@Override
public String getTitle(final IScoreboardContext context)
{
return "&e&lScore Attack";
}
@Override
public List<String> getContent(final IScoreboardContext context)
{
final INorthPlayer player = context.getPlayer();
final LocalArena arena = getArena(player);
final ElytraRacePlayer racePlayer = player.getPlayerData(ElytraRacePlayer.class);
if (arena == null || racePlayer == null)
{
return Collections.emptyList();
}
final ElytraScorePlayer scorePlayer = racePlayer.asScorePlayer();
final ContentBuilder builder = IScoreboardLayout.builder();
builder.box(this.msg).locale(player.getLocale());
builder.add("");
builder.translated("scoreboard.score.points", scorePlayer.getPoints());
builder.add("");
builder.translated("scoreboard.score.top");
final Map<ElytraScorePlayer, Integer> ranking = this.getRanking(arena, 5);
// maksymalna ilosc punktów posiadanych przez gracza w tym rankingu
final int max = ranking.values().iterator().next();
for (final Map.Entry<ElytraScorePlayer, Integer> entry : ranking.entrySet())
{
final String displayName = entry.getKey().getPlayer().getDisplayName();
builder.translated("scoreboard.score.top_line", this.align(max, entry.getValue()), displayName);
}
builder.add("");
builder.translated("scoreboard.ip");
return builder.getContent();
}
private String align(final int max, final int points)
{
final int maxLength = Math.max(2, String.valueOf(max).length()); // 2
final String pointsString = String.valueOf(points); // 3
return StringUtils.repeat('0', Math.max(0, maxLength - pointsString.length())) + pointsString;
}
private Map<ElytraScorePlayer, Integer> getRanking(final LocalArena arena, final int limit)
{
final Map<ElytraScorePlayer, Integer> ranking = new LinkedHashMap<>();
final ElytraRaceArena arenaData = arena.getArenaData();
for (final ElytraRacePlayer racePlayer : arenaData.getPlayers())
{
final ElytraScorePlayer playerData = racePlayer.asScorePlayer();
ranking.put(playerData, playerData.getPoints());
}
return ranking.entrySet()
.stream()
.sorted(this::rankingComparator)
.limit(limit)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
}
private int rankingComparator(final Map.Entry<ElytraScorePlayer, Integer> p1, final Map.Entry<ElytraScorePlayer, Integer> p2)
{
return p2.getValue() - p1.getValue();
}
@Override
public int updateEvery()
{
return 10;
}
@Override
public String toString()
{
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).toString();
}
}
| true |
572ed66d9986c4b3e55f59b59688ee4e13b4487f | Java | keyuri20/GraduateProgram | /src/main/java/springmvc/model/dao/applicationDao.java | UTF-8 | 164 | 1.773438 | 2 | [] | no_license | package springmvc.model.dao;
import java.util.List;
import springmvc.model.application;
public interface applicationDao
{
List<application> getApplication();
}
| true |
a764297a527769a87d43936ff1e8149d5a1ffd9b | Java | VUT-FEKT-IBE/School-IBE | /BPC-TIN/Czechbol/cviceni03/src/GrEditor/Slozenina.java | UTF-8 | 395 | 2.78125 | 3 | [
"MIT"
] | permissive | package GrEditor;
import java.awt.Graphics2D;
import java.util.Vector;
public class Slozenina extends GrObjekt {
public Slozenina(int x, int y) {
super(x, y);
}
private Vector<GrObjekt> slozenina = new Vector<>();
public void pridej(GrObjekt o) {
slozenina.add(o);
}
@Override
public void vykresli(Graphics2D g2d) {
for (GrObjekt o : slozenina) {
o.vykresli(g2d);
}
}
}
| true |
56b116d0ca79500013e731c757c2b06efa4c31cd | Java | Dud3k9/Client-Server | /src/S_PASSTIME_SERVER1/Client.java | UTF-8 | 2,156 | 2.84375 | 3 | [] | no_license | /**
* @author Petrykowski Maciej S19267
*/
package S_PASSTIME_SERVER1;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
public class Client {
private String host;
private int port;
private String id;
private SocketChannel sc;
public Client(String host, int port, String id) {
this.host = host;
this.port = port;
this.id = id;
}
public void connect() {
try {
sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(new InetSocketAddress(host, port));
while (!sc.finishConnect()) {}
} catch (IOException e) {
e.printStackTrace();
}
}
public String send(String req) {
try {
sc.write(Charset.defaultCharset().encode(req + "\n"));
String response = readResponse();
return response;
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
private String readResponse() throws IOException, InterruptedException {
ByteBuffer inBuf = ByteBuffer.allocateDirect(1024);
StringBuilder sb = new StringBuilder();
char a = 0, b = 0;
readLoop:
while (true) {
inBuf.clear();
int readBytes = sc.read(inBuf);
if (readBytes == 0) {
Thread.sleep(10);
continue;
} else if (readBytes == -1) {
break;
} else {
inBuf.flip();
CharBuffer cbuf = Charset.defaultCharset().decode(inBuf);
while (cbuf.hasRemaining()) {
char c = cbuf.get();
b = a;
a = c;
sb.append(c);
if (b == '\t' && a == '\t') break readLoop;
}
}
}
return sb.toString();
}
public String getId() {
return id;
}
}
| true |
a2346b76c4cf4b6922de40197298335eaa084bd5 | Java | chengyuehao/ImageSearch | /src/main/java/com/cheng/mapping/ImageMapper.java | UTF-8 | 225 | 1.851563 | 2 | [] | no_license | package com.cheng.mapping;
import com.cheng.model.Image;
import java.util.List;
public interface ImageMapper {
List<Image> selectImages();
void insertImage(Image image);
List<Image> selectImagByVid(int vid);
}
| true |
eabdc7f8ca9633f797fcda148af9187e60e655d2 | Java | dami2450/despegarTest | /app/src/main/java/com/example/damian/despegartest/RankingHotelActivity.java | UTF-8 | 5,593 | 2.03125 | 2 | [] | no_license | package com.example.damian.despegartest;
import android.app.ActionBar;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by damian on 5/2/2018.
*/
public class RankingHotelActivity extends Activity {
ImageView estrellaUno, estrellaDos, estrellaTres, estrellaCuatro, estrellaCinco;
int estrellas;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_ACTION_BAR);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND, WindowManager.LayoutParams.FLAG_DIM_BEHIND);
Display display = getWindowManager().getDefaultDisplay();
int height = 0;
WindowManager.LayoutParams params = getWindow().getAttributes();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
params.width = (int) (display.getWidth() * 0.6); //fixed width
params.height = (int) (display.getWidth() * 0.6); //fixed width
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
params.width = (int) (display.getWidth() * 0.8); //fixed width
params.height = (int) (display.getWidth() * 0.8); //fixed width
}
params.alpha = 1.0f;
params.dimAmount = 0.5f;
super.onCreate(savedInstanceState);
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(R.layout.layout_menu_dialogo);
View actionBar = getActionBar().getCustomView();
ImageView home = (ImageView) actionBar.findViewById(R.id.home_icono_actionbar);
TextView titulo = (TextView) actionBar.findViewById(R.id.actionbar_title);
titulo.setText("ESTRELLAS");
home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
this.setFinishOnTouchOutside(true);
setContentView(R.layout.activity_ranking_hotel);
estrellaUno = (ImageView) findViewById(R.id.estrellaUno);
estrellaDos = (ImageView) findViewById(R.id.estrellaDos);
estrellaTres = (ImageView) findViewById(R.id.estrellaTres);
estrellaCuatro = (ImageView) findViewById(R.id.estrellaCuatro);
estrellaCinco = (ImageView) findViewById(R.id.estrellaCinco);
estrellas = getIntent().getIntExtra(Constantes.ESTRELLAS, -1);
llenarEstrellas();
}
public void llenarEstrellas() {
switch (estrellas){
case 1:
estrellaUno.setImageResource(R.drawable.estrella_llena);
estrellaDos.setImageResource(R.drawable.estrella_vacia);
estrellaTres.setImageResource(R.drawable.estrella_vacia);
estrellaCuatro.setImageResource(R.drawable.estrella_vacia);
estrellaCinco.setImageResource(R.drawable.estrella_vacia);
break;
case 2:
estrellaUno.setImageResource(R.drawable.estrella_llena);
estrellaDos.setImageResource(R.drawable.estrella_llena);
estrellaTres.setImageResource(R.drawable.estrella_vacia);
estrellaCuatro.setImageResource(R.drawable.estrella_vacia);
estrellaCinco.setImageResource(R.drawable.estrella_vacia);
break;
case 3:
estrellaUno.setImageResource(R.drawable.estrella_llena);
estrellaDos.setImageResource(R.drawable.estrella_llena);
estrellaTres.setImageResource(R.drawable.estrella_llena);
estrellaCuatro.setImageResource(R.drawable.estrella_vacia);
estrellaCinco.setImageResource(R.drawable.estrella_vacia);
break;
case 4:
estrellaUno.setImageResource(R.drawable.estrella_llena);
estrellaDos.setImageResource(R.drawable.estrella_llena);
estrellaTres.setImageResource(R.drawable.estrella_llena);
estrellaCuatro.setImageResource(R.drawable.estrella_llena);
estrellaCinco.setImageResource(R.drawable.estrella_vacia);
break;
case 5:
estrellaUno.setImageResource(R.drawable.estrella_llena);
estrellaDos.setImageResource(R.drawable.estrella_llena);
estrellaTres.setImageResource(R.drawable.estrella_llena);
estrellaCuatro.setImageResource(R.drawable.estrella_llena);
estrellaCinco.setImageResource(R.drawable.estrella_llena);
break;
default:
estrellaUno.setImageResource(R.drawable.estrella_vacia);
estrellaDos.setImageResource(R.drawable.estrella_vacia);
estrellaTres.setImageResource(R.drawable.estrella_vacia);
estrellaCuatro.setImageResource(R.drawable.estrella_vacia);
estrellaCinco.setImageResource(R.drawable.estrella_vacia);
break;
}
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
}
| true |
08601908d1eb116c7079a00edb640277e161d30e | Java | nsullivan1307/Cards | /src/DragBox.java | UTF-8 | 2,815 | 3.515625 | 4 | [] | no_license | import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
/**
* This is an abstract rectangle that can be 'dragged' on the panel. In order to drag,
* you must click on the rectangle, put your mouse to where you want to put it, and then click
* again to release the rectangle
*
* @author (Nicholas Sullivan)
* @version (Jan 2016)
*/
public class DragBox
{
// this is the x and y positions, the width and the height
protected int x, y, w, h;
// The panel that the DragBox is put into.
protected JPanel p;
// The Point where the mouse currently is (defined later)
private Point point1;
// x and y positions of the mouse, and the x and y positions relative to the top left corner
private int xp, yp, xRel, yRel;
private boolean sel;
public DragBox()
{
sel = false;
}
public void setPosition(int x1, int y1)
{
// Sets the position
x = x1;
y = y1;
}
public void setSize(Dimension d1)
{
// Sets the size of the rectangle
w = (int)d1.getWidth();
h = (int)d1.getHeight();
}
public void addTo(JPanel panel)
{
// sets which panel it should be in.
p = panel;
// adds a mouse listener to the panel
p.addMouseMotionListener(new PositionListener());
p.addMouseListener(new ClickListener());
}
private class ClickListener implements MouseListener
{
// When the mouse is moved
public void mousePressed(MouseEvent event)
{
// get the mouse position
point1 = event.getPoint();
xp = point1.x;
yp = point1.y;
if (xp > x && xp < x + w && yp > y && yp < y + h)
{
sel = true;
xRel = xp-x;
yRel = yp-y;
}
}
public void mouseClicked(MouseEvent event) {}
public void mouseReleased(MouseEvent event)
{
sel = false;
}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
}
// This is the mouse motion listener
private class PositionListener implements MouseMotionListener
{
// When the mouse is moved
public void mouseMoved(MouseEvent event){}
public void mouseDragged(MouseEvent event)
{
if (sel)
{
// get the mouse position
point1 = event.getPoint();
xp = point1.x;
yp = point1.y;
// generate the x and y location from the x and y mouse position and the relative x and y
x = xp - xRel;
y = yp - yRel;
// repaint the panel
p.repaint();
}
}
}
}
| true |
082f5581db5cb335a80e8aefe24a7d474acc09d4 | Java | moutainhigh/chdHRP | /src/com/chd/hrp/budg/controller/budgincome/reportforms/query/MedInQueryController.java | UTF-8 | 3,948 | 1.898438 | 2 | [] | no_license | /**
* @Description:
* @Copyright: Copyright (c) 2015-9-16 下午9:54:34
* @Company: 杭州亦童科技有限公司
* @网站:www.s-chd.com
*/
package com.chd.hrp.budg.controller.budgincome.reportforms.query;
import java.util.Map;
import javax.annotation.Resource;
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 com.alibaba.fastjson.JSONObject;
import com.chd.base.BaseController;
import com.chd.base.SessionManager;
import com.chd.hrp.budg.service.budgincome.reportforms.query.BudgMedInQueryService;
import com.chd.hrp.budg.service.budgincome.toptodown.deptmonthinbudg.MedInDMBudgService;
import com.chd.hrp.budg.service.budgincome.toptodown.hosmonthinbudg.MedInHMBudgService;
/**
*
* @Description:
* 科室月份医疗收入预算
* @Table:
* BUDG_MED_INCOME_DEPT_MONTH
* @Author: bell
* @email: bell@e-tonggroup.com
* @Version: 1.0
*/
@Controller
public class MedInQueryController extends BaseController{
private static Logger logger = Logger.getLogger(MedInQueryController.class);
//引入Service服务
@Resource(name = "budgMedInQueryService")
private final BudgMedInQueryService budgmMedInQueryService = null;
/**
* @Description
* 医院医疗收入预算查询 页面跳转
* @param mode
* @return String
* @throws Exception
*/
@RequestMapping(value = "hrp/budg/budgincome/reportforms/query/budgMedInHosMainPage", method = RequestMethod.GET)
public String budgMedIncomeDeptMonthMainPage(Model mode) throws Exception {
return "hrp/budg/budgincome/reportforms/query/medInHosBudgMain";
}
/**
* @Description
* 医院医疗收入预算查询 页面跳转
* @param mode
* @return String
* @throws Exception
*/
@RequestMapping(value = "hrp/budg/budgincome/reportforms/query/budgMedInDeptMainPage", method = RequestMethod.GET)
public String budgMedInDeptYearMainPage(Model mode) throws Exception {
return "hrp/budg/budgincome/reportforms/query/medInDeptBudgMain";
}
/**
* @Description
* 查询数据 医院医疗收入预算
* @param mapVo
* @param mode
* @return Map<String, Object>
* @throws Exception
*/
@RequestMapping(value = "/hrp/budg/budgincome/reportforms/query/queryMedInHosBudg", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> queryBudgWorkHosMonthUp(@RequestParam Map<String, Object> mapVo, Model mode) throws Exception {
mapVo.put("group_id", SessionManager.getGroupId());
mapVo.put("hos_id", SessionManager.getHosId());
mapVo.put("copy_code", SessionManager.getCopyCode());
if(mapVo.get("year") == null){
mapVo.put("year", SessionManager.getAcctYear());
}
String budgMedIncomeHos = budgmMedInQueryService.queryMedInHosBudg(getPage(mapVo));
return JSONObject.parseObject(budgMedIncomeHos);
}
/**
* @Description
* 查询数据 科室医疗收入预算
* @param mapVo
* @param mode
* @return Map<String, Object>
* @throws Exception
*/
@RequestMapping(value = "/hrp/budg/budgincome/reportforms/query/queryMedInDeptBudg", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> queryBudgWorkDeptMonthUp(@RequestParam Map<String, Object> mapVo, Model mode) throws Exception {
mapVo.put("group_id", SessionManager.getGroupId());
mapVo.put("hos_id", SessionManager.getHosId());
mapVo.put("copy_code", SessionManager.getCopyCode());
if(mapVo.get("year") == null){
mapVo.put("year", SessionManager.getAcctYear());
}
String budgMedInDept = budgmMedInQueryService.queryMedInDeptBudg(getPage(mapVo));
return JSONObject.parseObject(budgMedInDept);
}
}
| true |
dadb9757b1d6c8314939a1f30cea985390edf89c | Java | laisgraziele/oberser-reservas | /src/Reservas.java | UTF-8 | 600 | 2.671875 | 3 | [] | no_license | import java.util.Observable;
public class Reservas extends Observable implements Notificacoes {
private String acao = "";
@Override
public void criacao() {
acao="criada";
System.out.println("Reserva foi criada!");
this.mudaStatus();
}
@Override
public void alteracao() {
acao="alterada";
System.out.println("Reserva foi alterada!");
this.mudaStatus();
}
@Override
public void cancelamento() {
acao = "cancelada";
System.out.println("Reserva foi cancelada!");
this.mudaStatus();
}
public void mudaStatus() {
setChanged();
notifyObservers(acao);
}
}
| true |
8b247d60126dd21bc14b60bbd30f38a0fa0f3784 | Java | CrazyStoneJy/CustomView | /CustomView/app/src/main/java/com/crazystone/me/customview/activity/TestActivity.java | UTF-8 | 3,732 | 2.375 | 2 | [] | no_license | package com.crazystone.me.customview.activity;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.crazystone.me.customview.R;
import com.crazystone.me.customview.practice.ColorFilterView;
import com.crazystone.me.customview.utils.ColorMatrixs;
import java.util.ArrayList;
import java.util.List;
/**
* Created by crazy_stone on 17-7-18.
*/
public class TestActivity extends Activity {
RecyclerView recyclerView;
ColorFilterView colorFilterView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
colorFilterView = (ColorFilterView) findViewById(R.id.colorFilterView);
initData();
}
private void initData() {
List<String> list = new ArrayList<>();
list.add("half");
list.add("prime");
list.add("gray");
list.add("reverse");
list.add("old");
list.add("black");
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(new ListRecyclerViewAdapter(this, list));
}
private class ListRecyclerViewAdapter extends RecyclerView.Adapter<ListRecyclerViewAdapter.ListViewHolder> {
private List<String> list;
private Context context;
public ListRecyclerViewAdapter(Context context, List<String> list) {
this.list = list;
this.context = context;
}
@Override
public ListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(context, android.R.layout.simple_list_item_1, null);
return new ListViewHolder(view);
}
@Override
public void onBindViewHolder(ListViewHolder holder, int position) {
holder.txt.setText(list.get(position));
final String str = list.get(position);
holder.txt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ("half".equals(str)) {
colorFilterView.setStyle(ColorMatrixs.HALF);
} else if ("prime".equals(str)) {
colorFilterView.setStyle(ColorMatrixs.PRIME);
} else if ("gray".equals(str)) {
colorFilterView.setStyle(ColorMatrixs.GRAY);
} else if ("reverse".equals(str)) {
colorFilterView.setStyle(ColorMatrixs.REVERSE);
} else if ("old".equals(str)) {
colorFilterView.setStyle(ColorMatrixs.OLD);
} else if ("black".equals(str)) {
colorFilterView.setStyle(ColorMatrixs.BLACK_WHITE);
}
}
});
}
@Override
public int getItemCount() {
return list != null ? list.size() : 0;
}
class ListViewHolder extends RecyclerView.ViewHolder {
TextView txt;
public ListViewHolder(View itemView) {
super(itemView);
txt = (TextView) itemView.findViewById(android.R.id.text1);
}
}
}
}
| true |
a72b17a5bce24e3cf1ead48973ace2aac641c323 | Java | PolyxeniCh/FeelyProject | /Feely/src/Destination.java | ISO-8859-7 | 666 | 2.46875 | 2 | [] | no_license | /*
* :
*/
public class Destination extends Category {
private String category; //
public Destination(String title, String link, String category) {
super(title, link);
this.category = category;
}
// ---------- GETTERS ----------
public String getCategory() {
return category;
}
// ------------------------------
// ---------- SETTERS ----------
public void setCategory(String category) {
this.category = category;
}
// ------------------------------
}
| true |
dc7da4a66143f2813cefd3fd86d7d657d71efefc | Java | xyf18362929560/SoftwareEngineering | /源代码/1209_2256/ExpressService/src/nju/express/dataservice/impl/SenderDataServiceImpl.java | UTF-8 | 1,151 | 2.25 | 2 | [] | no_license | package nju.express.dataservice.impl;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Vector;
import nju.express.dataservice.SenderDataService;
import nju.express.po.Sender;
import nju.express.util.DAO;
public class SenderDataServiceImpl extends UnicastRemoteObject implements SenderDataService {
/**
*
*/
private static final long serialVersionUID = 6730119679915437858L;
public SenderDataServiceImpl() throws RemoteException {
super();
}
@Override
public Sender getById(int id) throws RemoteException {
Sender sender = (Sender) DAO.getObById(Sender.class, id);
return sender;
}
@Override
public Vector<Sender> getAll() throws RemoteException {
Vector<Sender> senders = DAO.getList(Sender.class);
return senders;
}
@Override
public int insert(Sender sender) throws RemoteException {
return DAO.insertGetGeneratedKey(sender);
}
@Override
public boolean update(Sender sender) throws RemoteException {
return DAO.update(sender, sender.getId());
}
@Override
public boolean delete(int id) throws RemoteException {
return DAO.delete(Sender.class, id);
}
}
| true |
b4e73a1a92f12edeaa08823ac5a3ad445c5b6f2f | Java | NiteshPidiparars/CodeBlock | /Mix.java | UTF-8 | 823 | 3.5625 | 4 | [] | no_license | import java.util.*;
class Mix
{
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
int a1[],a2[],a3[],i,j,n;
System.out.println("Enter the number of value: ");
n=sc.nextInt();
a1=new int[n];
a2=new int[n];
a3=new int[n+n];
System.out.println("Enter the first array: ");
for(i=0;i<n;i++)
a1[i]=sc.nextInt();
System.out.println("Enter the second array: ");
for(i=0;i<n;i++)
a2[i]=sc.nextInt();
System.out.println("Combinning array is: ");
for(i=0;i<n;i++){
a3[2*i]=a1[i];
a3[2*i+1]=a2[i];
}
n*=2;
System.out.println("Resulting array is: ");
for(i=0;i<n;i++)
System.out.println(a3[i]+" ");
}
}
| true |
036e5084fa70739237103e1b188109c08eef107e | Java | micronaut-projects/micronaut-core | /core-processor/src/main/java/io/micronaut/inject/ast/annotation/MethodElementAnnotationMetadata.java | UTF-8 | 1,981 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2017-2023 original 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 io.micronaut.inject.ast.annotation;
import io.micronaut.core.annotation.AnnotationMetadata;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.inject.annotation.AnnotationMetadataHierarchy;
import io.micronaut.inject.ast.MethodElement;
/**
* The element annotation metadata for a method element.
*
* @author Denis Stepanov
* @since 4.0.0
*/
public final class MethodElementAnnotationMetadata extends AbstractElementAnnotationMetadata {
private final MethodElement methodElement;
private final MutableAnnotationMetadataDelegate<?> writeAnnotationMetadata;
private final AnnotationMetadata readAnnotationMetadata;
public MethodElementAnnotationMetadata(@NonNull MethodElement methodElement) {
this.methodElement = methodElement;
writeAnnotationMetadata = methodElement.getMethodAnnotationMetadata();
readAnnotationMetadata = new AnnotationMetadataHierarchy(
methodElement.getOwningType(),
writeAnnotationMetadata
);
}
@Override
public AnnotationMetadata getAnnotationMetadata() {
return readAnnotationMetadata;
}
@Override
protected MethodElement getReturnInstance() {
return methodElement;
}
@Override
protected MutableAnnotationMetadataDelegate<?> getAnnotationMetadataToWrite() {
return writeAnnotationMetadata;
}
}
| true |
9a32647527874ce8bfdfd14c9d4725f1bf0b6eb4 | Java | wstars1994/BTFinder | /src/com/boomzz/main/bencode/BencodeInteger.java | UTF-8 | 1,125 | 2.578125 | 3 | [] | no_license | /**
*
* 项目名称:[BTFounder]
* 包: [com.boomzz.main.bencode]
* 类名称: [BecodeInteger]
* 类描述: [一句话描述该类的功能]
* 创建人: [王新晨]
* 创建时间:[2018年3月31日 下午4:29:20]
* 修改人: [王新晨]
* 修改时间:[2018年3月31日 下午4:29:20]
* 修改备注:[说明本次修改内容]
* 版本: [v1.0]
*
*/
package com.boomzz.main.bencode;
import java.io.PushbackInputStream;
import java.util.LinkedHashMap;
import org.apache.commons.lang3.ArrayUtils;
import com.boomzz.main.bencode.model.ObjectBytesModel;
public class BencodeInteger extends AbstractBencode{
@Override
public ObjectBytesModel decode(PushbackInputStream stream, LinkedHashMap<String, Object> hashMap) throws Exception{
int num = 101;
String numStr = "";
byte res[] = {};
while ((num=stream.read())!=101) {
res = ArrayUtils.add(res, (byte)num);
numStr+=(char)num+"";
}
return new ObjectBytesModel(Integer.parseInt(numStr),res);
}
@Override
public byte[] encode(Object object) {
return ("i"+object+"e").getBytes();
}
}
| true |
6cf8c7d655c5866637e84450110bc84368b0a793 | Java | ebi-uniprot/uniprot-subcell | /src/main/java/uk/ac/ebi/uniprot/uniprotsubcell/import_data/CombineSubcellAndRefCount.java | UTF-8 | 3,213 | 2.71875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | package uk.ac.ebi.uniprot.uniprotsubcell.import_data;
import uk.ac.ebi.uniprot.uniprotsubcell.domains.Subcellular;
import uk.ac.ebi.uniprot.uniprotsubcell.dto.SubcellReferenceCount;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CombineSubcellAndRefCount {
private static final Logger LOG = LoggerFactory.getLogger(CombineSubcellAndRefCount.class);
public List<Subcellular> readFileImportAndCombine(String subcellFilePath, String referenceCountFilePath) {
subcellFilePath = subcellFilePath == null ? "" : subcellFilePath.trim();
referenceCountFilePath = referenceCountFilePath == null ? "" : referenceCountFilePath.trim();
List<String> allLines = null;
LOG.debug("File: {} to import subcell location data set ", subcellFilePath);
try {
allLines = Files.readAllLines(Paths.get(subcellFilePath));
} catch (IOException e) {
LOG.error("Exception Handle gracefully: Failed to read file {} ", subcellFilePath, e);
allLines = Collections.emptyList();
}
LOG.debug("total {} lines found in file ", allLines.size());
final ParseSubCellLines parser = new ParseSubCellLines();
List<Subcellular> subcellList = parser.parseLines(allLines);
LOG.info("total {} entries found in file ", subcellList.size());
LOG.debug("File: {} to import subcell reference count ", referenceCountFilePath);
final ParseReferenceCountLines refParser = new ParseReferenceCountLines();
Collection<SubcellReferenceCount> referenceCountList;
try {
referenceCountList = refParser.parseLinesFromReader(new FileReader(referenceCountFilePath));
} catch (IOException e) {
LOG.error("Exception Handle gracefully: Failed to read file {} ", referenceCountFilePath, e);
referenceCountList = Collections.emptyList();
}
LOG.info("total {} Reference count found in file ", referenceCountList.size());
updateSubcellWithReferenceCount(subcellList, referenceCountList);
return subcellList;
}
private void updateSubcellWithReferenceCount(List<Subcellular> subcellList, Collection<SubcellReferenceCount>
referenceCountList) {
// Loop on reference count list
referenceCountList.forEach(
// Find the subcell from subcell list
rc -> subcellList.stream().filter(d -> d.getIdentifier().equalsIgnoreCase(rc.getIdentifier()))
.findFirst()
.ifPresent(
//subcell found from list
seubcell -> {
//Updating subcell count from reference count object
seubcell.setSwissProtCount(rc.getSwissProtCount());
seubcell.setTremblCount(rc.getTremblCount());
}
)
);
}
}
| true |
8a82a8c1f5c2037ed933c7248d82b0feec506052 | Java | balajavajee/JavaJee | /components/MSOne/src/main/java/com/microservices/msone/repository/UserRepository.java | UTF-8 | 377 | 1.9375 | 2 | [] | no_license | package com.microservices.msone.repository;
import java.util.Collection;
import org.springframework.stereotype.Repository;
import com.microservices.msone.model.UserDetails;
@Repository
public interface UserRepository extends BaseRepository<UserDetails, String> {
boolean containsName(String name);
Collection<UserDetails> findByName(String name) throws Exception;
} | true |
4f12c02a926845511784f09389ab6f0b41074ad7 | Java | frsknalexis/crm-java | /crm_backend/src/main/java/com/dev/crm/core/service/impl/UsuarioServiceImpl.java | UTF-8 | 8,208 | 2.046875 | 2 | [
"Apache-2.0"
] | permissive | package com.dev.crm.core.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dev.crm.core.dao.UsuarioDAO;
import com.dev.crm.core.dto.ModuloResultViewModel;
import com.dev.crm.core.dto.PerfilUsuarioResultViewModel;
import com.dev.crm.core.dto.UsuarioPerfilRequest;
import com.dev.crm.core.model.entity.Usuario;
import com.dev.crm.core.repository.jdbc.ModuloResultJdbcRepository;
import com.dev.crm.core.repository.jdbc.PerfilUsuarioJdbcRepository;
import com.dev.crm.core.repository.jdbc.UsuarioPerfilJdbcRepository;
import com.dev.crm.core.security.UserDetail;
import com.dev.crm.core.service.UsuarioService;
import com.dev.crm.core.util.Constantes;
import com.dev.crm.core.util.DateUtil;
import com.dev.crm.core.util.GenericUtil;
import com.dev.crm.core.util.IpUtil;
@Service("usuarioService")
@Transactional("hibernateTransactionManager")
public class UsuarioServiceImpl implements UsuarioService {
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
@Qualifier("usuarioDAO")
private UsuarioDAO usuarioDAO;
@Autowired
@Qualifier("ModuloResultJdbcRepository")
private ModuloResultJdbcRepository moduloResultJdbcRepository;
@Autowired
@Qualifier("userDetail")
private UserDetail userDetail;
@Autowired
@Qualifier("perfilUsuarioJdbcRepository")
private PerfilUsuarioJdbcRepository perfilUsuarioJdbcRepository;
@Autowired
@Qualifier("usuarioPerfilJdbcRepository")
private UsuarioPerfilJdbcRepository usuarioPerfilJdbcRepository;
@Override
public List<Usuario> findAll() {
List<Usuario> usuarios = new ArrayList<Usuario>();
try {
usuarios = usuarioDAO.findAll(Usuario.class);
if(GenericUtil.isNotNull(usuarios)) {
return usuarios;
}
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public List<Usuario> getActiveList() {
List<Usuario> usuarios = new ArrayList<Usuario>();
try {
usuarios = usuarioDAO.getActiveList(Usuario.class);
if(GenericUtil.isNotNull(usuarios)) {
return usuarios;
}
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public Usuario getByUsuarioId(BigDecimal usuarioId) {
Usuario usuario = null;
try {
if(GenericUtil.isNotEmpty(usuarioId)) {
usuario = usuarioDAO.get(Usuario.class, usuarioId);
}
if(GenericUtil.isNotNull(usuario)) {
return usuario;
}
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public Usuario getByNombre(String nombreUsuario) {
Usuario usuario = null;
try {
if(!(GenericUtil.isEmpty(nombreUsuario))) {
usuario = usuarioDAO.getByNombre(nombreUsuario);
}
if(GenericUtil.isNotNull(usuario)) {
return usuario;
}
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public Usuario getByNombreUsuarioAndPassword(String nombreUsuario, String passwordUsuario) {
Usuario usuario = null;
try {
if(GenericUtil.isNotEmpty(nombreUsuario) && GenericUtil.isNotEmpty(passwordUsuario)) {
usuario = usuarioDAO.getByNombreUsuarioAndPassword(nombreUsuario, passwordUsuario);
}
if(GenericUtil.isNotNull(usuario)) {
return usuario;
}
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public Usuario getByDocumentoUsuario(String documentoUsuario) {
Usuario usuario = null;
try {
if(!(GenericUtil.isEmpty(documentoUsuario))) {
usuario = usuarioDAO.getByDocumentoUsuario(documentoUsuario);
}
if(GenericUtil.isNotNull(usuario)) {
return usuario;
}
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public void disabledUsuario(BigDecimal usuarioId) {
User usuarioLogueado = userDetail.findLoggedInUser();
try {
Usuario usuario = null;
if(GenericUtil.isNotEmpty(usuarioId)) {
usuario = usuarioDAO.get(Usuario.class, usuarioId);
usuario.setHabilitado(Constantes.INHABILITADO);
usuario.setFechaModificacion(DateUtil.getCurrentDate());
usuario.setFechaDesactivacion(DateUtil.getCurrentDate());
usuario.setModificadoPor(usuarioLogueado.getUsername());
usuario.setIpUsuario(IpUtil.getCurrentIPAddress());
usuario.setUsuarioMaquina(IpUtil.getCurrentUserMachine());
usuario.setUsuarioSistema(IpUtil.getCurrentUserSystem());
}
usuarioDAO.disabledUsuario(usuario);
}
catch(Exception e) {
e.printStackTrace();
}
}
@Override
public void enabledUsuario(BigDecimal usuarioId) {
User usuarioLogueado = userDetail.findLoggedInUser();
try {
Usuario usuario = null;
if(GenericUtil.isNotEmpty(usuarioId)) {
usuario = usuarioDAO.get(Usuario.class, usuarioId);
usuario.setHabilitado(Constantes.HABILITADO);
usuario.setFechaModificacion(DateUtil.getCurrentDate());
usuario.setFechaActivacion(DateUtil.getCurrentDate());
usuario.setModificadoPor(usuarioLogueado.getUsername());
usuario.setIpUsuario(IpUtil.getCurrentIPAddress());
usuario.setUsuarioMaquina(IpUtil.getCurrentUserMachine());
usuario.setUsuarioSistema(IpUtil.getCurrentUserSystem());
}
usuarioDAO.enabledUsuario(usuario);
}
catch(Exception e) {
e.printStackTrace();
}
}
@Override
public void saveOrUpdate(Usuario u) {
User usuarioLogueado = userDetail.findLoggedInUser();
try {
u.setHabilitado(Constantes.HABILITADO);
u.setIpUsuario(IpUtil.getCurrentIPAddress());
u.setUsuarioMaquina(IpUtil.getCurrentUserMachine());
u.setUsuarioSistema(IpUtil.getCurrentUserSystem());
u.setEncryptedPassword(bCryptPasswordEncoder.encode(u.getPasswordUsuario()));
if(GenericUtil.isNotEmpty(u.getUsuarioId()) && u.getUsuarioId().intValue() > 0) {
u.setModificadoPor(usuarioLogueado.getUsername());
u.setFechaModificacion(DateUtil.getCurrentDate());
usuarioDAO.update(u);
}
else {
u.setCreadoPor(usuarioLogueado.getUsername());
u.setFechaRegistro(DateUtil.getCurrentDate());
usuarioDAO.save(u);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
@Override
public boolean isUserPresent(String documentoUsuario) {
if(!(GenericUtil.isEmpty(documentoUsuario))) {
return usuarioDAO.isUserPresent(documentoUsuario);
}
return false;
}
@Override
public void actualizarPerfilPassword(UsuarioPerfilRequest request) {
try {
if(GenericUtil.isNotNull(request)) {
request.setEncryptedPasswordActual(bCryptPasswordEncoder.encode(request.getPasswordActual()));
usuarioPerfilJdbcRepository.actualizarPerfilPassword(request);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
@Override
public Long obtenerTotalRegistrosUsuario() {
try {
Long totalRegistrosUsuario = usuarioDAO.obtenerTotalRegistrosUsuario();
return totalRegistrosUsuario;
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public ModuloResultViewModel spListarModulo(String usuario,String numero) {
ModuloResultViewModel cDaOn;
try {
if(!GenericUtil.isEmpty(usuario) && !GenericUtil.isEmpty(numero)) {
cDaOn = moduloResultJdbcRepository.spListaModulo(usuario, numero);
if(GenericUtil.isNotNull(cDaOn)) {
return cDaOn;
}
else {
return null;
}
}
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public PerfilUsuarioResultViewModel perfilUsuario(String usuario) {
PerfilUsuarioResultViewModel perfilUsuario = null;
try {
if(GenericUtil.isNotNull(usuario)) {
perfilUsuario = perfilUsuarioJdbcRepository.perfilUsuario(usuario);
}
if(GenericUtil.isNotNull(perfilUsuario)) {
return perfilUsuario;
}
else {
return null;
}
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
}
| true |
1122470d3ecdbf90dc1288d6753ee2f796038c95 | Java | jinhanlai/JavaSourceCode | /src/main/java/thread/TestReadWriteLock.java | UTF-8 | 1,387 | 3.109375 | 3 | [] | no_license | package thread;
import org.junit.jupiter.api.Test;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @Author laijinhan
* @date 2020/12/20 下午5:58
*/
public class TestReadWriteLock {
@Test
public void testReadwrite() {
ReadWriteLock readWriteLock=new ReadWriteLock();
for (int i = 0; i < 10; i++) {
final int ii = i;
new Thread(() -> {
readWriteLock.put(String.valueOf(ii),ii);
}, String.valueOf(i)).start();
}
for (int i = 0; i < 10; i++) {
final int ii = i;
new Thread(() -> {
readWriteLock.get(String.valueOf(ii));
}, String.valueOf(i)).start();
}
}
}
class ReadWriteLock {
private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();
public void put(String key, Object value) {
readWriteLock.writeLock().lock();
System.out.println(Thread.currentThread().getName()+"写入"+key);
map.put(key, value);
System.out.println(Thread.currentThread().getName()+"写入ok");
readWriteLock.writeLock().unlock();
}
public void get(String key) {
readWriteLock.readLock().lock();
System.out.println(Thread.currentThread().getName()+"读取"+key);
map.get(key);
readWriteLock.readLock().unlock();
System.out.println(Thread.currentThread().getName()+"读取ok");
}
}
| true |
478a896da313ac0d08bb3bc30068a1007d82c15c | Java | Vanderzui/coffeemachine | /src/main/java/org/vanderzui/cofeemachine/controller/CoffeeMachineController.java | UTF-8 | 978 | 2.375 | 2 | [] | no_license | package org.vanderzui.cofeemachine.controller;
import org.vanderzui.cofeemachine.entity.RecipeEntity;
import org.vanderzui.cofeemachine.entity.RecipeType;
import org.vanderzui.cofeemachine.entity.SupplyEntity;
import org.vanderzui.cofeemachine.service.MoneyService;
import org.vanderzui.cofeemachine.service.SimpleMoneyService;
import java.util.ArrayList;
import java.util.List;
public class CoffeeMachineController {
private static final MoneyService moneyService = new SimpleMoneyService();
public int insertCredit(int money){
return moneyService.insertCredit(money);
}
public int returnCredit() {
return moneyService.returnCredit();
}
public int emptyBank(){
return moneyService.emptyBank();
}
public RecipeEntity chooseRecipe(RecipeType recipeType){
return new RecipeEntity();
}
public List<SupplyEntity> fillSupply(List<SupplyEntity> supplyEntities){
return new ArrayList<>();
}
}
| true |
07cb270440ee5addc89b8e0c809bc5d32e4b012c | Java | Tomones/Java | /src/main/java/com/lyss/java/concurrent/threadcommunication/ListAdd1.java | UTF-8 | 1,032 | 3.5625 | 4 | [] | no_license | package com.lyss.java.concurrent.threadcommunication;
import java.util.ArrayList;
import java.util.List;
public class ListAdd1 {
private volatile static List list = new ArrayList<>();
public void add(){
list.add("guotao");
}
public int size(){
return list.size();
}
public static void main(String[] args) {
final ListAdd1 listAdd1 = new ListAdd1();
new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
listAdd1.add();
System.out.println("当前线程:"+Thread.currentThread().getName()+"---添加了一个元素");
Thread.sleep(500);
}
} catch (Exception e) {
// TODO: handle exception
}
}
},"t1").start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (listAdd1.size()==5) {
System.out.println("当前线程:"+Thread.currentThread().getName()+"---list size == 5 线程终止");
throw new RuntimeException();
}
}
}
},"t2").start();
}
}
| true |
e42d58cd24365c7197dd43d1bd8016d769b88cf4 | Java | nanxinW/LearnJava | /Code/day04/SwitchTest01.java | UTF-8 | 2,342 | 4.34375 | 4 | [] | no_license | /*
switch语句:
1、switch语句的语法格式:
switch(值){
case 值1:
java语句;
java语句;
break;
case 值2:
java语句;
java语句;
break;
......
default:
java语句;
}
以上是一个完整的switch语句,其中break语句和default分支也不是必须的。
2、switch语句支持的值有哪些?
支持int类型和String类型。
但一定要注意JDK的版本,在JDK8之前不支持String类型,只支持int。当值为byte short char 类型时可以自动转换成int型。
3、执行原理
switch语句中“值”与“值1”、“值2”比较的时候会使用“==”进行比较。
先“值”与“值1”进行比较,如果相同,则执行该分支中的java语句,遇到“break”语句后,switch语句结束了。
如果不相同,则“值”与“值2”继续进行比较,然后遇到“break”就结束。
***注意:如果分支执行了,但是该分支中没有“break”语句,此时会出现break击穿现象,
比如"值" == “值1”执行第一个case分支,但是由于没有brake语句,所以会直接执行第二个case语句中的内容
以此类推下去。
***case 合并:
switch(值){
case 值1:case 值2:case 值3:-------》此处就是case合并问题
java语句;
java语句;
break;
case 值4:
java语句;
java语句;
break;
......
default:
java语句;
}
*/
/*
业务要求:
1、系统接收一个学生的考试成绩,根据考试成绩输出成绩的等级。
2、等级:
优:90-100
良:80-90
中:70-80
及格:70-60
不及格:0-60
*/
public class SwitchTest01
{
public static void main(String[] args)
{
java.util.Scanner s = new java.util.Scanner(System.in);
System.out.print("请输入分数:");
double score = s.nextDouble();
if (score < 0 || score > 100)
{
System.out.println("非法输入!!");
return;
}
String str = "不及格";
int grade = (int)(score/10);//95.5/10结果是9.55,强制转为int后为9
switch (grade)
{
case 10: case 9 :
str = "优";
break;
case 8:
str = "良";
break;
case 7:
str = "中";
break;
case 6:
str = "及格";
break;
}
System.out.println(str);
}
}
| true |
01ae67f9fa5fedc0732db83920c94b4a5f4c059b | Java | antonyanmher91/MherAntonyan | /MyMassanger/app/src/main/java/com/example/mymassanger/massange/MassangerItem.java | UTF-8 | 384 | 2.734375 | 3 | [] | no_license | package com.example.mymassanger.massange;
public class MassangerItem {
String name;
String mass;
public MassangerItem() {
}
public MassangerItem(String name, String massange) {
this.name = name;
this.mass = massange;
}
public String getName() {
return name;
}
public String getMassange() {
return mass;
}
}
| true |
d2d018269fb1cc5fe6ccd4de06ad61c633272151 | Java | sortaxie/babycar-mqtt | /src/main/java/com/adorgroup/babycar/mqtt/dao/DeviceMapper.java | UTF-8 | 875 | 2.015625 | 2 | [] | no_license | package com.adorgroup.babycar.mqtt.dao;
import com.adorgroup.babycar.mqtt.domain.Device;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
public interface DeviceMapper {
int deleteByPrimaryKey(Integer id);
int insert(Device record);
int insertSelective(Device record);
Device selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Device record);
int updateByPrimaryKey(Device record);
@Select("select * from dvc_device where rfid = #{rfid}")
Device selectByRfid(@Param("rfid") String rfid);
@Update("update dvc_device set station_id ={stationId},station_ks={ks},status={status} where rfid={rfid}")
void updateByRfid(@Param("rfid") String rfid,@Param("stationId") String stationId,@Param("ks") int ks,@Param("status") int status);
} | true |
c3c35d5b522fb0035c4aea833a65e05e077cf7f7 | Java | rossetti1983/lint | /src/dp/buttomUpDp/LongestCommonSubstring79.java | UTF-8 | 1,261 | 3.703125 | 4 | [] | no_license | package dp.buttomUpDp;
/**
* Created by zhizha on 10/1/17.
* Given two strings, find the longest common substring.
Return the length of it.
Notice
The characters in substring should occur continuously in original string. This is different with subsequence.
Have you met this question in a real interview? Yes
Example
Given A = "ABCD", B = "CBCE", return 2.
Challenge
O(n x m) time and memory.
*/
public class LongestCommonSubstring79 {
/*
* @param A: A string
* @param B: A string
* @return: the length of the longest common substring.
*/
public int longestCommonSubstring(String A, String B) {
// write your code here
if(A == null || A.trim().equals("")){
return 0;
}
if(B == null || B.trim().equals("")){
return 0;
}
int[][] dp = new int[A.length()+1][B.length()+1];
int max = 0;
for(int i = 1; i<= A.length(); i++){
for(int j = 1; j <= B.length(); j++){
if(A.charAt(i-1)==B.charAt(j-1)){
dp[i][j] = dp[i-1][j-1] + 1;
if(dp[i][j]>max){
max = dp[i][j];
}
}
}
}
return max;
}
}
| true |
2847eefac8d65a68c0c205a950a7fa7c5596ac94 | Java | SadManFahIm/HackerRank-Preparation-Kit | /Hash Tables-Ice Cream Parlour.java | UTF-8 | 1,197 | 3.0625 | 3 | [
"MIT"
] | permissive | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution
{
/**
* @param arr
* @param money
*/
static void solve (int[]arr, int money)
{
// Complete this function
if (arr == null || arr.length < 1)
{
System.out.println (-1 + " " + -1);
return;
}
// core logic
HashMap < Integer, Integer > hashMap = new HashMap <> ();
for (int i = 0; i < arr.length; i++)
{
if (arr[i] < money)
{
if (hashMap.containsKey (money - arr[i]))
{
int index = hashMap.get (money - arr[i]);
System.out.println ((index + 1) + " " + (i + 1));
return;
}
if (!hashMap.containsKey (arr[i]))
{
hashMap.put (arr[i], i);
}
}
}
}
public static void main (String[]args)
{
Scanner in = new Scanner (System.in);
int t = in.nextInt ();
for (int a0 = 0; a0 < t; a0++)
{
int money = in.nextInt ();
int n = in.nextInt ();
int[] arr = new int[n];
for (int arr_i = 0; arr_i < n; arr_i++)
{
arr[arr_i] = in.nextInt ();
}
solve (arr, money);
}
in.close ();
}
}
| true |
8a2cdcc35582bc2a95b911d6f2d23c97c1d1f23e | Java | katemeronandroid/Session8 | /app/src/main/java/com/firstexample/emarkova/session8/ItemEntity.java | UTF-8 | 141 | 2.21875 | 2 | [] | no_license | package com.firstexample.emarkova.session8;
public class ItemEntity {
public int i;
ItemEntity(int i) {
this.i = i;
}
}
| true |
5f4b2745dd48245a763097c96e5c9308e048d182 | Java | Yelson11/Thread-Competition | /src/view/GraphicInterface.java | UTF-8 | 18,990 | 2.296875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import controller.Simulator;
import java.awt.Graphics;
import controller.ThreadController;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
/**
*
* @author Yelson
*/
public class GraphicInterface extends javax.swing.JFrame {
private ThreadController controller;
private boolean checkStatus;
private boolean interruptStatus;
private boolean simulate;
private Simulator simulator;
private Timer updaterTimer;
private TimerTask timerTask;
public GraphicInterface() {
initComponents();
checkStatus = false;
simulate = false;
interruptStatus = true;
simulator = new Simulator();
controller = ThreadController.getInstace();
trackView1.create();
controller.start();
simulator.start();
simulator.suspend();
updaterTimer = new Timer();
timerTask = new TimerTask() {
@Override
public void run() {
lblSpeed3.setText("" + controller.getThreadPool()[0].getCreatedQuantity());
lblSpeed2.setText("" + controller.getThreadPool()[1].getCreatedQuantity());
lblSpeed1.setText("" + controller.getThreadPool()[2].getCreatedQuantity());
}
};
updaterTimer.schedule(timerTask, 0, 100);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
trackView1 = new view.TrackView();
jLabel2 = new javax.swing.JLabel();
cmbSpeed = new javax.swing.JComboBox<>();
btnSimulation = new javax.swing.JButton();
btnInterrupt = new javax.swing.JButton();
btnRevert = new javax.swing.JButton();
cbxImages = new javax.swing.JCheckBox();
jLabel3 = new javax.swing.JLabel();
txtBarrier = new javax.swing.JTextField();
txtValue = new javax.swing.JTextField();
btnCreate = new javax.swing.JButton();
jSeparator2 = new javax.swing.JSeparator();
btnAllBarriers = new javax.swing.JButton();
btnBarries = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
lblSpeed1 = new javax.swing.JLabel();
lblSpeed2 = new javax.swing.JLabel();
lblSpeed3 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout trackView1Layout = new javax.swing.GroupLayout(trackView1);
trackView1.setLayout(trackView1Layout);
trackView1Layout.setHorizontalGroup(
trackView1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
trackView1Layout.setVerticalGroup(
trackView1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 634, Short.MAX_VALUE)
);
jLabel2.setText("Value:");
cmbSpeed.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Speed 3", "Speed 2", "Speed 1" }));
btnSimulation.setText("Simulation");
btnSimulation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSimulationActionPerformed(evt);
}
});
btnInterrupt.setText("Interrupt");
btnInterrupt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnInterruptActionPerformed(evt);
}
});
btnRevert.setText("Revert");
btnRevert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRevertActionPerformed(evt);
}
});
cbxImages.setText("Images");
cbxImages.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbxImagesActionPerformed(evt);
}
});
jLabel3.setText("Barrier:");
txtValue.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtValueActionPerformed(evt);
}
});
btnCreate.setText("Create Runners");
btnCreate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCreateActionPerformed(evt);
}
});
btnAllBarriers.setText("Deactivate All Barriers");
btnAllBarriers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAllBarriersActionPerformed(evt);
}
});
btnBarries.setText("Activate");
btnBarries.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBarriesActionPerformed(evt);
}
});
jLabel1.setText("Speed 1:");
jLabel4.setText("Speed 2:");
jLabel5.setText("Speed 3:");
lblSpeed1.setText("0");
lblSpeed2.setText("0");
lblSpeed3.setText("0");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(cmbSpeed, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtValue, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(btnCreate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtBarrier, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnBarries, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(btnAllBarriers, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnRevert, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnInterrupt, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cbxImages)
.addComponent(btnSimulation, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblSpeed2, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblSpeed1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblSpeed3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap(37, Short.MAX_VALUE))
.addComponent(jSeparator2)
.addComponent(trackView1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(trackView1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 9, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmbSpeed, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(txtValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtBarrier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(btnRevert)
.addComponent(btnBarries))
.addComponent(cbxImages, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnCreate)
.addComponent(btnInterrupt)
.addComponent(btnSimulation)
.addComponent(btnAllBarriers)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(lblSpeed1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(lblSpeed2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(lblSpeed3))))
.addGap(11, 11, 11))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jbtBarrierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtBarrierActionPerformed
}//GEN-LAST:event_jbtBarrierActionPerformed
private void cbxImagesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxImagesActionPerformed
checkStatus = !checkStatus;
controller.setShowImages(checkStatus);
controller.changeImageStatus(checkStatus);
}//GEN-LAST:event_cbxImagesActionPerformed
private void txtValueActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtValueActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtValueActionPerformed
private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateActionPerformed
controller.createThreads(Integer.parseInt(this.txtValue.getText()), cmbSpeed.getSelectedIndex()+1);
txtValue.setText("");
}//GEN-LAST:event_btnCreateActionPerformed
private void btnInterruptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInterruptActionPerformed
if(interruptStatus){
btnInterrupt.setText("Continue");
}else{
btnInterrupt.setText("Interrupt");
}
interruptStatus = !interruptStatus;
controller.stateThread();
}//GEN-LAST:event_btnInterruptActionPerformed
private void btnRevertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRevertActionPerformed
controller.revert();
}//GEN-LAST:event_btnRevertActionPerformed
private void btnSimulationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSimulationActionPerformed
simulate = !simulate;
if(simulate){
simulator.resume();
btnSimulation.setText("Stop");
}else{
simulator.suspend();
btnSimulation.setText("Simulate");
}
}//GEN-LAST:event_btnSimulationActionPerformed
private void btnBarriesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBarriesActionPerformed
String barriers = txtBarrier.getText();
if(barriers.equals("")){
controller.getTrack().activateAllBarriers();
}else{
String barrierList[] = barriers.split(",");
for(int i = 0; i < barrierList.length; i++){
int lane = Integer.parseInt(barrierList[i]);
controller.getTrack().activateBarrier(lane-1);
}
}
txtBarrier.setText("");
}//GEN-LAST:event_btnBarriesActionPerformed
private void btnAllBarriersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAllBarriersActionPerformed
controller.getTrack().deactivateAllBarriers();
}//GEN-LAST:event_btnAllBarriersActionPerformed
/**
* @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(GraphicInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GraphicInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GraphicInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GraphicInterface.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 GraphicInterface().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAllBarriers;
private javax.swing.JButton btnBarries;
private javax.swing.JButton btnCreate;
private javax.swing.JButton btnInterrupt;
private javax.swing.JButton btnRevert;
private javax.swing.JButton btnSimulation;
private javax.swing.JCheckBox cbxImages;
private javax.swing.JComboBox<String> cmbSpeed;
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.JSeparator jSeparator2;
private javax.swing.JLabel lblSpeed1;
private javax.swing.JLabel lblSpeed2;
private javax.swing.JLabel lblSpeed3;
private view.TrackView trackView1;
private javax.swing.JTextField txtBarrier;
private javax.swing.JTextField txtValue;
// End of variables declaration//GEN-END:variables
}
| true |
f01af10580c8ddb82d3647e2ef58dafe5d6dadf5 | Java | cckmit/itss | /tags/06_Office_release_20110726/src/com/xpsoft/oa/model/system/FunUrl.java | UTF-8 | 3,361 | 2.09375 | 2 | [] | no_license | /* */ package com.xpsoft.oa.model.system;
/* */
/* */ import com.xpsoft.core.model.BaseModel;
/* */ import org.apache.commons.lang.builder.EqualsBuilder;
/* */ import org.apache.commons.lang.builder.HashCodeBuilder;
/* */ import org.apache.commons.lang.builder.ToStringBuilder;
/* */
/* */ public class FunUrl extends BaseModel
/* */ {
/* */ protected Long urlId;
/* */ protected String urlPath;
/* */ protected AppFunction appFunction;
/* */
/* */ public FunUrl()
/* */ {
/* */ }
/* */
/* */ public FunUrl(String urlPath)
/* */ {
/* 33 */ this.urlPath = urlPath;
/* */ }
/* */
/* */ public FunUrl(Long in_urlId)
/* */ {
/* 42 */ setUrlId(in_urlId);
/* */ }
/* */
/* */ public AppFunction getAppFunction()
/* */ {
/* 47 */ return this.appFunction;
/* */ }
/* */
/* */ public void setAppFunction(AppFunction in_appFunction) {
/* 51 */ this.appFunction = in_appFunction;
/* */ }
/* */
/* */ public Long getUrlId()
/* */ {
/* 60 */ return this.urlId;
/* */ }
/* */
/* */ public void setUrlId(Long aValue)
/* */ {
/* 67 */ this.urlId = aValue;
/* */ }
/* */
/* */ public Long getFunctionId()
/* */ {
/* 74 */ return getAppFunction() == null ? null : getAppFunction().getFunctionId();
/* */ }
/* */
/* */ public void setFunctionId(Long aValue)
/* */ {
/* 81 */ if (aValue == null) {
/* 82 */ this.appFunction = null;
/* 83 */ } else if (this.appFunction == null) {
/* 84 */ this.appFunction = new AppFunction(aValue);
/* 85 */ this.appFunction.setVersion(new Integer(0));
/* */ } else {
/* 87 */ this.appFunction.setFunctionId(aValue);
/* */ }
/* */ }
/* */
/* */ public String getUrlPath()
/* */ {
/* 96 */ return this.urlPath;
/* */ }
/* */
/* */ public void setUrlPath(String aValue)
/* */ {
/* 104 */ this.urlPath = aValue;
/* */ }
/* */
/* */ public boolean equals(Object object)
/* */ {
/* 111 */ if (!(object instanceof FunUrl)) {
/* 112 */ return false;
/* */ }
/* 114 */ FunUrl rhs = (FunUrl)object;
/* 115 */ return new EqualsBuilder()
/* 116 */ .append(this.urlId, rhs.urlId)
/* 117 */ .append(this.urlPath, rhs.urlPath)
/* 118 */ .isEquals();
/* */ }
/* */
/* */ public int hashCode()
/* */ {
/* 125 */ return new HashCodeBuilder(-82280557, -700257973)
/* 126 */ .append(this.urlId)
/* 127 */ .append(this.urlPath)
/* 128 */ .toHashCode();
/* */ }
/* */
/* */ public String toString()
/* */ {
/* 135 */ return new ToStringBuilder(this)
/* 136 */ .append("urlId", this.urlId)
/* 137 */ .append("urlPath", this.urlPath)
/* 138 */ .toString();
/* */ }
/* */ }
/* Location: C:\Users\Jack\Downloads\oa\joffice131Tomcat6\joffice131Tomcat6\tomcat6-joffice\webapps\joffice1.3.1\WEB-INF\classes\
* Qualified Name: com.xpsoft.oa.model.system.FunUrl
* JD-Core Version: 0.6.0
*/ | true |
7fec830203fbc841286bf4fcd771ce316439327d | Java | colinrobertson0911/soloproject | /src/main/java/com/fdmgroup/soloProject_Colin_OneDay/service/ItemService.java | UTF-8 | 617 | 2.0625 | 2 | [] | no_license | package com.fdmgroup.soloProject_Colin_OneDay.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fdmgroup.soloProject_Colin_OneDay.model.Item;
import com.fdmgroup.soloProject_Colin_OneDay.repository.ItemDao;
@Service
public class ItemService {
@Autowired
ItemDao itemDao;
public List<Item> findAll() {
return itemDao.findAll();
}
public void save(Item item) {
itemDao.save(item);
}
public Optional<Item> findById(long itemId) {
return itemDao.findById(itemId);
}
}
| true |
727938bca8c18f4b2f52b6323145ec485d02b426 | Java | bgould/thriftee | /libthrift-ext/src/main/java/org/thriftee/thrift/schema/SchemaReference.java | UTF-8 | 3,182 | 2 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2013-2016 Benjamin Gould, and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thriftee.thrift.schema;
import java.io.Serializable;
public final class SchemaReference implements Serializable {
private static final long serialVersionUID = 335224512770544907L;
private final SchemaReference.Type referenceType;
private final String moduleName;
private final String typeName;
public static SchemaReference referTo(
final SchemaReference.Type referenceType,
final String moduleName,
final String typeName) {
return new SchemaReference(referenceType, moduleName, typeName);
}
protected SchemaReference(
final SchemaReference.Type referenceType,
final String moduleName,
final String typeName) {
super();
this.referenceType = referenceType;
this.moduleName = moduleName;
this.typeName = typeName;
}
public String getModuleName() {
return this.moduleName;
}
public String getTypeName() {
return this.typeName;
}
public SchemaReference.Type getReferenceType() {
return referenceType;
}
public static enum Type {
EXCEPTION,
TYPEDEF,
STRUCT,
UNION,
ENUM,
;
}
@Override
public String toString() {
return "SchemaReference ["
+ "referenceType=" + referenceType + ", "
+ "moduleName=" + moduleName + ", "
+ "typeName=" + typeName + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime*result+((moduleName == null)?0:moduleName.hashCode());
result = prime*result+((referenceType == null)?0:referenceType.hashCode());
result = prime*result+((typeName == null)?0:typeName.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;
SchemaReference other = (SchemaReference) obj;
if (moduleName == null) {
if (other.moduleName != null)
return false;
} else if (!moduleName.equals(other.moduleName))
return false;
if (referenceType != other.referenceType)
return false;
if (typeName == null) {
if (other.typeName != null)
return false;
} else if (!typeName.equals(other.typeName))
return false;
return true;
}
public String toNamespacedIDL(String namespace) {
if (namespace != null && getModuleName() != null &&
namespace.equals(getModuleName())) {
return getTypeName();
} else {
return getModuleName() + "." + getTypeName();
}
}
}
| true |
0d297ad1d7d003ea09a89c87ec1492a2d0ab879d | Java | patelkarishma10/Garage | /src/Model/Vehicle.java | UTF-8 | 679 | 3.40625 | 3 | [] | no_license | package Model;
public abstract class Vehicle {
private String colour;
private String make;
private String model;
public Vehicle(String colour, String make, String model) {
this.colour = colour;
this.make = make;
this.model = model;
}
public String getColour() {
return colour;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public void setColour(String colour) {
this.colour = colour;
}
public void setMake(String make) {
this.make = make;
}
public void setModel(String model) {
this.model = model;
}
@Override
public String toString() {
return " " + colour + " " + make + " " + model;
}
}
| true |
29ca78332451f42b41b573efa19795ebf8c43b10 | Java | yuanqian-usf/CDATMController | /java/cdatm/src/test/java/com/circulardollar/cdatm/business/upstream/model/account/AccountRecordTest.java | UTF-8 | 2,507 | 2.40625 | 2 | [
"MIT"
] | permissive | package com.circulardollar.cdatm.business.upstream.model.account;
import static com.circulardollar.cdatm.TestBase.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.stream.IntStream;
import org.junit.Test;
public class AccountRecordTest {
@Test(expected = NullPointerException.class)
public void AccountRecord_not_null_whenExceptionThrown_thenExpectationSatisfied() {
AccountRecord.newBuilder().build();
}
@Test(expected = NullPointerException.class)
public void setAccountNumber_not_null_whenExceptionThrown_thenExpectationSatisfied() {
AccountRecord.newBuilder().setAccountNumber(null).build();
}
@Test(expected = NullPointerException.class)
public void setBalance_not_null_whenExceptionThrown_thenExpectationSatisfied() {
AccountRecord.newBuilder().setBalance(null).build();
}
@Test
public void getAccountNumber() {
IntStream.range(0, testAccountNumber.size())
.forEach(
index -> {
IAccountRecord account =
AccountRecord.newBuilder()
.setAccountNumber(testAccountNumber.get(index))
.setBalance(testBalance.get(index))
.build();
assertEquals(testAccountNumber.get(index), account.getAccountNumber());
});
}
@Test
public void getBalance() {
IntStream.range(0, testBalance.size())
.forEach(
index -> {
IAccountRecord account =
AccountRecord.newBuilder()
.setAccountNumber(testAccountNumber.get(index))
.setBalance(testBalance.get(index))
.build();
assertEquals(testBalance.get(index), account.getBalance());
});
}
@Test
public void newBuilder() {
IntStream.range(0, testBalance.size())
.forEach(
index -> {
IAccountRecord account =
AccountRecord.newBuilder()
.setAccountNumber(testAccountNumber.get(index))
.setBalance(testBalance.get(index))
.build();
assertEquals(testBalance.get(index), account.getBalance());
});
}
@Test
public void testToString() {
assertNotNull(
AccountRecord.newBuilder()
.setAccountNumber(randomString()).setBalance(randomInt())
.build().toString());
}
}
| true |
fa738235541c3c2c0c981c3854fd81fbba8a20b3 | Java | sweetca/oscar-controller | /src/main/java/com/oscar/controller/model/component/ComponentNvd.java | UTF-8 | 526 | 1.804688 | 2 | [
"MIT"
] | permissive | package com.oscar.controller.model.component;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Data
@Document
public class ComponentNvd {
Map<String, Set<String>> nvdMap = new HashMap<>();
@Id
private String id;
@Indexed
private String component;
@Indexed
private String version;
}
| true |
202ed825dcedad9f19d57e7bc285619c4e23639f | Java | kartheektrilochan/testprjct | /test-project/src/com/test/entity/UserRole.java | UTF-8 | 2,255 | 1.929688 | 2 | [] | no_license | package com.test.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
/**
* The persistent class for the USER_ROLES database table.
*
*/
@Entity
@Table(name="USER_ROLES")
@NamedQuery(name="UserRole.findAll", query="SELECT u FROM UserRole u")
public class UserRole implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private String id;
private Object createddate;
private String emailid;
private BigDecimal failurecounts;
private String isactive;
private Object lastlogin;
private Object lastupdated;
private String password;
@Column(name="\"ROLE\"")
private String role;
private String username;
public UserRole() {
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public Object getCreateddate() {
return this.createddate;
}
public void setCreateddate(Object createddate) {
this.createddate = createddate;
}
public String getEmailid() {
return this.emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public BigDecimal getFailurecounts() {
return this.failurecounts;
}
public void setFailurecounts(BigDecimal failurecounts) {
this.failurecounts = failurecounts;
}
public String getIsactive() {
return this.isactive;
}
public void setIsactive(String isactive) {
this.isactive = isactive;
}
public Object getLastlogin() {
return this.lastlogin;
}
public void setLastlogin(Object lastlogin) {
this.lastlogin = lastlogin;
}
public Object getLastupdated() {
return this.lastupdated;
}
public void setLastupdated(Object lastupdated) {
this.lastupdated = lastupdated;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return this.role;
}
public void setRole(String role) {
this.role = role;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
} | true |
04e7a88692d898deb33417e3f7e4f1143b611bf1 | Java | BrunaLauton/ProjetoAM_Dot | /src/br/dot/form/FormLogin.java | UTF-8 | 16,391 | 2.078125 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.dot.form;
import br.dot.dao.LoginDAO;
import br.dot.modelo.Login;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
public class FormLogin extends javax.swing.JFrame {
/**
* Creates new form formLogin
*/
public FormLogin() {
initComponents();
setLocationRelativeTo(null);
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtLogin = new javax.swing.JTextField();
txtSenha = new javax.swing.JPasswordField();
btnConectar = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
btnFinalizar = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
btnExit = new javax.swing.JButton();
btnConectar1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("Portal do Cliente");
setResizable(false);
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
jLabel2.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
jLabel2.setText("Login");
jLabel3.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
jLabel3.setText("Senha");
txtLogin.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
txtLogin.setToolTipText("");
txtLogin.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
txtLoginFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
txtLoginFocusLost(evt);
}
});
txtLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtLoginActionPerformed(evt);
}
});
txtSenha.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
txtSenha.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtSenhaActionPerformed(evt);
}
});
txtSenha.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txtSenhaKeyPressed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(34, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(15, Short.MAX_VALUE))
);
btnConectar.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
btnConectar.setText("Conectar");
btnConectar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnConectarActionPerformed(evt);
}
});
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/dotlogo.jpeg"))); // NOI18N
btnFinalizar.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
btnFinalizar.setText("Finalizar");
btnFinalizar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFinalizarActionPerformed(evt);
}
});
jPanel3.setBackground(new java.awt.Color(0, 0, 0));
jPanel3.setToolTipText("");
btnExit.setBackground(new java.awt.Color(0, 0, 0));
btnExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/exit.png"))); // NOI18N
btnExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnExitActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnExit, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(btnExit, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
btnConectar1.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
btnConectar1.setText("É novo? Crie seu login já!");
btnConectar1.setContentAreaFilled(false);
btnConectar1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnConectar1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(btnConectar1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(btnConectar)
.addGap(40, 40, 40)
.addComponent(btnFinalizar))
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel3, 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(0, 19, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btnConectar)
.addComponent(btnFinalizar)))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnConectar1)
.addGap(7, 7, 7)))
.addContainerGap())
);
getAccessibleContext().setAccessibleName("");
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnFinalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFinalizarActionPerformed
int resposta = JOptionPane.showConfirmDialog(this, "Tem certeza que deseja finalizar o programa?");
if(resposta == JOptionPane.YES_OPTION) {
LoginDAO login = new LoginDAO();
login.updateLoginOFF();
System.exit(0);
}
}//GEN-LAST:event_btnFinalizarActionPerformed
private void txtLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtLoginActionPerformed
}//GEN-LAST:event_txtLoginActionPerformed
private void btnConectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConectarActionPerformed
Conectar();
}//GEN-LAST:event_btnConectarActionPerformed
private void txtSenhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSenhaKeyPressed
if(evt.getKeyCode() == KeyEvent.VK_ENTER){
Conectar();
}
}//GEN-LAST:event_txtSenhaKeyPressed
private void txtLoginFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtLoginFocusLost
Focus();
if(Focus() == true){
}
else {
JOptionPane.showMessageDialog(this, "Login invalido");
// txtLogin.grabFocus();
txtLogin.setText("");
}
}//GEN-LAST:event_txtLoginFocusLost
private void txtSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSenhaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtSenhaActionPerformed
private void txtLoginFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtLoginFocusGained
}//GEN-LAST:event_txtLoginFocusGained
private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
int resposta = JOptionPane.showConfirmDialog(this, "Tem certeza que deseja fechar e sair do programa?");
if(resposta == JOptionPane.YES_OPTION) {
LoginDAO login = new LoginDAO();
login.updateLoginOFF();
System.exit(0);
}
}//GEN-LAST:event_btnExitActionPerformed
private void btnConectar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConectar1ActionPerformed
FormCadastrarLogin fl = new FormCadastrarLogin();
dispose();
fl.setVisible(true);
}//GEN-LAST:event_btnConectar1ActionPerformed
private boolean Focus(){
boolean b = true; //retirar este true depois
String login = txtLogin.getText();
//Usuario usuario = new Usuario(login);
//UsuarioDAO dao = new UsuarioDAO();
/* if(dao.pesquisarLogin(usuario)){
b = true;
}
else{
b = false;
} */
return b;
}
private void Conectar() {
String login = txtLogin.getText();
String senha = new String(txtSenha.getPassword());
if (login.equals("") || senha.equals("")) {
JOptionPane.showMessageDialog(this, "Os campos precisam ser preenchidos!");
} else {
Login usuario = new Login(0, login, senha, "S");
LoginDAO dao = new LoginDAO();
if (dao.logarSistema(usuario)) {
FormMenu fmenu = new FormMenu();
dispose();
fmenu.setVisible(true);
} else {
JOptionPane.showMessageDialog(this, "Usuário ou senha incorretos!");
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
try {
// select Look and Feel
//UIManager.setLookAndFeel("com.jtattoo.plaf.acryl.AcrylLookAndFeel");
//UIManager.setLookAndFeel("com.jtattoo.plaf.aero.AeroLookAndFeel");
//UIManager.setLookAndFeel("com.jtattoo.plaf.bernstein.BernsteinLookAndFeel");
//UIManager.setLookAndFeel("com.jtattoo.plaf.hifi.HiFiLookAndFeel");
UIManager.setLookAndFeel("com.jtattoo.plaf.mcwin.McWinLookAndFeel");
//UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel");
// start application
} catch (Exception ex) {
ex.printStackTrace();
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FormLogin().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnConectar;
private javax.swing.JButton btnConectar1;
private javax.swing.JButton btnExit;
private javax.swing.JButton btnFinalizar;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel3;
private javax.swing.JTextField txtLogin;
private javax.swing.JPasswordField txtSenha;
// End of variables declaration//GEN-END:variables
}
| true |
c405bdc952986a9ef8f327ea155cf70de41d8451 | Java | Kadphol/basic-java-test | /Potter/src/test/java/com/example/potter/book/BookServiceTest.java | UTF-8 | 2,609 | 2.921875 | 3 | [] | no_license | package com.example.potter.book;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Arrays;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class BookServiceTest {
@Mock
private BookRepository repository;
@Test
public void foundBookID01() throws BookNotFoundException {
Book mock = new Book(1,"Harry Potter and Philosopher's Stone",100,100);
when(repository.findById(1)).thenReturn(
Optional.of(mock)
);
BookService service = new BookService();
service.setRepository(repository);
BookResponse result = service.getBook(1);
assertEquals(1, result.getId());
assertEquals("Harry Potter and Philosopher's Stone", result.getTitle());
assertEquals(100, result.getPrice());
assertEquals(100, result.getStock());
}
@Test
public void BookNotFound() {
when(repository.findById(100)).thenReturn(
Optional.empty()
);
BookService service = new BookService();
service.setRepository(repository);
BookNotFoundException exception = assertThrows(BookNotFoundException.class, () -> service.getBook(100));
assertEquals("Book id 100 NOT FOUND!",exception.getMessage());
}
@Test
public void discountTest() {
BookService service = new BookService();
assertEquals(0, service.discount(0));
assertEquals(100, service.discount(1));
assertEquals(190, service.discount(2));
assertEquals(270, service.discount(3));
assertEquals(320, service.discount(4));
assertEquals(375, service.discount(5));
}
@Test
public void testBasicPrice() {
BookService service = new BookService();
assertEquals(100, service.calculatePrice(Arrays.asList(1)));
assertEquals(100*2, service.calculatePrice(Arrays.asList(1,1)));
assertEquals(100*3, service.calculatePrice(Arrays.asList(1,1,1)));
}
@Test
public void testBasicDiscountPrice() {
BookService service = new BookService();
assertEquals(100*2*0.95, service.calculatePrice(Arrays.asList(1,2)));
assertEquals(100*3*0.9, service.calculatePrice(Arrays.asList(1,2,3)));
assertEquals(100*4*0.8, service.calculatePrice(Arrays.asList(1,2,3,4)));
assertEquals(100*5*0.75, service.calculatePrice(Arrays.asList(1,2,3,4,5)));
}
} | true |
617b0a766cc71ba2d79fd7ac8f0bd9980c15f786 | Java | cwenlu/NestedScrolling | /app/src/main/java/com/cwl/nestedscrolling/TestView.java | UTF-8 | 1,607 | 2.5625 | 3 | [] | no_license | package com.cwl.nestedscrolling;
import android.content.Context;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by Administrator on 2017/3/1 0001.
*/
public class TestView extends View {
public TestView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
final int action = event.getAction();
int pointerCount = event.getPointerCount();
switch (action){
case MotionEvent.ACTION_DOWN:
scrollTo(50,50);
System.out.println(event.getX()+"--self--"+event.getY());
System.out.println(event.getRawX()+"--screen--"+event.getRawY());
System.out.println("trans---"+getTranslationX()+","+getTranslationY());
break;
case MotionEvent.ACTION_MOVE:
setTranslationX(5f+getTranslationX());
setTranslationY(-5f+getTranslationY());
break;
case MotionEvent.ACTION_UP:
System.out.println(getX()+"-x/y-"+getY());
System.out.println(getScrollX()+"--scroll--"+getScrollY());
break;
}
return true;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
//getLeft,....
System.out.println(left+","+top+","+right+","+bottom);
}
}
| true |
10067d2854ad5cc04450b584c827f7bdffd34fa7 | Java | ItaloChagas/EAD | /06-DesignPatterns/src/br/com/fiap/jpa/test/CalculadoraTest.java | UTF-8 | 321 | 2.21875 | 2 | [] | no_license | package br.com.fiap.jpa.test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import br.com.fiap.jpa.util.Calculadora;
class CalculadoraTest {
@Test
void somarTest() {
Calculadora calc = new Calculadora();
int soma = calc.somar(3, 5);
assertEquals(8, soma);
}
}
| true |
e9bef0f4653323e40aae0bf639e1f289355944a0 | Java | taylorkelly/ResponseSystem | /src/response/client/gui/MainPanel.java | UTF-8 | 2,591 | 2.734375 | 3 | [] | no_license | package response.client.gui;
import java.awt.Dimension;
import java.net.InetAddress;
import java.util.*;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import response.client.packets.*;
import response.shared.QuestionType;
/**
*
* @author taylor
*/
public class MainPanel extends JPanel {
private static WaitingPanel waiting;
private QuestionPanel qPanel = null;
private InetAddress address;
private int port;
public MainPanel(InetAddress address, int port) {
this.address = address;
this.port = port;
waiting = new WaitingPanel();
this.add(waiting);
requestQuestion();
}
private void requestQuestion() {
Timer timer = new Timer();
timer.schedule(new RequestTask(this, address, port), 100);
}
public void setAnswer(String answer) {
String response = new QuestionResponsePacket(answer, address, port).sendAndWaitForResponse(1000);
if (response != null && response.equals("1")) {
qPanel.reportSuccess();
} else {
JOptionPane.showMessageDialog(null,
"Error sending answer to server.",
"Invalid Response",
JOptionPane.ERROR_MESSAGE);
}
}
private class RequestTask extends TimerTask {
private JPanel panel;
private InetAddress address;
private int port;
public RequestTask(JPanel panel, InetAddress address, int port) {
this.panel = panel;
this.address = address;
this.port = port;
}
@Override
public void run() {
String response = new QuestionRequestPacket(address, port).sendAndWaitForResponse(-1);
if (response != null && !response.equals("0")) {
QuestionType type = QuestionType.valueOf(response);
remove(waiting);
switch (type) {
case MULTI_CHOICE:
qPanel = new MultiChoicePanel(MainPanel.this);
add(qPanel);
revalidate();
repaint();
break;
}
String answer = new AnswerRequestPacket(address, port).sendAndWaitForResponse(-1);
} else {
JOptionPane.showMessageDialog(null,
"Invalid Response for Question Type",
"Invalid Response",
JOptionPane.ERROR_MESSAGE);
}
this.cancel();
}
}
}
| true |
6612513cef2fd8127dd9a295259a7ecbec092378 | Java | Prabhat789/PhysicalWeb-12121454121456325125 | /app/src/main/java/com/pktworld/physicalweb/util/ApplicationConstant.java | UTF-8 | 457 | 1.65625 | 2 | [] | no_license | package com.pktworld.physicalweb.util;
/**
* Created by ubuntu1 on 4/5/16.
*/
public class ApplicationConstant {
public static final String BLE_URL_BROADCAST = "ble_url";
public static final String BLE_DATA = "ble_data";
public static final String APPLICATION_PREFERENCE_NAME = "com.pktworld.physicalweb.sharePref";
public static final String INTERVAL_MINUTE_BLE = "intervalInMinutesBle";
public static final String DATA = "data";
}
| true |
b9785f51ee5e5d4cb8e8b65feccc8185e0ac0f29 | Java | launchfirst2020/xxpay4new | /xxpay-merchant/src/main/java/org/xxpay/mch/order/ctrl/MemberPayController.java | UTF-8 | 34,010 | 1.984375 | 2 | [] | no_license | package org.xxpay.mch.order.ctrl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.core.common.Exception.ServiceException;
import org.xxpay.core.common.constant.*;
import org.xxpay.core.common.domain.BizResponse;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.util.*;
import org.xxpay.core.entity.*;
import org.xxpay.mch.common.ctrl.BaseController;
import org.xxpay.mch.common.service.RpcCommonService;
import java.util.Date;
/** 会员支付相关接口 */
@RestController
@RequestMapping(Constant.MCH_CONTROLLER_ROOT_PATH + "/memberPay")
public class MemberPayController extends BaseController {
private static final MyLog _log = MyLog.getLog(MemberPayController.class);
@Autowired
private RpcCommonService rpc;
@Autowired
private StringRedisTemplate stringRedisTemplate;
/** 收款(商扫客) **/
@RequestMapping("/bar")
public ResponseEntity<?> bar() {
//[1.] 获取当前登录用户的基本信息
Long mchId = getUser().getBelongInfoId(); //获取mchId
MchInfo currentMchInfo = rpc.rpcMchInfoService.findByMchId(mchId);
//[2.] 获取请求参数并验证参数是否合法
Long requiredAmount = getRequiredAmountL("requiredAmount"); //应付金额
Long realAmount = getRequiredAmountL("realAmount"); //实付金额
String barCode = getValStringRequired("barCode").trim(); //条码
String isvDeviceNo = getUser().getLoginDeviceNo(); //服务商设备编号
//是否押金模式
Byte depositMode = "1".equals(getValString("isDepositMode")) ? MchConstant.PUB_YES : MchConstant.PUB_NO;
boolean isDepositMode = depositMode == MchConstant.PUB_YES;
//金额是否合法
if(requiredAmount <= 0 || realAmount <= 0) throw ServiceException.build(RetEnum.RET_COMM_PARAM_ERROR);
//实付金额 > 应付金额
if(realAmount > requiredAmount) throw ServiceException.build(RetEnum.RET_MCH_REAL_AMOUNT_GT_REQUIRED);
//获取支付产品,并校验barCode是否可用
int productId = XXPayUtil.getProductIdByBarCode(barCode);
Byte tradeProductType = XXPayUtil.getTradeProductTypeByProductId(productId); //mchTradeOrder中的 productType
//押金模式
if(isDepositMode){
//不允许使用优惠金额
if(!realAmount.equals(requiredAmount)){
throw ServiceException.build(RetEnum.RET_MCH_ORDER_DEPOSIT_ORDER_AMOUNT_ERROR);
}
//商户是否开通了押金支付
if(currentMchInfo.getDepositModeStatus() != MchConstant.PUB_YES){
throw ServiceException.build(RetEnum.RET_MCH_DEPOSIT_STATUS_ERROR);
}
//产品是否被支持
if(productId != PayConstant.PAY_PRODUCT_WX_BAR && productId != PayConstant.PAY_PRODUCT_ALIPAY_BAR){
throw ServiceException.build(RetEnum.RET_MCH_DEPOSIT_PRODUCT_ERROR);
}
}
//[3.] 创建交易订单
String ipInfo = IPUtility.getClientIp(request);
MchTradeOrder addMchTradeOrder = rpc.rpcMchTradeOrderService.insertTradeOrderJWT(
currentMchInfo, MchConstant.TRADE_TYPE_PAY, requiredAmount, realAmount, tradeProductType, productId, ipInfo,
(mchTradeOrder) -> {
mchTradeOrder.setUserId(barCode); //用户ID
mchTradeOrder.setIsvDeviceNo(isvDeviceNo); //服务商设备编号
mchTradeOrder.setDepositMode(depositMode); //是否押金模式
//押金模式
if(isDepositMode){
mchTradeOrder.setOrderAmount(0L);
mchTradeOrder.setAmount(0L);
mchTradeOrder.setDiscountAmount(0L);
mchTradeOrder.setDepositAmount(realAmount);
}
});
//入库失败
if (addMchTradeOrder == null) throw ServiceException.build(RetEnum.RET_MCH_CREATE_TRADE_ORDER_FAIL);
//tradeOrderId
String tradeOrderId = addMchTradeOrder.getTradeOrderId();
//[4.] 调起 [支付网关] 接口
JSONObject retMsg = rpc.rpcMchTradeOrderService.callPayInterface(addMchTradeOrder, currentMchInfo, mainConfig.getPayUrl(), mainConfig.getNotifyUrl());
if(retMsg == null) { //支付网关返回结果验证失败
rpc.rpcMchTradeOrderService.updateStatus4Fail(tradeOrderId);
return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_CREATE_TRADE_ORDER_FAIL));
}
//无论接口返回确认成功状态,还是支付中,所有支付成功逻辑均在回调函数中实现。
String channelOrderStatus = retMsg.getString("orderStatus"); //支付网关 返回的订单状态, 1-支付中 2-支付成功
String channelPayOrderId = retMsg.getString("payOrderId"); //支付网关返回的支付订单号, 用于记录更新
//[6.] 更新订单号
MchTradeOrder updateRecord = new MchTradeOrder();
//如果押金模式 && 押金未结算状态下
if(isDepositMode && Byte.parseByte(channelOrderStatus) == PayConstant.PAY_STATUS_DEPOSIT_ING){
updateRecord.setStatus(MchConstant.TRADE_ORDER_STATUS_DEPOSIT_ING);
}
updateRecord.setTradeOrderId(tradeOrderId);
updateRecord.setPayOrderId(channelPayOrderId);
rpc.rpcMchTradeOrderService.updateById(updateRecord);
//[7.] 返回交易订单号 & 状态
JSONObject result = new JSONObject();
result.put("tradeOrderId", tradeOrderId);
result.put("orderStatus", channelOrderStatus);
result.put("productType", tradeProductType);
result.put("amount", addMchTradeOrder.getAmount());
return ResponseEntity.ok(XxPayResponse.buildSuccess(result));
}
/** 现金收款 **/
@RequestMapping("/cash")
public ResponseEntity<?> cash() {
//[1.] 获取当前登录用户的基本信息
Long mchId = getUser().getBelongInfoId(); //获取mchId
MchInfo currentMchInfo = rpc.rpcMchInfoService.findByMchId(mchId);
//[2.] 获取请求参数并验证参数是否合法
Long requiredAmount = getRequiredAmountL("requiredAmount"); //应付金额
Long realAmount = getRequiredAmountL("realAmount"); //实付金额
//金额是否合法
if(requiredAmount <= 0 || realAmount <= 0) throw ServiceException.build(RetEnum.RET_COMM_PARAM_ERROR);
//实付金额 > 应付金额
if(realAmount > requiredAmount) throw ServiceException.build(RetEnum.RET_MCH_REAL_AMOUNT_GT_REQUIRED);
//[3.] 创建交易订单
String ipInfo = IPUtility.getClientIp(request);
MchTradeOrder addMchTradeOrder = rpc.rpcMchTradeOrderService.insertTradeOrderJWT(
currentMchInfo, MchConstant.TRADE_TYPE_PAY, requiredAmount, realAmount, MchConstant.MCH_TRADE_PRODUCT_TYPE_CASH, null, ipInfo,
(mchTradeOrder) -> {
mchTradeOrder.setSubject("消费|现金支付"); //商品标题
mchTradeOrder.setBody("消费|现金支付"); //商品描述信息
mchTradeOrder.setStatus(MchConstant.TRADE_ORDER_STATUS_SUCCESS); //订单状态, 默认成功
});
//入库失败
if (addMchTradeOrder == null) throw ServiceException.build(RetEnum.RET_MCH_CREATE_TRADE_ORDER_FAIL);
//[4.] 返回交易订单号 & 状态
JSONObject result = new JSONObject();
result.put("tradeOrderId", addMchTradeOrder.getTradeOrderId());
result.put("orderStatus", addMchTradeOrder.getStatus());
return ResponseEntity.ok(XxPayResponse.buildSuccess(result));
}
/** 会员卡消费 **/
@RequestMapping("/balance")
public ResponseEntity<?> balancePay() {
//[1.] 获取当前登录用户的基本信息
Long mchId = getUser().getBelongInfoId(); //获取mchId
MchInfo currentMchInfo = rpc.rpcMchInfoService.findByMchId(mchId);
//[2.] 获取请求参数并验证参数是否合法
Long requiredAmount = getRequiredAmountL("requiredAmount"); //应付金额
Long realAmount = getRequiredAmountL("realAmount"); //实付金额
String memberNo = getValString("memberNo"); //memberNo 与 memberPayCode 二选一, 以memberNo为准 (支持手机号查询)
String memberPayCode = getValString("memberPayCode"); //memberPayCode 与 memberNo 二选一, 以memberNo为准
String couponNo = getValString("couponNo"); //会员优惠券核销码
//金额是否合法
if(requiredAmount <= 0 || realAmount <= 0) throw ServiceException.build(RetEnum.RET_COMM_PARAM_ERROR);
//实付金额 > 应付金额
if(realAmount > requiredAmount) throw ServiceException.build(RetEnum.RET_MCH_REAL_AMOUNT_GT_REQUIRED);
if(StringUtils.isAllEmpty(memberNo, memberPayCode)){ //如果 参数不存在
throw new ServiceException(RetEnum.RET_COMM_PARAM_ERROR);
}
Member member ;
if(StringUtils.isNotEmpty(memberNo)){ //如果存在会员卡号
member = rpc.rpcMemberService.getOne(
new QueryWrapper<Member>().lambda()
.eq(Member::getMchId, mchId)
.and(i -> i.eq(Member::getMemberNo, memberNo).or().eq(Member::getTel, memberNo)) //支持手机号查询
);
}else{
String memberIdStr = stringRedisTemplate.opsForValue().get(MchConstant.CACHEKEY_TOKEN_PREFIX_MBR_CODE + memberPayCode);
if(StringUtils.isEmpty(memberIdStr)){
throw new ServiceException(RetEnum.RET_MCH_NOT_EXISTS_PAYCODE); //无法获取会员付款码
}
member = rpc.rpcMemberService.getById(Long.parseLong(memberIdStr));
}
if(member == null) throw new ServiceException(RetEnum.RET_MCH_NOT_EXISTS_PAYCODE); //无法获取会员付款码
Long memberId = member.getMemberId(); //会员ID
Long discountAmount = 0L; //优惠金额
Long mchCouponId = null;
if(StringUtils.isNotEmpty(couponNo)){ //选择了优惠券
MemberCoupon memberCoupon = rpc.rpcMemberCouponService.getOne(new QueryWrapper<MemberCoupon>()
.lambda().eq(MemberCoupon::getCouponNo, couponNo).eq(MemberCoupon::getMemberId, memberId));
//判断优惠券是否可用
if(memberCoupon == null || memberCoupon.getStatus() != MchConstant.PUB_NO){
throw ServiceException.build(RetEnum.RET_MCH_COUPON_STATUS_ERROR);
}
MchCoupon mchCoupon = rpc.rpcMchCouponService.getById(memberCoupon.getCouponId());
//检查优惠券是否 满足使用条件
if(rpc.rpcMemberCouponService.useCouponPreCheck(mchCoupon, realAmount, getUser().getStoreId()) != null){
throw ServiceException.build(RetEnum.RET_MBR_COUPON_NOT_EXISTS);
}
mchCouponId = mchCoupon.getCouponId();
discountAmount = mchCoupon.getCouponAmount();
}
if (!discountAmount.equals(requiredAmount - realAmount)){
throw ServiceException.build(RetEnum.RET_MCH_STORE_SPEAKER_CODE_ERROR);
}
final Long finalMchCouponId = mchCouponId;
//[3.] 创建交易订单
String ipInfo = IPUtility.getClientIp(request);
MchTradeOrder addMchTradeOrder = rpc.rpcMchTradeOrderService.insertTradeOrderJWT(
currentMchInfo, MchConstant.TRADE_TYPE_PAY, requiredAmount, realAmount, MchConstant.MCH_TRADE_PRODUCT_TYPE_MEMBER_CARD, null, ipInfo,
(mchTradeOrder) -> {
mchTradeOrder.setUserId(member.getMemberId() + ""); //会员ID
mchTradeOrder.setMemberId(member.getMemberId()); //会员ID
mchTradeOrder.setMemberTel(member.getTel()); //会员手机号
mchTradeOrder.setMchCouponId(finalMchCouponId); //优惠券ID
mchTradeOrder.setMemberCouponNo(couponNo); //会员优惠券核销码
});
//入库失败
if (addMchTradeOrder == null) throw ServiceException.build(RetEnum.RET_MCH_CREATE_TRADE_ORDER_FAIL);
//[4.] 更新会员账户信息数据 & 积分数据 & 优惠券
int updatRow = rpc.rpcMchTradeOrderService.updateSuccess4MemberBalance(addMchTradeOrder.getTradeOrderId(), member.getMemberId(), couponNo);
//[5.] 返回交易订单号 & 状态
JSONObject result = new JSONObject();
result.put("tradeOrderId", addMchTradeOrder.getTradeOrderId());
result.put("orderStatus", addMchTradeOrder.getStatus());
if(updatRow > 0){
result.put("orderStatus", MchConstant.TRADE_ORDER_STATUS_SUCCESS);
}
return ResponseEntity.ok(XxPayResponse.buildSuccess(result));
}
/** 商户查单接口 **/
@RequestMapping("/queryStatus")
public ResponseEntity<?> queryStatus() {
Long mchId = getUser().getBelongInfoId(); //获取mchId
String tradeOrderId = getValStringRequired("tradeOrderId"); //商户交易单号
MchTradeOrder mchTradeOrder = rpc.rpcMchTradeOrderService.findByMchIdAndTradeOrderId(mchId, tradeOrderId);
if(mchTradeOrder != null){
JSONObject result = new JSONObject();
result.put("tradeOrderId", tradeOrderId);
result.put("orderStatus", mchTradeOrder.getStatus());
result.put("productType", mchTradeOrder.getProductType());
result.put("amount", mchTradeOrder.getAmount());
return ResponseEntity.ok(XxPayResponse.buildSuccess(result));
}
return ResponseEntity.ok(XxPayResponse.buildSuccess());
}
/** 订单同步接口 */
@RequestMapping("/orderSync")
public ResponseEntity<?> orderSync() {
//[1.] 获取当前登录用户的基本信息
Long mchId = getUser().getBelongInfoId(); //获取mchId
MchInfo currentMchInfo = rpc.rpcMchInfoService.findByMchId(mchId);
//[2.] 获取请求参数并验证参数是否合法
String tradeOrderId = getValStringRequired("tradeOrderId"); //商户交易单号
MchTradeOrder mchTradeOrder = rpc.rpcMchTradeOrderService.findByMchIdAndTradeOrderId(mchId, tradeOrderId);
if(mchTradeOrder == null) return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_RECORD_NOT_EXIST));
// 订单状态不属于[支付中],无需同步; 仅支付中订单需要同步状态
if(mchTradeOrder.getStatus() != MchConstant.TRADE_ORDER_STATUS_ING){
return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_TRADE_NOT_NEED_SYNC));
}
//充值订单 无需同步
if(mchTradeOrder.getTradeType() != MchConstant.TRADE_TYPE_PAY){
return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_TRADE_NOT_NEED_SYNC));
}
//现金收款 || 会员卡支付订单, 无需同步
if (mchTradeOrder.getProductType() == null){
return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_TRADE_TYPE_NOT_NEED_SYNC));
}else if(mchTradeOrder.getProductType() == MchConstant.MCH_TRADE_PRODUCT_TYPE_CASH ||
mchTradeOrder.getProductType() == MchConstant.MCH_TRADE_PRODUCT_TYPE_MEMBER_CARD )
{
return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_TRADE_TYPE_NOT_NEED_SYNC));
}
JSONObject sendReqParam = new JSONObject(); //发送参数
sendReqParam.put("mchId", mchTradeOrder.getMchId()); //商户ID
sendReqParam.put("mchOrderNo", mchTradeOrder.getTradeOrderId()); // 商户交易单号
sendReqParam.put("sign", PayDigestUtil.getSign(sendReqParam, currentMchInfo.getPrivateKey())); // 签名
String reqData = "params=" + sendReqParam.toJSONString();
_log.info("xxpay_req:{}", reqData);
String url = mainConfig.getPayUrl() + "/pay/query_order?";
String retResult = XXPayUtil.call4Post(url + reqData);
_log.info("xxpay_res:{}", retResult);
JSONObject retResultJSON = JSON.parseObject(retResult);
String iSign = PayDigestUtil.getSign(retResultJSON, currentMchInfo.getPrivateKey(), "sign");
//[5.] 验签
if(!iSign.equals(retResultJSON.getString("sign"))) { //验签失败
_log.error("验签失败 iSign={}, sign={}", iSign, retResultJSON.getString("sign"));
return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
}
Byte channelOrderStatus = retResultJSON.getByte("status"); //支付网关 返回的订单状态, 1-支付中 2-支付成功
if(channelOrderStatus == PayConstant.PAY_STATUS_SUCCESS){ //上游订单支付状态为成功
//TODO 需要与支付回调接口 处理业务逻辑相同!
if(MchConstant.TRADE_TYPE_PAY == mchTradeOrder.getTradeType()
&& "8020".equals(mchTradeOrder.getProductId())){ //交易类型为收款 ,且产品ID为8020表示微信被扫支付, 需要判断会员逻辑;
JSONObject openIdJSON = (JSONObject) JSON.parse(retResultJSON.get("channelAttach").toString());
rpc.rpcMchTradeOrderService.updateSuccess4Member(tradeOrderId, retResultJSON.getString("payOrderId"), mchTradeOrder.getMchIncome(),openIdJSON.getString("openId"));
}else{ //保持原有逻辑不变
rpc.rpcMchTradeOrderService.updateStatus4Success(tradeOrderId, retResultJSON.getString("payOrderId"), mchTradeOrder.getMchIncome(), 0L);
}
}else if(channelOrderStatus == PayConstant.PAY_STATUS_FAILED){ //上游返回支付订单状态为失败
rpc.rpcMchTradeOrderService.updateStatus4Fail(tradeOrderId);
}
JSONObject result = new JSONObject();
result.put("tradeOrderId", tradeOrderId);
result.put("channelOrderStatus", channelOrderStatus);
return ResponseEntity.ok(XxPayResponse.buildSuccess(result));
}
/** 会员充值接口*/
@RequestMapping("/recharge")
public ResponseEntity<?> recharge() {
//[1.] 获取当前登录用户的基本信息
Long mchId = getUser().getBelongInfoId();
MchInfo currentMchInfo = rpc.rpcMchInfoService.findByMchId(mchId);
//[2.] 获取请求参数并验证参数是否合法
Long memberId = getValLongRequired( "memberId"); //会员ID
Long ruleId = getValLong( "ruleId"); //充值规则
String amountStr = getValStringRequired("amount"); //充值金额
Long amount = Long.parseLong(AmountUtil.convertDollar2Cent(amountStr));
String barCode = getValStringRequired( "barCode"); //条码
if (ruleId != null) {
MchMemberRechargeRule rule = rpc.rpcMchMemberRechargeRuleService.getById(ruleId);
amount = rule.getRechargeAmount();
}
//金额有误
if(amount <= 0) return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_PARAM_ERROR));
//获取支付产品,并校验barCode是否可用
int productId = XXPayUtil.getProductIdByBarCode(barCode);
Byte tradeProductType = XXPayUtil.getTradeProductTypeByProductId(productId); //mchTradeOrder中的 productType
Member member = rpc.rpcMemberService.getOne(new QueryWrapper<Member>().lambda().eq(Member::getMchId, mchId).eq(Member::getMemberId, memberId));
if(member == null) throw new ServiceException(RetEnum.RET_MCH_NOT_EXISTS_PAYCODE); //没有该会员
//TODO 如果充值赠优惠券,需验证优惠券是否可领取
String ipInfo = IPUtility.getClientIp(request);
MchTradeOrder addMchTradeOrder = rpc.rpcMchTradeOrderService.insertTradeOrderJWT(
currentMchInfo, MchConstant.TRADE_TYPE_RECHARGE, amount, amount, tradeProductType, productId, ipInfo, (mchTradeOrder -> {
mchTradeOrder.setMemberId(memberId);//会员ID
mchTradeOrder.setMemberTel(member.getTel());//会员手机号
mchTradeOrder.setRuleId(ruleId);//会员充值规则ID
mchTradeOrder.setUserId(barCode); //用户ID
}));
//入库失败
if (addMchTradeOrder == null) throw ServiceException.build(RetEnum.RET_MCH_CREATE_TRADE_ORDER_FAIL);
//tradeOrderId
String tradeOrderId = addMchTradeOrder.getTradeOrderId();
//[4.] 调起 [支付网关] 接口
JSONObject retMsg = rpc.rpcMchTradeOrderService.callPayInterface(addMchTradeOrder, currentMchInfo, mainConfig.getPayUrl(), mainConfig.getNotifyUrl());
if(retMsg == null) { //支付网关返回结果验证失败
rpc.rpcMchTradeOrderService.updateStatus4Fail(tradeOrderId);
return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_CREATE_TRADE_ORDER_FAIL));
}
//无论接口返回确认成功状态,还是支付中,所有支付成功逻辑均在回调函数中实现。
String channelOrderStatus = retMsg.getString("orderStatus"); //支付网关 返回的订单状态, 1-支付中 2-支付成功
String channelPayOrderId = retMsg.getString("payOrderId"); //支付网关返回的支付订单号, 用于记录更新
//[6.] 更新订单号
MchTradeOrder updateRecord = new MchTradeOrder();
updateRecord.setTradeOrderId(tradeOrderId);
updateRecord.setPayOrderId(channelPayOrderId);
rpc.rpcMchTradeOrderService.updateById(updateRecord);
//[7.] 返回交易订单号 & 状态
JSONObject result = new JSONObject();
result.put("tradeOrderId", tradeOrderId);
result.put("orderStatus", channelOrderStatus);
return ResponseEntity.ok(XxPayResponse.buildSuccess(result));
}
/** 订单退款接口 **/
@RequestMapping("/refund")
public ResponseEntity<?> refund() {
String tradeOrderId = getValStringRequired( "tradeOrderId"); //申请退款的 [商户交易单号]
Long refundAmount = getRequiredAmountL( "refundAmount"); //退款金额
String refundDesc = getValString( "refundDesc"); //退款原因
//校验订单是否合法, 校验退款金额是否合法
MchTradeOrder dbOrder = rpc.rpcMchTradeOrderService.findByTradeOrderId(tradeOrderId);
//调用退款流程
JSONObject result = refund(dbOrder, refundAmount, tradeOrderId, refundDesc);
return ResponseEntity.ok(XxPayResponse.buildSuccess(result));
}
/** 订单退款验证退款密码接口 **/
@RequestMapping("/refund2")
public ResponseEntity<?> refund2() {
String tradeOrderId = getValStringRequired( "tradeOrderId"); //申请退款的 [商户交易单号]
Long refundAmount = getRequiredAmountL( "refundAmount"); //退款金额
String refundDesc = getValString( "refundDesc"); //退款原因
String refundPassword = getValString( "refundPassword"); //退款密码
//校验订单是否合法, 校验退款金额是否合法
MchTradeOrder dbOrder = rpc.rpcMchTradeOrderService.findByTradeOrderId(tradeOrderId);
if(dbOrder == null){
throw ServiceException.build(RetEnum.RET_MCH_TRADE_ORDER_NOT_EXIST); //没有该订单
}
//校验退款密码是否正确
MchStore mchStore = rpc.rpcMchStoreService.getById(dbOrder.getStoreId()); //所属门店
if (mchStore == null) throw ServiceException.build(RetEnum.RET_MCH_STORE_NOT_EXIST); //无门店
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
if(!encoder.matches(refundPassword, mchStore.getRefundPassword())) {
throw ServiceException.build(RetEnum.RET_MCH_REFUNDS_PASSWORD_ERROR); //验证密码错误
}
//调用退款流程
JSONObject result = refund(dbOrder, refundAmount, tradeOrderId, refundDesc);
return ResponseEntity.ok(XxPayResponse.buildSuccess(result));
}
/** 押金订单, 押金消费 **/
@RequestMapping("/depositConsume")
public XxPayResponse depositConsume() {
String tradeOrderId = getValStringRequired( "tradeOrderId"); //[商户交易单号]
Long consumeAmount = getRequiredAmountL( "consumeAmount"); //消费金额
//校验订单是否合法, 校验退款金额是否合法
MchTradeOrder dbOrder = rpc.rpcMchTradeOrderService.findByMchIdAndTradeOrderId(getUser().getBelongInfoId(), tradeOrderId);
if(dbOrder == null){
throw ServiceException.build(RetEnum.RET_MCH_TRADE_ORDER_NOT_EXIST); //没有该订单
}
//验证是否为 [押金模式] 订单
if(dbOrder.getDepositMode() != MchConstant.PUB_YES){
throw ServiceException.build(RetEnum.RET_MCH_ORDER_MODE_NOT_DEPOSIT_ERROR);
}
//不等于 [押金未结算] 状态
if(dbOrder.getStatus() != MchConstant.TRADE_ORDER_STATUS_DEPOSIT_ING){
throw ServiceException.build(RetEnum.RET_MCH_ORDER_STATUS_NOT_DEPOSIT_ING_ERROR);
}
//消费金额 不允许为0, 并且需要小于等于押金金额
if(consumeAmount <= 0 || consumeAmount > dbOrder.getDepositAmount() ) {
throw ServiceException.build(RetEnum.RET_MCH_ORDER_DEPOSIT_AMOUNT_ERROR);
}
if(dbOrder.getProductId() == PayConstant.PAY_PRODUCT_WX_BAR){
//调起微信接口 & 处理订单状态
rpcCommonService.rpcXxPayWxpayApiService.wxDepositConsume(tradeOrderId, consumeAmount);
}else if(dbOrder.getProductId() == PayConstant.PAY_PRODUCT_ALIPAY_BAR){
//调起支付宝接口 & 处理订单状态
rpcCommonService.rpcXxPayAlipayApiService.depositConsume(tradeOrderId, consumeAmount);
}
return XxPayResponse.buildSuccess();
}
/** 押金订单撤销 **/
@RequestMapping("/depositReverse")
public XxPayResponse depositReverse() {
String tradeOrderId = getValStringRequired( "tradeOrderId"); //[商户交易单号]
//校验订单是否合法, 校验退款金额是否合法
MchTradeOrder dbOrder = rpc.rpcMchTradeOrderService.findByMchIdAndTradeOrderId(getUser().getBelongInfoId(), tradeOrderId);
if(dbOrder == null){
throw ServiceException.build(RetEnum.RET_MCH_TRADE_ORDER_NOT_EXIST); //没有该订单
}
//验证是否为 [押金模式] 订单
if(dbOrder.getDepositMode() != MchConstant.PUB_YES){
throw ServiceException.build(RetEnum.RET_MCH_ORDER_MODE_NOT_DEPOSIT_ERROR);
}
//不等于 [押金未结算] 状态
if(dbOrder.getStatus() != MchConstant.TRADE_ORDER_STATUS_DEPOSIT_ING){
throw ServiceException.build(RetEnum.RET_MCH_ORDER_STATUS_NOT_DEPOSIT_ING_ERROR);
}
if(dbOrder.getProductId() == PayConstant.PAY_PRODUCT_WX_BAR){
//调起微信接口 & 处理订单状态
rpcCommonService.rpcXxPayWxpayApiService.wxDepositReverse(tradeOrderId);
}else if(dbOrder.getProductId() == PayConstant.PAY_PRODUCT_ALIPAY_BAR){
//调起微信接口 & 处理订单状态
rpcCommonService.rpcXxPayAlipayApiService.depositReverse(tradeOrderId);
}
return XxPayResponse.buildSuccess();
}
/** 创建退款订单 **/
private JSONObject createRefundOrder(MchTradeOrder mchTradeOrder, MchRefundOrder mchRefundOrder) {
JSONObject paramMap = new JSONObject();
paramMap.put("mchId", mchTradeOrder.getMchId()); //商户ID
paramMap.put("payOrderId", mchTradeOrder.getPayOrderId()); // 支付订单号
paramMap.put("mchOrderNo", mchTradeOrder.getTradeOrderId()); // 商户交易单号
paramMap.put("mchRefundNo", mchRefundOrder.getMchRefundOrderId()); // 商户退款单号
paramMap.put("amount", mchRefundOrder.getRefundAmount()); // 退款金额,单位分
paramMap.put("currency", "cny"); // 币种, cny-人民币
paramMap.put("clientIp", mchTradeOrder.getClientIp()); // 用户地址,IP或手机号
paramMap.put("device", mchTradeOrder.getDevice()); // 设备
paramMap.put("notifyUrl",""); // 回调URL
paramMap.put("remarkInfo", mchRefundOrder.getRefundDesc()); // 退款原因
paramMap.put("channelUser", mchTradeOrder.getUserId()); // openId
MchInfo mchInfo = rpc.rpcMchInfoService.findByMchId(getUser().getBelongInfoId()); //获取商户信息
String reqSign = PayDigestUtil.getSign(paramMap, mchInfo.getPrivateKey());
paramMap.put("sign", reqSign); // 签名
String reqData = "params=" + paramMap.toJSONString();
_log.info("xxpay_req:{}", reqData);
String url = mainConfig.getPayUrl() + "/refund/create_order?";
String result = XXPayUtil.call4Post(url + reqData);
_log.info("xxpay_res:{}", result);
JSONObject retMsg = JSON.parseObject(result);
return retMsg;
}
/** 退款验证执行流程 **/
private JSONObject refund(MchTradeOrder dbOrder, Long refundAmount, String tradeOrderId, String refundDesc) {
if(dbOrder == null){
throw ServiceException.build(RetEnum.RET_MCH_TRADE_ORDER_NOT_EXIST); //没有该订单
}
//订单状态 不是支付成功, 也不是部分退款状态时,不允许发起退款
if(dbOrder.getStatus() != MchConstant.TRADE_ORDER_STATUS_SUCCESS && dbOrder.getStatus() != MchConstant.TRADE_ORDER_STATUS_REFUND_PART){ //支付成功状态
throw ServiceException.build(RetEnum.RET_MCH_REFUND_STATUS_NOT_SUPPORT);
}
if(dbOrder.getAmount() <= dbOrder.getRefundTotalAmount() ) { //订单支付金额 <= 订单总退金额
throw ServiceException.build(RetEnum.RET_MCH_ALREADY_REFUNDS);
}
if(refundAmount > ( dbOrder.getAmount() - dbOrder.getRefundTotalAmount() ) ) { //退款金额 > (订单金额 - 总退款金额)
throw ServiceException.build(RetEnum.RET_MCH_REFUNDAMOUNT_GT_PAYAMOUNT);
}
//判断当前订单 是否存在[退款中] 订单
int ingRefundOrder = rpc.rpcMchRefundOrderService.count(
new QueryWrapper<MchRefundOrder>().lambda().eq(MchRefundOrder::getTradeOrderId, tradeOrderId)
.eq(MchRefundOrder::getStatus, MchConstant.MCH_REFUND_STATUS_ING));
if(ingRefundOrder > 0){
throw ServiceException.build(RetEnum.RET_MCH_TRADE_HAS_REFUNDING_ORDER);
}
//插入商户退款表
MchRefundOrder mchRefundOrder = new MchRefundOrder();
mchRefundOrder.setMchRefundOrderId(MySeq.getMchRefund()); //商户退款订单号
mchRefundOrder.setTradeOrderId(dbOrder.getTradeOrderId()); //支付订单号
mchRefundOrder.setMchId(dbOrder.getMchId()); //商户ID
mchRefundOrder.setPayAmount(dbOrder.getAmount()); //支付订单号
mchRefundOrder.setRefundAmount(refundAmount); //退款金额
mchRefundOrder.setCurrency("CNY"); //币种
mchRefundOrder.setStatus(MchConstant.MCH_REFUND_STATUS_ING); //默认退款单状态: 退款中
mchRefundOrder.setRefundDesc(refundDesc); //退款原因
mchRefundOrder.setCreateTime(new Date());
rpc.rpcMchRefundOrderService.save(mchRefundOrder); //插入商户退款表记录
if(dbOrder.getProductId() == null){ //无需调用上游接口, 直接为退款成功
mchRefundOrder.setStatus(MchConstant.MCH_REFUND_STATUS_SUCCESS);
} else{ //调起上游退款接口
JSONObject payResData = createRefundOrder(dbOrder, mchRefundOrder); //向上游发起退款申请
//返回code不等于0 , 退款异常
if(PayEnum.OK.getCode().equals(payResData.getString("retCode"))) {
if(PayConstant.REFUND_STATUS_FAIL == payResData.getByte("status")){ //退款失败
mchRefundOrder.setStatus(MchConstant.MCH_REFUND_STATUS_FAIL);
}else if(PayConstant.REFUND_STATUS_SUCCESS == payResData.getByte("status")){ //退款成功
mchRefundOrder.setStatus(MchConstant.MCH_REFUND_STATUS_SUCCESS);
} //其他情况,认为退款中
}
}
//退款成功
if(mchRefundOrder.getStatus() == MchConstant.MCH_REFUND_STATUS_SUCCESS){
//更新订单状态
rpc.rpcMchRefundOrderService.refundSuccess(mchRefundOrder, dbOrder);
}else if(mchRefundOrder.getStatus() == MchConstant.MCH_REFUND_STATUS_FAIL){ //退款失败
rpc.rpcMchRefundOrderService.refundFail(mchRefundOrder.getMchRefundOrderId());
}
JSONObject result = new JSONObject();
result.put("mchRefundOrderId", mchRefundOrder.getMchRefundOrderId()); //退款申请成功, 返回退款订单号
result.put("status", mchRefundOrder.getStatus()); //状态
return result;
}
}
| true |
41692f4a313580433b69773fd40d42f5fab9e4c3 | Java | 32248480/Java11 | /Class01.java | UTF-8 | 821 | 3.9375 | 4 | [] | no_license | abstract class CShape{
protected String color;
public CShape(String str){
color=str;
}
public abstract void show();
}
class CRectangle extends CShape{
int width,height;
public CRectangle(int w,int h){
super("Yellow");
width=w;
height=h;
}
public void show(){
System.out.print("color="+color+", ");
System.out.println("area="+width*height);
}
}
class CCircle extends CShape{
double radius;
public CCircle(double r){
super("Green");
radius=r;
}
public void show(){
System.out.print("color="+color+", ");
System.out.println("area="+3.14*radius*radius);
}
}
public class Main{
public static void main(String args[]){
CRectangle rect=new CRectangle(5,10);
rect.show();
CCircle cir=new CCircle(2.0);
cir.show();
}
}
//color=Yellow, area=50
//color=Green, area=12.56
| true |
bb73babee0a928e3f13a5f6aceee387a49f630cb | Java | jbzhang99/YS_Distribute | /yb-public-api/src/main/java/com/api/service/product/IColorMasterService.java | UTF-8 | 2,355 | 1.75 | 2 | [] | no_license | package com.api.service.product;
import com.api.hystric.product.CategoryMasterServiceHystrix;
import com.product.entity.ColorMasterEntity;
import com.system.util.ServiceResult;
import com.system.util.SystemException;
import org.springframework.cloud.openfeign.FeignClient;
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 java.util.List;
import java.util.Map;
@FeignClient(value = "yb-public-product", fallback = CategoryMasterServiceHystrix.class)
public interface IColorMasterService {
/**
* findList
*
* @Author qinwanli
* @Description
* @Date 2019/5/24 15:17
* @Param [params]
**/
@RequestMapping(value = "/color/findList", method = RequestMethod.GET)
ServiceResult<List<ColorMasterEntity>> findList(@RequestParam Map<String, Object> params) throws SystemException;
/**
* findInfo
*
* @Author qinwanli
* @Description
* @Date 2019/5/24 15:16
* @Param [params]
**/
@RequestMapping(value = "/color/findInfo", method = RequestMethod.GET)
ServiceResult<ColorMasterEntity> findInfo(@RequestParam Map<String, Object> params) throws SystemException;
/**
* doInsert
*
* @Author qinwanli
* @Description
* @Date 2019/5/24 15:16
* @Param [colorMasterEntity]
**/
@RequestMapping(value = { "/color/doInsert" }, method = { RequestMethod.POST })
ServiceResult<Integer> doInsert(@RequestBody ColorMasterEntity colorMasterEntity) throws SystemException;
/**
* doUpdate
*
* @Author qinwanli
* @Description
* @Date 2019/5/24 15:16
* @Param [colorMasterEntity]
**/
@RequestMapping(value = { "/color/doUpdate" }, method = { RequestMethod.POST })
ServiceResult<Integer> doUpdate(@RequestBody ColorMasterEntity colorMasterEntity) throws SystemException;
/**
* doDelete
*
* @Author qinwanli
* @Description
* @Date 2019/5/24 15:16
* @Param [colorId]
**/
@RequestMapping(value = { "/color/doDelete" }, method = { RequestMethod.POST })
ServiceResult<Boolean> doDelete(@RequestParam("colorId") int colorId) throws SystemException;
}
| true |
3c279227b431ba6d44b9300ecbeaaa331f4fec32 | Java | amhyry/hsrm.oose.2013.project.pacman | /src/de/hsrm/cs/oose13/GameTic.java | UTF-8 | 894 | 2.421875 | 2 | [] | no_license | package de.hsrm.cs.oose13;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
public class GameTic implements ActionListener {
GamePanel panel;
public GameTic(GamePanel gamePanel) {
this.panel = gamePanel;
}
@Override
public void actionPerformed(ActionEvent e) {
panel.game.moveAll();
panel.game.collisions();
panel.repaint();
switch (panel.game.checkGame()) {
case 0:
panel.newGame();
break;
case 1:
Object[] option = { "OK" };
JOptionPane.showOptionDialog(null, "Herzlichen Glueckwunsch",
"Sieg", JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE, null, option, option[0]);
panel.timer.stop();
panel.game.beginn.stop();
panel.game.death.stop();
panel.game.intermission.stop();
panel.f.dispose();
panel.menu.startGame(panel.menu.lvl++);
default:
break;
}
}
} | true |
9a02d41ff3a59b458ca13bcdde6df0e07f82674d | Java | RalphSu/789 | /p2p-facade/src/main/java/com/icebreak/p2p/rs/service/userManage/AppSetUserPwdService.java | UTF-8 | 2,844 | 2 | 2 | [] | no_license | package com.icebreak.p2p.rs.service.userManage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSONObject;
import com.icebreak.p2p.dataobject.Role;
import com.icebreak.p2p.dataobject.UserBaseInfoDO;
import com.icebreak.p2p.rs.base.ServiceBase;
import com.icebreak.p2p.rs.base.enums.APIServiceEnum;
import com.icebreak.p2p.rs.service.base.AppService;
import com.icebreak.p2p.session.SessionLocal;
import com.icebreak.p2p.session.SessionLocalManager;
import com.icebreak.p2p.user.result.UserBaseReturnEnum;
import com.icebreak.util.lang.ip.IPUtil;
public class AppSetUserPwdService extends ServiceBase implements AppService {
@Override
public JSONObject execute(Map<String, Object> params,
HttpServletRequest request) {
JSONObject json = new JSONObject();
Map<String, Object> result = new HashMap<String, Object>();
try{
String MD5UserBaseId = params.get("MD5UserBaseId").toString();
String logPassWord = params.get("logPassWord").toString();
String payPassWord = params.get("payPassWord").toString();
UserBaseInfoDO userBaseInfo = userBaseInfoManager.queryByMD5UserBaseId(MD5UserBaseId);
UserBaseReturnEnum returnEnum = UserBaseReturnEnum.EXECUTE_FAILURE;
returnEnum = userBaseInfoManager.updateLogPasswordAndPayPassword(userBaseInfo.getUserBaseId(), logPassWord, payPassWord);
if (returnEnum == UserBaseReturnEnum.EXECUTE_SUCCESS) {
//获取角色串begin
List<Role> roleList = null;
try {
roleList = authorityService.getRolesByUserId(userBaseInfo.getUserId());
} catch (Exception e) {
e.printStackTrace();
}
StringBuilder roleCodes = new StringBuilder();
String roleCodesStr = "";
if(roleList != null || roleList.size()>0){
for(int i=0;i<roleList.size();i++){
roleCodes.append("|").append(roleList.get(i).getCode());
}
roleCodesStr = roleCodes.substring(1);
}
//获取角色串end
SessionLocalManager.setSessionLocal(new SessionLocal(
authorityService.getPermissionsByUserId(userBaseInfo.getUserId()), userBaseInfo.getUserId(),
userBaseInfo.getUserBaseId(), roleCodesStr, userBaseInfo.getAccountId(),
userBaseInfo.getAccountName(), userBaseInfo.getRealName(),
userBaseInfo.getUserName(), IPUtil.getIpAddr(request)));
result.put("code", "1");
result.put("message", "设置密码成功");
json.put("dataMap", result);
}else{
result.put("code", "0");
result.put("message", "设置密码失败");
json.put("dataMap", result);
}
}catch(Exception e){
result.put("code", "0");
result.put("message", "设置密码异常");
json.put("dataMap", result);
}
return json;
}
@Override
public APIServiceEnum getServiceType() {
return APIServiceEnum.appSetUserPwd;
}
}
| true |
19320ecd63415f4de72ba4f33f02671f5f023297 | Java | mskjaldgaard/SwissKnightMinecraft | /SpongePowered/SpongeTests/src/main/java/ch/vorburger/minecraft/testsinfra/CommandTestHelper.java | UTF-8 | 10,083 | 1.765625 | 2 | [
"MIT"
] | permissive | /*
* This file is part of Michael Vorburger's SwissKnightMinecraft project, licensed under the MIT License (MIT).
*
* Copyright (c) Michael Vorburger <http://www.vorburger.ch>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package ch.vorburger.minecraft.testsinfra;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import org.junit.Assert;
import org.spongepowered.api.Game;
import org.spongepowered.api.service.command.CommandService;
import org.spongepowered.api.service.permission.Subject;
import org.spongepowered.api.service.permission.SubjectCollection;
import org.spongepowered.api.service.permission.SubjectData;
import org.spongepowered.api.service.permission.context.Context;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.Text.Literal;
import org.spongepowered.api.text.Text.Translatable;
import org.spongepowered.api.text.sink.MessageSink;
import org.spongepowered.api.text.translation.Translation;
import org.spongepowered.api.util.Tristate;
import org.spongepowered.api.util.command.CommandResult;
import org.spongepowered.api.util.command.CommandSource;
/**
* Helper for integration tests using Minecraft slash commands.
*
* @see CommandService
*
* @author Michael Vorburger
*/
public class CommandTestHelper implements ChatMessageCapturingPlugin.ChatMessageListener {
protected Game game;
private List<Text> pluginCapturedMessages = new ArrayList<Text>();
// TODO remove constructor, use @Inject Game game instead
public CommandTestHelper(Game game) {
this.game = game;
ChatMessageCapturingPlugin plugin = (ChatMessageCapturingPlugin) game.getPluginManager().getPlugin(ChatMessageCapturingPlugin.ID).get().getInstance();
// plugin.setListener(this);
}
public CommandResultWithChat process(String command) {
CommandSource source = (CommandSource) game.getServer();
return process(source, command);
}
public CommandResultWithChat process(CommandSource source, String command) {
ChatKeepingCommandSource wrappedSource = wrap(source);
CommandService commandService = game.getCommandDispatcher();
CommandResult result = commandService.process(wrappedSource, command);
// TODO Ideally make this more robust.. would require changes to core Sponge
assertDoesNotContainIgnoreCase(wrappedSource, "commands.generic.notFound"); // "Unknown command"
assertDoesNotContainIgnoreCase(wrappedSource, "Error occurred while executing command"); // as in SimpleCommandService
Chat thisChat = new Chat() {
@Override
public List<Text> getMessages() {
return pluginCapturedMessages;
}
};
return new CommandResultWithChat(result, thisChat);
}
public String toString(Text text) {
StringBuilder sb = new StringBuilder();
for (Text childText : text.withChildren()) {
if (sb.length() > 0)
sb.append("; ");
if (childText instanceof Literal) {
sb.append(((Literal)childText).getContent());
} else if (childText instanceof Translatable) {
Translation translation = ((Translatable)childText).getTranslation();
// We're opt. also adding Translation here Id because due to a
// strange problem get() doesn't always seem to work (weird
// MissingResourceException when called from here; but works
// normally elsewhere - more ClassLoader
// shit??)
if (!translation.getId().equals(translation.get(Locale.US))) {
sb.append('%');
sb.append(translation.getId());
sb.append(": ");
}
sb.append(translation.get(Locale.US));
} else {
// TODO Other sub classes of Text...
throw new IllegalArgumentException(childText.getClass().getName());
}
}
return sb.toString();
}
protected String toString(Chat chat) {
StringBuilder sb = new StringBuilder();
for (Text text : chat.getMessages()) {
if (sb.length() > 0)
sb.append('\n');
sb.append(toString(text));
}
return sb.toString();
}
public boolean contains(Chat chat, String text) {
return toString(chat).contains(text);
}
public boolean containsIgnoreCase(Chat chat, String text) {
return toString(chat).toLowerCase().contains(text.toLowerCase());
}
public void assertSingleChatReply(String command, String expectedChatReply) throws AssertionError {
CommandResultWithChat r = process(command);
List<Text> m = r.getChat().getMessages();
assertEquals(1, m.size());
assertEquals(expectedChatReply, toString(m.get(0)));
}
public void assertDoesNotContainIgnoreCase(Chat chat, String text) throws AssertionError {
Assert.assertFalse(toString(chat), containsIgnoreCase(chat, text));
}
public void assertContainsIgnoreCase(Chat chat, String text) throws AssertionError {
Assert.assertTrue(toString(chat), containsIgnoreCase(chat, text));
}
public void assertContainsNoErrors(Chat chat) throws AssertionError {
assertDoesNotContainIgnoreCase(chat, "error");
}
public void assertSuccessCount(CommandResult result) throws AssertionError {
if (!result.getSuccessCount().isPresent())
throw new AssertionError("CommandResult has no (empty) successCount");
int successCount = result.getSuccessCount().get().intValue();
if (successCount < 1)
throw new AssertionError("CommandResult had successCount != 1: " + successCount);
}
public /*static*/ class CommandResultWithChat {
private final CommandResult result;
private final Chat chat;
protected CommandResultWithChat(CommandResult result, Chat chat) {
this.result = result;
this.chat = chat;
}
public CommandResult getResult() {
return result;
}
public Chat getChat() {
return chat;
}
public CommandResultWithChat assertSuccessCount() throws AssertionError {
CommandTestHelper.this.assertSuccessCount(this.result);
return this;
}
public CommandResultWithChat assertChatNoErrors() throws AssertionError {
CommandTestHelper.this.assertContainsNoErrors(this.chat);
return this;
}
}
public static interface Chat {
List<Text> getMessages();
}
@Override
public void onMessage(Text message) {
pluginCapturedMessages.add(message);
}
protected ChatKeepingCommandSource wrap(CommandSource source) {
return new ChatKeepingCommandSource(source);
}
protected static class ChatKeepingCommandSource extends DelegatingCommandSource implements Chat {
private List<Text> sentMessages = new ArrayList<>();
public ChatKeepingCommandSource(CommandSource source) {
super(source);
}
@Override
public List<Text> getMessages() {
return sentMessages;
}
@Override
public void sendMessage(Iterable<Text> messages) {
for (Text message : messages) {
sentMessages.add(message);
}
super.sendMessage(messages);
}
@Override
public void sendMessage(Text... messages) {
for (Text message : messages) {
sentMessages.add(message);
}
super.sendMessage(messages);
}
}
protected static class DelegatingCommandSource implements CommandSource {
protected CommandSource delegate;
public DelegatingCommandSource(CommandSource source) {
this.delegate = source;
}
@Override
public String getName() {
return delegate.getName();
}
@Override
public void sendMessage(Text... messages) {
delegate.sendMessage(messages);
}
@Override
public void sendMessage(Iterable<Text> messages) {
delegate.sendMessage(messages);
}
@Override
public MessageSink getMessageSink() {
return delegate.getMessageSink();
}
@Override
public void setMessageSink(MessageSink sink) {
delegate.setMessageSink(sink);
}
@Override
public String getIdentifier() {
return delegate.getIdentifier();
}
@Override
public Optional<CommandSource> getCommandSource() {
return delegate.getCommandSource();
}
@Override
public SubjectCollection getContainingCollection() {
return delegate.getContainingCollection();
}
@Override
public SubjectData getSubjectData() {
return delegate.getSubjectData();
}
@Override
public SubjectData getTransientSubjectData() {
return delegate.getTransientSubjectData();
}
@Override
public boolean hasPermission(Set<Context> contexts, String permission) {
return delegate.hasPermission(contexts, permission);
}
@Override
public boolean hasPermission(String permission) {
return delegate.hasPermission(permission);
}
@Override
public Tristate getPermissionValue(Set<Context> contexts, String permission) {
return delegate.getPermissionValue(contexts, permission);
}
@Override
public boolean isChildOf(Subject parent) {
return delegate.isChildOf(parent);
}
@Override
public boolean isChildOf(Set<Context> contexts, Subject parent) {
return delegate.isChildOf(contexts, parent);
}
@Override
public List<Subject> getParents() {
return delegate.getParents();
}
@Override
public List<Subject> getParents(Set<Context> contexts) {
return delegate.getParents(contexts);
}
@Override
public Set<Context> getActiveContexts() {
return delegate.getActiveContexts();
}
}
}
| true |
9eb78c2765a34e0f80338326602714663994bd5d | Java | Gabrielgoc99/padraoMediator | /src/main/java/Hospital.java | UTF-8 | 1,015 | 2.609375 | 3 | [] | no_license | public class Hospital {
private static Hospital instancia = new Hospital();
private Hospital() {}
public static Hospital getInstancia() {
return instancia;
}
public String atestadoEncaminhamentoUTI (String atestado) {
return "Bem vindo ao Hospital St. Claude!\n"+
"Seu atestado de internação na UTI foi emitido.\n" +
">>" + Clinica.getInstancia().encaminhamentoUTI(atestado);
}
public String atestadoEncaminhamentoExame (String atestado) {
return "Bem vindo ao Hospital St. Claude!\n"+
"Seu atestado de realização de exames foi emitido.\n" +
">>" + Clinica.getInstancia().encaminhamentoExame(atestado);
}
public String atestadoEncaminhamentoConsulta (String atestado) {
return "Bem vindo ao Hospital St. Claude!\n"+
"Seu atestado de Consulta de Rotina foi emitido.\n" +
">>" + Clinica.getInstancia().encaminhamentoConsulta(atestado);
}
}
| true |
c30b6dc6a4e45b2451d6282898329eb8cb889c53 | Java | RexMilton/Old_Skill_Rack | /DC/2021/04/21/solution.java | UTF-8 | 1,085 | 3.109375 | 3 | [] | no_license | import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner q=new Scanner(System.in);
int x=q.nextInt(),y=q.nextInt();
char z[][]=new char[x][y];
q.nextLine();
for(int i=0;i<x;i++){
String[] t=q.nextLine().split(" ");
for(int j=0;j<y;j++){
z[i][j]=t[j].charAt(0);
if(z[i][j]=='B')
z[i][j]='-';
}
}
for(int j=0;j<y;j++){
for(int i=x-1;i>=0;i--){
//System.out.println(z[i][j]=="B"+"\n");
if(z[i][j]=='-'){
//System.out.println(i+" "+j+"\n");
boolean flag=true;
for(int k=0;k<i;k++){
if(z[k][j]=='A'){
z[k][j]='-';
z[i][j]='A';
flag=false;
break;
}
z[k][j]='-';
}
if(flag)
break;
}
}
}
for(int i=0;i<x;i++){
for(char j:z[i])
System.out.print(j+" ");
System.out.println();
}
}
}
| true |
975e8de54db1a73695087e63af55b0088796019c | Java | GJordao12/ISEP-LAPR4 | /lei20_21_s4_2dl_02/HelpdeskService/helpdesk.core/src/main/java/eapli/helpdesk/feedback/domain/FeedbackTicket.java | UTF-8 | 1,226 | 2.1875 | 2 | [
"MIT"
] | permissive | package eapli.helpdesk.feedback.domain;
import com.fasterxml.jackson.annotation.JsonProperty;
import eapli.framework.domain.model.AggregateRoot;
import eapli.framework.domain.model.DomainEntities;
import eapli.helpdesk.ticket.domain.Ticket;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.xml.bind.annotation.XmlElement;
@Entity
public class FeedbackTicket implements AggregateRoot<Long> {
@Id
@GeneratedValue
long id;
@XmlElement
@JsonProperty
private Classificacao classificacao;
@OneToOne
private Ticket ticket;
public FeedbackTicket(final Classificacao classificacao, final Ticket ticket) {
this.classificacao = classificacao;
this.ticket = ticket;
}
protected FeedbackTicket() {
// for ORM only
}
public Classificacao classificacao() {
return this.classificacao;
}
public Ticket ticket() {
return this.ticket;
}
@Override
public boolean sameAs(Object other) {
return DomainEntities.areEqual(this, other);
}
@Override
public Long identity() {
return this.id;
}
}
| true |
d575c974f6047a5e23bc5c18ca32b65159e7e179 | Java | Selesito/job4j_grabber | /src/main/java/ru/job4j/grabber/utils/SqlRuDateTimeParser.java | UTF-8 | 2,100 | 2.875 | 3 | [] | no_license | package ru.job4j.grabber.utils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.*;
public class SqlRuDateTimeParser implements DateTimeParser {
private static final Map<Long, String> MONTHS = new HashMap<>();
static {
MONTHS.put(1L, "янв");
MONTHS.put(2L, "фев");
MONTHS.put(3L, "мар");
MONTHS.put(4L, "апр");
MONTHS.put(5L, "май");
MONTHS.put(6L, "июн");
MONTHS.put(7L, "июл");
MONTHS.put(8L, "авг");
MONTHS.put(9L, "сен");
MONTHS.put(10L, "окт");
MONTHS.put(11L, "ноя");
MONTHS.put(12L, "дек");
}
private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
.appendPattern("d ")
.appendText(ChronoField.MONTH_OF_YEAR, MONTHS)
.appendPattern(" yy, ")
.appendPattern("HH:mm")
.toFormatter();
@Override
public LocalDateTime parse(String pars) {
LocalDateTime date;
int index = pars.indexOf(",");
if (pars.contains("сегодня")) {
int[] time = parseTime(pars, index);
date = LocalDate.now().atTime(time[0], time[1]);
} else if (pars.contains("вчера")) {
int[] time = parseTime(pars, index);
date = LocalDate.now().atTime(time[0], time[1]).minusDays(1);
} else {
date = LocalDateTime.parse(pars, FORMATTER);
}
return date;
}
private int[] parseTime(String pars, int index) {
pars = pars.substring(index + 2);
String[] rsl = pars.split(":");
int hours = Integer.parseInt(rsl[0]);
int minutes = Integer.parseInt(rsl[1]);
return new int[] {hours, minutes};
}
}
| true |
b1998b9a9de2daf7216edb45c933422171122353 | Java | sxinchuan/sxctest | /src/sxinchuan/TestInnerClass.java | GB18030 | 590 | 2.59375 | 3 | [] | no_license | package sxinchuan;
public class TestInnerClass {
public static void main(String[] args) {
// new Test().new Test2().print();
// new Test().new Test2().new Test3().print();
String url = " http://127.0.0.1:9000/ibot-robot-uap/robot-sgcc/services/robotService";
System.out.println(url.substring(0, url.indexOf("robot-sgcc")));
}
public class Test2{
public void print() {
System.out.println("һڲ");
}
public class Test3{
public void print() {
System.out.println("һڲڲ");
}
}
}
}
| true |
bdf79c4fb797c8754ef8240fa59053cb65b983ee | Java | andrewpedia/SlideHoldSmoothDemo | /app/src/main/java/com/ganshenml/slideholdsmoothdemo/ScrollingActivity.java | UTF-8 | 2,083 | 2.203125 | 2 | [] | no_license | package com.ganshenml.slideholdsmoothdemo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class ScrollingActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
//获取Toolbar
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
//使用CollapsingToolbarLayout必须把title设置到CollapsingToolbarLayout上,设置到Toolbar上则不会显示
CollapsingToolbarLayout mCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout);
mCollapsingToolbarLayout.setTitle("CollapsingToolbarLayout");
//通过CollapsingToolbarLayout修改字体颜色
mCollapsingToolbarLayout.setExpandedTitleColor(Color.WHITE);//设置还没收缩时状态下字体颜色
mCollapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE);//设置收缩后Toolbar上字体的颜色
initViews();
}
private void initViews() {
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setOffscreenPageLimit(2);
viewPager.setAdapter(new MPagerAdapter(getSupportFragmentManager()));
}
}
| true |
c9e8c1efc910c849ed4c017ed4fe29c207a7ef12 | Java | qaz4042/beBetter | /3-common/src/main/java/bebetter/basejpa/cfg/sub/CustomFormAuthenticationFilter.java | UTF-8 | 2,008 | 2.25 | 2 | [
"MIT"
] | permissive | package bebetter.basejpa.cfg.sub;
import cn.hutool.json.JSONUtil;
import bebetter.basejpa.model.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.http.HttpMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Slf4j
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
if (request instanceof HttpServletRequest) {
if (HttpMethod.OPTIONS.name().equals(((HttpServletRequest) request).getMethod())) {
return true;
}
}
return super.isAccessAllowed(request, response, mappedValue);
}
//没登录/没权限时
@Override
protected boolean onAccessDenied(ServletRequest req, ServletResponse resp) throws IOException {
boolean logined = SecurityUtils.getSubject().isAuthenticated();
int status = logined ? HttpServletResponse.SC_FORBIDDEN/*// 403 */ : HttpServletResponse.SC_UNAUTHORIZED/*// 401 */;
String info = logined ? "您暂无该权限." : "您未登录,或者登陆已过期.";
log.info("请求鉴权失败{}|失败原因:{}", status, info);
HttpServletResponse resp1 = (HttpServletResponse) resp;
resp1.setHeader("Access-Control-Allow-Origin", ((HttpServletRequest) req).getHeader("Origin"));
resp1.setHeader("Access-Control-Allow-Credentials", "true");
//resp1.setStatus(status);
resp1.setCharacterEncoding("UTF-8");
PrintWriter out = resp1.getWriter();
out.write(JSONUtil.toJsonStr(R.error(status, info)));
out.flush();
out.close();
return false;
}
}
| true |
d127b5856ced7239aa8bafcbe67e95bf08f5be81 | Java | 1033132510/SCM | /src/main/java/com/zzc/modules/sysmgr/common/service/impl/SequenceEntityServiceImpl.java | UTF-8 | 1,294 | 2.078125 | 2 | [] | no_license | package com.zzc.modules.sysmgr.common.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzc.core.dao.BaseDao;
import com.zzc.core.service.impl.BaseCrudServiceImpl;
import com.zzc.modules.sysmgr.common.dao.SequenceEntityDao;
import com.zzc.modules.sysmgr.common.entity.SequenceEntity;
import com.zzc.modules.sysmgr.common.service.SequenceEntityService;
@Service("sequenceEntityService")
public class SequenceEntityServiceImpl extends BaseCrudServiceImpl<SequenceEntity> implements SequenceEntityService {
@SuppressWarnings("unused")
private SequenceEntityDao sequenceEntityDao;
@Autowired
public SequenceEntityServiceImpl(BaseDao<SequenceEntity> sequenceEntityDao) {
super(sequenceEntityDao);
this.sequenceEntityDao = (SequenceEntityDao) sequenceEntityDao;
}
@Override
public SequenceEntity findSequenceEntityBySequenceName(String sequenceName) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("AND_EQ_sequenceName", sequenceName);
List<SequenceEntity> findAll = findAll(map, SequenceEntity.class);
if (findAll != null && findAll.size() == 1) {
return findAll.get(0);
}
return null;
}
}
| true |
4722d0deb75008cf5c61cc3060b785e790b0ed5c | Java | IsisVgoddess/isis | /commons/src/main/java/org/apache/isis/commons/internal/debug/xray/XrayUi.java | UTF-8 | 14,734 | 1.585938 | 2 | [
"Apache-2.0"
] | permissive | /*
* 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.apache.isis.commons.internal.debug.xray;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import org.apache.isis.commons.collections.Can;
import org.apache.isis.commons.internal.base._Casts;
import org.apache.isis.commons.internal.collections._Maps;
import org.apache.isis.commons.internal.debug.xray.XrayModel.HasIdAndLabel;
import org.apache.isis.commons.internal.debug.xray.XrayModel.Stickiness;
import lombok.RequiredArgsConstructor;
import lombok.val;
public class XrayUi extends JFrame {
private static final long serialVersionUID = 1L;
private final JTree tree;
private final DefaultMutableTreeNode root;
private final XrayModel xrayModel;
private static XrayUi INSTANCE;
private static AtomicBoolean startRequested = new AtomicBoolean();
private static CountDownLatch latch = null;
public static void start(final int defaultCloseOperation) {
val alreadyRequested = startRequested.getAndSet(true);
if(!alreadyRequested) {
latch = new CountDownLatch(1);
SwingUtilities.invokeLater(()->new XrayUi(defaultCloseOperation));
}
}
public static void updateModel(final Consumer<XrayModel> consumer) {
if(startRequested.get()) {
SwingUtilities.invokeLater(()->{
consumer.accept(INSTANCE.xrayModel);
((DefaultTreeModel)INSTANCE.tree.getModel()).reload();
_SwingUtil.setTreeExpandedState(INSTANCE.tree, true);
});
}
}
public static void waitForShutdown() {
if(latch==null
|| INSTANCE == null) {
return;
}
System.err.println("Waiting for XrayUi to shut down...");
try {
latch.await();
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean isXrayEnabled() {
return startRequested.get();
}
protected XrayUi(final int defaultCloseOperation) {
//create the root node
root = new DefaultMutableTreeNode("X-ray");
xrayModel = new XrayModelSimple(root);
//create the tree by passing in the root node
tree = new JTree(root);
tree.setShowsRootHandles(false);
val detailPanel = layoutUIAndGetDetailPanel(tree);
tree.getSelectionModel().addTreeSelectionListener((final TreeSelectionEvent e) -> {
val selPath = e.getNewLeadSelectionPath();
if(selPath==null) {
return; // ignore event
}
val selectedNode = (DefaultMutableTreeNode) selPath.getLastPathComponent();
val userObject = selectedNode.getUserObject();
//detailPanel.removeAll();
if(userObject instanceof XrayDataModel) {
((XrayDataModel) userObject).render(detailPanel);
} else {
val infoPanel = new JPanel();
infoPanel.add(new JLabel("Details"));
detailPanel.setViewportView(infoPanel);
}
detailPanel.revalidate();
detailPanel.repaint();
//System.out.println("selected: " + selectedNode.toString());
});
val popupMenu = new JPopupMenu();
val clearThreadsAction = popupMenu.add(new JMenuItem("Clear Threads"));
clearThreadsAction.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
doClearThreads();
}
});
val callStackMergeAction = popupMenu.add(new JMenuItem("Merge Logged Call-Stack"));
callStackMergeAction.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
doMergeCallStacksOnSelectedNodes();
}
});
val deleteAction = popupMenu.add(new JMenuItem("Delete"));
deleteAction.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
doRemoveSelectedNodes();
}
});
tree.setCellRenderer(new XrayTreeCellRenderer(
(DefaultTreeCellRenderer) tree.getCellRenderer(),
iconCache));
tree.addMouseListener(new MouseListener() {
@Override public void mouseReleased(final MouseEvent e) {}
@Override public void mousePressed(final MouseEvent e) {}
@Override public void mouseExited(final MouseEvent e) {}
@Override public void mouseEntered(final MouseEvent e) {}
@Override
public void mouseClicked(final MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
tree.addKeyListener(new KeyListener() {
@Override public void keyReleased(final KeyEvent e) {}
@Override public void keyTyped(final KeyEvent e) {}
@Override
public void keyPressed(final KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_DELETE) {
doRemoveSelectedNodes();
return;
}
if(e.getKeyCode() == KeyEvent.VK_F5) {
doClearThreads();
return;
}
}
});
// report key bindings to the UI
{
val root = xrayModel.getRootNode();
val env = xrayModel.addDataNode(root,
new XrayDataModel.KeyValue("isis-xray-keys", "X-ray Keybindings", Stickiness.CANNOT_DELETE_NODE));
env.getData().put("F5", "Clear Threads");
env.getData().put("DELETE", "Delete Selected Nodes");
}
this.setDefaultCloseOperation(defaultCloseOperation);
this.setTitle("X-ray Viewer (Apache Isis™)");
this.pack();
this.setSize(800, 600);
this.setLocationRelativeTo(null);
this.setVisible(true);
INSTANCE = this;
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
latch.countDown();
}
});
}
private Stream<DefaultMutableTreeNode> streamSelectedNodes() {
return Can.ofArray(tree.getSelectionModel().getSelectionPaths())
.stream()
.map(path->(DefaultMutableTreeNode)path.getLastPathComponent());
}
private Stream<DefaultMutableTreeNode> streamChildrenOf(final DefaultMutableTreeNode node) {
return IntStream.range(0, node.getChildCount())
.mapToObj(root::getChildAt)
.map(DefaultMutableTreeNode.class::cast);
}
private Optional<HasIdAndLabel> extractUserObject(final DefaultMutableTreeNode node) {
return _Casts.castTo(HasIdAndLabel.class, node.getUserObject());
}
private boolean canRemoveNode(final DefaultMutableTreeNode node) {
if(node.getParent()==null) {
return false; // don't remove root
}
return extractUserObject(node)
.map(HasIdAndLabel::getStickiness)
.map(stickiness->stickiness.isCanDeleteNode())
.orElse(true); // default: allow removal
}
private void removeNode(final DefaultMutableTreeNode nodeToBeRemoved) {
if(canRemoveNode(nodeToBeRemoved)) {
((DefaultTreeModel)tree.getModel()).removeNodeFromParent(nodeToBeRemoved);
xrayModel.remove(nodeToBeRemoved);
}
}
private void doClearThreads(){
val root = (DefaultMutableTreeNode) tree.getModel().getRoot();
val threadNodes = streamChildrenOf(root)
.filter(node->extractUserObject(node)
.map(HasIdAndLabel::getId)
.map(id->id.startsWith("thread-"))
.orElse(false))
.collect(Can.toCan()); // collect into can, before processing (otherwise concurrent modification)
threadNodes.forEach(this::removeNode);
}
private void doRemoveSelectedNodes() {
streamSelectedNodes().forEach(this::removeNode);
}
private void doMergeCallStacksOnSelectedNodes() {
val logEntries = streamSelectedNodes()
.filter(node->node.getUserObject() instanceof XrayDataModel.LogEntry)
.map(node->(XrayDataModel.LogEntry)node.getUserObject())
.collect(Can.toCan());
if(!logEntries.getCardinality().isMultiple()) {
System.err.println("must select at least 2 logs for merging");
return;
}
val callStackMerger = new _CallStackMerger(logEntries);
JFrame frame = new JFrame("Merged Log View");
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setOpaque(true);
// val canvas = _SwingUtil.canvas(g->{
// g.setColor(Color.GRAY);
// g.fill(g.getClip());
// callStackMerger.render(g);
// });
// JScrollPane scroller = new JScrollPane(canvas);
//Create a text area.
JTextArea textArea = new JTextArea("no content");
textArea.setFont(new Font("Serif", Font.PLAIN, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scroller = new JScrollPane(textArea);
callStackMerger.render(textArea);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.setPreferredSize(new Dimension(800, 600));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setResizable(true);
frame.setVisible(true);
}
private JScrollPane layoutUIAndGetDetailPanel(final JTree masterTree) {
JScrollPane masterScrollPane = new JScrollPane(masterTree);
JScrollPane detailScrollPane = new JScrollPane();
//Create a split pane with the two scroll panes in it.
val splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
masterScrollPane, detailScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(260);
//Provide minimum sizes for the two components in the split pane.
Dimension minimumSize = new Dimension(100, 50);
masterScrollPane.setMinimumSize(minimumSize);
detailScrollPane.setMinimumSize(minimumSize);
detailScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
detailScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
detailScrollPane.getVerticalScrollBar().setUnitIncrement(8);
//Provide a preferred size for the split pane.
splitPane.setPreferredSize(new Dimension(800, 600));
getContentPane().add(splitPane);
return detailScrollPane;
}
// -- CUSTOM TREE NODE ICONS
private final Map<String, Optional<ImageIcon>> iconCache = _Maps.newConcurrentHashMap();
@RequiredArgsConstructor
class XrayTreeCellRenderer implements TreeCellRenderer {
final DefaultTreeCellRenderer delegate;
final Map<String, Optional<ImageIcon>> iconCache;
@Override
public Component getTreeCellRendererComponent(
final JTree tree,
final Object value,
final boolean selected,
final boolean expanded,
final boolean leaf,
final int row,
final boolean hasFocus) {
val label = (DefaultTreeCellRenderer)
delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
Object o = ((DefaultMutableTreeNode) value).getUserObject();
if (o instanceof XrayDataModel) {
XrayDataModel dataModel = (XrayDataModel) o;
val imageIcon = iconCache.computeIfAbsent(dataModel.getIconResource(), iconResource->{
URL imageUrl = getClass().getResource(dataModel.getIconResource());
return Optional.ofNullable(imageUrl)
.map(ImageIcon::new);
});
imageIcon.ifPresent(label::setIcon);
label.setText(dataModel.getLabel());
}
return label;
}
}
}
| true |
24f9a159b59fcce16e3306ecbb32c07f50336296 | Java | akshayTesting/Java-Logical-Programming | /Programming/src/Array1D/LargestArray.java | UTF-8 | 315 | 3.28125 | 3 | [] | no_license | package Array1D;
public class LargestArray {
public static void main(String[] args)
{
int a[]= {1,2,-9,5,6,3,7,9,3};
int max=a[0];
for(int i=0;i<a.length-1;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
System.out.println("maximum number in the given array is "+max);
}
}
| true |
0a75e011df4b4ac0f8b1098d897fed0771a707e1 | Java | suyash-capiot/operations | /src/main/java/com/coxandkings/travel/operations/resource/user/CurrentCompany.java | UTF-8 | 3,687 | 2.203125 | 2 | [] | no_license |
package com.coxandkings.travel.operations.resource.user;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.io.Serializable;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"_id",
"name",
"goc",
"gc"
})
public class CurrentCompany implements Serializable
{
@JsonProperty("_id")
private String id;
@JsonProperty("name")
private String name;
@JsonProperty("goc")
private Goc goc;
@JsonProperty("gc")
private Gc gc;
private final static long serialVersionUID = -1193665725406117521L;
/**
* No args constructor for use in serialization
*
*/
public CurrentCompany() {
}
/**
*
* @param name
* @param goc
* @param id
* @param gc
*/
public CurrentCompany(String id, String name, Goc goc, Gc gc) {
super();
this.id = id;
this.name = name;
this.goc = goc;
this.gc = gc;
}
@JsonProperty("_id")
public String getId() {
return id;
}
@JsonProperty("_id")
public void setId(String id) {
this.id = id;
}
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
@JsonProperty("goc")
public Goc getGoc() {
return goc;
}
@JsonProperty("goc")
public void setGoc(Goc goc) {
this.goc = goc;
}
@JsonProperty("gc")
public Gc getGc() {
return gc;
}
@JsonProperty("gc")
public void setGc(Gc gc) {
this.gc = gc;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(CurrentCompany.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');
sb.append("id");
sb.append('=');
sb.append(((this.id == null)?"<null>":this.id));
sb.append(',');
sb.append("name");
sb.append('=');
sb.append(((this.name == null)?"<null>":this.name));
sb.append(',');
sb.append("goc");
sb.append('=');
sb.append(((this.goc == null)?"<null>":this.goc));
sb.append(',');
sb.append("gc");
sb.append('=');
sb.append(((this.gc == null)?"<null>":this.gc));
sb.append(',');
if (sb.charAt((sb.length()- 1)) == ',') {
sb.setCharAt((sb.length()- 1), ']');
} else {
sb.append(']');
}
return sb.toString();
}
@Override
public int hashCode() {
int result = 1;
result = ((result* 31)+((this.name == null)? 0 :this.name.hashCode()));
result = ((result* 31)+((this.goc == null)? 0 :this.goc.hashCode()));
result = ((result* 31)+((this.id == null)? 0 :this.id.hashCode()));
result = ((result* 31)+((this.gc == null)? 0 :this.gc.hashCode()));
return result;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof CurrentCompany) == false) {
return false;
}
CurrentCompany rhs = ((CurrentCompany) other);
return (((((this.name == rhs.name)||((this.name!= null)&&this.name.equals(rhs.name)))&&((this.goc == rhs.goc)||((this.goc!= null)&&this.goc.equals(rhs.goc))))&&((this.id == rhs.id)||((this.id!= null)&&this.id.equals(rhs.id))))&&((this.gc == rhs.gc)||((this.gc!= null)&&this.gc.equals(rhs.gc))));
}
}
| true |
65642e19369e96b29037047c165e149b8c9cdeed | Java | Alex-astakhov/Work_project_Java | /src/main/java/dataModels/apiModels/v1/errorModels/errorBlocks/ErrorDataWithBlocks.java | UTF-8 | 625 | 2.09375 | 2 | [] | no_license | package dataModels.apiModels.v1.errorModels.errorBlocks;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import dataModels.apiModels.v1.errorModels.ErrorData;
import java.util.List;
public class ErrorDataWithBlocks<T extends ErrorParams> extends ErrorData {
@SerializedName("errorBlocks")
@Expose
public List<ErrorBlock<T>> errorBlocks = null;
public class ErrorBlock<T> {
@SerializedName("notValidBlock")
@Expose
public Integer notValidBlock;
@SerializedName("dataParams")
@Expose
public T dataParams;
}
}
| true |
88048aec0f363c36a90b6a86142aac750659d63e | Java | light-max/mobileoffice | /src/main/java/com/lfq/mobileoffice/controller/sysadmin/AdminsController.java | UTF-8 | 3,473 | 2.109375 | 2 | [] | no_license | package com.lfq.mobileoffice.controller.sysadmin;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lfq.mobileoffice.constant.AssertException;
import com.lfq.mobileoffice.model.data.Pager;
import com.lfq.mobileoffice.model.entity.Admin;
import com.lfq.mobileoffice.service.AdminService;
import com.lfq.mobileoffice.util.UseDefaultSuccessResponse;
import com.lfq.mobileoffice.util.ump.ViewModelParameter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 管理员账号管理控制器
*
* @author 李凤强
*/
@Controller
public class AdminsController {
@Resource
AdminService adminService;
/**
* 分页查询所有管理员
*
* @param currentPage 指定查询的页码,不指定时查询第一页
*/
@GetMapping({"/sys/admin/list", "/sys/admin/list/{currentPage}"})
@ViewModelParameter(key = "view", value = "list")
public String list(Model model, @PathVariable(value = "currentPage", required = false) Long currentPage) {
Page<Admin> page = adminService.page(new Page<>(currentPage == null ? 1 : currentPage, 10));
List<Admin> admins = page.getRecords();
Pager pager = new Pager(page, "/sys/admin/list");
model.addAttribute("pager", pager);
model.addAttribute("admins", admins);
return "/sysadmin/admin/list";
}
/**
* 添加一个管理员账号
*/
@PostMapping("/sys/admin")
@ResponseBody
@UseDefaultSuccessResponse
public void add(Admin admin) {
adminService.addAdmin(admin);
}
/**
* 根据id删除管理员账号
*/
@DeleteMapping("/sys/admin/{id}")
@ResponseBody
@UseDefaultSuccessResponse
public void delete(@PathVariable("id") Integer id) {
adminService.removeById(id);
}
/**
* 根据id跳转到修改管理员账号的界面
*/
@GetMapping("/sys/admin/{id}")
public String toUpdatePage(Model model, @PathVariable("id") Integer id) {
model.addAttribute("admin", adminService.getById(id));
return "/sysadmin/admin/update";
}
/**
* 修改管理员账号信息的请求
*/
@PutMapping("/sys/admin/{id}")
public String update(Model model, Admin admin) {
try {
adminService.updateInfo(admin);
return "redirect:/sysadmin/admin/success";
} catch (AssertException e) {
model.addAttribute("admin", admin);
model.addAttribute("error_info", e.getMessage());
return "/sysadmin/admin/update";
}
}
/**
* 提交修改管理员密码的请求
*
* @param pwd 表单中应该包含三个pwd字段<br>
* pwd[0]: 旧密码<br>
* pwd[1]: 新密码<br>
* pwd[2]: 确认密码<br>
*/
@PostMapping("/sys/admin/pwd/{id}")
public String pwd(Model model, @PathVariable("id") Integer id, String[] pwd) {
try {
adminService.setPwd(id, pwd);
return "redirect:/sys/update_admin_success";
} catch (AssertException e) {
model.addAttribute("admin", adminService.getById(id));
model.addAttribute("error_pwd", e.getMessage());
model.addAttribute("pwd", pwd);
return "/sysadmin/admin/update";
}
}
}
| true |
1ce0dae8a666b5769fc9f0eb8a430d02c25af21d | Java | jpedraza/uPortal | /uportal-war/src/test/java/org/jasig/portal/jgroups/protocols/JdbcPingDaoTest.java | UTF-8 | 4,940 | 2 | 2 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"GPL-2.0-only",
"xpp",
"CC-BY-3.0",
"EPL-1.0",
"Classpath-exception-2.0",
"CPL-1.0",
"CDDL-1.0",
"MIT",
"LGPL-2.1-only",
"MPL-2.0",
"MPL-1.1",
"LicenseRef-scancode-unknown-license-reference",
... | permissive | /**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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.jasig.portal.jgroups.protocols;
import static junit.framework.Assert.assertEquals;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import org.jasig.portal.concurrency.CallableWithoutResult;
import org.jasig.portal.test.BasePortalJpaDaoTest;
import org.jgroups.Address;
import org.jgroups.PhysicalAddress;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.UUID;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:jpaPortalTestApplicationContext.xml")
public class JdbcPingDaoTest extends BasePortalJpaDaoTest {
@Autowired
private PingDao pingDao;
@Test
public void testPingLifecycle() throws UnknownHostException {
final String cluster = "cluster";
final UUID uuid = UUID.randomUUID();
final IpAddress ipAddress = new IpAddress("127.0.0.1", 1337);
final IpAddress ipAddress2 = new IpAddress("127.0.0.2", 7331);
//Doesn't exist
this.execute(new CallableWithoutResult() {
@Override
protected void callWithoutResult() {
final Map<Address, PhysicalAddress> addresses = pingDao.getAddresses(cluster);
assertEquals(0, addresses.size());
}
});
//Delete nothing
this.execute(new CallableWithoutResult() {
@Override
protected void callWithoutResult() {
final Collection<Address> addresses = Arrays.<Address>asList(ipAddress, ipAddress2);
pingDao.purgeOtherAddresses(cluster, addresses);
}
});
//Create
this.execute(new CallableWithoutResult() {
@Override
protected void callWithoutResult() {
pingDao.addAddress(cluster, uuid, ipAddress);
}
});
//verify
this.execute(new CallableWithoutResult() {
@Override
protected void callWithoutResult() {
final Map<Address, PhysicalAddress> addresses = pingDao.getAddresses(cluster);
assertEquals(1, addresses.size());
final Entry<Address, PhysicalAddress> entry = addresses.entrySet().iterator().next();
assertEquals(uuid, entry.getKey());
assertEquals(ipAddress, entry.getValue());
}
});
//Update
this.execute(new CallableWithoutResult() {
@Override
protected void callWithoutResult() {
pingDao.addAddress(cluster, uuid, ipAddress2);
}
});
//verify
this.execute(new CallableWithoutResult() {
@Override
protected void callWithoutResult() {
final Map<Address, PhysicalAddress> addresses = pingDao.getAddresses(cluster);
assertEquals(1, addresses.size());
final Entry<Address, PhysicalAddress> entry = addresses.entrySet().iterator().next();
assertEquals(uuid, entry.getKey());
assertEquals(ipAddress2, entry.getValue());
}
});
//Delete
this.execute(new CallableWithoutResult() {
@Override
protected void callWithoutResult() {
final Collection<Address> addresses = Arrays.<Address>asList(ipAddress);
pingDao.purgeOtherAddresses(cluster, addresses);
}
});
//Doesn't exist
this.execute(new CallableWithoutResult() {
@Override
protected void callWithoutResult() {
final Map<Address, PhysicalAddress> addresses = pingDao.getAddresses(cluster);
assertEquals(0, addresses.size());
}
});
}
} | true |
678e5f2b92f8fdd43599764f07ac8f05e8474c28 | Java | trabbis/test3 | /src/main/java/com/telus/mediation/usage/internal/model/SearchRawUsageDetailVO.java | UTF-8 | 840 | 1.84375 | 2 | [] | no_license | package com.telus.mediation.usage.internal.model;
import java.util.Date;
public class SearchRawUsageDetailVO extends ValueObject {
private Long dataServiceEventId;
private Date dataServiceEventTime;
private String dataServiceEventTypeCd;
public Long getDataServiceEventId() {
return dataServiceEventId;
}
public void setDataServiceEventId(Long dataServiceEventId) {
this.dataServiceEventId = dataServiceEventId;
}
public Date getDataServiceEventTime() {
return dataServiceEventTime;
}
public void setDataServiceEventTime(Date dataServiceEventTime) {
this.dataServiceEventTime = dataServiceEventTime;
}
public String getDataServiceEventTypeCd() {
return dataServiceEventTypeCd;
}
public void setDataServiceEventTypeCd(String dataServiceEventTypeCd) {
this.dataServiceEventTypeCd = dataServiceEventTypeCd;
}
}
| true |
eba01e8edba58d7edd470526a9cd8ac4c896f8b3 | Java | jbosstools/jbosstools-quarkus | /tests/org.jboss.tools.quarkus.lsp4e.test/projects/maven/microprofile-graphql/src/main/java/io/openliberty/graphql/sample/PrecipType.java | UTF-8 | 817 | 2.171875 | 2 | [
"Apache-2.0"
] | permissive | /******************************************************************************
* Copyright (c) 2019 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package io.openliberty.graphql.sample;
public enum PrecipType {
RAIN,
SNOW,
SLEET;
static PrecipType fromTempF(double tempF) {
if (tempF > 40) {
return RAIN;
}
if (tempF > 35) {
return SLEET;
}
return SNOW;
}
}
| true |
b79e4d5cedee0c92e4004e1abffedeb182798d1e | Java | meghajagadale99/TestMaximum | /src/main/java/com/bridgelabz/FindMax.java | UTF-8 | 899 | 3.53125 | 4 | [] | no_license | package com.bridgelabz;
import java.util.Arrays;
public class FindMax<T extends Comparable<T>> {
T[] elements;
public FindMax(T[] elements) {
this.elements = elements;
}
public static <T extends Comparable<T>> T maxOfValues(T[] elements) {
Arrays.sort(elements);
int length = elements.length;
T max = elements[length - 1];
System.out.printf("Maximum value of three is %s : ", max);
return max;
}
public static void main(String[] args) {
System.out.println("Welcome to the program to find maximum value using generics");
Integer[] intMax ={ 30, 98, 28, 23 ,45,};
maxOfValues(intMax);
Float[] floatMax = {4.7f, 12.4f, 53.2f, 3.67f, 23.5f};
maxOfValues(floatMax);
String[] stringMax = {"megha", "neha", "pranali", "alka", "prakash"};
maxOfValues(stringMax);
}
} | true |
84e7ebec73fbec96ba3d2609352491ef46d2cbe6 | Java | BidsTeam/LandOfDKL_project | /src/main/java/DAO/logic/EffectLogic.java | UTF-8 | 2,025 | 2.828125 | 3 | [] | no_license | package DAO.logic;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
@Entity
@Table(name="effect")
public class EffectLogic {
private int id;
@NotNull(message = "Название эффекта должно быть задано")
private String name;
@NotNull(message = "Описание эффекта не должно быть пустым")
private String description;
private int value;
private int duration;
public EffectLogic() {}
public EffectLogic(String name, String description, int value) {
this.name = name;
this.description = description;
this.value = value;
}
@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
@Column(name = "id", unique = true)
public int getId() {
return id;
}
public void setId(int id) { this.id = id; }
@Column(name = "name", unique = true)
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Column(name = "description")
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
@Column(name = "value")
public int getValue() { return value; }
public void setValue(int value) { this.value = value; }
@Column(name = "duration")
public int getDuration() { return duration; }
public void setDuration(int duration) { this.duration = duration; }
public Map<String, Object> putAllEffectInformation(){
Map<String,Object> result = new HashMap<>();
result.put("id", this.getId());
result.put("name", this.getName());
result.put("description", this.getDescription());
result.put("value", this.getValue());
result.put("duration", this.getDuration());
return result;
}
}
| true |
53d49fd17ebb2adf5e167a1a07c0fa0cde3d989a | Java | hazeluff/canucks-discord-bot | /src/main/java/com/hazeluff/nhl/game/data/LiveDataException.java | UTF-8 | 308 | 1.867188 | 2 | [] | no_license | package com.hazeluff.nhl.game.data;
public class LiveDataException extends Throwable {
private static final long serialVersionUID = 2076725347170125055L;
public LiveDataException(String message) {
super(message);
}
public LiveDataException(String message, Exception e) {
super(message, e);
}
}
| true |
0369745fa2fa9b0de823401f5bf1d1661f40ed38 | Java | NathanSalez/allSafe | /src/main/java/dao/impl/jdbc/UserJdbcDao.java | UTF-8 | 6,946 | 2.515625 | 3 | [] | no_license | package dao.impl.jdbc;
import dao.DAOException;
import dao.DAOFactory;
import dao.UserDao;
import model.Role;
import model.User;
import utils.DaoUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.TreeSet;
/**
* @author Nathan Salez
*/
public class UserJdbcDao extends JdbcDAO<User> implements UserDao {
private DAOFactory daoFactory;
private static final String SELECT_USER = "SELECT * FROM users WHERE pseudo = ?";
private static final String INSERT_USER = "INSERT INTO users(pseudo,password,date_inscription,role) values(?,?,NOW(),'SIMPLE')";
private static final String CONNECT_USER = "UPDATE users SET logged = 1 WHERE pseudo = ?";
private static final String DISCONNECT_USER = "UPDATE users SET logged = 0 WHERE pseudo = ?";
private static final String UPDATE_USER_ROLE = "UPDATE users set role = ? where pseudo = ?";
private static final String SELECT_ALL_USERS = "SELECT * FROM users";
private static final String COUNT_LOGGED_USERS = "SELECT COUNT(*) AS LOGGED_USERS FROM users where logged = 1";
private static final String DELETE_USER = "DELETE FROM users WHERE pseudo = ?";
public UserJdbcDao(DAOFactory daoFactory) {
this.daoFactory = daoFactory;
mapper = new RowMapper<User>() {
@Override
public User map(ResultSet rs) throws SQLException {
User u = new User();
u.setId(rs.getLong("id"));
u.setPseudo(rs.getString("pseudo"));
u.setPassword(rs.getString("password"));
u.setRole(Role.getRole((String) rs.getObject("role")));
u.setRegisterDate(rs.getDate("date_inscription"));
u.setLogged( rs.getBoolean("logged"));
return u;
}
};
}
@Override
public void create(User user) throws DAOException {
if( user == null)
throw new NullPointerException("user must be not null.");
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet generatedIdSet;
try {
connection = daoFactory.getConnection();
pstmt = DaoUtils.buildPreparedStatement(connection, INSERT_USER, true,
user.getPseudo(), user.getPassword());
int status = pstmt.executeUpdate();
if (status == 0)
throw new DAOException("Failed to create a new user in database : no line inserted.");
generatedIdSet = pstmt.getGeneratedKeys();
if (generatedIdSet.next())
user.setId(generatedIdSet.getLong(1));
else
throw new DAOException("Failed to create a new user in database : no id generated.");
} catch (SQLException e) {
throw new DAOException(e);
} finally {
DaoUtils.closeDatabaseConnexion(pstmt, connection);
}
}
@Override
public User find(String pseudo) throws DAOException {
if( pseudo == null)
return null;
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet resultSet = null;
User user = null;
try {
connection = daoFactory.getConnection();
pstmt = DaoUtils.buildPreparedStatement(connection, SELECT_USER, false, pseudo);
resultSet = pstmt.executeQuery();
if (resultSet.next()) {
user = mapper.map(resultSet);
}
} catch (SQLException e) {
throw new DAOException(e);
} finally {
DaoUtils.closeDatabaseConnexion(resultSet, pstmt, connection);
}
return user;
}
@Override
public void updateState(String pseudo, boolean connect) throws DAOException {
String request = connect ? CONNECT_USER : DISCONNECT_USER;
updateUser(request,pseudo);
}
@Override
public void updateRole(String pseudo, Role newRole) throws DAOException {
updateUser(UPDATE_USER_ROLE,newRole.name(),pseudo);
}
private void updateUser(String request, Object... args)
{
Connection connection = null;
PreparedStatement pstmt = null;
try {
connection = daoFactory.getConnection();
pstmt = DaoUtils.buildPreparedStatement(connection, request, false, args);
int nbAffectedLines = pstmt.executeUpdate();
if( nbAffectedLines == 0 )
{
throw new DAOException("User not found.");
} else if( nbAffectedLines != 1)
{
throw new DAOException("User is not unique.");
}
} catch (SQLException e) {
throw new DAOException(e);
} finally {
DaoUtils.closeDatabaseConnexion(pstmt, connection);
}
}
@Override
public Long countLoggedUsers() throws DAOException {
Connection connection = null;
ResultSet result = null;
Long nbLoggedUsers;
try {
connection = daoFactory.getConnection();
result = DaoUtils.executeSelectStatement(connection, COUNT_LOGGED_USERS);
if( result.next())
nbLoggedUsers = result.getLong("LOGGED_USERS");
else
throw new DAOException("No result found in users table.");
} catch (SQLException e) {
throw new DAOException(e);
} finally {
DaoUtils.closeDatabaseConnexion(result, connection);
}
return nbLoggedUsers;
}
@Override
public Collection<User> findAll() throws DAOException {
Connection connection = null;
ResultSet results = null;
TreeSet<User> collection = new TreeSet<>();
try {
connection = daoFactory.getConnection();
results = DaoUtils.executeSelectStatement(connection, SELECT_ALL_USERS);
while (results.next()) {
collection.add(mapper.map(results));
}
} catch (SQLException e) {
throw new DAOException(e);
} finally {
DaoUtils.closeDatabaseConnexion(results, connection);
}
return collection;
}
@Override
public void delete(String pseudo) throws DAOException {
Connection connection = null;
PreparedStatement pstmt = null;
try {
connection = daoFactory.getConnection();
pstmt = DaoUtils.buildPreparedStatement(connection, DELETE_USER, false, pseudo);
if( pstmt.executeUpdate() != 1 )
{
throw new DAOException("User " + pseudo + " not found.");
}
} catch (SQLException e) {
throw new DAOException(e);
} finally {
DaoUtils.closeDatabaseConnexion(pstmt, connection);
}
}
}
| true |
2b5c168e056b5bb97ef66241cab2d78d6cbfadb1 | Java | qcamei/scm | /java/com/genscript/gsscm/accounting/web/InitialServlet.java | UTF-8 | 1,516 | 2.296875 | 2 | [] | no_license | package com.genscript.gsscm.accounting.web;
import java.util.Timer;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.genscript.gsscm.accounting.dao.ArInvoiceDao;
import com.genscript.gsscm.accounting.service.OverDueService;
/**
* 定时执行的程序
* @author Administrator
*
*/
@Component("initialServlet")
public class InitialServlet extends HttpServlet{
private Timer timer = null;
// @Override
// public void contextDestroyed(ServletContextEvent event) {
// timer = new Timer(true);
// timer.schedule(new OverDueService(), 0,
// 60 * 60 * 1000);// 每小时执行一次
// }
//
// @Override
// public void contextInitialized(ServletContextEvent event) {
// timer.cancel();
// event.getServletContext().log("定时器销毁");
// System.out.println("销毁定时器...");
// }
@Override
public void destroy() {
timer.cancel();
System.out.println("销毁定时器...");
}
@Override
public void init(ServletConfig config) throws ServletException {
timer = new Timer(true);
ServletContext context = config.getServletContext();
timer.schedule(new OverDueService(context),1*60*1000,
24 * 60 * 60 * 1000);// 每24小时执行一次,5分钟后执行
}
}
| true |
fcfa6eefdcda5db0d248bd157ec1653872ee6856 | Java | stjordanis/artifactory-snyk-security-plugin | /snyk-sdk/src/main/java/io/snyk/sdk/api/v1/SnykHttpRequestBuilder.java | UTF-8 | 1,869 | 2.375 | 2 | [
"Apache-2.0"
] | permissive | package io.snyk.sdk.api.v1;
import io.snyk.sdk.SnykConfig;
import javax.annotation.Nonnull;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpRequest;
import java.util.HashMap;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.nio.charset.StandardCharsets.UTF_8;
public class SnykHttpRequestBuilder {
private final SnykConfig config;
private final HashMap<String, String> queryParams = new HashMap<>();
private String path = "";
private SnykHttpRequestBuilder(@Nonnull SnykConfig config) {
this.config = config;
}
public static SnykHttpRequestBuilder create(@Nonnull SnykConfig config) {
return new SnykHttpRequestBuilder(config);
}
public SnykHttpRequestBuilder withPath(@Nonnull String path) {
this.path = path;
return this;
}
public SnykHttpRequestBuilder withQueryParam(String key, String value) {
return withQueryParam(key, Optional.ofNullable(value));
}
public SnykHttpRequestBuilder withQueryParam(String key, Optional<String> value) {
value.ifPresent(v -> this.queryParams.put(key, v));
return this;
}
public HttpRequest build() {
return HttpRequest.newBuilder()
.GET()
.uri(buildURI())
.timeout(config.timeout)
.setHeader("Authorization", String.format("token %s", config.token))
.setHeader("User-Agent", config.userAgent)
.build();
}
private URI buildURI() {
String apiUrl = config.baseUrl + path;
String queryString = this.queryParams
.entrySet()
.stream()
.map((entry) -> String.format(
"%s=%s",
URLEncoder.encode(entry.getKey(), UTF_8),
URLEncoder.encode(entry.getValue(), UTF_8)))
.collect(Collectors.joining("&"));
if (!queryString.isBlank()) {
apiUrl += "?" + queryString;
}
return URI.create(apiUrl);
}
}
| true |
446d17c41e61f2fbaaab6673a1c2344ff065c7e3 | Java | lochuynh211/ePro-Toeic | /src/com/mZone/epro/client/data/BookItemServer.java | UTF-8 | 2,631 | 2.4375 | 2 | [] | no_license | package com.mZone.epro.client.data;
public class BookItemServer extends BookItem {
public static final int FREE = 0;
public static final int PAY_REQUIRED = 1;
private int localID;
private float bookPrice;
private String urlImage;
private String urlDownload;
private int paymentRequire;
private String updateDate;
private float scale;
public BookItemServer() {
// TODO Auto-generated constructor stub
}
public BookItemServer(int bookID, String bookName,
String bookAuthor, int bookType) {
super(bookID, BookItem.SERVER, bookName, bookAuthor, bookType);
// TODO Auto-generated constructor stub
}
public BookItemServer(int bookID, String bookName,
String bookAuthor, int bookType, float bookPrice, String urlImage,
String urlDownload, int paymentRequire) {
super(bookID, BookItem.SERVER, bookName, bookAuthor, bookType);
// TODO Auto-generated constructor stub
this.bookPrice = bookPrice;
this.urlImage = urlImage;
this.urlDownload = urlDownload;
this.paymentRequire = paymentRequire;
scale = 1.0f;
}
public float getBookPrice() {
return bookPrice;
}
public void setBookPrice(float bookPrice) {
this.bookPrice = bookPrice;
}
public String getUrlImage() {
return urlImage;
}
public void setUrlImage(String urlImage) {
this.urlImage = urlImage;
}
public String getUrlDownload() {
return urlDownload;
}
public void setUrlDownload(String urlDownload) {
this.urlDownload = urlDownload;
}
public int getPaymentRequire() {
return paymentRequire;
}
public void setPaymentRequire(int paymentRequire) {
this.paymentRequire = paymentRequire;
}
public String getUpdateDate() {
return updateDate;
}
public void setUpdateDate(String updateDate) {
this.updateDate = updateDate;
}
public int getLocalID() {
return localID;
}
public void setLocalID(int localID) {
this.localID = localID;
}
public float getScale() {
return scale;
}
public void setScale(float scale) {
if (this.scale == 1){
this.scale = scale;
}
else{
if(scale > this.scale)
this.scale = scale;
}
}
public void increaseScale(){
scale = scale + (1-scale)*0.05f;
if (scale > 1) scale = 1;
}
@Override
public String toString() {
return "BookItemServer [localID=" + localID + ", bookPrice="
+ bookPrice + ", urlImage=" + urlImage + ", urlDownload="
+ urlDownload + ", paymentRequire=" + paymentRequire
+ ", updateDate=" + updateDate + ", scale=" + scale
+ ", bookID=" + bookID + ", locationType=" + locationType
+ ", bookName=" + bookName + ", bookAuthor=" + bookAuthor
+ ", bookType=" + bookType + "]";
}
}
| true |
fd1f203fa2fb9d702060637664bbf29cd0fc0110 | Java | fengyongshe/distributed-system-example | /helix-example/src/main/java/com/fys/helix/rsyncfile/SetupCluster.java | UTF-8 | 2,395 | 2.28125 | 2 | [] | no_license | package com.fys.helix.rsyncfile;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.manager.zk.ZNRecordSerializer;
import org.apache.helix.manager.zk.ZkClient;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.tools.StateModelConfigGenerator;
public class SetupCluster {
public static final String DEFAULT_CLUSTER_NAME = "file-store-test";
public static final String DEFAULT_RESOURCE_NAME = "repository";
public static final int DEFAULT_PARTITION_NUMBER = 1;
public static final String DEFAULT_STATE_MODEL = "MasterSlave";
public static void main(String[] args) {
if (args.length < 2) {
System.err
.println("USAGE: java SetupCluster zookeeperAddress(e.g. localhost:2181) numberOfNodes");
System.exit(1);
}
final String zkAddr = args[0];
final int numNodes = Integer.parseInt(args[1]);
final String clusterName = DEFAULT_CLUSTER_NAME;
ZkClient zkclient = null;
try {
zkclient =
new ZkClient(zkAddr, ZkClient.DEFAULT_SESSION_TIMEOUT,
ZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
ZKHelixAdmin admin = new ZKHelixAdmin(zkclient);
// add cluster
admin.addCluster(clusterName, true);
// add state model definition
StateModelConfigGenerator generator = new StateModelConfigGenerator();
admin.addStateModelDef(clusterName, DEFAULT_STATE_MODEL,
new StateModelDefinition(generator.generateConfigForOnlineOffline()));
// addNodes
for (int i = 0; i < numNodes; i++) {
String port = "" + (12001 + i);
String serverId = "localhost_" + port;
InstanceConfig config = new InstanceConfig(serverId);
config.setHostName("localhost");
config.setPort(port);
config.setInstanceEnabled(true);
admin.addInstance(clusterName, config);
}
// add resource "repository" which has 1 partition
String resourceName = DEFAULT_RESOURCE_NAME;
admin.addResource(clusterName, resourceName, DEFAULT_PARTITION_NUMBER, DEFAULT_STATE_MODEL,
IdealState.RebalanceMode.SEMI_AUTO.toString());
admin.rebalance(clusterName, resourceName, 1);
} finally {
if (zkclient != null) {
zkclient.close();
}
}
}
}
| true |
a10438df17813e05ddd320e81400a6d00444c6ef | Java | topcoder-platform/tc-website | /src/main/com/topcoder/web/privatelabel/controller/request/BaseCredentialReminder.java | UTF-8 | 4,089 | 1.984375 | 2 | [] | no_license | package com.topcoder.web.privatelabel.controller.request;
import com.topcoder.security.admin.PrincipalMgrRemote;
import com.topcoder.shared.dataAccess.Request;
import com.topcoder.shared.dataAccess.resultSet.ResultSetContainer;
import com.topcoder.shared.util.EmailEngine;
import com.topcoder.shared.util.TCSEmailMessage;
import com.topcoder.web.common.NavigationException;
import com.topcoder.web.common.StringUtils;
import com.topcoder.web.common.TCWebException;
import com.topcoder.web.privatelabel.Constants;
import com.topcoder.web.privatelabel.model.SimpleRegInfo;
import java.util.Map;
import java.util.StringTokenizer;
/**
* @author dok
* @version $Revision$ $Date$
* Create Date: Jan 31, 2005
*/
public abstract class BaseCredentialReminder extends RegistrationBase {
protected void registrationProcessing() throws TCWebException {
String email = StringUtils.checkNull(getRequest().getParameter(Constants.EMAIL));
setDefault(Constants.COMPANY_ID, StringUtils.checkNull(getRequest().getParameter(Constants.COMPANY_ID)));
setDefault(Constants.LOCALE, getLocale().getLanguage());
StringTokenizer st = new StringTokenizer(email, "@.");
setIsNextPageInContext(true);
if (email.equals("")) {
setNextPage(getStartPage());
} else if (st.countTokens() < 3
|| !StringUtils.contains(email, '@')
|| !StringUtils.contains(email, '.')) {
String loc = getRequest().getParameter(Constants.LOCALE);
addError(Constants.EMAIL, getBundle().getProperty("error_invalid_email"));
setDefault(Constants.EMAIL, email);
setNextPage(getStartPage());
} else {
try {
Request r = new Request();
r.setContentHandle("user_info_using_email");
r.setProperty("email", email);
Map m = getDataAccess(db).getData(r);
ResultSetContainer rsc = (ResultSetContainer) m.get("user_info_using_email");
if (rsc.isEmpty()) {
throw new NavigationException("Sorry, this email address (" + StringUtils.htmlEncode(email) + ") does not exist in our system.");
} else {
PrincipalMgrRemote mgr = (PrincipalMgrRemote) com.topcoder.web.common.security.Constants.createEJB(PrincipalMgrRemote.class);
TCSEmailMessage mail = new TCSEmailMessage();
mail.setSubject(getEmailSubject());
mail.setBody(getEmailContent(rsc.getStringItem(0, "handle"), mgr.getPassword(rsc.getLongItem(0, "user_id"), db)));
mail.addToAddress(email, TCSEmailMessage.TO);
mail.setFromAddress(getEmailFromAddress(), getEmailFromAddressName());
log.info("sent reminder email to " + email);
EmailEngine.send(mail);
setNextPage(getSuccessPage());
}
} catch (TCWebException e) {
throw e;
} catch (Exception e) {
throw new TCWebException(e);
}
}
}
protected SimpleRegInfo makeRegInfo() throws Exception {
return null;
}
protected String getEmailContent(String handle, String password) {
StringBuffer buf = new StringBuffer(1000);
buf.append("Hello, \n\n");
buf.append("Your login is ").append(handle);
buf.append("\n");
buf.append("Your password is ").append(password);
buf.append("\n\nPlease keep this email for your records.\n\n");
buf.append("Good Luck,\n");
buf.append("TopCoder");
return buf.toString();
}
protected String getEmailSubject() {
return "Login Credentials from TopCoder";
}
protected String getEmailFromAddress() {
return "service@topcoder.com";
}
protected String getEmailFromAddressName() {
return "TopCoder Service";
}
abstract protected String getSuccessPage();
abstract protected String getStartPage();
} | true |
8e688c7b03e990c3150cd098c9173f9062223301 | Java | kbirudoju/1800-PetMeds-Android | /app/src/main/java/com/petmeds1800/model/entities/PaymentGroup.java | UTF-8 | 2,503 | 2.28125 | 2 | [] | no_license | package com.petmeds1800.model.entities;
import java.io.Serializable;
/**
* Created by pooja on 8/17/2016.
*/
public class PaymentGroup implements Serializable{
private String lastName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getExpirationYear() {
return expirationYear;
}
public void setExpirationYear(String expirationYear) {
this.expirationYear = expirationYear;
}
public String getExpirationMonth() {
return expirationMonth;
}
public void setExpirationMonth(String expirationMonth) {
this.expirationMonth = expirationMonth;
}
public String getCreditCardNumber() {
return creditCardNumber;
}
public void setCreditCardNumber(String creditCardNumber) {
this.creditCardNumber = creditCardNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getPaymentMethod() {
return paymentMethod;
}
public void setPaymentMethod(String paymentMethod) {
this.paymentMethod = paymentMethod;
}
private String state;
private String address1;
private String address2;
private String city;
private String amount;
private String postalCode;
private String expirationYear;
private String expirationMonth;
private String creditCardNumber;
private String firstName;
private String paymentMethod;
}
| true |
6389bd3a46150d4adfa9a7119e499f8f77d11f0f | Java | ehabarman/Grad_Project_Version_3 | /src/mutex/Driver.java | UTF-8 | 1,029 | 3 | 3 | [] | no_license | package mutex;
import mutex.models.MutexHandler;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) throws FileNotFoundException {
File input = new File("resources/input.txt");
Scanner s = new Scanner(input);
String path = s.nextLine();
MutexHandler mutexHandler = MutexHandler.getinstance();
while (mutexHandler.isWorking()) ; // handler is busy
mutexHandler.startWorking();
String msg = mutexHandler.isAvailable(path, MutexHandler.DOWNLOADREQUEST);
if (msg.compareTo("yes") == 0) {
mutexHandler.addLock(path, MutexHandler.DOWNLOADREQUEST);
mutexHandler.finishedWorking();
/**
* do your thing here
*/
mutexHandler.releaseLock(path, MutexHandler.DOWNLOADREQUEST);
} else {
System.out.println("can't serve yor request");
}
s.close();
}
}
| true |
6fde30eb2916a757a78929b715aa9b81dee684a0 | Java | tiendungcmd/LunivaCODE | /src/utils/Common.java | UTF-8 | 6,485 | 2.515625 | 3 | [] | no_license | /**
* Coppyright (C) 2020 Luvina
* Common.java, Nov 17, 2020, BuiTienDung
*/
package utils;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.servlet.http.HttpSession;
import Manageruser.properties.MessageErrorProperties;
/**
* @author Bùi Tiến Dũng
*
*/
public class Common {
/**
* hàm mã hóa password
*
* @param pw
* mat khẩu
* @param salt
* salt
* @return Chuoi đã mã hóa
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
public String EncodeCreatePassword(String pw, String salt)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
String saltIp = pw + salt;
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(saltIp.getBytes("UTF-8"));
return new BigInteger(1, crypt.digest()).toString(16);
}
// kiểm tra mã hoa
/**
* So sáng pass do người dùng nhập vào sau khi được mã hóa với pass lấy ra
* được trong DB
*
* @param pass
* pass do người dùng nhập vào sau khi được mã hóa
* @param passDB
* pass lấy ra được trong DB
* @return nếu giống nhau trả về true, nếu khác nhau trả về false
*/
public boolean compare(String pass, String passDB) {
// Nếu 1 trong 2 pass bị null
if (pass == null || passDB == null) {
//
return false;
}
return pass.equals(passDB);
}
/**
* Kiểm tra xem session đã tồn tại chưa
*
* @param ss
* tên session
* @return
*/
// kiem tra login session
public static boolean checkLogin(HttpSession ss) {
boolean check = true;
if ("".equals(ss.getAttribute("loginName")))
check = false;
return check;
}
/**
* Tao chuoi paging
*
* @param totalUser
* @param limit
* @param currentPage
* @return
*/
public static List<Integer> getListPaging(int totalUser, int limit, int currentPage) {
// tao danh sach chua các page sẽ hiển thị
List<Integer> lst = new ArrayList<>();
// tinh tong so page
int totalPage = getTotalPage(totalUser, limit);
// neu tong so page lon hon gia tri hien tai
int begin = 1;
if (totalPage >= currentPage) {
// neu page hien tai chia het cho 3 -> chi so bat dau cua lstpaging
if (currentPage % 3 == 0) {
begin = currentPage - 2;
} else {
// neu page hien tai khong chia het cho 3
begin = (currentPage / 3) * 3 + 1;
}
// duyet vong for de vuu vao mang
// danh sách chưa các page hiển thị là 3 page tính từ page vừa tính
// được
}
for (int i = 1; i <= 3 && begin <= totalPage; i++) {
lst.add(begin++);
}
// lst.add(i);
return lst;
}
/**
* lay vi tri data can lay
*
* @param currentPage
* @param limit
* @return vi tri data can lay
*/
public static int getOffset(int currentPage, int limit) {
return currentPage * limit - limit + 1;
}
/**
* lay so luong hien thi ban ghi tren 1 trang
*
* @return
*/
public static int getLimit() {
MessageErrorProperties me = new MessageErrorProperties();
return Integer.parseInt(me.getValueByKey("RECORD"));
}
/**
* tinh tong so trang
*
* @return
*/
public static int getTotalPage(int totalUser, int limit) {
int totalPage = totalUser / limit;
int totalPage1 = totalUser % limit;
if (totalPage1 != 0) {
return totalPage + 1;
}
return totalPage;
}
/**
* thay the các kí tự đặc biệt
*
* @param fullName
* @return
*/
public static String replaceWildcard(String fullName) {
fullName.replace("\\", "\\\\");
fullName.replace("%", "\\%");
fullName.replace("_", "\\_");
return fullName;
}
/**
* Lay nam hien tai
*
* @return nam hien tai
*/
public static int getYearNow() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.YEAR);
}
/**
* Lay thang hien tai
*
* @return thang hien tai
*/
public static int getMonthNow() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.MONTH);
}
/**
* Lay ngay hien tai
*
* @return ngay hien tai
*/
public static int getDayNow() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.DATE);
}
/**
* cho ngay thagn nam vao 1 danh sach
*
* @return list ngay thang nam
*/
public static List<Integer> getListDMY() {
List<Integer> lstDMY = new ArrayList<>();
lstDMY.add(Common.getYearNow());
lstDMY.add(Common.getMonthNow());
lstDMY.add(Common.getDayNow());
return lstDMY;
}
/**
* Lay danh sach cac năm từ 1900 - năm hiện tại
*
* @param yearFrom
* năm 1900
* @param yearTo
* năm hiện tại
* @return danh sách các năm
*/
public static List<Integer> getListYear(int yearFrom, int yearTo) {
List<Integer> lstYear = new ArrayList<>();
for (int i = yearFrom; i <= yearTo; i++) {
lstYear.add(i);
}
return lstYear;
}
/**
* Lấy danh sách tháng
*
* @return danh sách tháng
*/
public static List<Integer> getListMonth() {
List<Integer> lstMonth = new ArrayList<>();
for (int i = 1; i <= 12; i++) {
lstMonth.add(i);
}
return lstMonth;
}
/**
* lay danh sách ngày
*
* @return danh sách ngày
*/
public static List<Integer> getListDay() {
List<Integer> lstDay = new ArrayList<>();
for (int i = 1; i <= 31; i++) {
lstDay.add(i);
}
return lstDay;
}
/**
* Kiem tra checkMaxlength
* @param string chuoi can kiem tra
* @param max khoag max cua ki tu
* @return nếu vượt quá max kí tự trả về false, ngược lại trả về true
*/
public boolean checkMaxlength(String string,int max){
boolean check =true;
if(string.length()>max){
check=false;
}
return check;
}
// public boolean checkFomartLogin(String string){
//
// return false;
// }
/**
* Kiểm tra độ dài trong khoảng cho trước
* @param string chuỗi cần kiểm tra
* @param a độ dài từ a
* @param b độ dài đến b
* @return nếu vượt chuỗi truyền vào ở ngoài độ dài cần kiểm tra thì trả về false,ngược lại trả về true
*/
public boolean checkLength(String string ,int a,int b){
boolean check =true;
if(string.length()< a && string.length()>b){
check = false;
}
return check;
}
} | true |
0a16aa7eccae7ee7b94095f3476e0ddf38a73316 | Java | deepalikhetam/Cinderella | /NewCorporateSite/src/test/java/corporatesite/testcases/TC06VerifyHomePage.java | UTF-8 | 561 | 1.890625 | 2 | [] | no_license | package corporatesite.testcases;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import corporatesite.Browser;
import corporatesite.HomePage;
public class TC06VerifyHomePage extends Browser
{
@Test(priority = 6)
public void verifyHomePage_TC06() throws Exception
{
try{
Thread.sleep(2000);
driver.findElement(By.xpath("//*[@id='swm-mobi-nav-btn']/span/span")).click();
System.out.println("Clicked on Navigatin menu");
Thread.sleep(2000);
}
catch(Exception e)
{
}
HomePage.verifyHomePage();
}
}
| true |
0ac7a3ad5d4a08b29a2559ade1ffa493adb6ab78 | Java | TheSignalMessenger/TheSignal | /src/thesignal/utils/Util.java | UTF-8 | 3,204 | 3.03125 | 3 | [] | no_license | package thesignal.utils;
import java.awt.Color;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
import thesignal.entity.Message;
import net.tomp2p.peers.Number160;
import net.tomp2p.storage.Data;
public final class Util {
public static Number160 add(final Number160 left, final Number160 right)
{
byte[] leftBytes = left.toByteArray();
byte[] rightBytes = right.toByteArray();
return new Number160(new BigInteger(leftBytes).add(new BigInteger(rightBytes)).toByteArray());
}
public static Number160 inc(final Number160 val)
{
return add(val, new Number160(1));
}
/**
* Returns a pseudo-random number between 0 and Number160.MAX:VALUE,
* inclusive.
*
* @return random Number160.
* @see java.util.Random#nextBytes()
*/
public static Number160 randNumber160() {
// NOTE: Usually this should be a field rather than a method
// variable so that it is not re-seeded every call.
Random rand = new Random(System.currentTimeMillis());
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
byte[] randBytes = new byte[20];
rand.nextBytes(randBytes);
return new Number160(randBytes);
}
/**
* Returns a pseudo-random number between min and max, inclusive. The
* difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* @param min
* Minimum value
* @param max
* Maximum value. Must be greater than min.
* @return Integer between min and max, inclusive.
* @see java.util.Random#nextInt(int)
*/
public static int randInt(int min, int max) {
// NOTE: Usually this should be a field rather than a method
// variable so that it is not re-seeded every call.
Random rand = new Random(System.currentTimeMillis());
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static boolean less(Number160 left, Number160 right) {
String leftString = left.toString();
String rightString = right.toString();
if(leftString.length() < rightString.length())
{
return true;
}
else if(leftString.length() > rightString.length())
{
return false;
}
else
{
return leftString.compareTo(rightString) < 0;
}
}
public static boolean greater(Number160 left, Number160 right) {
return less(right, left);
}
public static String getMessageFromData(Data data)
{
String message = "";
Object dataObject = null;
try {
Message msg;
dataObject = data.getObject();
msg = (Message) dataObject;
message = msg.getPayload();
} catch (ClassNotFoundException e1) {
// e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassCastException e) {
message = dataObject.toString();
}
return message;
}
public static Color mix(Color left, Color right)
{
Color result = new Color((left.getRed() + right.getRed()) / 2, (left.getGreen() + right.getGreen()) / 2, (left.getBlue() + right.getBlue()) / 2, (left.getAlpha() + right.getAlpha()) / 2);
return result;
}
}
| true |