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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a4c568dad5c745d272d6a32ac539e4ae8e1f55bb | Java | edifangyi/Mobile-Security-Guards | /MobileSafe/app/src/main/java/com/fangyi/mobilesafe/view/FocusedTextView.java | UTF-8 | 1,311 | 2.640625 | 3 | [] | no_license | package com.fangyi.mobilesafe.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by FANGYI on 2016/5/29.
*/
public class FocusedTextView extends TextView {
/**
* 通常是在代码实例化的时候用
* @param context
*/
public FocusedTextView(Context context) {
super(context);
}
/**
* 在Android中,我们布局文件使用的中间控件,默认会调用钓友两个参数构造方法
* @param context
* @param attrs
*/
public FocusedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 设置样式的时候
* @param context
* @param attrs
* @param defStyleAttr
*/
public FocusedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public FocusedTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
/**
* 当前这个控件不一定获得的焦点,只是欺骗系统,让系统以为获得焦点的方式去处理事务
* @return
*/
@Override
public boolean isFocused() {
return true;
}
}
| true |
2549df15a287f4722089169110fb5cac89d1a980 | Java | coderone95/SecU | /src/main/java/com/coderone95/secu/entity/SecGeneralInfo.java | UTF-8 | 1,195 | 2.078125 | 2 | [] | no_license | package com.coderone95.secu.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
@Entity
@Table(name="tbl_sec_gen_info")
public class SecGeneralInfo {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="sec_gen_id")
private Long secGenId;
// @Column(name="user_id")
// private Long userId;
private String data;
@ManyToOne
@JoinColumn(name = "user_id")
@JsonBackReference
private User user;
public Long getSecGenId() {
return secGenId;
}
public void setSecGenId(Long secGenId) {
this.secGenId = secGenId;
}
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
| true |
6643e9473cd633848d99d94d8b45c01f82fe0592 | Java | KanadeSong/webserver | /user/src/main/java/com/seater/user/enums/UserWorkEnum.java | UTF-8 | 786 | 2.640625 | 3 | [] | no_license | package com.seater.user.enums;
/**
* @Description:人员工作枚举
* @Author yueyuzhe
* @Email 87167070@qq.com
* @Date 2019/12/11 0011 17:10
*/
public enum UserWorkEnum {
Unknow("未知",0),
BeginWork("上班",1),
EndWork("下班",2),
Leave("请假",3);
private String name;
private Integer value;
UserWorkEnum(String name,Integer value)
{
this.name = name;
this.value = value;
}
@Override
public String toString()
{
return this.name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
| true |
565e27c5f3a4e8bc218283d233cbf056cf8fe976 | Java | Lavamancer/koru-libgdx | /core/src/io/anuke/koru/ucore/ecs/Require.java | UTF-8 | 284 | 1.992188 | 2 | [] | no_license | package io.anuke.koru.ucore.ecs;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**Used to mark trait requirements for a specfic trait.*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Require{
public Class<? extends Trait>[] value();
}
| true |
0c91d29a79b1f28125f6b4fbae4636c3dd77d95e | Java | netconstructor/GeoTools | /modules/plugin/jdbc/jdbc-db2/src/test/java/org/geotools/data/db2/DB2DateTest.java | UTF-8 | 311 | 1.539063 | 2 | [] | no_license | package org.geotools.data.db2;
import org.geotools.jdbc.JDBCDateTest;
import org.geotools.jdbc.JDBCDateTestSetup;
/**
*
*
* @source $URL$
*/
public class DB2DateTest extends JDBCDateTest {
@Override
protected JDBCDateTestSetup createTestSetup() {
return new DB2DateTestSetup();
}
}
| true |
1572162708240be3c93dc06d18d699014de857d9 | Java | paolomastroo/progetto | /taskmanager/src/main/java/it/uniroma3/siw/taskmanager/controller/ProjectController.java | UTF-8 | 5,930 | 2.015625 | 2 | [] | no_license | package it.uniroma3.siw.taskmanager.controller;
import java.util.Iterator;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import it.uniroma3.siw.taskmanager.controller.session.SessionData;
import it.uniroma3.siw.taskmanager.controller.validation.CredentialsValidator;
import it.uniroma3.siw.taskmanager.controller.validation.ProjectValidator;
import it.uniroma3.siw.taskmanager.model.Credentials;
import it.uniroma3.siw.taskmanager.model.Project;
import it.uniroma3.siw.taskmanager.model.User;
import it.uniroma3.siw.taskmanager.service.CredentialsService;
import it.uniroma3.siw.taskmanager.service.ProjectService;
import it.uniroma3.siw.taskmanager.service.UserService;
@Controller
public class ProjectController {
@Autowired
CredentialsService credentialsService;
@Autowired
ProjectService projectService;
@Autowired
UserService userService;
@Autowired
ProjectValidator projectValidator;
@Autowired
SessionData sessionData;
@Autowired
CredentialsValidator credentialsValidator;
@RequestMapping(value="/projects", method=RequestMethod.GET)
public String myOwnedProjects(Model model) {
User loggedUser = sessionData.getLoggedUser();
List<Project> projectsList = projectService.retrieveProjectsOwnedBy(loggedUser);
model.addAttribute("loggedUser", loggedUser);
model.addAttribute("myOwnedProjects", projectsList);
return"myOwnedProjects";
}
@RequestMapping(value= {"/projects/{projectId}"}, method = RequestMethod.GET)
public String project(Model model, @PathVariable Long projectId) {
Project project = projectService.getProject(projectId);
User loggedUser = sessionData.getLoggedUser();
if(project==null)
return "redirect:/projects";
List<User> members = userService.getMembers(project);
if(!project.getOwner().equals(loggedUser) && !members.contains(loggedUser))
return "redirect:/projects";
model.addAttribute("loggedUser", loggedUser);
model.addAttribute("project", project);
model.addAttribute("members", members);
return "project";
}
@RequestMapping (value= {"/projects/add"}, method = RequestMethod.GET)
public String createProjectForm(Model model) {
User loggedUser = sessionData.getLoggedUser();
model.addAttribute("loggedUser", loggedUser);
model.addAttribute("projectForm", new Project());
return "addProject";
}
@RequestMapping (value= {"/projects/add"}, method = RequestMethod.POST)
public String createProject(@Valid @ModelAttribute("projectForm") Project project,
BindingResult projectBindingResult,
Model model) {
User loggedUser= sessionData.getLoggedUser();
List<Project> myOwnedProject = loggedUser.getOwnedProjects();
projectValidator.validate(project, projectBindingResult);
if(!projectBindingResult.hasErrors()) {
project.setOwner(loggedUser);
myOwnedProject.add(project);
loggedUser.setOwnedProjects(myOwnedProject);
this.projectService.saveProject(project);
this.userService.saveUser(loggedUser);
return"redirect:/projects/" + project.getId();
}
model.addAttribute("loggedUser", loggedUser);
return "addProject";
}
@RequestMapping(value = {"/project/me/{projectId}/delete"}, method=RequestMethod.POST)
public String deleteProject(Model model, @PathVariable Long projectId) {
User loggedUser = sessionData.getLoggedUser();
List<Project> myOwnedProject = loggedUser.getOwnedProjects();
Iterable<Project> it = myOwnedProject;
for(Project deletedProject : it) {
if(deletedProject.getId()==projectId) {
this.projectService.deleteProject(deletedProject);
}
}
model.addAttribute("loggedUser", loggedUser);
model.addAttribute("myOwnedProject", myOwnedProject);
return "myOwnedProjects";
}
@RequestMapping(value = {"/sharedProjectsWithMe"}, method = RequestMethod.GET)
public String sharedProjectsWithMe(Model model) {
User loggedUser = sessionData.getLoggedUser();
List<Project> sharedProjectsList = projectService.retrieveProjectsSharedWith(loggedUser);
model.addAttribute("loggedUser", loggedUser);
model.addAttribute("sharedProjectsList", sharedProjectsList);
return "sharedProjectsWithMe";
}
@RequestMapping(value = {"projects/{projectId}/share"}, method = RequestMethod.POST)
public String shareProject(@Valid @ModelAttribute("shareCredentialsForm") Credentials shareCredentialsForm,
BindingResult shareCredentialsFormBindingResult,
@PathVariable("projectId") Long projectId,
Model model) {
Project project = this.projectService.getProject(projectId);
Credentials sharerCredentials = sessionData.getLoggedCredentials();
if(project.getOwner().equals(sharerCredentials.getUser()) || sharerCredentials.getRole().equals("ADMIN")) {
this.credentialsValidator.validateSharing(sharerCredentials, shareCredentialsForm, shareCredentialsFormBindingResult);
if(!shareCredentialsFormBindingResult.hasErrors()) {
User user2ShareWith = credentialsService.getUserByUsername(shareCredentialsForm.getUsername());
this.projectService.shareProjectWithUser(project, user2ShareWith);
return "redirect:/projects/"+projectId.toString();
}
}
model.addAttribute("loggedCredentials", sharerCredentials);
model.addAttribute("shareCredentialsForm", shareCredentialsForm);
return "redirect:/projects/"+project.getId().toString();
}
}
| true |
e8b22005618508dfe0743a88b64e491df039e7ba | Java | CHIKHAOUI-Firas99/PIjavaFX | /src/services/enc.java | UTF-8 | 1,018 | 2.46875 | 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 services;
/**
*
* @author LENOVO
*/
import Alert.AlertDialog;
import org.mindrot.jbcrypt.BCrypt;
public class enc {
public static boolean checkPassword(String passwordText, String DbHash) {
boolean password_verified = false;
DbHash = DbHash.substring(0,2)+'a'+DbHash.substring(3);
if (null == DbHash || !DbHash.startsWith("$2a$")) {
AlertDialog.showNotification("Error !","vous-devez verifier votre mot de passe ",AlertDialog.image_cross);
}
password_verified = BCrypt.checkpw(passwordText, DbHash);
return (password_verified);
}
public static String encryptPassword(String password){
String pw = BCrypt.hashpw(password, BCrypt.gensalt());
pw = pw.substring(0,2)+'y'+pw.substring(3);
return pw;
}
} | true |
2397ecd5a9892f22da2af11aa548280ca06f5bc7 | Java | madcecilb/information-retrieval-lucene-assignment-2 | /information-retrieval-web-search-engine/src/Robot.java | UTF-8 | 1,128 | 3.15625 | 3 | [] | no_license | import java.util.ArrayList;
public class Robot {
private Boolean considerable;
private ArrayList<String> disallowList;
public Robot(String robotString){
String[] strArray = robotString.split(" Disallow: ");
disallowList = new ArrayList<>();
//"gent: *" is part of User-Agent: *, what means that this rule is for all agents
//here we use gent instead of agent, because it could be agent or Agent
if(strArray[0].contains("gent: *")){
considerable = true;
for(int i = 1; i < strArray.length; i++){
disallowList.add(strArray[i].split(" ")[0]);
}
}
else{
considerable = false;
}
}
public String toString(){
String str = considerable.toString();
for (String disallow : disallowList) {
str = str + " " + disallow;
}
return str;
}
public Boolean getIsForUs() {
return considerable;
}
public void setIsForUs(Boolean consid) {
considerable = consid;
}
public ArrayList<String> getDisallowList() {
return disallowList;
}
public void setDisallowList(ArrayList<String> disallows) {
disallowList = disallows;
}
}
| true |
7417466191ac58e9f603bef427bddeeffe83bc82 | Java | Tooci/JavaProblem | /src/main/java/p2.java | UTF-8 | 1,591 | 3.484375 | 3 | [] | no_license |
//饿汉式单例,直接创建对象,不存在线程安全问题
public class p2 {
//1 构造器私有化
//2 自行创建,静态变量保存
//3 向外提供实例
public static final p2 instance=new p2();
private p2(){
}
//static {
// try{//Properties pro new Properties();
// //pro.load(p2.class.getClassLoader().getRessourceAsStream())
// //instance=new p2(pro.getPropertty(""));
// }catch(IOException e){
// throw new RuntimeException}
// }
public static p2 getInstance(){
return instance;
}
}
//懒汉式单例,延迟创建对象,存在线程安全问题
class s1{
//1 构造器私有化
//2 静态变量保存唯一的实例
//3 静态方法获取对象
private static s1 instance;
private s1(){
}
static s1 getInstance(){
if (instance==null){
instance=new s1();
}
return instance;
}
}
//双检锁
class s2{
private static s2 instance;
private s2(){
}
public static s2 getInstance(){
if (instance==null){
synchronized (s2.class){
if (instance==null){
instance=new s2();
}
}
}
return instance;
}
}
//静态内部类
class s3 {
private static class pl5{
private static final s3 INSTANCE=new s3();
}
private s3(){
}
public static final s3 getInstance(){
return pl5.INSTANCE;
}
}
//枚举
enum s4{
INSTANCE;
public void anyMethod(){
}
}
| true |
5387a48955c2a407c26816c51c071ec18d608a0f | Java | hsw123456/designPattern | /src/com/hsw/designPattern/ioc/Main.java | UTF-8 | 991 | 2.9375 | 3 | [] | no_license | package com.hsw.designPattern.ioc;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Main {
// TODO
public static void ioc(String className, Shiyanlou s, String methodName, String name) {
try {
Class c = Class.forName(className);
Object o = c.newInstance();
Field[] fields = c.getDeclaredFields();
for (Field f : fields) {
if (f.getType().isAssignableFrom(Shiyanlou.class)) {
String fName = f.getName();
String setName = "set" + fName.substring(0, 1).toUpperCase() + fName.substring(1);
Method method = c.getDeclaredMethod(setName, Shiyanlou.class);
method.invoke(o, s);
}
}
Method method = c.getDeclaredMethod(methodName, String.class);
method.invoke(o, name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
059829f664a57800010309b44759aeec1b237423 | Java | Dazucad/LambdaStream | /src/ru/lokyanvs/Generator.java | UTF-8 | 624 | 3.09375 | 3 | [] | no_license | package ru.lokyanvs;
import java.util.function.Supplier;
public class Generator implements Supplier<Integer> /*,UnaryOperator<Integer>*/{
private int first;
private int second;
public Generator(int second) {
this.second = second;
}
public Generator(int first,int second){
this.first=first;
this.second=second;
}
//@Override
public Integer apply(Integer o) {
second += first;
first = o;
return second;
}
@Override
public Integer get() {
int temp=first+second;
first=second;
return second=temp;
}
}
| true |
60b3a8df24d39c781fbc9f4940aee9ce308274e5 | Java | sudippain/ProductApplication | /services/src/main/java/com/example/ProductApplication/models/ProductDetails.java | UTF-8 | 2,174 | 2.625 | 3 | [] | no_license | package com.example.ProductApplication.models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
@Entity
@Table(name = "inventory")
public class ProductDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@NotBlank(message = "product can't be empty")
private String product;
@NotNull(message = "Quantity can't be empty")
private int quantity;
@NotNull(message = "Price can't be empty")
private int price;
@NotBlank(message = "UserEmail can't be empty")
@Pattern(regexp="^([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_]{2,5})\\.([a-zA-Z]{2,5})$",message="Email must Follow Email Pattern")
private String userEmail;
public ProductDetails() {
super();
// TODO Auto-generated constructor stub
}
public ProductDetails(int id, String product, int quantity, int price, String userEmail) {
super();
this.id = id;
this.product = product;
this.quantity = quantity;
this.price = price;
this.userEmail = userEmail;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
@Override
public String toString() {
return "ProductDetails [id=" + id + ", product=" + product + ", quantity=" + quantity + ", price=" + price
+ ", userEmail=" + userEmail + "]";
}
}
| true |
cae84f69601644812985dc4d586a04b60d7dd42b | Java | AnilSener/tms-j2ee-project | /src/controller/RetrieveEmployerReport.java | UTF-8 | 9,293 | 2.109375 | 2 | [] | no_license | package controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import model.Assignment;
import model.Employer;
import model.LineItem;
import model.Project;
import DAO.DataManager;
/**
* Servlet implementation class RetrieveReportServlet
*/
@WebServlet("/retrieveEmployerReport")
public class RetrieveEmployerReport extends DBConnectionServlet {
private static final long serialVersionUID = 1L;
private DataManager dataManager;
private String path="";
/**
* @see HttpServlet#HttpServlet()
*/
public RetrieveEmployerReport() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
dataManager=super.getDataManager();
ServletContext context = getServletContext();
path = context.getInitParameter("filesystempath");
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
java.util.Date now=new java.util.Date();
int reportFileID=0;
Workbook workbook = null;
String fileName="Monthly_Job_Posts_Per_Employer"+"_"+formatter.format(now)+".xlsx";
if(fileName.endsWith("xlsx")){
workbook = new XSSFWorkbook();
}else if(fileName.endsWith("xls")){
workbook = new HSSFWorkbook();
}else{
try {
throw new Exception("invalid file name, should be xls or xlsx");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Sheet sheet = workbook.createSheet("Monthly Job Post Report");
Calendar c = Calendar.getInstance();
c.setTime(now);
c.add(Calendar.MONTH, -1);
int month = c.get(Calendar.MONTH) + 1;
int year = c.get(Calendar.YEAR);
System.out.println("last month"+month);
System.out.println("year"+year);
sheet.addMergedRegion(new CellRangeAddress(/*Row*/0,0,/*Column*/0,2));
int rowIndex = 0;
Row row0 = sheet.createRow(rowIndex++);
Cell cell0 = row0.createCell(0);
cell0.setCellValue("Monthly Job Post Per Employer Report");
//Report Name Cell Style
CellStyle style=workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBorderRight(CellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
Font reportNameFont=workbook.createFont();
reportNameFont.setColor(IndexedColors.WHITE.getIndex());
reportNameFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
reportNameFont.setFontHeightInPoints((short)14);
reportNameFont.setFontName("Calibri");
style.setFont(reportNameFont);
cell0.setCellStyle(style);
CellStyle style2=workbook.createCellStyle();
style2.setAlignment(CellStyle.ALIGN_LEFT);
style2.setBorderTop(CellStyle.BORDER_THIN);
style2.setBorderBottom(CellStyle.BORDER_THIN);
style2.setBorderLeft(CellStyle.BORDER_THIN);
style2.setBorderRight(CellStyle.BORDER_THIN);
CellStyle style3=workbook.createCellStyle();
style3.setAlignment(CellStyle.ALIGN_LEFT);
style3.setBorderTop(CellStyle.BORDER_THIN);
style3.setBorderBottom(CellStyle.BORDER_THIN);
style3.setBorderRight(CellStyle.BORDER_THIN);
Font fieldNameFont=workbook.createFont();
fieldNameFont.setColor(IndexedColors.BLACK.getIndex());
fieldNameFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
fieldNameFont.setFontHeightInPoints((short)11);
fieldNameFont.setFontName("Calibri");
style2.setFont(fieldNameFont);
Row row1 = sheet.createRow(rowIndex++);
Cell cell10 = row1.createCell(0);
cell10.setCellValue("Reporting Date:");
cell10.setCellStyle(style2);
Cell cell11 = row1.createCell(1);
cell11.setCellStyle(style3);
cell11.setCellValue(sdf.format(new java.util.Date()));
Row row2 = sheet.createRow(rowIndex++);
Cell cell20 = row2.createCell(0);
cell20.setCellValue("Year:");
cell20.setCellStyle(style2);
Cell cell21 = row2.createCell(1);
cell21.setCellValue(year);
cell21.setCellStyle(style3);
Row row3 = sheet.createRow(rowIndex++);
Cell cell30 = row3.createCell(0);
cell30.setCellValue("Month:");
cell30.setCellStyle(style2);
Cell cell31 = row3.createCell(1);
cell31.setCellValue(month);
cell31.setCellStyle(style3);
Row row4 = sheet.createRow(rowIndex++);
Cell cell40 = row4.createCell(0);
cell40.setCellValue("Company Name");
cell40.setCellStyle(style2);
Cell cell41 = row4.createCell(1);
cell41.setCellValue("No of Jobs");
cell41.setCellStyle(style2);
//Collect Data
List<NameValuePair> employerJobList=(List<NameValuePair>) dataManager.getAllEmployerMonthlyPosts(year,month);
Iterator<NameValuePair> iterator = employerJobList.iterator();
while(iterator.hasNext()){
NameValuePair pair = iterator.next();
Row row5 = sheet.createRow(rowIndex++);
Cell cell50 = row5.createCell(0);
cell50.setCellValue(pair.getName());
cell50.setCellStyle(style3);
Cell cell51 = row5.createCell(1);
cell51.setCellValue(pair.getValue());
cell51.setCellStyle(style3);
}
//autosizing the columns according to the with of of the inputs
sheet.autoSizeColumn(0);
sheet.autoSizeColumn(1);
String fullpath=path + File.separator + fileName;
FileOutputStream fos = new FileOutputStream(fullpath);
workbook.write(fos);
fos.close();
//System.out.println(fullpath + " written successfully");
reportFileID=dataManager.insertFileDataUnchecked("admin","monthly_employer_report", fullpath);
String basePath=request.getRequestURL().toString().substring(0,request.getRequestURL().toString().indexOf(request.getServletPath()));
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(basePath+"/retrievefile?type=monthly_employer_report&contenttype=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&fileID="+reportFileID);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
BufferedInputStream in = new BufferedInputStream(is);
ServletOutputStream out;
out = response.getOutputStream();
BufferedOutputStream bout = new BufferedOutputStream(out);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
int ch =0;
while((ch=in.read())!=-1)
{
bout.write(ch);
}
in.close();
in.close();
bout.close();
out.close();
out.flush();
out=null;
httpClient.close();
}
catch(Exception ex){ex.printStackTrace();}
}
}
| true |
9b927adc5e8b42b25d438fdb69ca7dac25a4f33a | Java | iagoGB/POO | /src/br/com/poo/smd/lista10/exception/ContaInexistenteException.java | UTF-8 | 237 | 2.0625 | 2 | [] | no_license | package br.com.poo.smd.lista10.exception;
public class ContaInexistenteException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public ContaInexistenteException(String msg) {
super(msg);
}
}
| true |
12b4d174aea87452d472499886baf906da8874c5 | Java | stg-tud/rxrefactoring-code | /RxRefactoringTestsTemplate/src/framework/AbstractTest.java | UTF-8 | 2,848 | 2.671875 | 3 | [] | no_license | package framework;
import static org.junit.Assert.assertEquals;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
/**
* Description: Abstract test class for common functions<br>
* Author: Grebiel Jose Ifill Brito<br>
* Created: 11/13/2016
*/
public abstract class AbstractTest
{
/**
* Get the source code as a string given a path
*
* @param path
* the path of the source including the file name with the
* extension. This path is searched under resources<br>
* Example: for /resources/example.directory/Example.java use the
* following arguments: <br>
* "example.directory", "Example.java"
* @return The source code as a String
* @throws IOException
* io exception
*/
protected String getSourceCode( String... path ) throws IOException
{
Path p = Paths.get( "resources", path );
FileInputStream in = new FileInputStream( p.toString() );
StringBuilder sb = new StringBuilder();
int ch;
while ( ( ch = in.read() ) != -1 )
{
sb.append( (char) ch );
}
return sb.toString();
}
/**
* This method can be used to compare to source codes without considering
* line breaks
*
* @param expectedSourceCode
* expected source code
* @param actualSourceCode
* actual source code
*/
protected void assertEqualSourceCodes( String expectedSourceCode, String actualSourceCode )
{
String inputSourceCodeStandardFormat = getStandardFormat( actualSourceCode );
String expectedSourceCodeStandardFormat = getStandardFormat( expectedSourceCode );
assertEquals( expectedSourceCodeStandardFormat, inputSourceCodeStandardFormat );
}
/**
* Compares all compilation units in result with the target file and returns
* its source code
*
* @param targetFile
* target file
* @param results
* map containing results
* @return source code of the target file or emtpy if the file is not found
*/
protected String getSourceCodeByFileName( String targetFile, Map<ICompilationUnit, String> results )
{
String actualSourceCode = "";
for ( ICompilationUnit cu : results.keySet() )
{
if ( targetFile.equals( cu.getElementName() ) )
{
return results.get( cu );
}
}
return actualSourceCode;
}
// ### Private Methods ###
private String getStandardFormat( String source )
{
ASTParser javaParser = ASTParser.newParser( AST.JLS8 );
javaParser.setSource( source.toCharArray() );
CompilationUnit compilationUnit = (CompilationUnit) javaParser.createAST( null );
return compilationUnit.toString();
}
}
| true |
ee62105bcce93f59098b6142cda2089154417b7d | Java | GaTech-dannyhtaylor/BuzzTracker | /BuzzTracker/app/src/main/java/com/cs2340/binarybros/buzztracker/Controllers/InventoryListAdapter.java | UTF-8 | 2,499 | 2.59375 | 3 | [] | no_license | package com.cs2340.binarybros.buzztracker.Controllers;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.cs2340.binarybros.buzztracker.Models.Donation;
import java.util.List;
import java.util.Objects;
class InventoryListAdapter extends ArrayAdapter<Donation> {
private final Context listContext;
private final int mResource;
static class ViewHolder {
TextView title;
TextView category;
TextView location;
TextView price;
//ImageView icon;
}
public InventoryListAdapter(Context listContext, int resource, List<Donation> objects) {
super(listContext, resource, objects);
this.listContext = listContext;
mResource = resource;
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
View convertView1 = convertView;
String title = Objects.requireNonNull(getItem(position)).getTitle();
String category = Objects.requireNonNull(getItem(position)).getCategory();
String location = Objects.requireNonNull(getItem(position)).getLocation();
String price = Objects.requireNonNull(getItem(position)).getPrice();
//Create the donation object with the information
Donation donation = new Donation(title, category, location, price);
ViewHolder holder;
if(convertView1 == null) {
LayoutInflater inflater = LayoutInflater.from(listContext);
convertView1 = inflater.inflate(mResource, parent, false);
holder = new ViewHolder();
// holder.icon = (ImageView) convertView.findViewById(R.id.listItem_image);
holder.title = convertView1.findViewById(R.id.donation_title);
holder.category = convertView1.findViewById(R.id.category_label);
holder.location = convertView1.findViewById(R.id.location_label);
holder.price = convertView1.findViewById(R.id.price_label);
convertView1.setTag(holder);
} else {
holder = (ViewHolder) convertView1.getTag();
}
holder.title.setText(title);
holder.category.setText(category);
holder.location.setText(location);
holder.price.setText("$" + price);
return convertView1;
}
}
| true |
273a4b8818d91ff04d4ff60e6b63c4e62abe9318 | Java | Deron84/xxxTest | /src/com/huateng/po/mchnt/CstMchtFeeInfPK.java | UTF-8 | 2,858 | 2.390625 | 2 | [] | no_license | package com.huateng.po.mchnt;
import java.io.Serializable;
@SuppressWarnings("serial")
public class CstMchtFeeInfPK implements Serializable {
protected int hashCode = Integer.MIN_VALUE;
private java.lang.String mchtCd;
private java.lang.String txnNum;
private java.lang.String cardType;
public CstMchtFeeInfPK () {}
public CstMchtFeeInfPK (
java.lang.String mchtCd,
java.lang.String txnNum,
java.lang.String cardType) {
this.setMchtCd(mchtCd);
this.setTxnNum(txnNum);
this.setCardType(cardType);
}
/**
* Return the value associated with the column: mcht_cd
*/
public java.lang.String getMchtCd () {
return mchtCd;
}
/**
* Set the value related to the column: mcht_cd
* @param mchtCd the mcht_cd value
*/
public void setMchtCd (java.lang.String mchtCd) {
this.mchtCd = mchtCd;
}
/**
* Return the value associated with the column: txn_num
*/
public java.lang.String getTxnNum () {
return txnNum;
}
/**
* Set the value related to the column: txn_num
* @param txnNum the txn_num value
*/
public void setTxnNum (java.lang.String txnNum) {
this.txnNum = txnNum;
}
/**
* Return the value associated with the column: card_type
*/
public java.lang.String getCardType () {
return cardType;
}
/**
* Set the value related to the column: card_type
* @param cardType the card_type value
*/
public void setCardType (java.lang.String cardType) {
this.cardType = cardType;
}
public boolean equals (Object obj) {
if (null == obj) return false;
if (!(obj instanceof CstMchtFeeInfPK)) return false;
else {
CstMchtFeeInfPK mObj = (CstMchtFeeInfPK) obj;
if (null != this.getMchtCd() && null != mObj.getMchtCd()) {
if (!this.getMchtCd().equals(mObj.getMchtCd())) {
return false;
}
}
else {
return false;
}
if (null != this.getTxnNum() && null != mObj.getTxnNum()) {
if (!this.getTxnNum().equals(mObj.getTxnNum())) {
return false;
}
}
else {
return false;
}
if (null != this.getCardType() && null != mObj.getCardType()) {
if (!this.getCardType().equals(mObj.getCardType())) {
return false;
}
}
else {
return false;
}
return true;
}
}
public int hashCode () {
if (Integer.MIN_VALUE == this.hashCode) {
StringBuilder sb = new StringBuilder();
if (null != this.getMchtCd()) {
sb.append(this.getMchtCd().hashCode());
sb.append(":");
}
else {
return super.hashCode();
}
if (null != this.getTxnNum()) {
sb.append(this.getTxnNum().hashCode());
sb.append(":");
}
else {
return super.hashCode();
}
if (null != this.getCardType()) {
sb.append(this.getCardType().hashCode());
sb.append(":");
}
else {
return super.hashCode();
}
this.hashCode = sb.toString().hashCode();
}
return this.hashCode;
}
} | true |
57a1d791a39112e1fc61d89a027949bdbfae0ea4 | Java | arnaldi/bank-cli | /src/main/java/co/arnaldi/operation/LoginOperation.java | UTF-8 | 1,907 | 2.546875 | 3 | [] | no_license | package co.arnaldi.operation;
import co.arnaldi.dto.AccountDto;
import co.arnaldi.dto.ActiveAccount;
import co.arnaldi.model.Account;
import co.arnaldi.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.transaction.Transactional;
import java.math.BigDecimal;
@Component("LOGINOperation")
public class LoginOperation extends CommandOperation {
private ActiveAccount activeAccount;
private AccountService accountService;
private Logger logger = LoggerFactory.getLogger(LoginOperation.class);
public LoginOperation(AccountService accountService, ActiveAccount activeAccount){
this.accountService = accountService;
this.activeAccount = activeAccount;
}
@Override
@Transactional
public boolean execute() throws IllegalArgumentException {
validateInput();
Account activeAcc = accountService.getAccountLogin(this.getArgs()[1]);
activeAccount.setAccount(activeAcc);
AccountDto account = accountService.getAccountDto(activeAcc);
logger.info("Hello "+account.getName() + "!");
logger.info("Your balance is " +account.getBalance());
account.getDebts().stream().filter(d -> d.getAmount().compareTo(BigDecimal.ZERO) > 0).forEach(debt -> logger.info("Owing "+debt.getAmount() +" to "+ debt.getCreditorAccountName()));
account.getCredits().stream().filter(d -> d.getAmount().compareTo(BigDecimal.ZERO) > 0 ).forEach(debt -> logger.info("Owing "+debt.getAmount() +" from "+ debt.getDebitorAccountName()));
return true;
}
@Override
void validateInput() throws IllegalArgumentException {
if(this.getArgs().length < 2){
throw new IllegalArgumentException("Please input your name for login");
}
}
}
| true |
625134c0b0bc4308219d8bf6b0e708c36da94b07 | Java | xzw999/jinjie | /app/src/main/java/com/xinzhengwei/dianshangjinjieyuekaoti/model/ModelImp.java | UTF-8 | 1,736 | 2.25 | 2 | [] | no_license | package com.xinzhengwei.dianshangjinjieyuekaoti.model;
import com.xinzhengwei.dianshangjinjieyuekaoti.presenter.PresenterImp;
import com.xinzhengwei.dianshangjinjieyuekaoti.presenter.PresenterInter;
import com.xinzhengwei.dianshangjinjieyuekaoti.util.RetrofitUtil;
import java.util.Map;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
/**
* Created by 辛政维 on 2018/3/31.
*/
public class ModelImp implements ModelInter {
private PresenterInter presenterInter;
private Disposable d;
public ModelImp(PresenterInter presenterInter) {
this.presenterInter=presenterInter;
}
@Override
public void getNetData(String url, Map<String, String> map) {
RetrofitUtil.getService().doGet(url,map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
ModelImp.this.d=d;
}
@Override
public void onNext(ResponseBody responseBody) {
presenterInter.onSuccess(responseBody);
}
@Override
public void onError(Throwable e) {
presenterInter.onError(e);
}
@Override
public void onComplete() {
}
});
}
@Override
public void unsubrice() {
}
}
| true |
ef210d0396639dcdce71f0a650faa90223b7ee4a | Java | chonghuidt/observer | /src/main/java/com/lp/observer/simple/Subject.java | UTF-8 | 431 | 2.53125 | 3 | [] | no_license | package com.lp.observer.simple;
/**
* @Author: lp
* @Date: 2020/12/1 9:28
* 主题
*/
public interface Subject {
/**
* 注册观察者
* @param observer
*/
public void register(Observer observer);
/**
* 删除观察者
* @param observer
*/
public void remove(Observer observer);
/**
* 主题变更的时候,通知观察者
*/
public void notifyMessage();
}
| true |
1ac89f4f2759fd967d5cdbe0c745ce97ea53620b | Java | nomyzs/FlipView | /app/src/main/java/ultimatefanlive/com/flipanimationexample/MainActivityFragment.java | UTF-8 | 1,810 | 2.484375 | 2 | [] | no_license | package ultimatefanlive.com.flipanimationexample;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import ultimatefanlive.com.flipview.FlipView;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment {
private FlipView flipView;
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.fragment_fab).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
flipViews();
}
});
flipView = (FlipView) view.findViewById(R.id.flip_view);
flipView.setUpWithViews(getFlipadbleViews());
}
private List<View> getFlipadbleViews() {
Random generator = new Random();
List<View> list = new LinkedList<>();
for (int i = 0; i < 4; i++) {
TextView tv = new TextView(getContext());
tv.setBackgroundColor(Color.rgb(generator.nextInt(255), generator.nextInt(255), generator.nextInt(255)));
tv.setText("Page nr " + i);
list.add(tv);
}
return list;
}
private void flipViews() {
flipView.flipNext();
}
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
| true |
9c4df6bdf28730417dcfe89cbe73a11667552f1f | Java | ricoapon/MockFrameworkAggregator | /MockFrameworkReference/src/main/java/com/keylane/HelloWorld.java | UTF-8 | 2,673 | 2.546875 | 3 | [] | no_license | package com.keylane;
import com.keylane.mock.method.MockParameter;
import com.keylane.mock.method.MockParameterType;
import com.keylane.mock.response.Response;
import com.keylane.mock.response.ResponseBuilder;
import com.keylane.mock.url.MockUrl;
import com.keylane.mock.url.MockUrlMatcher;
import java.util.Map;
public class HelloWorld {
@MockUrl("hello-world")
public Response helloWorld() {
return ResponseBuilder.start()
.setBody("hello world")
.create();
}
@MockUrl("hello-world-body")
public Response helloWorldBody(@MockParameter(MockParameterType.BODY) String body) {
return ResponseBuilder.start()
.setBody("hello" + body + "world")
.create();
}
@MockUrl("hello-world-header")
public Response helloWorldHeader(@MockParameter(MockParameterType.HEADERS) Map<String, String> headers) {
return createMapResponse(headers);
}
@MockUrl("hello-world-url")
public Response helloWorldUrl(@MockParameter(MockParameterType.URL) String url) {
return ResponseBuilder.start()
.setBody(url)
.create();
}
@MockUrl("hello-world-parameter")
public Response helloWorldParameter(@MockParameter(MockParameterType.PARAMETERS) Map<String, String> parameters) {
return createMapResponse(parameters);
}
@MockUrl("/hello-world-verb")
public Response helloWorldParameter(@MockParameter(MockParameterType.VERB) String verb) {
return ResponseBuilder.start()
.setBody(verb)
.create();
}
@MockUrlMatcher("/hello-world-.*-something")
public Response helloWorldMatcher() {
return ResponseBuilder.start()
.setBody("You matched!")
.create();
}
@MockUrl("/hello-world-file")
public Response helloWorldFile() {
return ResponseBuilder.start()
.fillBodyWithFileContent("HelloWorld.xml")
.create();
}
@MockUrl("/hello-world-file2")
public Response helloWorldFile2() {
return ResponseBuilder.start()
.fillBodyWithFileContent("mydir/HelloWorld2.xml")
.create();
}
private Response createMapResponse(Map<String, String> map) {
StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : map.entrySet()) {
stringBuilder.append(entry.getKey()).append(":").append(entry.getValue()).append("\n");
}
return ResponseBuilder.start()
.setBody(stringBuilder.toString())
.create();
}
}
| true |
134026516d04b60adceb9226f5b62b7f2e077cef | Java | HugoStevenPoveda/AppListaSupermercado | /src/view/UpdateProduct.java | UTF-8 | 3,825 | 2.65625 | 3 | [] | no_license | package view;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import controller.ControllerProducto;
import model.Producto;
public class UpdateProduct {
private JFrame frmMain;
private int indiceProducto;
private JTextField campoNombre, campoPrecio, campoInventario;
private ControllerProducto controlador;
public UpdateProduct(int indice) {
this.indiceProducto = indice;
initialize();
}
private void construirFrameMain() {
frmMain = new JFrame();
frmMain.setTitle("Actualizar Producto");
frmMain.setBounds(100, 100, 450, 300);
frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMain.getContentPane().setLayout(new BorderLayout(0, 0));
frmMain.setVisible(true);
}
private void construirTitulo() {
JPanel panel = new JPanel();
frmMain.getContentPane().add(panel, BorderLayout.NORTH);
JLabel titulo = new JLabel("Ingrese los nuevos valores");
titulo.setForeground(new Color(102, 0, 102));
titulo.setFont(new Font("Comic Sans MS", Font.BOLD, 16));
panel.add(titulo);
}
private void construirPanelIngresoDatos() {
JPanel panelAgregarProducto = new JPanel();
panelAgregarProducto.setBackground(new Color(255, 255, 153));
panelAgregarProducto.setBorder(BorderFactory.createLineBorder(Color.WHITE, 5));
frmMain.add(panelAgregarProducto, BorderLayout.CENTER);
panelAgregarProducto.setLayout(new GridLayout(3, 2, 2, 2));
JLabel nombre = new JLabel("Nombre");
nombre.setHorizontalAlignment(SwingConstants.CENTER);
nombre.setFont(new Font("Tahoma", Font.BOLD, 14));
JLabel precio = new JLabel("Precio");
precio.setHorizontalAlignment(SwingConstants.CENTER);
precio.setFont(new Font("Tahoma", Font.BOLD, 14));
JLabel inventario = new JLabel("Invetario");
inventario.setHorizontalAlignment(SwingConstants.CENTER);
inventario.setFont(new Font("Tahoma", Font.BOLD, 14));
campoNombre = new JTextField();
campoPrecio = new JTextField();
campoInventario = new JTextField();
panelAgregarProducto.add(nombre);
panelAgregarProducto.add(campoNombre);
panelAgregarProducto.add(precio);
panelAgregarProducto.add(campoPrecio);
panelAgregarProducto.add(inventario);
panelAgregarProducto.add(campoInventario);
}
private Producto crearProducto(int indice) {
controlador = new ControllerProducto();
String nuevoNombre = campoNombre.getText();
Double nuevoPrecio = Double.parseDouble(campoPrecio.getText());
int nuevoInventario = Integer.parseInt(campoInventario.getText());
int codigoNuevo = controlador.obtenerProducto(indice).getCodigo();
Producto productoActualizado = new Producto(codigoNuevo, nuevoNombre, nuevoPrecio, nuevoInventario);
return productoActualizado;
}
private void actualizarProducto() {
controlador = new ControllerProducto();
Producto producto = crearProducto(indiceProducto);
controlador.actualizar(producto);
}
private void construirBotonActualizarProducto() {
JPanel panelBoton = new JPanel();
panelBoton.setBackground(new Color(255, 255, 153));
frmMain.add(panelBoton, BorderLayout.SOUTH);
JButton actualizarProducto = new JButton("Actualizar Producto");
actualizarProducto.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
actualizarProducto();
}
});
panelBoton.add(actualizarProducto);
}
private void initialize() {
construirFrameMain();
construirTitulo();
construirPanelIngresoDatos();
construirBotonActualizarProducto();
}
}
| true |
5b70aad88b35bb3a8b6370955950656b3f0bf2a0 | Java | titanmet/JavaSchoolSber | /lesson24_Introduction_in_API_tests_Rest_Assured/src/test/java/com/ratnikov/utils/UserUpdate.java | UTF-8 | 303 | 1.84375 | 2 | [] | no_license | package com.ratnikov.utils;
import com.ratnikov.model.CreateUserRequest;
public class UserUpdate {
public static CreateUserRequest putSimpleUser() {
return CreateUserRequest.builder()
.name("simple 2")
.job("zion resident")
.build();
}
}
| true |
13f379b35a628038a18e267669a6df32331b15e6 | Java | zhongxingyu/Seer | /Diff-Raw-Data/2/2_b740b1864500644bd97df58d9876a21cd1c94a59/JUMPInstallerTool/2_b740b1864500644bd97df58d9876a21cd1c94a59_JUMPInstallerTool_s.java | UTF-8 | 33,731 | 1.515625 | 2 | [] | no_license | /*
* Copyright 1990-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.jumpimpl.module.installer;
import com.sun.jump.common.JUMPAppModel;
import com.sun.jump.common.JUMPApplication;
import com.sun.jump.common.JUMPContent;
import com.sun.jump.executive.JUMPExecutive;
import com.sun.jump.module.JUMPModuleFactory;
import com.sun.jump.module.download.JUMPDownloadDescriptor;
import com.sun.jump.module.download.JUMPDownloadDestination;
import com.sun.jump.module.download.JUMPDownloadException;
import com.sun.jump.module.download.JUMPDownloadModule;
import com.sun.jump.module.download.JUMPDownloadModuleFactory;
import com.sun.jump.module.download.JUMPDownloader;
import com.sun.jump.module.installer.JUMPInstallerModule;
import com.sun.jump.module.installer.JUMPInstallerModuleFactory;
import com.sun.jumpimpl.module.download.DownloadDestinationImpl;
import com.sun.jumpimpl.module.download.OTADiscovery;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;
/**
* This class is an installation tool for downloading,
* installing, uninstalling, and listing content in the
* content store application repository.
*
* This class should be routinely modified with more
* features as development continues.
*
* The current supported commands are:
* list, info, install, install_all, uninstall, uninstall_all
*
* The commands install and uninstall will provide the user with an interactive
* way to choose files to be installed or uninstalled. The command install_all
* and uninstall_all will install or uninstall all content without interactive
* with the user.
*
* Usage:
* <cvm> <system properties> -cp <classpath> com.sun.jumpimpl.module.installer.JUMPInstallerTool -ProvisioningServerURL <url of provisioning server> <options> -command <command>
* <system properties> is optional, but it should be known that contentstore.root
* can be overridden here if desired.
* For example, -Dcontentstore.root=<repository dir> can be specified
* <command> can currently be list, info, install, install_all, uninstall, and uninstall_all
* <options>
* -verbose: print debugging messages
*
* Ex:
* cvm -cp $JUMP_JARS com.sun.jumpimpl.module.installer.JUMPInstallerTool -command list
* cvm -Dcontentstore.root=data2 -cp $JUMP_JARS com.sun.jumpimpl.module.installer.JUMPInstallerTool -command install
* cvm -cp $JUMP_JARS com.sun.jumpimpl.module.installer.JUMPInstallerTool -command uninstall
* cvm -cp $JUMP_JARS com.sun.jumpimpl.module.installer.JUMPInstallerTool -verbose -command install_all
* cvm -cp $JUMP_JARS com.sun.jumpimpl.module.installer.JUMPInstallerTool -command uninstall_all
*
*/
public class JUMPInstallerTool {
/**
* xlet installer module object
*/
protected JUMPInstallerModule xletInstaller = null;
/**
* midlet installer module object
*/
protected JUMPInstallerModule midletInstaller = null;
/**
* main installer module object
*/
protected JUMPInstallerModule mainInstaller = null;
/**
* holds download module object
*/
protected JUMPDownloadModule downloadModule = null;
/**
* URL used for Provisioning Server location
*/
protected String ProvisioningServer = null;
/**
* The current command to be run
*/
protected String Command = null;
/**
* Sub-values for the current command to be run
*/
protected String Value = null;
/**
* Whether or not to print debug messages
*/
protected boolean Verbose = false;
/**
* URL containing the content to be installed.
*/
protected String ContentURL = null;
/**
* URI of the descriptor file of the content to be installed
*/
protected String DescriptorURI = null;
/**
* The protocol of the content. The value should be either:
* ota/midp or ota/oma
*/
protected String Protocol = null;
/**
* The current root of content store where applications are located
*/
private String repository = null;
/**
* The property name holding the root of content store
*/
private static final String repositoryProperty = "contentstore.root";
/**
* Creates a new instance of JUMPInstallerTool
* @param hash properties
*/
public JUMPInstallerTool(Hashtable hash) {
this.Command = (String)hash.get("Command");
String verbose = (String)hash.get("Verbose");
if (verbose != null && verbose.equals("true")) {
this.Verbose = true;
}
this.ProvisioningServer = (String)hash.get("ProvisioningServerURL");
// The three lines of code below, along with usage of the fields,
// is for a future case where the tool will allow local installations.
this.ContentURL = (String)hash.get("ContentURL");
this.DescriptorURI = (String)hash.get("DescriptorURI");
this.Protocol = (String)hash.get("Protocol");
trace("JUMPInstallerTool Settings:");
trace(" Command: " + Command);
trace(" ProvisioningServerURL: " + ProvisioningServer);
trace("");
trace("=============================================");
trace("JUMPInstallerTool Settings");
trace("--------------------------");
trace("");
trace(" Command: " + Command);
trace("App Server: " + ProvisioningServer);
trace("=============================================");
trace("");
if (!setup()) {
System.exit(-1);
};
doCommand();
}
private void usage() {
System.out.println("Usage:");
System.out.println(" <cvm> <system properties> -cp <classpath> com.sun.jumpimpl.module.installer.JUMPInstallerTool <options> -command <command>");
System.out.println("Available commands that can be used are: list, install, install_all, uninstall, and uninstall_all.");
System.out.println("Available options: -verbose");
System.out.println("");
System.out.println("Ex:");
System.out.println(" cvm -cp $JUMP_JARS com.sun.jumpimpl.module.installer.JUMPInstallerTool -verbose -command list");
System.out.println("");
}
private void trace(String str) {
if (this.Verbose) {
System.out.println(str);
}
}
private boolean setup() {
if (Command == null) {
System.out.println("ERROR: No command specified.");
usage();
System.exit(0);
}
repository = System.getProperty(repositoryProperty);
if (repository != null) {
// test setup, make a repository root
File file = new File(repository);
if (!file.exists()) {
System.out.println("ERROR: " + repository + " directory not found.");
return false;
}
}
if (JUMPExecutive.getInstance() == null) {
JUMPModuleFactory factory = null;
factory = new com.sun.jumpimpl.module.installer.InstallerFactoryImpl();
factory.load(com.sun.jumpimpl.process.JUMPModulesConfig.getProperties());
factory = new com.sun.jumpimpl.module.contentstore.StoreFactoryImpl();
factory.load(com.sun.jumpimpl.process.JUMPModulesConfig.getProperties());
factory = new com.sun.jumpimpl.module.download.DownloadModuleFactoryImpl();
factory.load(com.sun.jumpimpl.process.JUMPModulesConfig.getProperties());
}
return true;
}
private JUMPInstallerModule createInstaller(JUMPAppModel type) {
JUMPInstallerModule module = null;
if (type == JUMPAppModel.MAIN) {
module = JUMPInstallerModuleFactory.getInstance().getModule(JUMPAppModel.MAIN);
} else if (type == JUMPAppModel.XLET) {
module = JUMPInstallerModuleFactory.getInstance().getModule(JUMPAppModel.XLET);
} else if (type == JUMPAppModel.MIDLET) {
module = JUMPInstallerModuleFactory.getInstance().getModule(JUMPAppModel.MIDLET);
}
if (module == null) {
return null;
}
return module;
}
private void doCommand() {
if (Command.equals("install")) {
if (ContentURL != null && DescriptorURI != null && Protocol != null) {
doInstall(ContentURL, DescriptorURI, Protocol);
} else {
doInstall(ProvisioningServer, true);
}
} else if (Command.equals("install_all")) {
doInstall(ProvisioningServer, false);
} else if (Command.equals("list")) {
doList();
} else if (Command.equals("uninstall")) {
doUninstall(true);
} else if (Command.equals("uninstall_all")) {
doUninstall(false);
} else if (Command.equals("info")) {
doInfo();
}
}
private void error() {
System.out.println("ERROR: Could not install.");
if (!this.Verbose) {
System.out.println("==> Please run with -verbose for more information.");
}
}
private void doInfo() {
System.out.println("");
System.out.println("---------------------------------");
System.out.println("Applications Within Content Store");
System.out.println("---------------------------------");
System.out.println("");
JUMPInstallerModule installers[] = JUMPInstallerModuleFactory.getInstance().getAllInstallers();
int numApps = 0;
for (int i = 0; i < installers.length; i++) {
JUMPContent[] content = installers[i].getInstalled();
if (content != null) {
for(int j = 0; j < content.length; j++) {
numApps++;
JUMPApplication app = (JUMPApplication)content[j];
System.out.println("App #" + numApps + ": " + app.getTitle());
JUMPAppModel model = app.getAppType();
if (model == JUMPAppModel.XLET) {
XLETApplication xlet = (XLETApplication)app;
System.out.println(" Bundle: " + xlet.getBundle());
System.out.println(" Jar: " + xlet.getClasspath());
System.out.println("Install ID: " + xlet.getId());
URL iconPath = xlet.getIconPath();
if (iconPath == null) {
System.out.println(" Icon: <none>");
} else {
System.out.println(" Icon: " + iconPath.getFile());
}
System.out.println(" Model: " + JUMPAppModel.XLET.toString());
} else if (model == JUMPAppModel.MAIN) {
MAINApplication main = (MAINApplication)app;
System.out.println(" Bundle: " + main.getBundle());
System.out.println(" Jar: " + main.getClasspath());
System.out.println("Install ID: " + main.getId());
URL iconPath = main.getIconPath();
if (iconPath == null) {
System.out.println(" Icon: <none>");
} else {
System.out.println(" Icon: " + iconPath.getFile());
}
System.out.println(" Model: " + JUMPAppModel.MAIN.toString());
} else if (model == JUMPAppModel.MIDLET) {
System.out.println(" Suite ID: " + app.getProperty("MIDletApplication_suiteid"));
System.out.println("Install ID: " + app.getId());
URL iconPath = app.getIconPath();
if (iconPath == null) {
System.out.println(" Icon: <none>");
} else {
System.out.println(" Icon: " + iconPath.getFile());
}
System.out.println(" Model: " + JUMPAppModel.MAIN.toString());
}
System.out.println("");
}
}
}
System.out.println("");
}
private void doInstall(String url, String uri, String protocol) {
JUMPDownloadModule module = null;
if (protocol.equals(JUMPDownloadModuleFactory.PROTOCOL_MIDP_OTA)) {
module = JUMPDownloadModuleFactory.getInstance().getModule(JUMPDownloadModuleFactory.PROTOCOL_MIDP_OTA);
} else if (protocol.equals(JUMPDownloadModuleFactory.PROTOCOL_OMA_OTA)) {
module = JUMPDownloadModuleFactory.getInstance().getModule(JUMPDownloadModuleFactory.PROTOCOL_OMA_OTA);
} else {
System.err.println("Error: Unknown protocol: " + protocol);
error();
return;
}
trace( "doInstall - Creating descriptor for " + uri );
JUMPDownloadDescriptor descriptor = null;
try {
descriptor = module.createDescriptor( uri );
} catch (JUMPDownloadException ex) {
ex.printStackTrace();
}
if (descriptor == null) {
trace("doInstall - Could not create descriptor.");
error();
return;
}
URL contentURL = null;
try {
if (url.startsWith("file://")) {
url = url.substring(7);
} else if (url.startsWith("http://")) {
System.err.println
("ERROR: The tool does not support descriptors using the http:// protocol.");
return;
}
contentURL = new URL("file", null, url);
} catch (Exception e) {
e.printStackTrace();
}
JUMPDownloadDescriptor[] descriptors = new JUMPDownloadDescriptor[1];
descriptors[0] = descriptor;
URL[] contentURLs = new URL[1];
contentURLs[0] = contentURL;
install(contentURLs, descriptors);
}
private void install(URL url[], JUMPDownloadDescriptor desc[]) {
if (url.length != desc.length) {
System.err.println("ERROR: Number of URLs to install does not equal the number of given download descriptors.");
error();
return;
}
for (int i = 0; i < url.length; i++) {
if (desc != null && url != null) {
System.out.println("");
System.out.println("==> Installing: " + desc[i].getName() + " from: " + url[i].toString());
Properties apps[] = desc[i].getApplications();
if (apps == null) {
trace("ERROR: Could not install. Descriptor contains no information on application.");
error();
return;
}
String appType = apps[0].getProperty("JUMPApplication_appModel");
JUMPInstallerModule installer = null;
if (appType.equals("xlet")) {
installer = createInstaller(JUMPAppModel.XLET);
} else if (appType.equals("main")) {
installer = createInstaller(JUMPAppModel.MAIN);
} else if (appType.equals("midlet")) {
installer = createInstaller(JUMPAppModel.MIDLET);
} else {
trace("ERROR: Unknown application type: " + appType);
error();
return;
}
JUMPContent installedApps[] = installer.install(url[i], desc[i]);
if (installedApps != null) {
// Print installed apps.
for(int j = 0; j < installedApps.length; j++) {
System.out.println("Application Installed: " + ((JUMPApplication)installedApps[j]).getTitle());
}
} else {
System.out.println("ERROR: No applications were installed for: " + desc[i].getName() + ".");
error();
}
System.out.println("==> Finished Installing: " + desc[i].getName());
System.out.println("");
}
}
}
private void doInstall(String provisioningServerURL, boolean userInteractive) {
DownloadTool downloadTool = new DownloadTool(provisioningServerURL);
downloadTool.startTool(userInteractive);
install(downloadTool.getURLs(), downloadTool.getDescriptors());
}
private void doUninstall(boolean userInteractive) {
if (userInteractive) {
userInteractiveUninstall();
} else {
nonInteractiveUninstall();
}
}
private void uninstall(JUMPApplication[] apps) {
if (apps == null) {
trace("ERROR: No apps specified to uninstall.");
error();
return;
}
for (int i = 0; i < apps.length; i++) {
System.out.println("");
System.out.println("==> Uninstalling: " + apps[i].getTitle());
if (apps[i] == null) {
System.out.println("ERROR: " + apps[i].getTitle() + " not found in content store.");
} else {
JUMPInstallerModule installer = null;
if (apps[i].getAppType() == JUMPAppModel.XLET) {
installer = createInstaller(JUMPAppModel.XLET);
} else if (apps[i].getAppType() == JUMPAppModel.MAIN) {
installer = createInstaller(JUMPAppModel.MAIN);
} else if (apps[i].getAppType() == JUMPAppModel.MIDLET) {
installer = createInstaller(JUMPAppModel.MIDLET);
}
installer.uninstall(apps[i]);
}
System.out.println("==> Finished Uninstalling: " + apps[i].getTitle());
System.out.println("");
}
}
private void userInteractiveUninstall() {
System.setProperty("jump.installer.interactive", "true");
JUMPInstallerModule installers[] = JUMPInstallerModuleFactory.getInstance().getAllInstallers();
Vector appsVector = new Vector();
// Get all of the apps
for (int i = 0, totalApps = 0; i < installers.length; i++) {
JUMPContent[] content = installers[i].getInstalled();
if (content != null) {
for(int j = 0; j < content.length; j++) {
appsVector.add(totalApps, content[j]);
totalApps++;
}
}
}
if (appsVector.size() == 0) {
System.out.println("No applications are installed in the content store.");
return;
}
// Show what is available and read input for a choice.
System.out.println( "uninstall choices: " );
Object apps[] = appsVector.toArray();
for (int i = 0; i < apps.length ; i++ ) {
System.out.println( "(" + i + "): " + ((JUMPApplication)apps[i]).getTitle());
}
String message = "Enter choice (-1 to exit) [-1]: ";
String choice = Utilities.promptUser(message);
int chosenUninstall = Integer.parseInt(choice);
System.out.println( chosenUninstall );
JUMPApplication app = (JUMPApplication)appsVector.get(chosenUninstall);
JUMPApplication[] chosenApps = new JUMPApplication[1];
chosenApps[0] = app;
uninstall(chosenApps);
}
private void nonInteractiveUninstall() {
System.setProperty("jump.installer.interactive", "false");
JUMPInstallerModule installers[] = JUMPInstallerModuleFactory.getInstance().getAllInstallers();
for (int i = 0; i < installers.length; i++) {
JUMPContent[] content = installers[i].getInstalled();
while (content != null && content.length > 0) {
if (content[0] != null) {
System.out.println("");
System.out.println("==> Uninstalling: " + ((JUMPApplication)content[0]).getTitle());
installers[i].uninstall(content[0]);
System.out.println("==> Finished Uninstalling: " + ((JUMPApplication)content[0]).getTitle());
System.out.println("");
}
content = installers[i].getInstalled();
}
}
}
private void doList() {
System.out.println("");
System.out.println("---------------------------------");
System.out.println("Applications Within Content Store");
System.out.println("---------------------------------");
System.out.println("");
JUMPInstallerModule installers[] = JUMPInstallerModuleFactory.getInstance().getAllInstallers();
int numApps = 0;
for (int i = 0; i < installers.length; i++) {
JUMPContent[] content = installers[i].getInstalled();
if (content != null) {
for(int j = 0; j < content.length; j++) {
numApps++;
System.out.println("App #" + numApps + ": " + ((JUMPApplication)content[j]).getTitle());
}
}
}
System.out.println("");
}
class DownloadTool {
private String provisioningServerURL = null;
// Values only used for a JSR 124 server
private final String omaSubDirectory = "oma";
private final String midpSubDirectory = "jam";
private boolean downloadFinished = false;
private boolean downloadAborted = false;
String outputFile = null;
byte[] buffer = null;
int bufferIndex = 0;
private Vector descriptorVector = null;
private Vector urlVector = null;
public DownloadTool(String provisioningServerURL) {
this.provisioningServerURL = provisioningServerURL;
setup();
}
void setup() {
// Determine the discovery URL
if (provisioningServerURL != null) {
System.out.println( "Using provisioning server URL at: " + provisioningServerURL );
} else {
System.out.println("A provisioning server url needs to be supplied.");
System.out.println("Please run again with an value set to the -ProvisioningServerURL flag.");
System.exit(0);
}
descriptorVector = new Vector();
urlVector = new Vector();
}
public URL[] getURLs() {
return (URL[])urlVector.toArray(new URL[]{});
}
public JUMPDownloadDescriptor[] getDescriptors() {
return (JUMPDownloadDescriptor[])descriptorVector.toArray(new JUMPDownloadDescriptor[]{});
}
void startTool() {
startTool(true);
}
void startTool(boolean userInteractive) {
String[] downloads = null;
String[] downloadNames = null;
if (provisioningServerURL == null) {
System.err.println("ERROR: A provisioning URL needs to be specified.");
System.exit(0);
}
// Check if we're using a JSR 124 server
if (provisioningServerURL.endsWith("ri-test")) {
HashMap applistOMA = new OTADiscovery().discover(provisioningServerURL + "/" + omaSubDirectory);
HashMap applistMIDP = new OTADiscovery().discover(provisioningServerURL + "/" + midpSubDirectory);
downloads = new String[ applistOMA.size() + applistMIDP.size() ];
downloadNames = new String[ applistOMA.size() + applistMIDP.size() ];
int i = 0;
for ( Iterator e = applistOMA.keySet().iterator(); e.hasNext(); ) {
String s = (String)e.next();
downloads[ i ] = s;
downloadNames[ i ] = (String)applistOMA.get( s );
i++;
}
for ( Iterator e = applistMIDP.keySet().iterator(); e.hasNext(); ) {
String s = (String)e.next();
downloads[ i ] = s;
downloadNames[ i ] = (String)applistMIDP.get( s );
i++;
}
} else {
// we're using an apache-based server
HashMap applist = new OTADiscovery().discover(provisioningServerURL);
downloads = new String[ applist.size() ];
downloadNames = new String[ applist.size() ];
int i = 0;
for ( Iterator e = applist.keySet().iterator(); e.hasNext(); ) {
String s = (String)e.next();
downloads[ i ] = s;
downloadNames[ i ] = (String)applist.get( s );
i++;
}
}
if (userInteractive) {
userInteractiveDownload(downloads, downloadNames);
} else {
nonInteractiveDownload(downloads, downloadNames);
}
}
void nonInteractiveDownload(String[] downloads, String[] downloadNames) {
for (int i = 0; i < downloads.length; i++) {
trace("Downloading: " + downloadNames[i]);
doDownload(downloadNames[i], downloads[i]);
}
}
void userInteractiveDownload(String[] downloads, String[] downloadNames) {
// Show what is available and read input for a choice.
System.out.println( "download choices: " );
for (int i = 0; i < downloadNames.length ; i++ ) {
System.out.println( "(" + i + "): " + downloadNames[ i ] );
}
String message = "Enter choice (-1 to exit) [-1]: ";
String choice = Utilities.promptUser(message);
int chosenDownload = Integer.parseInt(choice);
// If no valid choice, quit
if ( chosenDownload < 0 ) {
System.exit( 0 );
}
System.out.println( chosenDownload + ": " + downloads[ chosenDownload ] );
boolean rv = doDownload(downloadNames[chosenDownload], downloads[chosenDownload]);
}
private boolean doDownload(String name, String uri) {
// Initiate a download. We've specified ourselves
// as the handler of the data.
if (uri.endsWith(".dd")) {
startDownload(name, uri, JUMPDownloadModuleFactory.PROTOCOL_OMA_OTA);
} else if (uri.endsWith(".jad")) {
startDownload(name, uri, JUMPDownloadModuleFactory.PROTOCOL_MIDP_OTA);
} else {
System.out.println("ERROR: Unknown URI type: " + uri);
System.exit(0);
}
// Wait for either failure or success
while ( downloadFinished == false &&
downloadAborted == false ) {
System.out.println( "waiting for download" );
try {
Thread.sleep( 100 );
} catch ( java.lang.InterruptedException ie ) {
ie.printStackTrace();
// Eat it
}
}
// Some resolution
if ( ! downloadFinished ) {
trace( "Download failed!" );
return false;
} else {
trace( "Download succeeded!" );
return true;
}
}
void startDownload(String name, String uri, String protocol) {
downloadFinished = false;
downloadAborted = false;
System.out.println("");
System.out.println("==> Downloading: " + name);
trace( "Creating descriptor for " + uri );
JUMPDownloadModule module =
JUMPDownloadModuleFactory.getInstance().getModule(protocol);
try {
JUMPDownloadDescriptor descriptor = module.createDescriptor( uri );
if (descriptor == null) {
System.out.println("ERROR: Returned descriptor is NULL for " + uri);
System.exit(0);
}
JUMPDownloader downloader = module.createDownloader(descriptor);
JUMPDownloadDestination destination = new DownloadDestinationImpl(descriptor);
// Trigger the download
URL url = downloader.start( destination );
trace( "Download returns url: " + url);
downloadFinished = true;
descriptorVector.add(descriptor);
urlVector.add(url);
} catch ( JUMPDownloadException o ) {
System.out.println( "Download failed for " + uri);
if (Verbose) {
o.printStackTrace();
}
downloadAborted = true;
} catch ( Exception o ) {
System.out.println( "Download failed for " + uri);
if (Verbose) {
o.printStackTrace();
}
downloadAborted = true;
} finally {
System.out.println("==> Finished Downloading: " + name);
System.out.println("");
}
}
}
/**
*
* @param args
*/
public static void main(String[] args) {
Hashtable argTable = new Hashtable();
String arg = null;
// The options -ContentURL, -DescriptorURI, and -Protocol are not
// yet functional yet as our download implementation's createDescriptor
// methods assume an http connection.
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-ProvisioningServerURL")) {
arg = args[++i];
argTable.put("ProvisioningServerURL", arg);
} else if (args[i].equals("-command")) {
arg = args[++i];
argTable.put("Command", arg);
} else if (args[i].equals("-verbose")) {
System.setProperty("installer.verbose", "true");
argTable.put("Verbose", "true");
} else if (args[i].equals("-ContentURL")) {
arg = args[++i];
argTable.put("ContentURL", arg);
} else if (args[i].equals("-DescriptorURI")) {
arg = args[++i];
argTable.put("DescriptorURI", arg);
} else if (args[i].equals("-Protocol")) {
arg = args[++i];
argTable.put("Protocol", arg);
}
}
new JUMPInstallerTool(argTable);
}
}
| true |
17256bb9180b1095b1904fcbca1718d4370a2392 | Java | AY1920S1-CS2103T-T17-2/main | /src/main/java/seedu/address/calendar/model/event/exceptions/DuplicateEventException.java | UTF-8 | 324 | 2.484375 | 2 | [
"MIT"
] | permissive | package seedu.address.calendar.model.event.exceptions;
/**
* Represents an error when the user tries to add two events that are of the same type.
*/
public class DuplicateEventException extends RuntimeException {
public DuplicateEventException() {
super("Operation would result in duplicate events");
}
}
| true |
ac5adc1fbe4efe0e0af1632993166b7b26686172 | Java | SC0d3r/Mafia-Game | /EndOfDayVotingState.java | UTF-8 | 332 | 2.203125 | 2 | [] | no_license | /**
* this class will just goes to disable chat state
*/
public class EndOfDayVotingState extends ServerState {
public EndOfDayVotingState(Narrator narrator, GameServer server) {
super(narrator, server);
}
@Override
public boolean run() {
this.narrator.changeState(STATES.DISABLE_CHAT);
return false;
}
}
| true |
753da04571e63a3410aec9a6afac45152fe760ed | Java | OscarFarg/multiplex-game | / multiplex-game/multiplex/src/multiplex/spelementen/StatischObject.java | UTF-8 | 174 | 2.03125 | 2 | [] | no_license | package multiplex.spelementen;
import multiplex.level.Level;
public class StatischObject extends SpelElement {
public StatischObject(Level level)
{
super(level);
}
}
| true |
718e413fd37f1219aed6fa26fa14ddd29f72d15c | Java | rwd117/Toy-Project | /MyProject/src/main/java/kr/co/korea/controller/AlaramController.java | UTF-8 | 1,884 | 2.265625 | 2 | [] | no_license | package kr.co.korea.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import kr.co.korea.beans.AlarmBean;
import kr.co.korea.service.AlarmService;
@RestController
@RequestMapping("/msg")
public class AlaramController {
@Autowired
private AlarmService alarmservice;
@PostMapping("/no")
public List<AlarmBean> alarmlist(){
List<AlarmBean> list = new ArrayList<>();
list = alarmservice.alarmlist(currentUserName() );
return list;
}
@PostMapping("/countalarm")
public int alarmcount() {
int count = 0;
try {
count = alarmservice.alarmcount(currentUserName());
}catch(Exception e) {
e.printStackTrace();
count =0;
}
return count;
}
@PostMapping("/savealarm")
public Map<String,Object> alarminsert(@RequestBody AlarmBean alarmbean) {
Map<String,Object> map = new HashMap<String, Object>();
try {
alarmbean.setAmid(currentUserName());
alarmservice.alarminsert(alarmbean);
map.put("result", "success");
}catch(Exception e) {
e.printStackTrace();
map.put("result", "fail");
}
return map;
}
//유저의 아이디를 가져옴
private String currentUserName() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String user = auth.getName();
return user;
}
}
| true |
e5ab828a093c502d518358dcc6c9039a9f50fff0 | Java | Bambino33/bowling | /src/main/java/com/casestudy/bowling/BowlingCal.java | UTF-8 | 442 | 2.828125 | 3 | [] | no_license | package com.casestudy.bowling;
import com.google.common.collect.Lists;
import java.util.List;
public class BowlingCal {
private List<Round> rounds = Lists.newArrayList();
public void addRound(Round round) {
this.rounds.add(round);
}
public int getTotalScore() {
int totalScore = 0;
for (Round round:rounds){
totalScore += round.getScore();
}
return totalScore;
}
}
| true |
f42469dfdff251b66bdec1c2e0348966cd55574b | Java | l-e-i-n-a-d/SWitCH | /DSOFT1/src/aula20171011/SumTwoArrays.java | UTF-8 | 254 | 3.15625 | 3 | [] | no_license | package aula20171011;
public class SumTwoArrays {
public static int[] sum(int[] a, int[] b) {
int[] result = new int[Math.max(a.length, b.length)];
for (int i = 0; i < result.length; i++) {
result[i] = a[i] + b[i];
}
return result;
}
}
| true |
4fd2333dd44aeb8796078a5f0475afffb0a91b7b | Java | szagot/java_spring_ionic_backend | /src/main/java/com/zefuinha/spring_ionic_backend/services/ProdutoService.java | UTF-8 | 3,595 | 2.421875 | 2 | [] | no_license | package com.zefuinha.spring_ionic_backend.services;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.zefuinha.spring_ionic_backend.domain.Categoria;
import com.zefuinha.spring_ionic_backend.domain.Produto;
import com.zefuinha.spring_ionic_backend.repositories.CategoriaRepository;
import com.zefuinha.spring_ionic_backend.repositories.ProdutoRepository;
import com.zefuinha.spring_ionic_backend.services.exceptions.ObjectNotFoundException;
@Service
public class ProdutoService {
@Autowired
private ProdutoRepository repository;
@Autowired
private CategoriaRepository categoriaRepository;
@Autowired
private CNService cnService;
@Value("${image.product.small.size}")
private String smallSize;
public List<Produto> findAll() {
return repository.findAll();
}
public Produto findById(Integer id) {
// O Optional evita que ocorra um NullException caso não seja encontrada a
// produto do id informado
Optional<Produto> produto = repository.findById(id);
// Retorna a produto, ou então uma exceção
return produto.orElseThrow(() -> new ObjectNotFoundException(
"Produto não encontrado. Id: " + id + ", Nome: " + Produto.class.getName()));
}
/**
* Busca todos os produtos pertencentes às categorias de IDs informados que
* possuam o texto de busca em seus nomes
*
* @param busca
* @param catIds
* @param page
* @param limit
* @param orderBy
* @param direction
* @return
*/
public Page<Produto> search(String busca, List<Integer> catIds, Integer page, Integer limit, String orderBy,
String direction) {
PageRequest pageRequest = PageRequest.of(page, limit, Direction.valueOf(direction), orderBy);
// Pega as categorias da lista de Ids informados
List<Categoria> categorias = categoriaRepository.findAllById(catIds);
return repository.findDistinctByNomeContainingIgnoreCaseAndCategoriasIn(busca, categorias, pageRequest);
}
/**
* Faz o upload de uma foto de produto e salva
*
* @param multipartFile
* @param id
* @param isSmall
* @return
*/
private URI uploadPicture(MultipartFile multipartFile, Integer id, boolean isSmall) {
// Pega a categoria informada
Produto produto = findById(id);
// O profileSize está vazio ou não é miniatura?
if (smallSize == null || smallSize.isEmpty() || !isSmall) {
smallSize = "0";
}
// Faz o upload da imagem
URI uri = cnService.uploadFile(multipartFile, Integer.parseInt(smallSize));
// Salva a imagem no produto
if (isSmall)
produto.setImageSmallUrl(uri.toString());
else
produto.setImageUrl(uri.toString());
repository.save(produto);
// Devolve a uri da imagem
return uri;
}
/**
* Faz o upload de uma foto normal de produto e salva
*
* @param multipartFile
* @param id
* @param isSmall
* @return
*/
public URI uploadPicture(MultipartFile multipartFile, Integer id) {
return uploadPicture(multipartFile, id, false);
}
/**
* Faz o upload de uma foto miniatura de produto e salva
*
* @param multipartFile
* @param id
* @param isSmall
* @return
*/
public URI uploadSmallPicture(MultipartFile multipartFile, Integer id) {
return uploadPicture(multipartFile, id, true);
}
}
| true |
8281f40fa177afca131edefcbd81e6bd31865ce4 | Java | ajoxe/Grupp | /app/src/main/java/com/example/c4q/capstone/userinterface/user/userprofilefragments/userprofileviews/GroupViewHolder.java | UTF-8 | 2,226 | 2.140625 | 2 | [] | no_license | package com.example.c4q.capstone.userinterface.user.userprofilefragments.userprofileviews;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.example.c4q.capstone.R;
import com.example.c4q.capstone.userinterface.user.userprofilefragments.UPCreateGroupFragment;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* Created by melg on 3/18/18.
*/
public class GroupViewHolder extends RecyclerView.ViewHolder {
private final Context context;
private CircleImageView groupImage;
private TextView groupName;
public GroupViewHolder(final View itemView) {
super(itemView);
groupImage = itemView.findViewById(R.id.group_image);
context = itemView.getContext();
groupName = itemView.findViewById(R.id.group_name);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UPCreateGroupFragment upCreateGroupFragment = new UPCreateGroupFragment();
//FragmentTransaction fragmentTransaction =
}
});
}
public void onBind(int position) {
groupName.setText("Grupp " + String.valueOf(position));
// groupImage.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//// Intent groupDetailIntent = new Intent(context, UPCreateGroupFragment.class);
//// context.startActivity(groupDetailIntent);
//
//// UPCreateGroupFragment upGroupDisplayFragment = new UPCreateGroupFragment();
//// // FragmentManager fragmentManager =
//// FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//// fragmentTransaction.replace(R.id.up_bottom_frag_cont, upGroupDisplayFragment);
//// fragmentTransaction.commit();
//
//
// // FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
// //transaction.replace(R.id.up_bottom_frag_cont, fragment).commit();
//
//
// }
// });
}
}
| true |
1442364b4f0c3ab480f9ef14f8f69e70ce2dabd4 | Java | SebastianTang/oc-server | /oc-server-core/src/main/java/com/oc/cluster/collection/set/CustomSetFactory.java | UTF-8 | 1,587 | 2.3125 | 2 | [] | no_license | /**
*
*/
package com.oc.cluster.collection.set;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hazelcast.core.HazelcastInstance;
import com.oc.cluster.collection.set.hazelcast.ClusteredSetFactoryStrategy;
import com.oc.cluster.collection.set.local.DefaultCustomSetFactoryStrategy;
import io.netty.util.internal.PlatformDependent;
/**
* @Description:
* @author chuangyeifang
* @createDate 2020年1月4日
* @version v 1.0
*/
public class CustomSetFactory {
private static Logger log = LoggerFactory.getLogger(CustomSetFactory.class);
private static Map<String, CustomSet<?>> sets = PlatformDependent.newConcurrentHashMap();
private static CustomSetFactoryStrategy ocQueueFactoryStrategy;
private static CustomSetFactoryStrategy clusteredOCQueueFactoryStrategy;
private static CustomSetFactoryStrategy localOCQueueFactoryStrategy;
private CustomSetFactory() {}
static {
localOCQueueFactoryStrategy = new DefaultCustomSetFactoryStrategy();
ocQueueFactoryStrategy = localOCQueueFactoryStrategy;
}
public static synchronized void startCluster(HazelcastInstance hi) {
log.info("SetFactory 开启Hazelcast集群模式.");
clusteredOCQueueFactoryStrategy = new ClusteredSetFactoryStrategy(hi);
ocQueueFactoryStrategy = clusteredOCQueueFactoryStrategy;
}
@SuppressWarnings("unchecked")
public static <T extends CustomSet<?>> T createQueue(String name) {
T t = (T)sets.get(name);
if (null == t) {
t = (T)ocQueueFactoryStrategy.createOCSet(name);
sets.put(name, t);
}
return t;
}
}
| true |
796ba5cc89d2e6cc6f2386c22953ca89301b095c | Java | zUnixBR/All-Mineplex-2015 | /Nautilus.Game.Arcade/src/nautilus/game/arcade/gui/privateServer/page/RemoveAdminPage.java | UTF-8 | 1,624 | 2.34375 | 2 | [] | no_license | package nautilus.game.arcade.gui.privateServer.page;
import java.util.HashSet;
import java.util.Iterator;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.shop.item.IButton;
import nautilus.game.arcade.ArcadeManager;
import nautilus.game.arcade.gui.privateServer.PrivateServerShop;
public class RemoveAdminPage extends BasePage
{
public RemoveAdminPage(ArcadeManager plugin, PrivateServerShop shop, Player player)
{
super(plugin, shop, "Remove Admin", player);
buildPage();
}
@Override
protected void buildPage()
{
addBackButton(4);
HashSet<String> admins = _manager.getAdminList();
Iterator<String> iterator = admins.iterator();
int slot = 9;
while (iterator.hasNext())
{
String name = iterator.next();
ItemStack head = getPlayerHead(name, C.cGreen + C.Bold + name, new String[] {ChatColor.RESET + C.cGray + "Click to Remove Admin"});
addButton(slot, head, getRemoveAdminButton(slot, name));
slot++;
}
}
private IButton getRemoveAdminButton(final int slot, final String playerName)
{
return new IButton()
{
@Override
public void onClick(Player player, ClickType clickType)
{
_manager.removeAdmin(playerName);
removeButton(slot);
UtilPlayer.message(getPlayer(), F.main("Server", "You removed admin power from " + F.name(playerName) + "."));
}
};
}
}
| true |
79a47b247738a1a3911ac4c1a2843d7c90f71095 | Java | efrik1989/SimpleCalc | /src/main/java/simplecalc/NumberListener.java | UTF-8 | 2,780 | 3.453125 | 3 | [] | no_license | package simplecalc;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static simplecalc.CalcGUI.getTextField;
/**
* Класс слушатель кнопок
*/
class NumberListener implements ActionListener {
private static final char EQUALLY = '=';
private static final char CANCEL = 'C';
private static String temp;
/**
* Действия пр нажатии кнопок
*
* @throws NumberFormatException
*/
@Override
public void actionPerformed(ActionEvent e) throws NumberFormatException {
String buttonCommand = e.getActionCommand();
if (!buttonCommand.equals(".")) {
if (temp != null) {
if (!buttonCommand.equals(EQUALLY)) {
temp = temp + buttonCommand;
}
getTextField().setText(temp);
switch (buttonCommand.charAt(0)) {
case EQUALLY:
Calc calc = new Calc();
getTextField().setText(calc.calculate(getTemp().
replaceAll("=", "").
replaceAll(" ", "")));
System.out.println("SimpleCalc.stringCalc вызов = " + getTextField().getText());
break;
case CANCEL:
try {
cancel();
} catch (Exception e1) {
e1.printStackTrace();
}
break;
}
} else temp = buttonCommand;
}
}
/**
* Проверка на корректность введенных значений
*/
private static void checkCorrectSymbol(String expression) throws Exception {
if (!(expression.length() == 0)) {
char symbol = expression.charAt(expression.length() - 1);
String s = String.valueOf(symbol);
if (s.matches("[a-zA-ZА-Яа-я]")) {
setTemp("Введите числовое выражение.");
}
}
}
/**
* Получение значения переменной Temp
*/
public static String getTemp() {
return temp;
}
/**
* Назначение переменной Temp
*/
public static void setTemp(String temp) throws Exception {
NumberListener.temp = temp;
checkCorrectSymbol(temp);
}
/**
* Метод очистки поля ввода и временных переменных
* @throws Exception
*/
public static void cancel() throws Exception {
setTemp("");
getTextField().setText("");
}
} | true |
1121159f80b9cda90059756da87c2e1a950f03d7 | Java | phongtran0715/SpiderClient | /java/netxms-eclipse/Charts/src/org/netxms/ui/eclipse/charts/api/HistoricalDataChart.java | UTF-8 | 3,827 | 2.375 | 2 | [] | no_license | /**
* NetXMS - open source network management system
* Copyright (C) 2003-2014 Victor Kirhenshtein
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.netxms.ui.eclipse.charts.api;
import java.util.Date;
import java.util.List;
import org.netxms.client.datacollection.DciData;
import org.netxms.client.datacollection.GraphItem;
import org.netxms.client.datacollection.GraphItemStyle;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.widgets.Canvas;
/**
* Historical data chart interface
*
*/
public interface HistoricalDataChart extends DataChart {
/**
* Set time range for chart.
*
* @param from
* @param to
*/
public abstract void setTimeRange(Date from, Date to);
/**
* @return the zoomEnabled
*/
public abstract boolean isZoomEnabled();
/**
* @param zoomEnabled
* the zoomEnabled to set
*/
public abstract void setZoomEnabled(boolean enableZoom);
/**
* @return the itemStyles
*/
public abstract List<GraphItemStyle> getItemStyles();
/**
* @param itemStyles
* the itemStyles to set
*/
public abstract void setItemStyles(List<GraphItemStyle> itemStyles);
/**
* Add new parameter to chart.
*
* @param item
* parameter
* @return assigned index
*/
public abstract int addParameter(GraphItem item);
/**
* Update data for parameter
*
* @param index
* parameter's index
* @param data
* data for parameter
* @param updateChart
* if true, chart will be updated (repainted)
*/
public abstract void updateParameter(int index, DciData data,
boolean updateChart);
/**
* Adjust X axis to fit all data
*
* @param repaint
* if true, chart will be repainted after change
*/
public abstract void adjustXAxis(boolean repaint);
/**
* Adjust Y axis to fit all data
*
* @param repaint
* if true, chart will be repainted after change
*/
public abstract void adjustYAxis(boolean repaint);
/**
* Zoom in
*/
public abstract void zoomIn();
/**
* Zoom out
*/
public abstract void zoomOut();
/**
* Set stacked mode
*
* @param stacked
*/
public abstract void setStacked(boolean stacked);
/**
* Get current settings for "stacked" mode
*
* @return
*/
public abstract boolean isStacked();
/**
* Set extended legend mode (when legend shows min, max, and average values)
*
* @param extended
*/
public void setExtendedLegend(boolean extended);
/**
* Get current settings for extended legend mode
*
* @return
*/
public boolean isExtendedLegend();
/**
* Set line width for chart
*
* @param width
*/
public void setLineWidth(int width);
/**
* Get line width
*
* @return
*/
public int getLineWidth();
/**
* Modify Y base
*
* @param modifyYBase
* true to use min DCI value as Y base
*/
public void modifyYBase(boolean modifyYBase);
/**
* Add mouse listener to chart
*
* @param listener
* to add
*/
public void addMouseListener(MouseListener listener);
/**
* Gets the plot area.
*
* @return the plot area
*/
public Canvas getPlotArea();
}
| true |
31dedb588943d8c825c8683f07cadd306f0044dd | Java | Debayan-Majumdar/DesignPrinciples_Handson | /Singleton_Handson/src/main/java/com/debayan/designpattern/Singleton_Handson/Test/TestDBConn.java | UTF-8 | 598 | 2.703125 | 3 | [] | no_license | /**
*
*/
package com.debayan.designpattern.Singleton_Handson.Test;
import com.debayan.designpattern.Singleton_Handson.DBConn;
import jdk.jfr.internal.Logger;
/**
* @author DEBAYAN
*
*/
public class TestDBConn {
/**
* @param args
*/
public static void main(String[] args) {
int instance1 = DBConn.getInstance().hashCode();
System.out.println(instance1);
int instance2 = DBConn.getInstance().hashCode();
System.out.println(instance2);
if (instance1 == instance1) {
System.out.println("SingleTon Design Principal is applied");
}
}
}
| true |
42107edf4a32f008684bf36e946e4253d8586b25 | Java | collinsauve/azure-sdk-for-java | /management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineOperations.java | UTF-8 | 78,754 | 1.851563 | 2 | [
"Apache-2.0"
] | permissive | /**
*
* Copyright (c) Microsoft and contributors. All rights reserved.
*
* 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.
*
*/
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
package com.microsoft.windowsazure.management.compute;
import com.microsoft.windowsazure.core.OperationResponse;
import com.microsoft.windowsazure.core.OperationStatusResponse;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineCaptureOSImageParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineCaptureVMImageParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineCreateDeploymentParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineCreateParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineGetRemoteDesktopFileResponse;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineGetResponse;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineShutdownParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineShutdownRolesParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineStartRolesParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineUpdateLoadBalancedSetParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineUpdateParameters;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.xml.sax.SAXException;
/**
* The Service Management API includes operations for managing the virtual
* machines in your subscription. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157206.aspx for more
* information)
*/
public interface VirtualMachineOperations {
/**
* The Begin Capturing Role operation creates a copy of the operating system
* virtual hard disk (VHD) that is deployed in the virtual machine, saves
* the VHD copy in the same storage location as the operating system VHD,
* and registers the copy as an image in your image gallery. From the
* captured image, you can create additional customized virtual machines.
* For more information about images and disks, see Manage Disks and Images
* at http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx.
* For more information about capturing images, see How to Capture an Image
* of a Virtual Machine Running Windows Server 2008 R2 at
* http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/
* or How to Capture an Image of a Virtual Machine Running Linux at
* http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* restart.
* @param parameters Required. Parameters supplied to the Begin Capturing
* Virtual Machine operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
OperationResponse beginCapturingOSImage(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureOSImageParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException;
/**
* The Begin Capturing Role operation creates a copy of the operating system
* virtual hard disk (VHD) that is deployed in the virtual machine, saves
* the VHD copy in the same storage location as the operating system VHD,
* and registers the copy as an image in your image gallery. From the
* captured image, you can create additional customized virtual machines.
* For more information about images and disks, see Manage Disks and Images
* at http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx.
* For more information about capturing images, see How to Capture an Image
* of a Virtual Machine Running Windows Server 2008 R2 at
* http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/
* or How to Capture an Image of a Virtual Machine Running Linux at
* http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* restart.
* @param parameters Required. Parameters supplied to the Begin Capturing
* Virtual Machine operation.
* @return A standard service response including an HTTP status code and
* request ID.
*/
Future<OperationResponse> beginCapturingOSImageAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureOSImageParameters parameters);
/**
* Begin capturing role as VM template.
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* restart.
* @param parameters Required. Parameters supplied to the Capture Virtual
* Machine operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
OperationResponse beginCapturingVMImage(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureVMImageParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException;
/**
* Begin capturing role as VM template.
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* restart.
* @param parameters Required. Parameters supplied to the Capture Virtual
* Machine operation.
* @return A standard service response including an HTTP status code and
* request ID.
*/
Future<OperationResponse> beginCapturingVMImageAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureVMImageParameters parameters);
/**
* The Begin Creating Role operation adds a virtual machine to an existing
* deployment. You can refer to the OSDisk in the Add Role operation in the
* following ways: Platform/User Image - Set the SourceImageName to a
* platform or user image. You can optionally specify the DiskName and
* MediaLink values as part the operation to control the name and location
* of target disk. When DiskName and MediaLink are specified in this mode,
* they must not already exist in the system, otherwise a conflict fault is
* returned; UserDisk - Set DiskName to a user supplied image in image
* repository. SourceImageName must be set to NULL. All other properties
* are ignored; or Blob in a Storage Account - Set MediaLink to a blob
* containing the image. SourceImageName and DiskName are set to NULL.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters supplied to the Begin Creating
* Virtual Machine operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
OperationResponse beginCreating(String serviceName, String deploymentName, VirtualMachineCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException;
/**
* The Begin Creating Role operation adds a virtual machine to an existing
* deployment. You can refer to the OSDisk in the Add Role operation in the
* following ways: Platform/User Image - Set the SourceImageName to a
* platform or user image. You can optionally specify the DiskName and
* MediaLink values as part the operation to control the name and location
* of target disk. When DiskName and MediaLink are specified in this mode,
* they must not already exist in the system, otherwise a conflict fault is
* returned; UserDisk - Set DiskName to a user supplied image in image
* repository. SourceImageName must be set to NULL. All other properties
* are ignored; or Blob in a Storage Account - Set MediaLink to a blob
* containing the image. SourceImageName and DiskName are set to NULL.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters supplied to the Begin Creating
* Virtual Machine operation.
* @return A standard service response including an HTTP status code and
* request ID.
*/
Future<OperationResponse> beginCreatingAsync(String serviceName, String deploymentName, VirtualMachineCreateParameters parameters);
/**
* The Begin Creating Virtual Machine Deployment operation provisions a
* virtual machine based on the supplied configuration. When you create a
* deployment of a virtual machine, you should make sure that the cloud
* service and the disk or image that you use are located in the same
* region. For example, if the cloud service was created in the West US
* region, the disk or image that you use should also be located in a
* storage account in the West US region. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param parameters Required. Parameters supplied to the Begin Creating
* Virtual Machine Deployment operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
OperationResponse beginCreatingDeployment(String serviceName, VirtualMachineCreateDeploymentParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException;
/**
* The Begin Creating Virtual Machine Deployment operation provisions a
* virtual machine based on the supplied configuration. When you create a
* deployment of a virtual machine, you should make sure that the cloud
* service and the disk or image that you use are located in the same
* region. For example, if the cloud service was created in the West US
* region, the disk or image that you use should also be located in a
* storage account in the West US region. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param parameters Required. Parameters supplied to the Begin Creating
* Virtual Machine Deployment operation.
* @return A standard service response including an HTTP status code and
* request ID.
*/
Future<OperationResponse> beginCreatingDeploymentAsync(String serviceName, VirtualMachineCreateDeploymentParameters parameters);
/**
* The Begin Deleting Role operation deletes the specified virtual machine.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* delete.
* @param deleteFromStorage Required. Specifies that the source blob(s) for
* the virtual machine should also be deleted from storage.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
OperationResponse beginDeleting(String serviceName, String deploymentName, String virtualMachineName, boolean deleteFromStorage) throws IOException, ServiceException;
/**
* The Begin Deleting Role operation deletes the specified virtual machine.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* delete.
* @param deleteFromStorage Required. Specifies that the source blob(s) for
* the virtual machine should also be deleted from storage.
* @return A standard service response including an HTTP status code and
* request ID.
*/
Future<OperationResponse> beginDeletingAsync(String serviceName, String deploymentName, String virtualMachineName, boolean deleteFromStorage);
/**
* The Begin Restarting role operation restarts the specified virtual
* machine. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* restart.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
OperationResponse beginRestarting(String serviceName, String deploymentName, String virtualMachineName) throws IOException, ServiceException;
/**
* The Begin Restarting role operation restarts the specified virtual
* machine. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* restart.
* @return A standard service response including an HTTP status code and
* request ID.
*/
Future<OperationResponse> beginRestartingAsync(String serviceName, String deploymentName, String virtualMachineName);
/**
* The Shutdown Role operation shuts down the specified virtual machine.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* shutdown.
* @param parameters Required. The parameters for the shutdown vm operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
OperationResponse beginShutdown(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineShutdownParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException;
/**
* The Shutdown Role operation shuts down the specified virtual machine.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* shutdown.
* @param parameters Required. The parameters for the shutdown vm operation.
* @return A standard service response including an HTTP status code and
* request ID.
*/
Future<OperationResponse> beginShutdownAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineShutdownParameters parameters);
/**
* The Begin Shutting Down Roles operation stops the specified set of
* virtual machines. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn469421.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters to pass to the Begin Shutting Down
* Roles operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
OperationResponse beginShuttingDownRoles(String serviceName, String deploymentName, VirtualMachineShutdownRolesParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException;
/**
* The Begin Shutting Down Roles operation stops the specified set of
* virtual machines. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn469421.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters to pass to the Begin Shutting Down
* Roles operation.
* @return A standard service response including an HTTP status code and
* request ID.
*/
Future<OperationResponse> beginShuttingDownRolesAsync(String serviceName, String deploymentName, VirtualMachineShutdownRolesParameters parameters);
/**
* The Begin Starting Role operation starts the specified virtual machine.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* start.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
OperationResponse beginStarting(String serviceName, String deploymentName, String virtualMachineName) throws IOException, ServiceException;
/**
* The Begin Starting Role operation starts the specified virtual machine.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* start.
* @return A standard service response including an HTTP status code and
* request ID.
*/
Future<OperationResponse> beginStartingAsync(String serviceName, String deploymentName, String virtualMachineName);
/**
* The Begin Starting Roles operation starts the specified set of virtual
* machines. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn469419.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters to pass to the Begin Starting
* Roles operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
OperationResponse beginStartingRoles(String serviceName, String deploymentName, VirtualMachineStartRolesParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException;
/**
* The Begin Starting Roles operation starts the specified set of virtual
* machines. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn469419.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters to pass to the Begin Starting
* Roles operation.
* @return A standard service response including an HTTP status code and
* request ID.
*/
Future<OperationResponse> beginStartingRolesAsync(String serviceName, String deploymentName, VirtualMachineStartRolesParameters parameters);
/**
* The Begin Updating Role operation adds a virtual machine to an existing
* deployment. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of your virtual machine.
* @param parameters Required. Parameters supplied to the Begin Updating
* Virtual Machine operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
OperationResponse beginUpdating(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException;
/**
* The Begin Updating Role operation adds a virtual machine to an existing
* deployment. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of your virtual machine.
* @param parameters Required. Parameters supplied to the Begin Updating
* Virtual Machine operation.
* @return A standard service response including an HTTP status code and
* request ID.
*/
Future<OperationResponse> beginUpdatingAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineUpdateParameters parameters);
/**
* The Begin Updating Load Balanced Endpoint Set operation changes the
* specified load-balanced InputEndpoints on all the roles of an
* Infrastructure as a Service deployment. Non-load-balanced endpoints must
* be changed using UpdateRole. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn469417.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters supplied to the Begin Updating
* Load Balanced Endpoint Set operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
OperationResponse beginUpdatingLoadBalancedEndpointSet(String serviceName, String deploymentName, VirtualMachineUpdateLoadBalancedSetParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException;
/**
* The Begin Updating Load Balanced Endpoint Set operation changes the
* specified load-balanced InputEndpoints on all the roles of an
* Infrastructure as a Service deployment. Non-load-balanced endpoints must
* be changed using UpdateRole. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn469417.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters supplied to the Begin Updating
* Load Balanced Endpoint Set operation.
* @return A standard service response including an HTTP status code and
* request ID.
*/
Future<OperationResponse> beginUpdatingLoadBalancedEndpointSetAsync(String serviceName, String deploymentName, VirtualMachineUpdateLoadBalancedSetParameters parameters);
/**
* The Capture Role operation creates a copy of the operating system virtual
* hard disk (VHD) that is deployed in the virtual machine, saves the VHD
* copy in the same storage location as the operating system VHD, and
* registers the copy as an image in your image gallery. From the captured
* image, you can create additional customized virtual machines. For more
* information about images and disks, see Manage Disks and Images at
* http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx. For
* more information about capturing images, see How to Capture an Image of
* a Virtual Machine Running Windows Server 2008 R2 at
* http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/
* or How to Capture an Image of a Virtual Machine Running Linux at
* http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* restart.
* @param parameters Required. Parameters supplied to the Capture Virtual
* Machine operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
OperationStatusResponse captureOSImage(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureOSImageParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException;
/**
* The Capture Role operation creates a copy of the operating system virtual
* hard disk (VHD) that is deployed in the virtual machine, saves the VHD
* copy in the same storage location as the operating system VHD, and
* registers the copy as an image in your image gallery. From the captured
* image, you can create additional customized virtual machines. For more
* information about images and disks, see Manage Disks and Images at
* http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx. For
* more information about capturing images, see How to Capture an Image of
* a Virtual Machine Running Windows Server 2008 R2 at
* http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/
* or How to Capture an Image of a Virtual Machine Running Linux at
* http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* restart.
* @param parameters Required. Parameters supplied to the Capture Virtual
* Machine operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
Future<OperationStatusResponse> captureOSImageAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureOSImageParameters parameters);
/**
* Capture role as VM template.
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* restart.
* @param parameters Required. Parameters supplied to the Capture Virtual
* Machine operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
OperationStatusResponse captureVMImage(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureVMImageParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException;
/**
* Capture role as VM template.
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* restart.
* @param parameters Required. Parameters supplied to the Capture Virtual
* Machine operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
Future<OperationStatusResponse> captureVMImageAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureVMImageParameters parameters);
/**
* The Create Role operation adds a virtual machine to an existing
* deployment. You can refer to the OSDisk in the Add Role operation in the
* following ways: Platform/User Image - Set the SourceImageName to a
* platform or user image. You can optionally specify the DiskName and
* MediaLink values as part the operation to control the name and location
* of target disk. When DiskName and MediaLink are specified in this mode,
* they must not already exist in the system, otherwise a conflict fault is
* returned; UserDisk - Set DiskName to a user supplied image in image
* repository. SourceImageName must be set to NULL. All other properties
* are ignored; or Blob in a Storage Account - Set MediaLink to a blob
* containing the image. SourceImageName and DiskName are set to NULL.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters supplied to the Create Virtual
* Machine operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
OperationStatusResponse create(String serviceName, String deploymentName, VirtualMachineCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException;
/**
* The Create Role operation adds a virtual machine to an existing
* deployment. You can refer to the OSDisk in the Add Role operation in the
* following ways: Platform/User Image - Set the SourceImageName to a
* platform or user image. You can optionally specify the DiskName and
* MediaLink values as part the operation to control the name and location
* of target disk. When DiskName and MediaLink are specified in this mode,
* they must not already exist in the system, otherwise a conflict fault is
* returned; UserDisk - Set DiskName to a user supplied image in image
* repository. SourceImageName must be set to NULL. All other properties
* are ignored; or Blob in a Storage Account - Set MediaLink to a blob
* containing the image. SourceImageName and DiskName are set to NULL.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters supplied to the Create Virtual
* Machine operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
Future<OperationStatusResponse> createAsync(String serviceName, String deploymentName, VirtualMachineCreateParameters parameters);
/**
* The Create Virtual Machine Deployment operation provisions a virtual
* machine based on the supplied configuration. When you create a
* deployment of a virtual machine, you should make sure that the cloud
* service and the disk or image that you use are located in the same
* region. For example, if the cloud service was created in the West US
* region, the disk or image that you use should also be located in a
* storage account in the West US region. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param parameters Required. Parameters supplied to the Create Virtual
* Machine Deployment operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
OperationStatusResponse createDeployment(String serviceName, VirtualMachineCreateDeploymentParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException;
/**
* The Create Virtual Machine Deployment operation provisions a virtual
* machine based on the supplied configuration. When you create a
* deployment of a virtual machine, you should make sure that the cloud
* service and the disk or image that you use are located in the same
* region. For example, if the cloud service was created in the West US
* region, the disk or image that you use should also be located in a
* storage account in the West US region. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param parameters Required. Parameters supplied to the Create Virtual
* Machine Deployment operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
Future<OperationStatusResponse> createDeploymentAsync(String serviceName, VirtualMachineCreateDeploymentParameters parameters);
/**
* The Delete Role operation deletes the specified virtual machine. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* delete.
* @param deleteFromStorage Required. Specifies that the source blob(s) for
* the virtual machine should also be deleted from storage.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
OperationStatusResponse delete(String serviceName, String deploymentName, String virtualMachineName, boolean deleteFromStorage) throws IOException, ServiceException, InterruptedException, ExecutionException;
/**
* The Delete Role operation deletes the specified virtual machine. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* delete.
* @param deleteFromStorage Required. Specifies that the source blob(s) for
* the virtual machine should also be deleted from storage.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
Future<OperationStatusResponse> deleteAsync(String serviceName, String deploymentName, String virtualMachineName, boolean deleteFromStorage);
/**
* The Get Role operation retrieves information about the specified virtual
* machine. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157193.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Get Virtual Machine operation response.
*/
VirtualMachineGetResponse get(String serviceName, String deploymentName, String virtualMachineName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException;
/**
* The Get Role operation retrieves information about the specified virtual
* machine. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157193.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine.
* @return The Get Virtual Machine operation response.
*/
Future<VirtualMachineGetResponse> getAsync(String serviceName, String deploymentName, String virtualMachineName);
/**
* The Download RDP file operation retrieves the Remote Desktop Protocol
* configuration file from the specified virtual machine. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157183.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The Download RDP file operation response.
*/
VirtualMachineGetRemoteDesktopFileResponse getRemoteDesktopFile(String serviceName, String deploymentName, String virtualMachineName) throws IOException, ServiceException;
/**
* The Download RDP file operation retrieves the Remote Desktop Protocol
* configuration file from the specified virtual machine. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157183.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine.
* @return The Download RDP file operation response.
*/
Future<VirtualMachineGetRemoteDesktopFileResponse> getRemoteDesktopFileAsync(String serviceName, String deploymentName, String virtualMachineName);
/**
* The Restart role operation restarts the specified virtual machine. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* restart.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
OperationStatusResponse restart(String serviceName, String deploymentName, String virtualMachineName) throws InterruptedException, ExecutionException, ServiceException, IOException;
/**
* The Restart role operation restarts the specified virtual machine. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* restart.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
Future<OperationStatusResponse> restartAsync(String serviceName, String deploymentName, String virtualMachineName);
/**
* The Shutdown Role operation shuts down the specified virtual machine.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* shutdown.
* @param parameters Required. The parameters for the shutdown virtual
* machine operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
OperationStatusResponse shutdown(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineShutdownParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException;
/**
* The Shutdown Role operation shuts down the specified virtual machine.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx
* for more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* shutdown.
* @param parameters Required. The parameters for the shutdown virtual
* machine operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
Future<OperationStatusResponse> shutdownAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineShutdownParameters parameters);
/**
* The Shutdown Roles operation stops the specified set of virtual machines.
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters to pass to the Shutdown Roles
* operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
OperationStatusResponse shutdownRoles(String serviceName, String deploymentName, VirtualMachineShutdownRolesParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException;
/**
* The Shutdown Roles operation stops the specified set of virtual machines.
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters to pass to the Shutdown Roles
* operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
Future<OperationStatusResponse> shutdownRolesAsync(String serviceName, String deploymentName, VirtualMachineShutdownRolesParameters parameters);
/**
* The Start Role operation starts the specified virtual machine. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* start.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
OperationStatusResponse start(String serviceName, String deploymentName, String virtualMachineName) throws InterruptedException, ExecutionException, ServiceException, IOException;
/**
* The Start Role operation starts the specified virtual machine. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* start.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
Future<OperationStatusResponse> startAsync(String serviceName, String deploymentName, String virtualMachineName);
/**
* The Start Roles operation starts the specified set of virtual machines.
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters to pass to the Start Roles
* operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
OperationStatusResponse startRoles(String serviceName, String deploymentName, VirtualMachineStartRolesParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException;
/**
* The Start Roles operation starts the specified set of virtual machines.
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters to pass to the Start Roles
* operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
Future<OperationStatusResponse> startRolesAsync(String serviceName, String deploymentName, VirtualMachineStartRolesParameters parameters);
/**
* The Update Role operation adds a virtual machine to an existing
* deployment. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of your virtual machine.
* @param parameters Required. Parameters supplied to the Update Virtual
* Machine operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
OperationStatusResponse update(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineUpdateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException;
/**
* The Update Role operation adds a virtual machine to an existing
* deployment. (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of your virtual machine.
* @param parameters Required. Parameters supplied to the Update Virtual
* Machine operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
Future<OperationStatusResponse> updateAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineUpdateParameters parameters);
/**
* The Update Load Balanced Endpoint Set operation changes the specified
* load-balanced InputEndpoints on all the roles of an Infrastructure as a
* Service deployment. Non-load-balanced endpoints must be changed using
* UpdateRole.
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters supplied to the Update Load
* Balanced Endpoint Set operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
OperationStatusResponse updateLoadBalancedEndpointSet(String serviceName, String deploymentName, VirtualMachineUpdateLoadBalancedSetParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException;
/**
* The Update Load Balanced Endpoint Set operation changes the specified
* load-balanced InputEndpoints on all the roles of an Infrastructure as a
* Service deployment. Non-load-balanced endpoints must be changed using
* UpdateRole.
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters supplied to the Update Load
* Balanced Endpoint Set operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
Future<OperationStatusResponse> updateLoadBalancedEndpointSetAsync(String serviceName, String deploymentName, VirtualMachineUpdateLoadBalancedSetParameters parameters);
}
| true |
796b25e4fdf4b16e765f487ffaf03382703ed3c8 | Java | Brotherta/RogueLike | /src/main/java/game/entity/living/npc/monster/monsters/Bat.java | UTF-8 | 1,550 | 2.71875 | 3 | [] | no_license | package game.entity.living.npc.monster.monsters;
import game.elements.GameRule;
import game.elements.GameState;
import game.entity.living.npc.monster.AbstractMonster;
import game.entity.living.npc.monster.Monster;
import game.entity.living.npc.monster.MonsterStats;
import game.entity.living.npc.monster.MonsterType;
import game.entity.living.npc.monster.monsterStrategy.Strategy;
import utils.Colors;
import utils.Position;
/**
* This class describe the monster Bat
* He has some basic statistic
* @author luca
*/
public class Bat extends AbstractMonster implements Monster {
/**
* Create a new Bat
*
* @param position his position in the room
* @param name his name
* @param level his level
* @param strategy his strategy to apply
*/
public Bat(Position position, String name, int level, Strategy strategy) {
super(position, name, Colors.BROWN, Colors.BROWN, MonsterType.BAT, strategy,
new MonsterStats(1,1,1,1,1,1,1,level, 1));
GameRule.setMonstersStats(this, MonsterType.BAT);
setSprites("\\o/", " ", getUpColor());
setBasicSprites("\\o/", " ");
}
@Override
public void doAction(GameState gameState) {
getStrategy().doAct(this, gameState.getPlayer(), gameState.getGridMap());
if (getStrategy().getStrategyDescription() != null) {
gameState.getDescriptor().updateDescriptor(getStrategy().getStrategyDescription());
}
}
@Override
public boolean isWeak() {
return true;
}
}
| true |
376db152f3bb72b04c4c375725ff5dff1f6b5079 | Java | selvaprasath2706/LICET-Students-Management-System-App | /app/src/main/java/com/example/licet/Main12Activity.java | UTF-8 | 1,884 | 2.203125 | 2 | [] | no_license | package com.example.licet;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main12Activity extends AppCompatActivity {
public String date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main12);
}
public void dateselector(View view) {
String d1, d2, d3;
DatePickerDialog.OnDateSetListener selva = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
int i0=Integer.parseInt(String.valueOf(i1));
i0=i0+1;
date = i2 + ":" + i0 + ":" + i;
}
};
Calendar c = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat("dd:MM:yyyy");
String date = s.format(c.getTime());
String values[] = date.split(":");
d1 = values[0];
d2 = values[1];
d3 = values[2];
int i1, i2, i3;
i1 = Integer.parseInt(d1);
i2 = Integer.parseInt(d2);
i3 = Integer.parseInt(d3);
i2 = i2 - 1;
DatePickerDialog d = new DatePickerDialog(Main12Activity.this, selva, i3, i2, i1);
d.show();
}
public void movetonextpage(View view) {
Intent intent=new Intent(Main12Activity.this,Main11Activity.class);
intent.putExtra("date",date);
startActivity(intent);
}
@Override
public void onBackPressed() {
Intent intent1=new Intent(this,Main2Activity.class);
startActivity(intent1);
}
}
| true |
aee46502b03750c85e656e84c8d6a9ad62c8d1c8 | Java | huanglongf/enterprise_project | /service-impl-wms/src/main/java/com/jumbo/dao/hub2wms/WmsSalesOrderQueueDao.java | UTF-8 | 3,420 | 1.757813 | 2 | [] | no_license | package com.jumbo.dao.hub2wms;
import java.math.BigDecimal;
import java.util.List;
import loxia.annotation.NamedQuery;
import loxia.annotation.NativeQuery;
import loxia.annotation.NativeUpdate;
import loxia.annotation.QueryParam;
import loxia.dao.GenericEntityDao;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.SingleColumnRowMapper;
import org.springframework.transaction.annotation.Transactional;
import com.jumbo.wms.model.hub2wms.WmsSalesOrderQueue;
@Transactional
public interface WmsSalesOrderQueueDao extends GenericEntityDao<WmsSalesOrderQueue, Long> {
/**
* 查询过仓队列表rowlimit条数据,设置"区分单据是否可创建定时任务"开始标志
*
* @param rowlimit
*/
@NativeUpdate
Integer setBeginFlagForOrder(@QueryParam("rowlimit") int rowlimit);
@NativeUpdate
Integer setBeginFlagForOrderNotin(@QueryParam("rowlimit") int rowlimit);
@NativeQuery
List<Long> getNeedExecuteWarehouse();
/**
* 查询所有设置了开始标识位的单据
*
* @param beanPropertyRowMapper
* @return
*/
@NativeQuery
List<WmsSalesOrderQueue> findAllOrderHaveFlag(BeanPropertyRowMapper<WmsSalesOrderQueue> beanPropertyRowMapper);
@NativeUpdate
Integer updateBeginFlagByPriorityOrder();
@NativeUpdate
Integer updateBeginFlagByOwner(@QueryParam("limit") int limit, @QueryParam("owner") String owner);
@NativeUpdate
Integer updateBeginFlagBycommonOwner(@QueryParam("limit") int limit, @QueryParam("owner") List<String> owner);
@NativeUpdate
void updateBeginFlagByAnalyzeOwner(@QueryParam("limit") int limit);
/**
* 查询当前默认发货仓为当前仓的单据
*
* @param id
*
* @param beanPropertyRowMapper
* @return
*/
@NativeQuery
List<WmsSalesOrderQueue> getOrderToSetFlagByOuId(@QueryParam("ouId") Long id, BeanPropertyRowMapper<WmsSalesOrderQueue> beanPropertyRowMapper);
/**
* 查询是否所有的单子都打上了能否创单标识
*
* @param singleColumnRowMapper
*/
@NativeQuery
Boolean getIsAllHaveFlag(SingleColumnRowMapper<Boolean> singleColumnRowMapper);
/**
* 查询所有可创的单子
*
* @param singleColumnRowMapper
* @return
*/
@NativeQuery
List<Long> getAllOrderToCreate(SingleColumnRowMapper<Long> singleColumnRowMapper);
@NativeQuery
List<Long> getAllOrderInvCheckCreate(@QueryParam("rownum") Long rownum, SingleColumnRowMapper<Long> singleColumnRowMapper);
/**
* 根据单据号
*
* @param id
*
* @param beanPropertyRowMapperExt
* @return
*/
@NamedQuery
WmsSalesOrderQueue getOrderToSetFlagByOrderCode(@QueryParam("code") String orderCode);
@NamedQuery
List<WmsSalesOrderQueue> findWmsSalesOrderQueueSendMq();
@NamedQuery
List<WmsSalesOrderQueue> queryErrorCount();
@NativeUpdate
int cleanDataByOrderId(@QueryParam("id") Long id);
@NativeQuery
List<WmsSalesOrderQueue> getWmsSalesOrderQueueByBeginFlag(@QueryParam("beginFlag") Integer beginFlag, BeanPropertyRowMapper<WmsSalesOrderQueue> beanPropertyRowMapper);
@NativeQuery
List<WmsSalesOrderQueue> sendMqTomsByMqLogTime(@QueryParam("num") BigDecimal num, BeanPropertyRowMapper<WmsSalesOrderQueue> beanPropertyRowMapper);
}
| true |
3037e80d14a4558a3ab2d3c7a755c9b9c924985d | Java | sunsunich/cmas | /CmasWeb/src/java/org/cmas/backend/ImageResizer.java | UTF-8 | 7,995 | 2.5625 | 3 | [] | no_license | package org.cmas.backend;
import com.mortennobel.imagescaling.ImageUtils;
import com.mortennobel.imagescaling.ResampleOp;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* Created on Mar 12, 2018
*
* @author Alexander Petukhov
*/
@SuppressWarnings("NumericCastThatLosesPrecision")
public final class ImageResizer {
private ImageResizer() {
}
public static BufferedImage scaleDownSavingProportions(BufferedImage imageToScale, float maxWidth, float maxHeight) {
float initHeight = (float) imageToScale.getHeight();
float initWidth = (float) imageToScale.getWidth();
if (initHeight <= maxHeight && initWidth <= maxWidth) {
return imageToScale;
}
float scaledWidth = initWidth;
float scaledHeight = initHeight;
if (initHeight > maxHeight) {
scaledHeight = maxHeight;
scaledWidth = maxHeight / initHeight * initWidth;
}
if (scaledWidth > maxWidth) {
scaledHeight = maxWidth / scaledWidth * scaledHeight;
scaledWidth = maxWidth;
}
return scaleDown(imageToScale, scaledWidth, scaledHeight);
}
public static BufferedImage scaleDown(BufferedImage imageToScale, float newWidth, float newHeight) {
int imageType;
if (ImageUtils.nrChannels(imageToScale) > 0) {
imageType = imageToScale.getType();
} else {
imageType = imageToScale.getColorModel().hasAlpha() ?
BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR;
}
BufferedImage after = new BufferedImage((int) newWidth, (int) newHeight, imageType);
BufferedImageOp resampleOp = new ResampleOp((int) newWidth, (int) newHeight);
resampleOp.filter(imageToScale, after);
return after;
}
public static void main(String[] args) throws IOException {
// generateAllBackgrounds("404",
// "/Users/sunsunich/workplace/сmas/CmasWeb/web/i/404_land_2888.png",
// "/Users/sunsunich/workplace/сmas/CmasWeb/web/i/404_portrait_960.png",
// "/Users/sunsunich/workplace/сmas/CmasWeb/web/i/404_long_portrait_1080.png",
// "/Users/sunsunich/workplace/сmas/CmasWeb/web/i/404_tab_portrait_1024.png"
// );
// generateAllBackgrounds("firstScreenBackground",
// "/Users/sunsunich/workplace/сmas/CmasWeb/web/i/firstScreenBackground_land_2840.png",
// null,
// null,
// null
// );
// generateAllBackgrounds("insurance",
// "/Users/sunsunich/workplace/сmas/CmasWeb/web/i/insurance_land_2133.png",
// new int[]{1920, 1680, 1440, 1280, 1024, 962, 840, 720, 640, 512, 480, 320, 240},
// null,
// null,
// null
// );
// generateAllBackgrounds("certificates",
// "/Users/sunsunich/workplace/сmas/CmasWeb/web/i/certificates_land_1065.png",
// new int[]{1024, 962, 640, 480, 420, 360, 320, 256, 240, 160, 120},
// null,
// null,
// null
// );
// generateAllBackgrounds("buddies",
// "/Users/sunsunich/workplace/сmas/CmasWeb/web/i/buddies_land_1065.png",
// new int[]{1024, 962, 640, 480, 420, 360, 320, 256, 240, 160, 120},
// null,
// null,
// null
// );
// generateAllBackgrounds("spots",
// "/Users/sunsunich/workplace/сmas/CmasWeb/web/i/spots_land_1065.png",
// new int[]{1024, 962, 640, 480, 420, 360, 320, 256, 240, 160, 120},
// null,
// null,
// null
// );
// generateAllBackgrounds("memories",
// "/Users/sunsunich/workplace/сmas/CmasWeb/web/i/memories_land_1065.png",
// new int[]{1024, 962, 640, 480, 420, 360, 320, 256, 240, 160, 120},
// null,
// null,
// null
// );
generateAllBackgrounds("firstScreenFooter",
"/Users/sunsunich/workplace/сmas/CmasWeb/web/i/firstScreenFooter_land_2842.png",
null,
null,
null
);
}
private static void generateAllBackgrounds(String baseName,
String landImageFilePath,
String portImageFilePath,
String portLongImageFilePath,
String portTabImageFilePath) throws IOException {
int[] landWidthParams = {2560, 1920, 1680, 1440, 1280, 1024, 962, 640, 480};
generateAllBackgrounds(baseName,
landImageFilePath,
landWidthParams,
portImageFilePath,
portLongImageFilePath,
portTabImageFilePath);
}
private static void generateAllBackgrounds(String baseName,
String landImageFilePath,
int[] landWidthParams,
String portImageFilePath,
String portLongImageFilePath,
String portTabImageFilePath) throws IOException {
File landImageFile = new File(landImageFilePath);
generateFilesForAllWidth(baseName, landImageFile, landWidthParams, "land");
if (portImageFilePath != null) {
int[] portWidthParams = {800, 516, 320};
File portImageFile = new File(portImageFilePath);
generateFilesForAllWidth(baseName, portImageFile, portWidthParams, "portrait");
}
if (portLongImageFilePath != null) {
int[] portLongWidthParams = {1080, 720, 601, 540, 480, 414, 375, 320};
File portLongImageFile = new File(portLongImageFilePath);
generateFilesForAllWidth(baseName, portLongImageFile, portLongWidthParams, "long_portrait");
}
if (portTabImageFilePath != null) {
int[] portTabWidthParams = {1024, 834, 768};
File portTabImageFile = new File(portTabImageFilePath);
generateFilesForAllWidth(baseName, portTabImageFile, portTabWidthParams, "tab_portrait");
}
}
private static void generateFilesForAllWidth(String baseName, File imageFile, int[] widthParams, String prefix) throws IOException {
BufferedImage image = ImageIO.read(new FileInputStream(imageFile));
for (int width : widthParams) {
File outputFile = new File(imageFile.getParentFile().getAbsolutePath() + File.separatorChar + baseName +
"_"
+ prefix
+ "_"
+ width + ".png");
BufferedImage scaledImage = scaleDownSavingProportions(image, (float) width, Float.MAX_VALUE);
ImageIO.write(scaledImage, "png", outputFile);
}
}
}
| true |
63b919e002bd0095f4531bcb0c18c023731728d2 | Java | nayanigc/ElasticSearch | /src/main/java/com/example/Tourist/hooks/SitesIndexer.java | UTF-8 | 1,499 | 1.914063 | 2 | [] | no_license | package com.example.Tourist.hooks;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class SitesIndexer {
/*
private static final Logger LOGGER = LoggerFactory.getLogger(SitesIndexer.class);
private static final String SITES_INDEX = "sites";
private static final String SITES_INDEX_ALIAS = "sites";
@Autowired
private RestHighLevelClient restHighLevelClient;
private SiteClient siteClient;
@Autowired
private Gson gson;
@Scheduled(fixedDelay = 86400000, initialDelay = 5000)
public void reindex() throws IOException {
LOGGER.info("start reindexing again...");
List<EsSite> uniscoSites = siteClient.getSites();
// delete index if it exists
boolean indexExist = restHighLevelClient.indices().exists(new GetIndexRequest(SITES_INDEX), RequestOptions.DEFAULT);
if(indexExist) {
DeleteIndexRequest deleteIndex = new DeleteIndexRequest(SITES_INDEX);
restHighLevelClient.indices().delete(deleteIndex, RequestOptions.DEFAULT);
}
BulkRequest bulkRequest = new BulkRequest();
uniscoSites.forEach(site -> {
IndexRequest indexRequest = new IndexRequest(SITES_INDEX)
.source(gson.toJson(site), JSON);
bulkRequest.add(indexRequest);
});
restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
LOGGER.info("end reindexing...");
}
*/
} | true |
c45e7a55544753d9ecea0a3242cded1c48df64c0 | Java | dingjianhui1013/xnr | /xnradmin-model/xnradmin-data/src/main/java/com/xnradmin/po/wx/WXPayInfo.java | UTF-8 | 2,439 | 2.1875 | 2 | [] | no_license | /**
*2014年9月11日 上午11:41:23
*/
package com.xnradmin.po.wx;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Index;
import com.cntinker.util.ReflectHelper;
/**
* @author: liubin
*
*/
@Entity
@Table(name = "wx_payinfo")
public class WXPayInfo implements java.io.Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "ID", unique = true, nullable = false)
private Long id;
@Index(name = "idx_wxpayInfo_wxuserid")
private Long wxuserid;
// 财付通商户号
private String partner;
// 财付通密钥
private String partnerKey;
// paysignkey 128位字符串(非appkey)
private String appKey;
// 支付完成后的回调处理页面,*替换成notify_url.asp所在路径
private String notify_url;
// 日志保存路径
private String loging_dir;
private String bankType = "WX";
//字符集
private String inputCharset = "UTF-8";
public String toString() {
String res = "";
try {
res = ReflectHelper.makeToString(this);
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
public Long getId() {
return id;
}
public Long getWxuserid() {
return wxuserid;
}
public String getPartner() {
return partner;
}
public String getPartnerKey() {
return partnerKey;
}
public String getAppKey() {
return appKey;
}
public String getNotify_url() {
return notify_url;
}
public String getLoging_dir() {
return loging_dir;
}
public void setId(Long id) {
this.id = id;
}
public void setWxuserid(Long wxuserid) {
this.wxuserid = wxuserid;
}
public void setPartner(String partner) {
this.partner = partner;
}
public void setPartnerKey(String partnerKey) {
this.partnerKey = partnerKey;
}
public void setAppKey(String appKey) {
this.appKey = appKey;
}
public void setNotify_url(String notify_url) {
this.notify_url = notify_url;
}
public void setLoging_dir(String loging_dir) {
this.loging_dir = loging_dir;
}
public String getBankType() {
return bankType;
}
public String getInputCharset() {
return inputCharset;
}
public void setBankType(String bankType) {
this.bankType = bankType;
}
public void setInputCharset(String inputCharset) {
this.inputCharset = inputCharset;
}
}
| true |
75e7e9f578cccfb9ed1eaf8fe5b9d2874618fb3d | Java | HaoTianZhao/netctoss | /src/main/java/com/barista/dao/PrivilegeMapper.java | UTF-8 | 643 | 1.984375 | 2 | [] | no_license | package com.barista.dao;
import com.barista.entity.Privilege;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface PrivilegeMapper {
int deleteByPrimaryKey(@Param("privilegeGroupId") Integer privilegeGroupId, @Param("privilegeId") Integer privilegeId);
int insert(Privilege record);
int insertSelective(Privilege record);
Privilege selectByPrimaryKey(@Param("privilegeGroupId") Integer privilegeGroupId, @Param("privilegeId") Integer privilegeId);
int updateByPrimaryKeySelective(Privilege record);
int updateByPrimaryKey(Privilege record);
} | true |
4a45855a4cd90897ace88a33c6ad7f3150b3d094 | Java | Voropay/debt_collection_case_example | /src/main/java/com/intrum/homework/debt/service/CustomerService.java | UTF-8 | 305 | 1.921875 | 2 | [] | no_license | package com.intrum.homework.debt.service;
import com.intrum.homework.debt.domain.customer.Customer;
import com.intrum.homework.debt.domain.customer.CustomerEntity;
public interface CustomerService {
CustomerEntity findByPersonalId(String personalId);
CustomerEntity create(Customer customer);
}
| true |
5f500bd9b58d8258afc99b36cacf0b9b3e309038 | Java | cha63506/CompSecurity | /nbc_source/src/org/joda/time/chrono/BasicDayOfMonthDateTimeField.java | UTF-8 | 3,009 | 2.125 | 2 | [] | no_license | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package org.joda.time.chrono;
import org.joda.time.DateTimeFieldType;
import org.joda.time.DurationField;
import org.joda.time.ReadablePartial;
import org.joda.time.field.PreciseDurationDateTimeField;
// Referenced classes of package org.joda.time.chrono:
// BasicChronology
final class BasicDayOfMonthDateTimeField extends PreciseDurationDateTimeField
{
private static final long serialVersionUID = 0xbf1729b8dddcd735L;
private final BasicChronology iChronology;
BasicDayOfMonthDateTimeField(BasicChronology basicchronology, DurationField durationfield)
{
super(DateTimeFieldType.dayOfMonth(), durationfield);
iChronology = basicchronology;
}
private Object readResolve()
{
return iChronology.dayOfMonth();
}
public int get(long l)
{
return iChronology.getDayOfMonth(l);
}
public int getMaximumValue()
{
return iChronology.getDaysInMonthMax();
}
public int getMaximumValue(long l)
{
return iChronology.getDaysInMonthMax(l);
}
public int getMaximumValue(ReadablePartial readablepartial)
{
if (readablepartial.isSupported(DateTimeFieldType.monthOfYear()))
{
int i = readablepartial.get(DateTimeFieldType.monthOfYear());
if (readablepartial.isSupported(DateTimeFieldType.year()))
{
int j = readablepartial.get(DateTimeFieldType.year());
return iChronology.getDaysInYearMonth(j, i);
} else
{
return iChronology.getDaysInMonthMax(i);
}
} else
{
return getMaximumValue();
}
}
public int getMaximumValue(ReadablePartial readablepartial, int ai[])
{
boolean flag = false;
int j = readablepartial.size();
for (int i = 0; i < j; i++)
{
if (readablepartial.getFieldType(i) == DateTimeFieldType.monthOfYear())
{
int k = ai[i];
for (i = ((flag) ? 1 : 0); i < j; i++)
{
if (readablepartial.getFieldType(i) == DateTimeFieldType.year())
{
i = ai[i];
return iChronology.getDaysInYearMonth(i, k);
}
}
return iChronology.getDaysInMonthMax(k);
}
}
return getMaximumValue();
}
protected int getMaximumValueForSet(long l, int i)
{
return iChronology.getDaysInMonthMaxForSet(l, i);
}
public int getMinimumValue()
{
return 1;
}
public DurationField getRangeDurationField()
{
return iChronology.months();
}
public boolean isLeap(long l)
{
return iChronology.isLeapDay(l);
}
}
| true |
60571f0116e4a00e0da7d4ca6c738f45605ebb67 | Java | tawn0414/self_exercise | /workbook/p060_05_Mobile.java | UTF-8 | 1,107 | 2.875 | 3 | [] | no_license | package workbook;
public class p060_05_Mobile {
private String mobileName;
private int batterySize;
private String osType;
public p060_05_Mobile() {
}
public p060_05_Mobile(String mobileName, int batterySize, String osType) {
super();
this.mobileName = mobileName;
this.batterySize = batterySize;
this.osType = osType;
}
public String getMobileName() {
return mobileName;
}
public void setMobileName(String mobileName) {
this.mobileName = mobileName;
}
public int getBatterySize() {
return batterySize;
}
public void setBatterySize(int batterySize) {
this.batterySize = batterySize;
}
public String getOsType() {
return osType;
}
public void setOsType(String osType) {
this.osType = osType;
}
public int operate(int time) {
int result = this.batterySize-(10*time);
setBatterySize(result);
return result;
}
public int charge(int time) {
int result = this.batterySize+(10*time);
setBatterySize(result);
return result;
}
public void print() {
System.out.println(this.getMobileName()+"\t"+this.getBatterySize()+"\t"+this.getOsType());
}
}
| true |
0fc653d30034f5399450d86291e639def73d3414 | Java | HerperPlain/hpcloud-parent | /hpcloud-common/src/main/java/com/hpsgts/hpcloud/common/utils/SerializeUtil.java | UTF-8 | 4,787 | 3.046875 | 3 | [] | no_license | package com.hpsgts.hpcloud.common.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.*;
/**
* 对象序列化及反序列化
* @author 黄朴(Herper.Plain)
* @Date 2018/02/01 下午12:30
*/
public class SerializeUtil {
private static Logger logger = LoggerFactory.getLogger(SerializeUtil.class);
/**
* 关闭此流并释放与此流关联的所有系统资源。如果已经关闭该流,则调用此方法无效
*
* @param closeable
*/
public static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
logger.info("Unable to close " + closeable, e);
}
}
}
/**
* 反序列化举例:
*
* @param bytes
* @return
*/
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 对象序列化
*
* @param value
* @return byte[]
*/
public static byte[] serialize(Object value) {
if (value == null) {
throw new NullPointerException("Can't serialize null");
}
byte[] rv = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
os.writeObject(value);
os.close();
bos.close();
rv = bos.toByteArray();
} catch (Exception e) {
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
close(os);
close(bos);
}
return rv;
}
/**
* 对象反序列化
*
* @param in
* @return
*/
public static Object deserialize(byte[] in) {
if (in == null) {
throw new NullPointerException("Can't deserialize null");
}
Object result = null;
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
result = is.readObject();
is.close();
bis.close();
}
} catch (Exception e) {
throw new RuntimeException("对象反序列化异常:" + e);
} finally {
close(is);
close(bis);
}
return result;
}
/**
* 序列化List对象
*
* @param <T>
* @param value
* @return
*/
@SuppressWarnings("unchecked")
public static <T> byte[] serializeList(List<T> value) {
if (value == null) {
throw new NullPointerException("Can't serialize null");
}
List<Object> values = (List<Object>) value;
byte[] results = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
for (Object m : values) {
os.writeObject(m);
}
os.close();
bos.close();
results = bos.toByteArray();
} catch (IOException e) {
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
close(os);
close(bos);
}
return results;
}
/**
* 反序列化List对象
*
* @param <T>
* @param in
* @return
*/
@SuppressWarnings("unchecked")
public static <T> List<T> deserializeList(byte[] in) {
List<T> list = new ArrayList<T>();
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
while (true) {
T m = (T) is.readObject();
if (m == null) {
break;
}
list.add(m);
}
is.close();
bis.close();
}
} catch (Exception e) {
throw new RuntimeException("反序列化异常:" + e);
} finally {
close(is);
close(bis);
}
return list;
}
/**
* 序列化Map对象
*
* @param hash
* @return Map<byte[], byte[]>
*/
public static Map<byte[], byte[]> serializehmoo2mbb(Map<Object, Object> hash) {
Map<byte[], byte[]> result = new HashMap<byte[], byte[]>();
try {
Set<Object> keys = hash.keySet();
if (keys != null && keys.size() > 0) {
for (Object key : keys) {
result.put(serialize(key), serialize(hash.get(key)));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 反序列化Map对象
*
* @param hash
* @return Map<Object, Object>
*/
public static Map<Object, Object> unserializehmbb2moo(final Map<byte[], byte[]> hash) {
Map<Object, Object> result = new HashMap<Object, Object>();
try {
Set<byte[]> keys = hash.keySet();
if (keys != null && keys.size() > 0) {
for (byte[] key : keys) {
result.put(deserialize(key), deserialize(hash.get(key)));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
| true |
40330ca078b88c112edc5a645ef4157a9318de81 | Java | erwindl0/hallvard-caltopia-ptolemy-graphiti | /org.ptolemy.graphiti.generic/src/org/ptolemy/graphiti/generic/actordiagram/PortGA.java | UTF-8 | 1,495 | 1.710938 | 2 | [] | no_license | /**
*/
package org.ptolemy.graphiti.generic.actordiagram;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.graphiti.mm.algorithms.PlatformGraphicsAlgorithm;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Port GA</b></em>'.
* <!-- end-user-doc -->
*
*
* @see org.ptolemy.graphiti.generic.actordiagram.ActordiagramPackage#getPortGA()
* @model
* @generated
*/
public interface PortGA extends PlatformGraphicsAlgorithm {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @model kind="operation" dataType="org.ptolemy.graphiti.generic.actordiagram.EPoint"
* @generated
*/
Point getTipAnchorPoint();
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @model kind="operation" dataType="org.ptolemy.graphiti.generic.actordiagram.EPoint"
* @generated
*/
Point getBaseAnchorPoint();
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @model kind="operation" dataType="org.ptolemy.graphiti.generic.actordiagram.ERectangle"
* @generated
*/
Rectangle getTipBounds();
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @model kind="operation" dataType="org.ptolemy.graphiti.generic.actordiagram.ERectangle"
* @generated
*/
Rectangle getBaseBounds();
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @model kind="operation"
* @generated
*/
PortShape getPortShape();
} // PortGA
| true |
bdc56795ce900cd61ff1c680541908937409d695 | Java | EweLoHD/FortniteReplayReader | /src/main/java/fortnitereplayreader/model/MatchStats.java | UTF-8 | 1,853 | 2.5625 | 3 | [
"MIT"
] | permissive | package fortnitereplayreader.model;
public class MatchStats {
private float accuracy;private int assists;
private int eliminations;
private int weaponDamage;
private int otherDamage;
private int revives;
private int damageTaken;
private int damageToStructures;
private int materialsGathered;
private int materialsUsed;
private int totalTraveled;
public MatchStats(float accuracy, int assists, int eliminations, int weaponDamage, int otherDamage, int revives, int damageTaken, int damageToStructures, int materialsGathered, int materialsUsed, int totalTraveled) {
this.accuracy = accuracy;
this.assists = assists;
this.eliminations = eliminations;
this.weaponDamage = weaponDamage;
this.otherDamage = otherDamage;
this.revives = revives;
this.damageTaken = damageTaken;
this.damageToStructures = damageToStructures;
this.materialsGathered = materialsGathered;
this.materialsUsed = materialsUsed;
this.totalTraveled = totalTraveled;
}
public float getAccuracy() {
return accuracy;
}
public int getAssists() {
return assists;
}
public int getEliminations() {
return eliminations;
}
public int getWeaponDamage() {
return weaponDamage;
}
public int getOtherDamage() {
return otherDamage;
}
public int getRevives() {
return revives;
}
public int getDamageTaken() {
return damageTaken;
}
public int getDamageToStructures() {
return damageToStructures;
}
public int getMaterialsGathered() {
return materialsGathered;
}
public int getMaterialsUsed() {
return materialsUsed;
}
public int getTotalTraveled() {
return totalTraveled;
}
}
| true |
98ea3e1c2f18b06cd3c7cb68f55dcd1bd9d2e830 | Java | zhibihuaxiyou/BwCareShop4 | /app/src/main/java/com/bwie/bwcareshop/mvp/presenter/MyWalletPresenter.java | UTF-8 | 1,069 | 2.171875 | 2 | [] | no_license | package com.bwie.bwcareshop.mvp.presenter;
import com.bwie.bwcareshop.bean.WalletBean;
import com.bwie.bwcareshop.mvp.callback.MyCallBack;
import com.bwie.bwcareshop.mvp.callback.MyWalletCallBack;
import com.bwie.bwcareshop.mvp.model.MyWalletModel;
import com.bwie.bwcareshop.mvp.view.MyView;
import com.bwie.bwcareshop.mvp.view.MyWalletView;
import java.util.Map;
/**
* author:张腾
* date:2019/1/4
*/
public class MyWalletPresenter {
private MyWalletView myWalletView;
private MyWalletModel myModel;
public MyWalletPresenter(MyWalletView myWalletView){
this.myWalletView = myWalletView;
myModel = new MyWalletModel();
}
public void show(int page, int count){
myModel.showWallet(page, count, new MyWalletCallBack() {
@Override
public void onSuccess(WalletBean walletBean) {
myWalletView.onSuccess(walletBean);
}
@Override
public void onFailer(String msg) {
myWalletView.onFailer(msg);
}
});
}
}
| true |
b547ce16d6c746ed3e0ccc1fbaf536ff58ec81ef | Java | cristian07/swrTaxiDailySubmission | /java-bootcamp-Sebasti-n_Alejandro_Suarez/java-bootcamp-Sebasti-n_Alejandro_Suarez/OOP/src/Author.java | UTF-8 | 529 | 3.125 | 3 | [
"Apache-2.0"
] | permissive |
public class Author {
private String name;
private String email;
private char gender;
public Author(String name,String email,char gender){
this.name=name;
this.email=email;
this.gender=gender;
}
// getters
public String getName() {return name;}
public String getEmail() {return email;}
public char getGender() {return gender;}
public String toString() {return name+" ("+gender+") at "+email;}
// seters
public void setName(String name){
this.name=name;
}
public void setEmail(String email){
this.email=email;
}
}
| true |
156d174bafce5a8b787a04b966bd3ea925290ea0 | Java | wu305813704/qcwyJava | /src/main/java/com/qcwy/entity/PartDetail.java | UTF-8 | 2,975 | 2.0625 | 2 | [] | no_license | package com.qcwy.entity;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.io.Serializable;
/**
* Created by KouKi on 2017/3/2.
*/
public class PartDetail implements Serializable {
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer part_detail_id;
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer part_no;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String model;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String unit;
@JsonInclude(JsonInclude.Include.NON_NULL)
private Double price;
@JsonInclude(JsonInclude.Include.NON_NULL)
private Double price_old;
@JsonInclude(JsonInclude.Include.NON_NULL)
private Double price_new;
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer is_guarantees;
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer guarantees_limit;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String remark;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String image;
//非表中的字段
@JsonInclude(JsonInclude.Include.NON_NULL)
private String name;
public int getPart_detail_id() {
return part_detail_id;
}
public void setPart_detail_id(int part_detail_id) {
this.part_detail_id = part_detail_id;
}
public int getPart_no() {
return part_no;
}
public void setPart_no(int part_no) {
this.part_no = part_no;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice_old() {
return price_old;
}
public void setPrice_old(double price_old) {
this.price_old = price_old;
}
public double getPrice_new() {
return price_new;
}
public void setPrice_new(double price_new) {
this.price_new = price_new;
}
public int getIs_guarantees() {
return is_guarantees;
}
public void setIs_guarantees(int is_guarantees) {
this.is_guarantees = is_guarantees;
}
public int getGuarantees_limit() {
return guarantees_limit;
}
public void setGuarantees_limit(int guarantees_limit) {
this.guarantees_limit = guarantees_limit;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| true |
f6ed13d970a947051b00f498f10102753e9f4840 | Java | grilla99/Drone_Simulation_JavaFX | /AaronGrill27011203/src/ArenaItem.java | UTF-8 | 774 | 3.0625 | 3 | [] | no_license |
public abstract class ArenaItem {
protected double xPos;
protected double yPos;
protected double rad;
protected char col;
/**
* Constructor to create an arena item
* @param x
* @param y
* @param r
*/
public ArenaItem(double x, double y, double r) {
this.xPos = x;
this.yPos = y;
this.rad = r;
}
/**
*
* @return xPosition of arena item
*/
public double getXPosition() {
return xPos;
};
/**
*
* @return yPosition of arena item
*/
public double getYPosition() {
return yPos;
};
/**
*
* @return radians of arena item
*/
public double getRadians() {
return rad;
};
/**
*
* @return colour of arena item
*/
public char getCol() {
return col;
}
}
| true |
f7855025d44a006d581bbf851cfcc11b0ce61cbf | Java | ztyzty070818/study | /src/main/java/bigdata/druid/sequence/test/YieldTest.java | UTF-8 | 844 | 2.859375 | 3 | [] | no_license | package bigdata.druid.sequence.test;
import bigdata.druid.sequence.*;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
/**
* Created by zty on 18-11-6
*/
public class YieldTest {
public static void main(String[] args) throws IOException {
Sequence<String> sequence = Sequences.simple(ImmutableList.of("a","b","c"));
Yielder<String> yielder = sequence.toYielder("1", new YieldingAccumulator<String, String>() {
@Override
public String accumulate(String accumulated, String in) {
yield();
return accumulated + "\n" + in;
}
});
String item = yielder.get();
System.out.println(yielder.get());
while (!yielder.isDone()) {
Yielder<String> oldYielder = yielder;
yielder = yielder.next("2");
oldYielder.close();
System.out.println(yielder.get());
}
yielder.close();
}
}
| true |
8f07ad7f1f6263daf259660e29f0b55b1dd25e1b | Java | shinow/tjec | /src/com/wfzcx/fam/common/MessageJob.java | UTF-8 | 827 | 1.828125 | 2 | [] | no_license | package com.wfzcx.fam.common;
import java.util.List;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import com.jbf.common.util.WebContextFactoryUtil;
public class MessageJob implements Job {
@Autowired
MessageComponent mcComponent;
@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
// TODO Auto-generated method stub
try {
if (mcComponent == null) {
mcComponent = (MessageComponent) WebContextFactoryUtil.getBean("com.wfzcx.fam.common.MessageComponent");
}
List zhList = mcComponent.getSendMessage();
mcComponent.sendMessage(zhList);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true |
8167ddc3452d381a34f6d98d0402d19057d66e93 | Java | bellmit/myGitSpace | /mybatis/enjoyDemoList/mybatis-demo-2019/src/test/java/com/enjoylearning/mybatis/James.java | UTF-8 | 1,206 | 2.515625 | 3 | [] | no_license | package com.enjoylearning.mybatis;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.enjoylearning.mybatis.factory.product.SmallMovie;
import com.enjoylearning.mybatis.factory.real.CangSmallMovieFactory;
import com.enjoylearning.mybatis.factory.real.SmallMovieFactory;
import com.enjoylearning.mybatis.factory.simple.SimpleSmallMovieFactory;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class James {
@Resource(name="simpleSmallMovieFactoryImpl")
private SimpleSmallMovieFactory factory1;
@Resource(name="cangSmallMovieFactory")
private SmallMovieFactory factory2;
@Test
public void watchSmallMovie() {
System.out.println("---------------简单工厂模式------------------");
//简单工厂使用
SmallMovie movie1 = factory1.createMovie("cang");
movie1.watch();
System.out.println("---------------工厂模式------------------");
//工厂模式使用
SmallMovie movie2 = factory2.createMovie();
movie2.watch();
}
}
| true |
a53ce2dc48df09c248d64ef0472dc5d928510a41 | Java | pengyunhao520/ssm-MaternalAndChildHealthCare | /src/mapper/AntenatalInitialInspectionMapper.java | UTF-8 | 297 | 1.882813 | 2 | [] | no_license | package mapper;
import java.util.List;
import domain.AntenatalInitialInspection;
import domain.PremaritaHealthInformation;
public interface AntenatalInitialInspectionMapper extends BaseMapper<AntenatalInitialInspection>{
List<AntenatalInitialInspection> selectAllByidnumber(String idnumber);
} | true |
63403652b26483ff1f10b647e03609a72e09cb47 | Java | pullsaki/git-one | /Circle.java | UTF-8 | 690 | 4.4375 | 4 | [] | no_license | /* Exercise 5: Write a Java program to display the Diameter, Circumference and Area of a circle.
Test Data
Radius value: 6
Expected Output
Diameter of a circle : 12.0
Circumference of a circle: 37.68
Area of a Circle: 113.04 */
import java.util.Scanner;
public class Circle {
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
float r, d, C, A;
System.out.print("Enter radius of the circle: ");
r = input.nextFloat();
d = 2 * r;
C = 2 * 3.14f * r;
A = 3.14f * r * r;
System.out.println("Diameter of the circle is " + d);
System.out.println("Circumference of the circle is " + C);
System.out.println("Area of the circle is " + A);
}
}
| true |
626c2b38117da301462649eb6a5dc8e633b1476f | Java | XueXue-feng/demo_Tomcat_Servlet | /src/main/java/com/xuexue/dao/ServiceDao.java | UTF-8 | 813 | 2.109375 | 2 | [] | no_license | package com.xuexue.dao;
import com.sample.RollCompanyService;
import com.xuexue.util.JdbcUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**
* @ProjectName: demo_Tomcat_Servlet
* @Package: com.xuexue.dao
* @ClassName: ServiceDao
* @Author: XueXue-Li
* @Description:
* @Date: 2021/7/11 10:46
* @Version: 1.0
*/
public class ServiceDao {
private JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDataSource());
public List<com.sample.RollCompanyService> queryForService() {
String sql = "select * from roll_company_service";
List<RollCompanyService> query = template.query(sql, new BeanPropertyRowMapper<RollCompanyService>(RollCompanyService.class));
return query;
}
}
| true |
5f580e3d3efddbd2c513a6d5df0da118a1ebdc76 | Java | utarsuno/DairyRun | /Dairy_Run/src/com/uladzislau/dairy_run/world/Map.java | UTF-8 | 860 | 2.703125 | 3 | [] | no_license | package com.uladzislau.dairy_run.world;
import com.uladzislau.dairy_run.information.ScreenUtil;
public class Map {
public static int number_of_vertical_blocks;
public static int number_of_horizontal_blocks_off_edge_included;
public static int size;
private static float current_scroll;
private static int ground_level;
public static void init() {
Map.number_of_vertical_blocks = 8;
Map.size = ScreenUtil.screen_height / Map.number_of_vertical_blocks;
Map.number_of_horizontal_blocks_off_edge_included = ScreenUtil.screen_width / Map.size + 1;
}
public static int getGroundLevel() {
return ground_level;
}
public static void setGroundLevel(int gl) {
ground_level = gl;
}
public static void setCurrentScroll(float f) {
Map.current_scroll = f;
}
public static int getCurrentScrollAsInt() {
return ((int) current_scroll);
}
} | true |
082fa9ac61ad9c23934e15b4201b9e8e8e170b86 | Java | MacrossGithub-coder/ShoppingMall | /src/main/java/org/macross/shopping_mall/controller/CommoditySeckillController.java | UTF-8 | 2,957 | 2.21875 | 2 | [] | no_license | package org.macross.shopping_mall.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.ibatis.annotations.Param;
import org.macross.shopping_mall.service.CommoditySeckillService;
import org.macross.shopping_mall.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("api/v1/pri/seckill")
public class CommoditySeckillController {
@Autowired
CommoditySeckillService commoditySeckillService;
@RequestMapping("get_path")
public JsonData getSeckillPath(@RequestParam("commodity_id") Integer commodityId, HttpServletRequest request) {
Integer userId = (Integer) request.getAttribute("user_id");
//验证验证码
//TODO
String path = commoditySeckillService.createSeckillPath(commodityId, userId);
return path != null ? JsonData.buildSuccess(path) : JsonData.buildError("获取Path失败");
}
/**
* -1 :库存不足秒杀失败
* -2 : 该用户存在重复下单行为
* 0 :排队中,继续轮询
*/
@RequestMapping("/{path}/commodity_seckill")
public JsonData commoditySeckill(@RequestParam("commodity_id") Integer commodityId, HttpServletRequest request, @PathVariable("path") String path) throws JsonProcessingException {
Integer userId = (Integer) request.getAttribute("user_id");
//Redis:{key:"path:userId:commodityId,Value:str}
String key = "path:" + userId + ":" + commodityId;
boolean valid = commoditySeckillService.confirmPathValid(key, path);
if (!valid) return JsonData.buildError("秒杀Path有误!");
int result = commoditySeckillService.doCommoditySeckill(commodityId, userId);
return result == 0 ? JsonData.buildSuccess("排队中……") :
(result == -1 ? JsonData.buildError(-1, "库存不足秒杀失败") : JsonData.buildError(-2, "该用户存在重复下单行为"));
}
/**
* -1 :商品库存不足
* 0 :排队中,继续轮询
* 秒杀成功,返回订单ID
*/
@RequestMapping("get_seckill_result")
public JsonData getSeckillResult(@RequestParam("commodity_id") Integer commodityId, HttpServletRequest request) {
Integer userId = (Integer) request.getAttribute("user_id");
int result = commoditySeckillService.getSeckillResult(commodityId, userId);
return result > 0 ? JsonData.buildSuccess("商品秒杀成功,订单号为:" + result) :
(result == -1 ? JsonData.buildError(-1, "商品库存不足秒杀失败") : JsonData.buildError(0, "订单尚未处理完"));
}
}
| true |
df1ddd50e496b59e192b7391c1f682b64795512a | Java | angelavarcila/zabbixDataSets | /src/model/Functions.java | UTF-8 | 3,707 | 2.234375 | 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 model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author ove
*/
@Entity
@Table(name = "functions")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Functions.findAll", query = "SELECT f FROM Functions f"),
@NamedQuery(name = "Functions.findByFunctionid", query = "SELECT f FROM Functions f WHERE f.functionid = :functionid"),
@NamedQuery(name = "Functions.findByFunction", query = "SELECT f FROM Functions f WHERE f.function = :function"),
@NamedQuery(name = "Functions.findByParameter", query = "SELECT f FROM Functions f WHERE f.parameter = :parameter")})
public class Functions implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "functionid")
private Long functionid;
@Basic(optional = false)
@Column(name = "function")
private String function;
@Basic(optional = false)
@Column(name = "parameter")
private String parameter;
@JoinColumn(name = "itemid", referencedColumnName = "itemid")
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Items itemid;
@JoinColumn(name = "triggerid", referencedColumnName = "triggerid")
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Triggers triggerid;
public Functions() {
}
public Functions(Long functionid) {
this.functionid = functionid;
}
public Functions(Long functionid, String function, String parameter) {
this.functionid = functionid;
this.function = function;
this.parameter = parameter;
}
public Long getFunctionid() {
return functionid;
}
public void setFunctionid(Long functionid) {
this.functionid = functionid;
}
public String getFunction() {
return function;
}
public void setFunction(String function) {
this.function = function;
}
public String getParameter() {
return parameter;
}
public void setParameter(String parameter) {
this.parameter = parameter;
}
public Items getItemid() {
return itemid;
}
public void setItemid(Items itemid) {
this.itemid = itemid;
}
public Triggers getTriggerid() {
return triggerid;
}
public void setTriggerid(Triggers triggerid) {
this.triggerid = triggerid;
}
@Override
public int hashCode() {
int hash = 0;
hash += (functionid != null ? functionid.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Functions)) {
return false;
}
Functions other = (Functions) object;
if ((this.functionid == null && other.functionid != null) || (this.functionid != null && !this.functionid.equals(other.functionid))) {
return false;
}
return true;
}
@Override
public String toString() {
return "model.Functions[ functionid=" + functionid + " ]";
}
}
| true |
e14784e3629fe0e9199a4b76b34731d1da8c144b | Java | dotanloc1998/Sach24h | /app/src/main/java/com/sinhvien/sach24h/Adapter/BinhLuanAdapter.java | UTF-8 | 1,909 | 2.28125 | 2 | [] | no_license | package com.sinhvien.sach24h.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.sinhvien.sach24h.Model.BinhLuan;
import com.sinhvien.sach24h.R;
import java.util.List;
public class BinhLuanAdapter extends BaseAdapter {
Context context;
List<BinhLuan> binhLuans;
public BinhLuanAdapter(Context context, List<BinhLuan> binhLuans) {
this.context = context;
this.binhLuans = binhLuans;
}
@Override
public int getCount() {
return binhLuans.size();
}
@Override
public Object getItem(int i) {
return binhLuans.get(i);
}
@Override
public long getItemId(int i) {
return binhLuans.get(i).getId();
}
public class ViewHolder {
TextView textViewTenNguoiDung, textViewSoDiem, textViewNoiDungComment;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.dong_binh_luan, null);
viewHolder = new ViewHolder();
viewHolder.textViewTenNguoiDung = view.findViewById(R.id.textViewTenNguoiDung);
viewHolder.textViewSoDiem = view.findViewById(R.id.textViewSoDiem);
viewHolder.textViewNoiDungComment = view.findViewById(R.id.textViewNoiDungComment);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BinhLuan binhLuan = binhLuans.get(i);
viewHolder.textViewTenNguoiDung.setText(binhLuan.getEmail());
viewHolder.textViewSoDiem.setText(binhLuan.getSoDiem() + "");
viewHolder.textViewNoiDungComment.setText(binhLuan.getNoiDung());
return view;
}
}
| true |
9fa775ff048bd78c3987c6b6818686bed26cfffd | Java | BetterITOrg/BitBase | /src/main/java/com/betterit/BitBase/dao/repository/kaligia/SiteMapper.java | UTF-8 | 2,477 | 2.03125 | 2 | [] | no_license | package com.betterit.kaligia.dao.repository.kaligia;
import com.betterit.kaligia.dao.model.kaligia.Site;
import com.betterit.kaligia.dao.model.kaligia.SiteExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface SiteMapper {
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table kaligia.site
* @mbggenerated Mon Mar 28 12:28:13 EDT 2016
*/
int deleteByExample(SiteExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table kaligia.site
* @mbggenerated Mon Mar 28 12:28:13 EDT 2016
*/
int deleteByPrimaryKey(Integer siteId);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table kaligia.site
* @mbggenerated Mon Mar 28 12:28:13 EDT 2016
*/
int insert(Site record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table kaligia.site
* @mbggenerated Mon Mar 28 12:28:13 EDT 2016
*/
int insertSelective(Site record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table kaligia.site
* @mbggenerated Mon Mar 28 12:28:13 EDT 2016
*/
List<Site> selectByExample(SiteExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table kaligia.site
* @mbggenerated Mon Mar 28 12:28:13 EDT 2016
*/
Site selectByPrimaryKey(Integer siteId);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table kaligia.site
* @mbggenerated Mon Mar 28 12:28:13 EDT 2016
*/
int updateByExampleSelective(@Param("record") Site record, @Param("example") SiteExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table kaligia.site
* @mbggenerated Mon Mar 28 12:28:13 EDT 2016
*/
int updateByExample(@Param("record") Site record, @Param("example") SiteExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table kaligia.site
* @mbggenerated Mon Mar 28 12:28:13 EDT 2016
*/
int updateByPrimaryKeySelective(Site record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table kaligia.site
* @mbggenerated Mon Mar 28 12:28:13 EDT 2016
*/
int updateByPrimaryKey(Site record);
} | true |
0efc62bc846ab43bd277b1915df69110ce8c82fc | Java | lemote1/COP3330 | /Melesse_PA4/Melesse_P2/src/Melesse_P2/DuplicateCounter.java | UTF-8 | 1,963 | 3.375 | 3 | [] | no_license |
package Melesse_P2;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Iterator;
public class DuplicateCounter {
HashMap<String, Integer> wordCounter;
public DuplicateCounter(){
wordCounter = new HashMap<String, Integer>();
}
public void count(String dataFile){
try{
BufferedReader bufferedReader = new BufferedReader(new FileReader(dataFile));
String line = null;
while ((line = bufferedReader.readLine())!=null){
String[] words = line.split(" ");
for (int i = 0; i<words.length; i++){
String word = words[i].replace("\n", "").replace(" ", "").toLowerCase();
if (wordCounter.containsKey(word)){
wordCounter.put(word, wordCounter.get(word)+1);
}
else{
wordCounter.put(word, 1);
}
}
}
}
catch (Exception e){
System.out.println("Error reading file.");
System.out.println(e);
}
}
public void write(String outputFile){
try{
File file = new File(outputFile);
file.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
Iterator i = wordCounter.entrySet().iterator();
while (i.hasNext()){
HashMap.Entry mapElement = (HashMap.Entry)i.next();
writer.write(mapElement.getKey() + " : " + mapElement.getValue() + "\n");
}
writer.close();
}
catch (Exception e){
System.out.println("Error writing file.");
System.out.println(e);
}
}
}
| true |
c803aae6268356a981e33de124379320a17c8b1b | Java | AgaevAlex/job4j | /chapter_001/src/main/java/ru/job4j/array/Turn.java | UTF-8 | 609 | 3.5 | 4 | [
"Apache-2.0"
] | permissive | package ru.job4j.array;
/**
* 6.2. Перевернуть массив.[#122496].
*/
public class Turn {
/**
* Класс, переворачивающий массив.
*
* @param array - передаваемый массив.
* @return перевернутый массив чисел.
*/
public int[] back(int[] array) {
for (int count = 0; count < array.length / 2; count++) {
int a = array[count];
array[count] = array[array.length - count - 1];
array[array.length - count - 1] = a;
}
return array;
}
}
| true |
60466894f1edb303f9df48afae9ddb4c59b8f6bf | Java | UrielCh/ovh-java-sdk | /ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/iploadbalancing/ssl/OvhSsl.java | UTF-8 | 1,179 | 2.21875 | 2 | [
"BSD-3-Clause"
] | permissive | package net.minidev.ovh.api.iploadbalancing.ssl;
import java.util.Date;
import net.minidev.ovh.api.iploadbalancing.OvhSslTypeEnum;
/**
* Ssl
*/
public class OvhSsl {
/**
* Subject Alternative Name of your SSL certificate
*
* canBeNull && readOnly
*/
public String[] san;
/**
* Serial of your SSL certificate (Deprecated, use fingerprint instead !)
*
* canBeNull && readOnly
*/
public String serial;
/**
* Subject of your SSL certificate
*
* canBeNull && readOnly
*/
public String subject;
/**
* Human readable name for your ssl certificate, this field is for you
*
* canBeNull && readOnly
*/
public String displayName;
/**
* Fingerprint of your SSL certificate
*
* canBeNull && readOnly
*/
public String fingerprint;
/**
* Expire date of your SSL certificate
*
* canBeNull && readOnly
*/
public Date expireDate;
/**
* Id of your SSL certificate
*
* canBeNull && readOnly
*/
public Long id;
/**
* Type of your SSL certificate.
'built' for SSL certificates managed by the IP Load Balancing. 'custom' for user manager certificates.
*
* canBeNull && readOnly
*/
public OvhSslTypeEnum type;
}
| true |
f66312a65de0bff91757c44069f390d5e7e7d53e | Java | SpartanB312/Epsilon | /Client/src/main/java/club/eridani/epsilon/client/mixin/mixins/network/MixinMinecraftServer.java | UTF-8 | 1,338 | 1.90625 | 2 | [] | no_license | package club.eridani.epsilon.client.mixin.mixins.network;
import net.minecraft.server.MinecraftServer;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(MinecraftServer.class)
public class MixinMinecraftServer {
/*
private static WorldServer world;
@ModifyVariable(method = "loadAllWorlds", at = @At(value = "STORE", ordinal = 0))
public WorldServer a(WorldServer in) {
world = in;
return in;
}
@Inject(method = "loadAllWorlds", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/eventhandler/EventBus;post(Lnet/minecraftforge/fml/common/eventhandler/Event;)Z", shift = At.Shift.BEFORE),remap = false)
public void a(String p_71247_1_, String p_71247_2_, long p_71247_3_, WorldType p_71247_5_, String p_71247_6_, CallbackInfo ci) {
if (world != null && world.isRemote) {
WorldEvent.Load.INSTANCE.post();
world.addEventListener(WorldManager.INSTANCE);
}
}
@Redirect(method = "stopServer", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/WorldServer;flush()V"))
public void b(WorldServer worldServer) {
if (world != null && world.isRemote){
WorldEvent.Unload.INSTANCE.post();
world.removeEventListener(WorldManager.INSTANCE);
}
worldServer.flush();
}
*/
}
| true |
3e51a0fbabf2cf1a4396dd673c4c8b9ad9660dbf | Java | jordansmith04/Automation | /ParaBank-UI-Automation/src/test/java/com/jordan/ParaBankTests/Utility/DataManager.java | UTF-8 | 22,758 | 2.25 | 2 | [] | no_license | using EHBsBDDFramework.Constants;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Framework.Utility
{
public class DataManager
{
/*
public static GranteeEntity FindGrantee()
{
using (DBConnection DB = new DBConnection())
{
string query = QueryScripts.PAR_Find_A_Grantee;
List<GranteeEntity> data = DB.GetTable(query).ToList<GranteeEntity>();
return data.FirstOrDefault();
}
}
public static ReviewerEntity FindReviewer(RoleType reviewerRole, ReviewerType reviewerType, string TrackingNumber)
{
using (DBConnection DB = new DBConnection())
{
string query = string.Empty;
switch (reviewerType)
{
case ReviewerType.Individual:
case ReviewerType.TeamAssigned:
query = QueryScripts.PAR_Find_A_Reviewer_Individual + " WHERE task.TaskStatusCode!=3 AND par.TrackingNumber in ('" + TrackingNumber + "') AND usrRole.RoleId = '" + Convert.ToInt32(reviewerRole) + "'";
break;
case ReviewerType.TeamUnassigned:
query = QueryScripts.PAR_Find_A_Reviewer_Team + " WHERE task.TaskStatusCode!=3 AND par.TrackingNumber in ('" + TrackingNumber + "') AND usrRole.RoleId = '" + Convert.ToInt32(reviewerRole) + "'"
+ " ORDER BY ReviewerUserName desc";
break;
}
List<ReviewerEntity> data = DB.GetTable(query).ToList<ReviewerEntity>();
return data.FirstOrDefault();
}
}
public static ReviewerEntity FindCurrentReviewer(string TrackingNumber)
{
using (DBConnection DB = new DBConnection())
{
string query = QueryScripts.PAR_Find_Current_Reviewer + " WHERE t.TaskStatusCode!=3 AND TrackingNumber in ('" + TrackingNumber + "')";
List<ReviewerEntity> data = DB.GetTable(query).ToList<ReviewerEntity>();
var CurrentNonGMSRole = data.Where(r=>!r.Role.Equals("GMS")).ToList().FirstOrDefault();
if (CurrentNonGMSRole!= null)
{
return CurrentNonGMSRole;
}
else
{
var CurrentGMSRole = data.Where(r=>r.Role.Equals("GMS")).ToList().FirstOrDefault();
return CurrentGMSRole != null ? CurrentGMSRole : null;
}
}
}
public static RoleType FindCurrentReviewerRole(string TrackingNumber)
{
RoleType currentReviewerRole = 0;
if (!string.IsNullOrEmpty(TrackingNumber))
{
using (DBConnection DB = new DBConnection())
{
var currentReviewer = FindCurrentReviewer(TrackingNumber);
if (currentReviewer != null)
currentReviewerRole = GetRoleType(currentReviewer.Role);
}
}
return currentReviewerRole;
}
public static void SaveRequestTest(PriorApprovalTestGroup TestGroup)
{
string wbk = ConfigManager.DataPath();
string wksRequest = "PA_Requests_TestData";
string wksReview = "PA_Reviews_TestData";
ExcelHelper.WriteRequestTestResult(wbk, wksRequest, wksReview, TestGroup);
}
public static string GetTrackingNumber(int rowNo)
{
string wbk = ConfigManager.DataPath();
string wks = "PA_Requests_TestData";
return ExcelHelper.GetCellData(wbk, wks, rowNo, 4);
}
public static string GetTrackingNumber()
{
string trackingNumber = string.Empty;
using (ExcelConnection DB = new ExcelConnection())
{
string query = "SELECT * FROM [PA_Reviews_TestData$] WHERE [SN] IS NOT NULL AND [ReviewTestType] IS NULL ORDER BY SN";
DataTable dt = DB.GetTable(query);
if (dt.Rows.Count>0)
trackingNumber = (dt.Rows.Count > 0) ? (dt.Rows[0]["TrackingNumber"]).ToString() : string.Empty;
}
return trackingNumber;
}
public static void SaveReviewTest(PriorApprovalTestGroup TestGroup)
{
int rowNo = GetRowNo(TestGroup.Request.TrackingNumber);
if (rowNo > 0)
{
string wbk = ConfigManager.DataPath();
string wks = "PA_Reviews_TestData";
ExcelHelper.WriteReviewTestResult(wbk, wks, TestGroup, rowNo);
}
else
{
throw new Exception("Unable to get Excel row number of the tracking number");
}
}
public static void LogTestResultToFile(PriorApprovalTestGroup testGroup)
{
if (testGroup.Results.Count > 0)
{
string filePath = ConfigManager.ReportsPath();
string fileName = testGroup.Context.ReportFilePrefix + DateTime.Now.ToShortDateString().Replace('/', '-');
using (StreamWriter file = File.AppendText(filePath + fileName + ".txt"))
{
int colWidth = 25;
file.WriteLine();
file.WriteLine("-------------------------------------------------// Start New Test //-------------------------------------------------");
file.WriteLine(String.Format("{0,-" + colWidth + "} {1}", "Time".PadRight(colWidth, '.'), DateTime.Now.ToString()));
file.WriteLine(String.Format("{0,-" + colWidth + "} {1}", "Test Group".PadRight(colWidth, '.'), testGroup.Context.TestGroupName));
file.WriteLine(String.Format("{0,-" + colWidth + "} {1}", "Environment".PadRight(colWidth, '.'), testGroup.Context.TestEnvironment));
file.WriteLine(String.Format("{0,-" + colWidth + "} {1}", "Machine".PadRight(colWidth, '.'), Environment.MachineName));
file.WriteLine();
switch ((TestType)testGroup.Context.TestType)
{
case TestType.PriorApprovalRequest:
if (testGroup.Request != null)
{
file.WriteLine(String.Format("{0,-" + colWidth + "} {1}", "Grant Number".PadRight(colWidth, '.'), (testGroup.Request.Grantee != null && !string.IsNullOrEmpty(testGroup.Request.Grantee.GrantNumber)) ? testGroup.Request.Grantee.GrantNumber : string.Empty));
file.WriteLine(String.Format("{0,-" + colWidth + "} {1}", "Grantee UserName".PadRight(colWidth, '.'), (testGroup.Request.Grantee != null && !string.IsNullOrEmpty(testGroup.Request.Grantee.GranteeUserName)) ? testGroup.Request.Grantee.GranteeUserName : string.Empty));
file.WriteLine(String.Format("{0,-" + colWidth + "} {1}", "Request Type".PadRight(colWidth, '.'), GetRequestTypeName((PriorApprovalRequestType)testGroup.Request.RequestType)));
file.WriteLine(String.Format("{0,-" + colWidth + "} {1}", "Tracking Number".PadRight(colWidth, '.'), (!string.IsNullOrEmpty(testGroup.Request.TrackingNumber)) ? testGroup.Request.TrackingNumber : string.Empty));
file.WriteLine(String.Format("{0,-" + colWidth + "} {1}", "Test Result".PadRight(colWidth, '.'), testGroup.Passed ? "Passed" : "Failed"));
}
break;
case TestType.PriorApprovalReview:
file.WriteLine(String.Format("{0,-" + colWidth + "} {1}", "Tracking Number".PadRight(colWidth, '.'), (!string.IsNullOrEmpty(testGroup.Request.TrackingNumber)) ? testGroup.Request.TrackingNumber : string.Empty));
file.WriteLine(String.Format("{0,-" + colWidth + "} {1}", "Review Test Type".PadRight(colWidth, '.'), GetReviewTestTypeName((ReviewTestType)testGroup.ReviewTestType)));
file.WriteLine(String.Format("{0,-" + colWidth + "} {1}", "Reviewer Option".PadRight(colWidth, '.'), !string.IsNullOrEmpty(testGroup.ReviewerAssignmentOption) ? testGroup.ReviewerAssignmentOption : string.Empty));
file.WriteLine(String.Format("{0,-" + colWidth + "} {1}", "Review Workflow".PadRight(colWidth, '.'), !string.IsNullOrEmpty(testGroup.ReviewWorkflow) ? testGroup.ReviewWorkflow : string.Empty));
file.WriteLine(String.Format("{0,-" + colWidth + "} {1}", "Test Result".PadRight(colWidth, '.'), ((testGroup.Results.Count > 0) && !(testGroup.Results.Any(r => r.Result == false))) ? "Passed" : "Failed"));
file.WriteLine();
if (testGroup.Reviews != null && testGroup.Reviews.Count > 0)
{
file.WriteLine("Reviewers:");
file.WriteLine(String.Format("{0,-12} {1,-30} {2,-10} {3,-25} {4,-50}",
"Reviewer#".PadRight(12, '.'),
"UserName".PadRight(30, '.'),
"Role".PadRight(10, '.'),
"Recommendation".PadRight(25, '.'),
"TeamName"
));
foreach (var review in testGroup.Reviews)
{
if (review.Reviewer != null && !string.IsNullOrEmpty(review.Reviewer.ReviewerUserName))
{
file.WriteLine(String.Format("{0,-12} {1,-30} {2,-10} {3,-25} {4,-50}",
review.ReviewSequence.ToString().PadRight(12, '.'),
review.Reviewer.ReviewerUserName.PadRight(30, '.'),
review.Reviewer.Role.PadRight(10, '.'),
GetReviewRecommendationName((ReviewRecommendations)review.ReviewRecommendation).PadRight(25, '.'),
review.Reviewer.TeamName
));
}
}
}
break;
}
file.WriteLine();
file.WriteLine();
//log test results
List<TestResult> Results = testGroup.Results.Where(r => r.ErrorStatus == false).ToList();
if (Results.Count != 0)
{
file.WriteLine("Test Results: ");
foreach (var test in Results)
{
file.WriteLine(String.Format("{0,-68} {1,-25} {2,-15}", test.Name.PadRight(68, '.'), test.DateTimeStamp.PadRight(25, '.'), (test.Result ? "Passed" : "Failed")));
}
}
//log exceptions
List<TestResult> Exceptions = testGroup.Results.Where(r => r.ErrorStatus == true).ToList();
if (Exceptions.Count != 0)
{
file.WriteLine();
file.WriteLine("Exceptions:");
foreach (var ex in Exceptions)
{
file.WriteLine("Test Name: " + ex.Name);
file.WriteLine(ex.ErrMessage);
}
}
file.WriteLine("----------------------------------------------------// End Test //---------------------------------------------------");
file.WriteLine();
}
}
}
public static int GetRowNo(string trackingNumber)
{
int rowNo = 0;
using (ExcelConnection DB = new ExcelConnection())
{
string query = "SELECT * FROM [PA_Reviews_TestData$] WHERE [TrackingNumber] = '" + trackingNumber + "'";
DataTable dt = DB.GetTable(query);
if (dt.Rows.Count > 0)
rowNo = (dt.Rows.Count > 0) ? Convert.ToInt32((dt.Rows[0]["SN"])): 0;
DB.Close();
DB.Dispose();
}
return (rowNo>0)? (++rowNo):(rowNo);
}*/
public static string GetReviewerTypeName(ReviewerType reviewerType)
{
string reviewerTypeName = string.Empty;
switch (reviewerType)
{
case ReviewerType.Individual:
reviewerTypeName = PriorApprovalConstatnts.ReviewerType_Individual;
break;
case ReviewerType.TeamAssigned:
reviewerTypeName = PriorApprovalConstatnts.ReviewerType_TeamAssigned;
break;
case ReviewerType.TeamUnassigned:
reviewerTypeName = PriorApprovalConstatnts.ReviewerType_TeamUnassigned;
break;
}
return reviewerTypeName;
}
public static string GetReviewerAssignmentOption(ReviewerType reviewerType)
{
string reviewerTypeName = string.Empty;
switch (reviewerType)
{
case ReviewerType.Individual:
reviewerTypeName = "Individual";
break;
case ReviewerType.TeamAssigned:
reviewerTypeName = "TeamAssigned";
break;
case ReviewerType.TeamUnassigned:
reviewerTypeName = "TeamUnassigned";
break;
}
return reviewerTypeName;
}
public static string GetReviewTypeName(TestType testType)
{
string testTypeName = string.Empty;
switch (testType)
{
case TestType.PriorApprovalRequest:
testTypeName = PriorApprovalConstatnts.TestType_Request;
break;
case TestType.PriorApprovalReview:
testTypeName = PriorApprovalConstatnts.TestType_Review;
break;
}
return testTypeName;
}
public static string GetReviewRecommendationName(ReviewRecommendations reviewRecommendation)
{
string reviewRecommendationName = string.Empty;
switch (reviewRecommendation)
{
case ReviewRecommendations.Approve:
reviewRecommendationName = PriorApprovalConstatnts.ReviewerRecommendation_Approve;
break;
case ReviewRecommendations.Disapprove:
reviewRecommendationName = PriorApprovalConstatnts.ReviewerRecommendation_Disapprove;
break;
case ReviewRecommendations.NoDecision:
reviewRecommendationName = PriorApprovalConstatnts.ReviewerRecommendation_NoDecision;
break;
case ReviewRecommendations.RecommendApproval:
reviewRecommendationName = PriorApprovalConstatnts.ReviewerRecommendation_RecommendApproval;
break;
case ReviewRecommendations.RequestChange:
reviewRecommendationName = PriorApprovalConstatnts.ReviewerRecommendation_RequestChange;
break;
}
return reviewRecommendationName;
}
public static int GetColumnNo()
{
int colNo = 1;
//get col no
return colNo;
}
public static RoleType GetRoleType(string role)
{
RoleType roleType = 0;
switch (role)
{
case "PO":
roleType = RoleType.PO;
break;
case "PQC":
roleType = RoleType.PQC;
break;
case "PAO":
roleType = RoleType.PAO;
break;
case "GMS":
roleType = RoleType.GMS;
break;
}
return roleType;
}
public static string GetRoleName(RoleType role)
{
string roleName = string.Empty;
switch (role)
{
case RoleType.PO:
roleName = "PO";
break;
case RoleType.PQC:
roleName = "PQC";
break;
case RoleType.PAO:
roleName = "PAO";
break;
case RoleType.GMS:
roleName = "GMS";
break;
}
return roleName;
}
public static string GMSReviewDecision(String GMSReviewDecision)
{
string Decision = string.Empty;
switch (GMSReviewDecision)
{
case "Accepted":
Decision = "1";
break;
case "Pending Decision":
Decision = "3";
break;
case "Awaiting Final Financial Report":
Decision = "4";
break;
case "Change Requested":
Decision = "2";
break;
}
return Decision;
}
public static string GetRequestTypeName(PriorApprovalRequestType requestType)
{
string requestTypeName = string.Empty;
switch (requestType)
{
case PriorApprovalRequestType.PD:
requestTypeName = "PD";
break;
case PriorApprovalRequestType.Other:
requestTypeName = "Other";
break;
}
return requestTypeName;
}
public static string GetReviewTestTypeName(ReviewTestType reviewTestType)
{
string reviewTestTypeName = string.Empty;
switch (reviewTestType)
{
case ReviewTestType.Approval:
reviewTestTypeName = "Approval";
break;
case ReviewTestType.ChangeRequestFromPreviousReviewer:
reviewTestTypeName = "ChangeRequestFromPreviousReviewer";
break;
}
return reviewTestTypeName;
}
public static string GetStatusCode(SubmissionCode submissioncode)
{
string requestsubmissioncode = string.Empty;
switch (submissioncode)
{
case SubmissionCode.NotStarted:
requestsubmissioncode = "1";
break;
case SubmissionCode.InProgress:
requestsubmissioncode = "2";
break;
case SubmissionCode.DataEntryInProgress:
requestsubmissioncode = "3";
break;
case SubmissionCode.ReviewInProgress:
requestsubmissioncode = "4";
break;
case SubmissionCode.Processed:
requestsubmissioncode = "5";
break;
case SubmissionCode.ChangeRequested:
requestsubmissioncode = "6";
break;
case SubmissionCode.AdministrativelyClosed:
requestsubmissioncode = "10";
break;
}
return requestsubmissioncode;
}
/* public static InternalReviewerRoleEntity FindInternalReviewer(RoleType roleType , TaskTypeCode taskTypeCode)
{
using (DBConnection DB = new DBConnection())
{
string query = string.Format(QueryScripts.Internal_Reviewer, (int)roleType, (int)taskTypeCode);
List<InternalReviewerRoleEntity> data = DB.GetTable(query).ToList<InternalReviewerRoleEntity>();
return data.FirstOrDefault();
}
}*/
}
public enum RoleType : int
{
GMS = 6,
PO = 9,
PAO = 41,
PQC = 44,
DIR_REVIEWER = 29,
QC_REVIEWER = 10,
GMO = 5,
GA = 23////
}
public enum PriorApprovalRequestType : int
{
PD = 3,
Other = 7
}
public enum ReviewerType : int
{
TeamUnassigned = 1,
TeamAssigned = 2,
Individual = 3
}
public enum PriorApprovalReviewType : int
{
Internal =1,
ProgramOffice = 2,
GrantOffice = 3
}
public enum WorkflowOPtions : int
{
SendForFurtherReviewToPrograms = 1,
SendForFurtherReviewToGrants = 2,
MarkAsComplete=3,
RequestChangeFromPreviousReviewer=4
}
public enum ReviewRecommendations : int
{
RecommendApproval = 1,
Approve = 2,
Disapprove=3,
RequestChange=4,
NoDecision=5
}
public enum GrantRecommendations : int
{
NonMonetaryAdministrativeChanges = 1
}
public enum ReviewTestType : int
{
Approval = 1,
ChangeRequestFromPreviousReviewer = 2
}
public enum TestType : int
{
PriorApprovalRequest = 1,
PriorApprovalReview = 2
}
public enum TaskTypeCode : int
{
PrepareNoA = 1,
QCReview = 4,
SignAwards = 5,
}
public enum SubmissionCode : int
{
NotStarted = 1,
InProgress = 2,
DataEntryInProgress=3,
ReviewInProgress = 4,
Processed = 5,
ChangeRequested = 6,
AdministrativelyClosed=10,
}
public class TestEnvironment
{
public const string ExternalUTL2 = "externalutl2";
public const string ExternalUTL9 = "externalutl9";
public const string ExternalUTL16 = "externalutl16";
public const string ExternalREIINT = "externalreiint";
public const string InternalUTL2 = "internalutl2";
public const string InternalUTL9 = "internalutl9";
public const string InternalUTL16 = "internalutl16";
public const string InternalSBX8 = "internalsbx8";
public const string InternalREIINT = "internalreiint";
public const string InternalHRSAINT = "internalhrsaint";
public const string InternalHRSAQA = "internalhrsaqa";
public const string InternalHRSAOS = "internalhrsaos";
public const string GrantdotGov = "grantdotgov";
public const string PMS = "pms";
}
} | true |
fbb928fde814575239f6dfd310162400aae2c214 | Java | bellmit/eparkingMicroservice | /eparkingCloud/src/main/java/com/eparking/controller/work/PropertyBillItemsController.java | UTF-8 | 3,389 | 1.851563 | 2 | [] | no_license | package com.eparking.controller.work;
import com.common.annotation.HttpLog;
import com.common.entity.ActionRsp;
import com.common.entity.ControllerRsp;
import com.common.entity.eparkingCloud.TPropertyBillItems;
import com.eparking.insideService.TPropertyBillItemsInsideService;
import com.eparking.service.PropertyBillItemsService;
import com.common.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/propertybillitems")
public class PropertyBillItemsController {
private static final Logger logger= LoggerFactory.getLogger(PropertyBillItemsController.class);
@Autowired
private PropertyBillItemsService propertyBillItemsService;
@Autowired
private TPropertyBillItemsInsideService tPropertyBillItemsInsideService;
@PostMapping(value = "/getPropertybillitemsList")
@HttpLog(operationType = "0",modularTypeName = "查询缴费项目列表")
public ActionRsp getPropertybillitemsList(TPropertyBillItems tPropertyBillItems){
tPropertyBillItems.setCompanyId(SessionUtil.getCompany().getId());
tPropertyBillItems.setParkId(SessionUtil.getParkId());
// return ControllerRspUtil.Success(propertyBillItemsService.getPropertyBillItems(tPropertyBillItems));
return tPropertyBillItemsInsideService.getTPropertyBillItems(tPropertyBillItems);
}
@PostMapping(value = "/getPropertybillitemsListbyPage")
@HttpLog(operationType = "0",modularTypeName = "查询缴费项目列表(分页)")
public ControllerRsp getPropertybillitemsListbyPage(TPropertyBillItems tPropertyBillItems, Integer page, Integer limit){
tPropertyBillItems.setCompanyId(SessionUtil.getCompany().getId());
tPropertyBillItems.setParkId(SessionUtil.getParkId());
// return ControllerRspUtil.Success(propertyBillItemsService.getPropertyBillItemsbyPage(tPropertyBillItems,page,limit));
return tPropertyBillItemsInsideService.getTPropertyBillItemsbyPage(tPropertyBillItems,page,limit);
}
@PostMapping(value = "/updatePropertybillitemsList")
@HttpLog(operationType = "1",modularTypeName = "编辑缴费项目")
public ActionRsp updatePropertybillitemsList(TPropertyBillItems tPropertyBillItems){
tPropertyBillItems.setCompanyId(SessionUtil.getCompany().getId());
tPropertyBillItems.setParkId(SessionUtil.getParkId());
tPropertyBillItems.setCreateTime(DateUtil.getCurDateTime());
tPropertyBillItems.setUpdateTime(DateUtil.getCurDateTime());
// return ActionRspUtil.Success(propertyBillItemsService.updatePropertyBillItems(tPropertyBillItems));
return tPropertyBillItemsInsideService.UpdateTPropertyBillItems(tPropertyBillItems);
}
@PostMapping(value = "/deletePropertybillitemsList")
@HttpLog(operationType = "1",modularTypeName = "删除缴费项目")
public ActionRsp deletePropertybillitemsList(TPropertyBillItems tPropertyBillItems){
// return ActionRspUtil.Success(propertyBillItemsService.deletePropertyBillItems(tPropertyBillItems));
return tPropertyBillItemsInsideService.DeleteTPropertyBillItems(tPropertyBillItems);
}
}
| true |
6c5ae20e49560ceb68a7742978d6d07ede0e6033 | Java | DynamicApproach/Java-Work | /Euler549/src/Euler549.java | UTF-8 | 4,988 | 3.15625 | 3 | [
"MIT"
] | permissive |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
/**
*
* @author User
*/
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class Euler549 {
public static void main(String[] args) {
FactorialDivisibility tester = new FactorialDivisibility();
for (int i = 2; i <= 100; i++) {
System.out.println(i + ": " + tester.sOfI(i));
}
//tester.runner();
}
}
class FactorialDivisibility {
private HashMap<Integer, BigInteger> factorials = new HashMap();
private HashMap<Integer, Integer> intToMinFactorial = new HashMap();
private int sum = 0;
private HashMap<Long, Integer> primeFactors = new HashMap();
private Long number = 0L;
private ArrayList<Long> factors = new ArrayList();
public FactorialDivisibility() {
this.factorials.put(1, BigInteger.ONE);
}
public void runner() {
for (int i = 2; i <= (int) Math.pow(10, 2); i++) {
this.primeFactors.clear();
this.sum = this.sum + this.sOfI(i);
}
System.out.println("total: " + this.sum);
}
public int sOfI(int i) {
if (this.isPrime((long) i)) {
return i;
}
else {
this.number = (long) i;
this.primeFactors.clear();
this.getPrimeFactors();
int seed = 1;
int max = 1;
for(long x: this.primeFactors.keySet()){
if(Math.pow(x, this.primeFactors.get(x)) > max){
max = (int) Math.pow(x, this.primeFactors.get(x));
seed = (int) x;
}
}
if(this.primeFactors.get((long) seed) == 1){
return seed;
}
else if(this.intToMinFactorial.keySet().contains(max)){
if(this.intToMinFactorial.keySet().contains(max)){
return this.intToMinFactorial.get(max);
}
else{
long j = this.primeFactors.get(seed);
this.computeMin(seed, j);
return this.intToMinFactorial.get((int) Math.pow(seed, max));
}
}
return seed;
}
}
public void computeMin(long p, long j){
int total = 0;
for (long i = p; i <= p*j; i = i + p) {
this.primeFactors.clear();
this.number = (long) i;
this.getPrimeFactors();
//System.out.println(i + "; " + j );
total = total + this.primeFactors.get((long) p);
if(total >= j){
break;
}
}
this.intToMinFactorial.put((int) Math.pow(p, j), total);
}
public boolean isPrime(Long n) {
ArrayList<Long> arrayOfFactors = getFactorsOfInterest(n);
if (arrayOfFactors.isEmpty()) { //If n has no factors less than or equal to the square root of n,
return true; // then n must be prime.
}
return false; // Otherwise, it is not prime.
}
public void getPrimeFactors() {
if(this.isPrime(this.number)){
this.primeFactors.put(this.number, 1);
}
while ((this.number != 1) && (!isPrime(this.number))) {
this.factors = this.getFactorsOfInterest(this.number);
for (Long x : this.factors) {
if (isPrime(x)) {
if (!this.primeFactors.keySet().contains(x)) {
primeFactors.put(x, 1);
}
else {
this.primeFactors.replace(x, primeFactors.get(x) + 1);
}
if (isPrime(this.number / x)) {
if (!this.primeFactors.keySet().contains(this.number / x)) {
primeFactors.put(this.number / x, 1);
}
else {
this.primeFactors.replace(this.number / x, primeFactors.get(this.number / x) + 1);
}
}
else {
this.number = this.number / x;
break;
}
this.number = this.number / x;
}
}
}
//this.printPrimeFactors();
}
public ArrayList<Long> getFactorsOfInterest(Long n) {
ArrayList<Long> factors = new ArrayList();
for (Long i = 2L; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
factors.add(i);
}
}
return factors;
}
public BigInteger factorialCalculator(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
} | true |
9b21dc4c9fad7450a91b920f2d74e7a5c4b164a6 | Java | efftushkin/HillelJavaGradle | /src/main/java/com/efftushkin/app/SimpleCalculator.java | UTF-8 | 2,775 | 3.890625 | 4 | [] | no_license | package com.efftushkin.app;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
System.out.println("main.java.com.efftushkin.app.SimpleCalculator: Welcome!");
Scanner scanner = new Scanner(System.in);
BigDecimal num1 = null;
BigDecimal num2 = null;
do {
System.out.println("Please input the first number");
if (scanner.hasNextBigDecimal()) {
num1 = scanner.nextBigDecimal();
System.out.println("Your input " + num1.toPlainString() + " as the first number");
} else {
System.out.println("Incorrect entry, exception " + scanner.nextLine() + ". Please enter numbers. Try again");
}
}
while (num1 == null);
do {
System.out.println("Please input the second number");
if (scanner.hasNextBigDecimal()) {
num2 = scanner.nextBigDecimal();
System.out.println("Your input " + num2.toPlainString() + " as the second number");
} else {
System.out.println("Incorrect entry, exception " + scanner.nextLine() + ". Please enter numbers. Try again");
}
}
while (num2 == null);
BigDecimal sum = (num1.add(num2));
int newScale = sum.scale();
if (newScale > 8) {
newScale = 8;
}
sum = sum.setScale(newScale, RoundingMode.HALF_UP);
BigDecimal dif = (num1.subtract(num2));
newScale = dif.scale();
if (newScale > 8) {
newScale = 8;
}
dif = dif.setScale(newScale, RoundingMode.HALF_UP);
BigDecimal mul = (num1.multiply(num2));
newScale = mul.scale();
if (newScale > 8) {
newScale = 8;
}
mul = mul.setScale(newScale, RoundingMode.HALF_UP);
String divOutput;
if (!num2.equals(BigDecimal.ZERO)) {
BigDecimal div = num1.divide(num2, 8, RoundingMode.HALF_UP);
newScale = div.scale();
if (newScale > 8) {
newScale = 8;
}
div = div.setScale(newScale, RoundingMode.HALF_UP);
divOutput = div.toPlainString();
} else {
divOutput = "You can't divide by zero";
}
System.out.println("Results:");
System.out.println("Sum is: " + sum.toPlainString());
System.out.println("Difference is: " + dif.toPlainString());
System.out.println("Multiplication is: " + mul.toPlainString());
System.out.println("Division is: " + divOutput);
scanner.close();
System.exit(0);
}
} | true |
d12cf8fcb73b2451445ed2a2a0d13035ee1ac584 | Java | HorizenSS/WZ_ESPRIT_JavaEE_JSF_Nature-Spirit_Project | /nature-spirit-ejb/src/main/java/tn/esprit/entities/DonationId.java | UTF-8 | 1,558 | 2.515625 | 3 | [] | no_license | package tn.esprit.entities;
import java.io.Serializable;
import javax.persistence.Embeddable;
@Embeddable
public class DonationId implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer idMember;
private Integer idEvent;
public DonationId() {
// TODO Auto-generated constructor stub
}
public DonationId(Integer idMember, Integer idEvent) {
super();
this.idMember = idMember;
this.idEvent = idEvent;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((idEvent == null) ? 0 : idEvent.hashCode());
result = prime * result + ((idMember == null) ? 0 : idMember.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;
DonationId other = (DonationId) obj;
if (idEvent == null) {
if (other.idEvent != null)
return false;
} else if (!idEvent.equals(other.idEvent))
return false;
if (idMember == null) {
if (other.idMember != null)
return false;
} else if (!idMember.equals(other.idMember))
return false;
return true;
}
public Integer getIdMember() {
return idMember;
}
public void setIdMember(Integer idMember) {
this.idMember = idMember;
}
public Integer getIdEvent() {
return idEvent;
}
public void setIdEvent(Integer idEvent) {
this.idEvent = idEvent;
}
}
| true |
1d6eb613ebe93659fd010b56ca16b1f24f065e19 | Java | Emily-Jiang/microprofile-service-mesh-service-a | /src/main/java/org/eclipse/microprofile/servicemesh/servicea/ServiceA.java | UTF-8 | 2,701 | 2.046875 | 2 | [
"Apache-2.0"
] | permissive | /*
*******************************************************************************
* Copyright (c) 2018 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* 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.
*
* Contributors:
* 2018-06-19 - Jon Hawkes / IBM Corp
* Initial code
*
*******************************************************************************/
package org.eclipse.microprofile.servicemesh.servicea;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.net.InetAddress;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import org.eclipse.microprofile.metrics.Counter;
import org.eclipse.microprofile.metrics.annotation.Counted;
import org.eclipse.microprofile.metrics.annotation.Metric;
/**
* ServiceA tries to call ServiceB (via a Rest Client) and then wrap the response up in a data bean to be returned.
* It keeps track of how many times it has been called through an ApplicationScoped CallCounter.
*/
@RequestScoped
public class ServiceA {
@Inject
ServiceBClientImpl serviceBClient;
@Inject
@Metric(name="callCounter")
Counter callCounter;
@Counted(name="callCounter", monotonic=true)
public ServiceData call(TracerHeaders ts, String userAgent) throws Exception {
long callCount = callCounter.getCount();
Future<ServiceData> serviceBFuture = serviceBClient.call(ts, userAgent);
ServiceData serviceBData = serviceBFuture.get(60, TimeUnit.SECONDS);
String hostname;
try {
hostname = InetAddress.getLocalHost()
.getHostName();
} catch (java.net.UnknownHostException e) {
hostname = e.getMessage();
}
ServiceData data = new ServiceData();
data.setSource(this.toString());
data.setMessage("Hello from serviceA on >" + hostname + "< and user-agent >" + userAgent + "< @ "+ data.getTime());
data.setData(serviceBData);
data.setCallCount(callCount);
data.setTries(1);
return data;
}
}
| true |
2f7b61aabaa6089cce18d4901f4b015b98001afd | Java | nperrier/music-server | /indexer/src/main/java/com/perrier/music/tag/MockTag.java | UTF-8 | 390 | 2.390625 | 2 | [] | no_license | package com.perrier.music.tag;
public class MockTag extends AbstractTag {
private MockTag(Builder builder) {
super(builder);
}
public final static class Builder extends AbstractTagBuilder<MockTag> {
@Override
public MockTag build() {
return new MockTag(this);
}
@Override
public String toString() {
return "Builder [toString()=" + super.toString() + "]";
}
}
}
| true |
628d390a9a7e9dce6aa2b97a90e409d2f25b5ca2 | Java | Seconight/Project | /student_sign_demo/src/test/java/com/Attendance/student_sign_demo/repository/AttendanceRepositoryTest.java | UTF-8 | 984 | 2.171875 | 2 | [] | no_license | package com.Attendance.student_sign_demo.repository;
import com.Attendance.student_sign_demo.entity.Attendance;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class AttendanceRepositoryTest {
@Autowired
private AttendanceRepository repository;
@Test
void findAll(){
List<Attendance> list=repository.findAll();
for(Attendance attendance:list) {
System.out.println(attendance);
}
}
@Test
void findByAttendanceNo(){
Attendance attendance=repository.findByAttendanceNo("0000000001");
System.out.println(attendance);
}
@Test
void findByAttendanceCourseNo(){
List<Attendance> attendance=repository.findByAttendanceCourseNo("0000000001");
System.out.println(attendance);
}
} | true |
b488d69bf6e0295fed634b3cc99740d7c6b5e7d7 | Java | ChandhiniPM/SpringProjects | /springwebORMMVC/src/main/java/com/spring/springormmvc/user/dao/UserDaoImpl.java | UTF-8 | 840 | 2.265625 | 2 | [] | no_license | package com.spring.springormmvc.user.dao;
import java.io.Serializable;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.spring.springormmvc.user.entity.User;
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public int create(User user) {
Integer result = (Integer) hibernateTemplate.save(user);
return result;
}
public List<User> findAll() {
return hibernateTemplate.loadAll(User.class);
}
}
| true |
cd73cdba1e4b909b6b12d470d24b9553abc35acb | Java | b3lg1c4/java-ejercicios | /Ejercicio4/src/cuartoEjercicio/Main.java | UTF-8 | 1,026 | 3.484375 | 3 | [] | no_license | package cuartoEjercicio;
import java.util.Scanner;
public class Main {
static Scanner input = new Scanner(System.in);
static int SIZE = 5;
private static int[] getEnteros(int[] enteros) {
for (int i = 0; i < SIZE; i++) {
enteros[i] = input.nextInt();
}
;
return enteros;
};
private static int[] getMayores(int entero, int[] enteros) {
int[] tempArray = new int[SIZE];
int counter = 0;
for (int i = 0; i < SIZE; i++) {
if (enteros[i] > entero) {
tempArray[counter] = enteros[i];
counter += 1;
}
;
}
;
return tempArray;
};
private static void mostrarMayores(int[] mayoresAEntero) {
for (int entero : mayoresAEntero) {
if (entero != 0) {
System.out.println(entero);
}
;
}
;
};
public static void main(String[] args) {
int entero = input.nextInt();
int[] enteros = new int[SIZE];
int[] mayoresAEntero = new int[SIZE];
enteros = getEnteros(enteros);
mayoresAEntero = getMayores(entero, enteros);
mostrarMayores(mayoresAEntero);
}
}
| true |
430bd21fcd77a0e9bbc22492f3457c2a6af8d965 | Java | master-spike/Blade2D | /src/com/blade2d/drawelements/Image.java | UTF-8 | 2,112 | 3.21875 | 3 | [] | no_license | package com.blade2d.drawelements;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.IntBuffer;
import javax.imageio.ImageIO;
/**
* An image designed for use as an OpenGL texture
*/
public class Image {
/**
* Raw pixel data
*/
private final int[] data;
/**
* Width in pixels
*/
public final int width;
/**
* Height in pixels
*/
public final int height;
/**
* Pixel data as a buffer
*/
public final IntBuffer buffer;
/**
* @param filename - path to image to load
*/
public Image(String filename) {
BufferedImage image = loadImageFile(filename);
width = image.getWidth();
height = image.getHeight();
data = getPixelsFromImage(image);
buffer = Buffers.createIntBuffer(data).asReadOnlyBuffer();
}
// create an Image from only a section of the file
public Image(String filename, int x, int y, int w, int h) {
BufferedImage image = loadImageFile(filename);
width = w;
height = h;
data = getPixelsFromImageSection(image, x, y, w, h);
buffer = Buffers.createIntBuffer(data).asReadOnlyBuffer();
}
private BufferedImage loadImageFile(String filename) {
BufferedImage image = null;
// Attempt to load image file
try {
image = ImageIO.read(new FileInputStream(filename));
} catch (IOException e){
e.printStackTrace();
throw new Error("Could not load image: " + filename);
}
return image;
}
private int[] getPixelsFromImage(BufferedImage image) {
return getPixelsFromImageSection(image, 0,0,image.getWidth(),image.getHeight());
}
int[] getPixelsFromImageSection(BufferedImage image, int x, int y, int w, int h) {
// Grab raw pixel data
int[] pixels = new int[w * h];
image.getRGB(x, y, w, h, pixels, 0, w);
// Reorder argb into abgr
int[] data = new int[w * h];
for(int i = 0; i < w * h; i++){
int a = (pixels[i] & 0xff000000) >> 24;
int r = (pixels[i] & 0xff0000) >> 16;
int g = (pixels[i] & 0xff00) >> 8;
int b = (pixels[i] & 0xff);
data[i] = a << 24 | b << 16 | g << 8 | r;
}
return data;
}
}
| true |
f7112720e01c82a948feb749a3a1079ce1919f69 | Java | claudiomoscoso/aga-app | /src/cl/builderSoft/product/simulation/MainSimulation.java | UTF-8 | 2,667 | 2.296875 | 2 | [] | no_license | /*
* Created on 08-01-2008
*/
package cl.builderSoft.product.simulation;
import java.sql.Connection;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import cl.builderSoft.framework.exception.BSException;
import cl.builderSoft.framework.exception.BSProgrammerException;
import cl.builderSoft.framework.mvc.ioService.BSServiceData;
import cl.builderSoft.framework.service.BSAbstractProcess;
import cl.builderSoft.framework.service.BSProcess;
import cl.builderSoft.framework.util.BSConfigManager;
import cl.builderSoft.framework.util.BSConstants;
import cl.builderSoft.framework.util.BSStaticManager;
import cl.builderSoft.framework.util.BSXMLManager;
/**
* @author cmoscoso
*/
public class MainSimulation extends BSAbstractProcess implements BSProcess {
public BSServiceData execute(BSServiceData serviceData) throws BSException {
return executeTransaction(serviceData, null);
}
public BSServiceData executeTransaction(BSServiceData serviceData, Connection conn) throws BSException {
String processName = serviceData.getProcessName();
String serviceName = serviceData.getServiceName();
Document serviceDataDocument = serviceData.getDocument();
String sessionID = serviceDataDocument.selectSingleNode("/Service/Session/@ID").getText();
String pathFile = BSConfigManager.getConfigPath() + "Simulation" + BSConstants.FILE_SEPARATOR + processName
+ ".xml";
String fileContent = (String) BSStaticManager.getFileContent(pathFile);
Document fileDocument = null;
try {
fileDocument = BSXMLManager.stringToDocument(fileContent);
} catch (BSProgrammerException e) {
throw new BSProgrammerException("No se pudo interpretar correctamente el archivo [" + pathFile + "]", true);
}
putSimulationInResponse(serviceDataDocument, fileDocument);
/**
* <code>
serviceDataDocument.clearContent();
serviceDataDocument.add((Element)fileDocument.getRootElement().clone());
serviceData.setProcessName(processName);
serviceData.setServiceName(serviceName);
serviceDataDocument.selectSingleNode("/Service/Session/@ID").setText(sessionID);
</code>
*/
return null;
}
private void putSimulationInResponse(Document serviceDataDocument, Document fileDocument) {
List nodeList = fileDocument.selectNodes("/Service/Response/Fields/*");
Element object = null;
Element targetElement = (Element) serviceDataDocument.selectSingleNode("/Service/Response/Fields");
for (Iterator iterator = nodeList.iterator(); iterator.hasNext();) {
object = (Element) iterator.next();
targetElement.add((Element) object.clone());
}
}
} | true |
95a8626e8662c01c7eb8b02ca31c9c80f3860db1 | Java | MarinaBekavac/Java | /src/main/java/sample/DodavanjeNoveZupanijeController.java | UTF-8 | 2,183 | 2.4375 | 2 | [] | no_license | package main.java.sample;
import hr.java.covidportal.load.BazaPodataka;
import hr.java.covidportal.model.Zupanija;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TextField;
import java.sql.SQLException;
import static hr.java.covidportal.load.Loaders.dodajZupanijuUDatoteku;
public class DodavanjeNoveZupanijeController {
@FXML
private TextField nazivZupanijeField;
@FXML
private TextField brStanovnikaField;
@FXML
private TextField brZarazenihStanovnikaField;
@FXML
public void spremiZupaniju(){
String naziv = nazivZupanijeField.getText();
Integer brStanovnika = Integer.valueOf(brStanovnikaField.getText());
Integer brZarazenihStanovnika = Integer.valueOf(brZarazenihStanovnikaField.getText());
Long id = PretragaZupanijaController.getId()+1;
Zupanija z = new Zupanija(naziv,brStanovnika,brZarazenihStanovnika,id);
PretragaZupanijaController.dodajZupaniju(new Zupanija(naziv,brStanovnika,brZarazenihStanovnika,id));
//int correct = dodajZupanijuUDatoteku(z);
int correct = 1;
if(naziv.equals("") || brStanovnika<0 || brZarazenihStanovnika>brStanovnika)
correct = 0;
if(correct==1){
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Alert window");
alert.setHeaderText("Uspjesno dodavanje zupanije;");
alert.setContentText("Vasa zupanije je uspjesno dodana u listu zupanija");
alert.showAndWait();
//dodajZupanijuUDatoteku(z);
try {
BazaPodataka.spremiNovuZupaniju(z);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}else{
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Alert window");
alert.setHeaderText("Neuspjesno dodavanje zupanije;");
alert.setContentText("Vasa zupanije NIJE uspjesno dodana u listu zupanija");
alert.showAndWait();
}
}
}
| true |
11f1334a79911f9a4e033bf44b820478b6ba132d | Java | JPedroSilveira/greenshare-api | /src/main/java/com/greenshare/entity/address/Address.java | UTF-8 | 6,197 | 2.5 | 2 | [] | no_license | package com.greenshare.entity.address;
import static javax.persistence.GenerationType.SEQUENCE;
import java.io.Serializable;
import java.util.ArrayList;
import javax.persistence.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.greenshare.entity.FlowerShop;
import com.greenshare.entity.abstracts.AbstractEntity;
import com.greenshare.entity.user.User;
import com.greenshare.enumeration.AddressType;
/**
* Persistence class for the table address
*
* @author joao.silva
*/
@Entity
@Table(name = "address")
public class Address extends AbstractEntity<Address> implements Serializable {
private static final long serialVersionUID = 1L;
private static final String SEQUENCE_NAME = "address_seq";
@Id
@GeneratedValue(strategy = SEQUENCE, generator = SEQUENCE_NAME)
@SequenceGenerator(name = SEQUENCE_NAME, sequenceName = SEQUENCE_NAME)
@Basic(optional = false)
@Column(name = "address_id")
private Long id;
@Basic(optional = false)
@NotNull(message = "O número não pode ser nulo.")
@Column(name = "number")
private Integer number;
@Basic(optional = false)
@NotNull(message = "O tipo de endereço não pode ser nulo.")
@Column(name = "type")
private Integer type;
@Basic(optional = false)
@Size(min = 1, max = 200, message = "O bairro deve conter entre 1 e 200 caracteres.")
@NotNull(message = "O bairro não pode ser nulo.")
@Column(name = "neighborhood", length = 200)
private String neighborhood;
@Basic(optional = false)
@Size(min = 1, max = 200, message = "O endereço deve conter entre 1 e 200 caracteres.")
@NotNull(message = "O endereço não pode ser nulo.")
@Column(name = "addressName", length = 200)
private String addressName;
@Basic(optional = true)
@Column(name = "complement", length = 200)
private String complement;
@Basic(optional = true)
@Column(name = "referencia", length = 200)
private String apartment;
@Basic(optional = false)
@NotNull(message = "Cidade não poder ser nula.")
@ManyToOne
@Valid
@JoinColumn(name = "city_id")
private City city;
@JsonIgnore
@Basic(optional = true)
@OneToOne(mappedBy = "address")
@Valid
private User user;
@JsonIgnore
@Basic(optional = true)
@Valid
@OneToOne(mappedBy = "address")
private FlowerShop flowerShop;
protected Address() {
super(false);
}
public Address(City city, Integer number, String neighborhood, String addressName, String complement,
String apartment, Integer type) {
super(true);
this.city = city;
this.number = number;
this.neighborhood = neighborhood;
this.addressName = addressName;
if (isNotNull(complement) && complement.isEmpty()) {
this.complement = null;
} else {
this.complement = complement;
}
if (isNull(apartment) || apartment.isEmpty() || type != AddressType.Apartment.getValue()) {
this.apartment = null;
} else {
this.apartment = apartment;
}
this.type = type;
this.validationErrors = new ArrayList<>();
}
public Address(Address address) {
super(true);
this.city = address.getCity();
this.number = address.getNumber();
this.neighborhood = address.getNeighborhood();
this.addressName = address.getAddressName();
if (isNull(address.getComplement()) || address.getComplement().isEmpty()) {
this.complement = null;
} else {
this.complement = address.getComplement();
}
if (isNull(address.getApartment()) || address.getApartment().isEmpty() || address.getType() != AddressType.Apartment.getValue()) {
this.apartment = null;
} else {
this.apartment = address.getApartment();
}
this.type = address.getType();
this.validationErrors = new ArrayList<>();
}
@Override
public boolean isValid() {
this.validationErrors.clear();
if (isNull(this.city)) {
this.validationErrors.add("Cidade nula.");
} else if (this.city.isNotValid()) {
this.validationErrors.addAll(this.city.getValidationErrors());
}
if (isNull(this.number) || is(this.number).smallerThan(1)) {
this.validationErrors.add("O número não pode ser nulo ou menor que um.");
}
if (isNull(this.neighborhood) || is(this.neighborhood).orSmallerThan(1).orBiggerThan(200)) {
this.validationErrors.add("O bairro não pode ser nulo e deve conter entre 1 e 200 caracteres.");
}
if (isNull(this.addressName) || is(this.addressName).orSmallerThan(1).orBiggerThan(200)) {
this.validationErrors.add("O endereço não pode ser nulo e deve conter entre 1 e 200 caracteres.");
}
if (isNotNull(this.complement) && is(this.complement).orSmallerThan(1).orBiggerThan(200)) {
this.validationErrors.add("O complemento deve conter entre 1 e 200 caracteres.");
}
if ((this.type == AddressType.Apartment.getValue()) && (isNull(this.apartment) || is(this.apartment).orSmallerThan(1).orBiggerThan(200))) {
this.validationErrors.add("A número do apartamento não pode ser nulo e deve conter entre 1 e 200 caracteres quando o tipo de endereço for apartamento.");
}
if (isNull(this.type) || !AddressType.exists(this.type)) {
this.validationErrors.add("O tipo de endereço é inválido.");
}
return this.validationErrors.isEmpty();
}
@Override
public Long getId() {
return this.id;
}
public User getUser() {
return this.user;
}
public City getCity() {
return city;
}
public Integer getNumber() {
return number;
}
public Integer getType() {
return type;
}
public String getNeighborhood() {
return neighborhood;
}
public String getAddressName() {
return addressName;
}
public String getComplement() {
return complement;
}
public String getApartment() {
return apartment;
}
public FlowerShop getFlowerShop() {
return flowerShop;
}
@Override
public void update(Address address) {
this.number = address.getNumber();
this.neighborhood = address.getNeighborhood();
this.addressName = address.getAddressName();
this.complement = address.getComplement();
this.apartment = address.getApartment();
this.city = address.getCity();
this.type = address.getType();
}
@JsonIgnore
public boolean isInUse() {
return isNull(this.flowerShop) && isNull(this.user);
}
} | true |
d58789cbbd2dbf192470a7098403a6fbdf2527e9 | Java | stephsun21/java-projects | /Zinnformatics.java | UTF-8 | 1,723 | 3.515625 | 4 | [] | no_license | import javax.swing.JOptionPane;
import java.text.NumberFormat;
//Author:Stephanie Sun
//Zinnformatics.java
//
//This method takes the input company name and quantity orderd and output a final invoice through a message box.
public class Zinnformatics{
public static void main(String[]args){
int again;
do{
String companyName = JOptionPane.showInputDialog ("Enter your company name:");
String quantityStr = JOptionPane.showInputDialog ("Enter the number of packages that they would like to order:");
int quantity = Integer.parseInt(quantityStr);
NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
NumberFormat fmt2 = NumberFormat.getPercentInstance();
JOptionPane.showMessageDialog (null, "Thank you for your order "+companyName+" ! You have ordered "+ quantityStr+ " packages, at a "+fmt2.format(discount(quantity))+ " discount. Your final cost will be " + fmt1.format(zinnformatics(quantity)));
again = JOptionPane.showConfirmDialog (null, "Do you want to continue the program?");
}
while (again == JOptionPane.YES_OPTION);
}
//This method takes the quantity orderd and returns the discount the user gets.
public static double discount(int quantity){
if(quantity<=9)
return 0;
else if(quantity >= 10 && quantity < 20)
return 0.2;
else if(quantity >= 20 && quantity < 50)
return 0.3;
else if(quantity >= 50 && quantity < 100)
return 0.4;
else
return 0.5;
}
//This method takes the quantity orderd and discount and returns the final price.
public static double zinnformatics(int quantity){
return 99*quantity*(1-discount(quantity));
}
}
| true |
6af0949a95c07b0188f3f36ffbec8d2493539f47 | Java | warlockopy/MzoneApi | /src/main/java/place/PlaceReader.java | UTF-8 | 1,750 | 2.96875 | 3 | [] | no_license | package place;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import utilities.Tokenizer;
public class PlaceReader {
public ArrayList <Place> readPlaces (String fileName){
ArrayList <Place> places = new ArrayList ();
FileReader fReader = null;
BufferedReader reader = null;
try {
fReader = new FileReader (fileName);
reader = new BufferedReader (fReader);
int lineNo = 0;
String line;
while ((line = reader.readLine()) != null)
if (++lineNo > 1){
Tokenizer tok = new Tokenizer (line);
Place place = new Place ();
String POIName = tok.nextToken(); //Se carga en la Description del Place
String Description = tok.nextToken();
double longitude = tok.nextDouble();
double latitude = tok.nextDouble();
String address1 = tok.nextToken();
String address2 = tok.nextToken();
String city = tok.nextToken();
String state = tok.nextToken();
int zipCode = tok.nextInt();
String country = tok.nextToken();
double POIBuffer = tok.nextDouble() / 100.0;
String actionType = tok.nextToken();
int generateAlert = tok.nextInt();
String geometry = "POINT(" + longitude + " " + latitude + ")";
place.setBufferValue(POIBuffer);
place.setDescription(POIName);
place.setGeometry(geometry);
place.setPlaceType(1);
places.add(place);
}
reader.close ();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return places;
}
}
| true |
d29d5f1ce81654f73d60a6ac11bbc3ecf8eb2316 | Java | TaaviTilk/I200-JAVA | /Eksami_variandid/src/Algoritm/PikadSoned.java | UTF-8 | 1,067 | 2.984375 | 3 | [] | no_license | package Algoritm;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Antud on massiiv. Mitu sõne on massiivis keskmisest pikemad?
*/
public class PikadSoned {
public static void main(String[] args) {
//String[] naide = {"kaalikas", "joonas", "maakera", "homeros", "mandel"}; // vastus on 3
//ArrayList<String> sonad = new ArrayList<String>();
String[] naide = {"kaalikas", "joonas", "maakera", "homeros", "mandel"}; // vastus on 3
int sum = 0;
double kesk = 0;
double list = naide.length;
int count = 0;
//int word = naide[i].length();
for (int i = 0; i <naide.length; i++) {
sum += naide[i].length();
System.out.println(naide[i].length());
//kesk = sum/naide.length;
//ystem.out.println(sum+"ja kesk-"+kesk);
}
kesk = sum/list;
System.out.println(kesk);
for (int i = 0; i < list ; i++) {
if (naide[i].length()>kesk)count++;
}
System.out.println(count);
}
}
| true |
40f99b7e421dbbbd9eaea7326a64e1f7f7196f62 | Java | googleads/google-ads-java | /google-ads/src/main/java/com/google/ads/googleads/lib/logging/RequestLogger.java | UTF-8 | 6,385 | 2.171875 | 2 | [
"BSD-3-Clause",
"Classpath-exception-2.0",
"GPL-2.0-only",
"Apache-2.0",
"MIT",
"CDDL-1.1"
] | permissive | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ads.googleads.lib.logging;
import com.google.ads.googleads.lib.logging.Event.Detail;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
/**
* Dispatches logging requests to the logging library, decoupling logging from the RPC interceptor.
*/
public class RequestLogger {
@VisibleForTesting
static final String TRUNCATE_MESSAGE =
"\n... TRUNCATED. See README.md to configure/disable log truncation.";
private static final Logger libraryLogger = LoggerFactory.getLogger(RequestLogger.class);
private static final String LOG_LENGTH_LIMIT_KEY = "api.googleads.maxLogMessageLength";
private static final int DEFAULT_LOG_LENGTH_LIMIT = 1000;
private final Logger detailLogger;
private final Logger summaryLogger;
private final int logLengthLimit;
public RequestLogger() {
// These loggers are explicitly configured with constants to ensure consistency of logging
// configuration across refactorings.
this(
LoggerFactory.getLogger("com.google.ads.googleads.lib.request.summary"),
LoggerFactory.getLogger("com.google.ads.googleads.lib.request.detail"),
() ->
System.getProperties().containsKey(LOG_LENGTH_LIMIT_KEY)
? parseLogLengthLimit(System.getProperty(LOG_LENGTH_LIMIT_KEY))
: DEFAULT_LOG_LENGTH_LIMIT);
}
@VisibleForTesting
RequestLogger(
Logger summaryLogger, Logger detailLogger, Supplier<Integer> logLengthLimitSupplier) {
this.summaryLogger = summaryLogger;
this.detailLogger = detailLogger;
this.logLengthLimit = logLengthLimitSupplier.get();
Preconditions.checkArgument(logLengthLimit >= -1, LOG_LENGTH_LIMIT_KEY + " must be >= -1");
}
/**
* Checks if the detailed (request) logger is enabled. This operation will complete quickly and
* can be used to guard expensive logger statements.
*/
public boolean isDetailEnabled(Level level) {
return isLevelEnabled(level, detailLogger);
}
/**
* Checks if the summary (headers/trailers) logger is enabled. This operation will complete
* quickly and can be used to guard expensive logger statements.
*/
public boolean isSummaryEnabled(Level level) {
return isLevelEnabled(level, summaryLogger);
}
/**
* Logs a summary of an RPC call. Has no effect if the logger is not enabled at the level
* requested.
*/
public void logSummary(Level level, Event.Summary event) {
logAtLevel(
summaryLogger,
level,
"{} REQUEST SUMMARY. "
+ "Method: {}, "
+ "Endpoint: {}, "
+ "CustomerID: {}, "
+ "RequestID: {}, "
+ "ResponseCode: {}, "
+ "Fault: {}.",
event.isSuccess() ? "SUCCESS" : "FAILURE",
event.getMethodName(),
event.getEndpoint(),
event.getCustomerId(),
event.getRequestId(),
event.getResponseCode(),
event.getResponseDescription());
}
/**
* Logs the request/response of an RPC call. Has no effect if the logger is not enabled at the
* level requested.
*/
public void logDetail(Level level, Event.Detail event) {
logAtLevel(
detailLogger,
level,
"{} REQUEST DETAIL.\n"
+ "Request\n"
+ "-------\n"
+ "MethodName: {}\n"
+ "Endpoint: {}\n"
+ "Headers: {}\n"
+ "Body: {}\n\n"
+ "Response\n"
+ "--------\n"
+ "Headers: {}\n"
+ "Body: {}\n"
+ "Failure message: {}\n"
+ "Status: {}.",
event.isSuccess() ? "SUCCESS" : "FAILURE",
event.getMethodName(),
event.getEndpoint(),
event.getScrubbedRequestHeaders(),
event.getRequest(),
event.getResponseHeaderMetadata(),
truncate(event.getResponseAsText()),
getDeserializedFailureMessage(event),
event.getResponseStatus());
}
private String truncate(String responseMsg) {
if (responseMsg == null) {
return null;
}
if (logLengthLimit > -1 && responseMsg.length() > logLengthLimit) {
responseMsg = responseMsg.substring(0, logLengthLimit) + TRUNCATE_MESSAGE;
}
return responseMsg;
}
private static Integer parseLogLengthLimit(String propertyValue) {
try {
return Integer.parseInt(propertyValue);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException(
"Invalid " + LOG_LENGTH_LIMIT_KEY + " supplied, must be a number: " + propertyValue);
}
}
private static void logAtLevel(Logger logger, Level level, String format, Object... argList) {
if (level == Level.INFO) {
logger.info(format, argList);
} else if (level == Level.WARN) {
logger.warn(format, argList);
} else if (level == Level.DEBUG) {
logger.debug(format, argList);
} else {
throw new IllegalStateException("Unexpected log level: " + level);
}
}
private static boolean isLevelEnabled(Level logLevel, Logger logger) {
return (logLevel == Level.INFO && logger.isInfoEnabled())
|| (logLevel == Level.WARN && logger.isWarnEnabled())
|| (logLevel == Level.DEBUG && logger.isDebugEnabled());
}
private static Message getDeserializedFailureMessage(Detail event) {
try {
return event.deserializeFailureMessage().orElse(null);
} catch (InvalidProtocolBufferException e) {
libraryLogger.debug("GoogleAdsFailure message was present but not readable.", e);
return null;
}
}
}
| true |
8f9ccbcfe1dd74fa35783e3fd06685cac9042d96 | Java | fedor-malyshkin/story_line2_crawler | /src/main/java/ru/nlp_project/story_line2/crawler/parse_site/ParseSiteCrawler.java | UTF-8 | 2,794 | 2.65625 | 3 | [] | no_license | package ru.nlp_project.story_line2.crawler.parse_site;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.URLCanonicalizer;
import edu.uci.ics.crawler4j.url.WebURL;
import ru.nlp_project.story_line2.crawler.CrawlerConfiguration.ParseSiteConfiguration;
import ru.nlp_project.story_line2.crawler.IContentProcessor;
import ru.nlp_project.story_line2.crawler.IContentProcessor.DataSourcesEnum;
/**
* Краулер для новостей.
*
* @author fedor
*/
public class ParseSiteCrawler extends WebCrawler {
private IContentProcessor contentProcessor;
private ParseSiteConfiguration siteConfig;
private WebURL seedWebURL;
private WebURL seedWebURLCannoninicalized;
ParseSiteCrawler(ParseSiteConfiguration siteConfig, IContentProcessor contentProcessor) {
this.siteConfig = siteConfig;
this.contentProcessor = contentProcessor;
this.seedWebURL = new WebURL();
this.seedWebURL.setURL(siteConfig.seed);
this.seedWebURLCannoninicalized = new WebURL();
this.seedWebURLCannoninicalized.setURL(URLCanonicalizer.getCanonicalURL(siteConfig.seed));
}
void initialize() {
contentProcessor.initialize(siteConfig.source);
}
/**
* This method receives two parameters. The first parameter is the page in which we have
* discovered this new url and the second parameter is the new url. You should implement this
* function to specify whether the given url should be crawled or not (based on your crawling
* logic). In this example, we are instructing the crawler to ignore urls that have css, js,
* git, ... extensions and to only accept urls that start with "http://www.ics.uci.edu/". In
* this case, we didn't need the referringPage parameter to make the decision.
*/
@Override
public boolean shouldVisit(Page referringPage, WebURL url) {
// в случае если страница будет отвергнута -- она не будет проанализирована и самой
// библиотекой
return contentProcessor.shouldVisit(DataSourcesEnum.PARSE, url);
}
/**
* This function is called when a page is fetched and ready to be processed by your program.
*/
@Override
public void visit(Page page) {
WebURL webURL = page.getWebURL();
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String html = htmlParseData.getHtml();
contentProcessor.processHtml(DataSourcesEnum.PARSE, webURL, html);
}
}
@Override
protected boolean isSeedUrl(WebURL curURL) {
return seedWebURL.equals(curURL) || seedWebURLCannoninicalized.equals(curURL);
}
}
| true |
4b361f72792f40dd3dd78ffb1f36d27a6b6dafa2 | Java | zNiGhTFoXz/airlines2 | /java/src/project/view/flight/FlightUpdateView.java | UTF-8 | 2,404 | 2.75 | 3 | [] | no_license | package project.view.flight;
import core.view.View;
import project.entity.Flight;
import project.helpers.property.FlightProperty;
import java.util.Scanner;
public class FlightUpdateView extends View {
public String init(Flight flight) {
do {
System.out.println("---- UPDATE FLIGHT -----");
Scanner scanner = new Scanner(System.in); // получаем InputStream
System.out.print("[Number]: ");
String number = scanner.nextLine();
System.out.print("[Airbus]: ");
String airbus = scanner.nextLine();
System.out.print("[Time from]: ");
String timeFrom = scanner.nextLine();
System.out.print("[Time path]: ");
String timePath = scanner.nextLine();
System.out.print("[Route](UUID): ");
String route = scanner.nextLine();
System.out.printf("[Number]: %s [Airbus]: %s [Time from]: %s [Time path]: %s [Route](UUID): %s\n", number, airbus, timeFrom, timePath, route);
System.out.println("\nMenu:");
System.out.println("[1] - Confirm");
System.out.println("[2] - Decline");
System.out.println("[0] - Back");
int b = scanner.nextInt();
switch (b) {
case 1:
return "Flight/update?" +
FlightProperty.UUID + "=" + flight.getUUID() + "&" +
FlightProperty.NUMBER + "=" + number + "&" +
FlightProperty.AIRBUS + "=" + airbus + "&" +
FlightProperty.TIME_FROM + "=" + timeFrom + "&" +
FlightProperty.TIME_PATH + "=" + timePath + "&" +
FlightProperty.ROUTE + "=" + route;
case 2:
break;
case 0:
return "Flight/get?"+ FlightProperty.UUID + "=" + flight.getUUID();
}
} while (true);
}
public String error(){
System.out.println("Error");
System.out.println("Press any key!");
(new Scanner(System.in)).nextLine();
return "Flight/get";
}
public String success(){
System.out.println("Error");
System.out.println("Press any key!");
(new Scanner(System.in)).nextLine();
return "Flight/get";
}
}
| true |
e3dbd393fc3883800dcf25b4146870316cfd71bf | Java | ceballos1019/IngenieriaWeb | /EjemploSpring/test/co/edu/udea/iw/dao/impl/ClienteDAOImplTest.java | UTF-8 | 2,574 | 2.59375 | 3 | [] | no_license | /**
*
*/
package co.edu.udea.iw.dao.impl;
import static org.junit.Assert.*;
import java.sql.Date;
import java.util.Calendar;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import co.edu.udea.iw.dao.ClienteDAO;
import co.edu.udea.iw.dto.Cliente;
import co.edu.udea.iw.dto.Usuario;
import co.edu.udea.iw.exception.MyException;
/**
* @author andres.ceballoss
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@ContextConfiguration(locations = "classpath:SpringConfig.xml")
public class ClienteDAOImplTest {
@Autowired
private ClienteDAO clienteDAO;
/**
* Test method for {@link co.edu.udea.iw.dao.impl.ClienteDAOImpl#obtener()}.
*/
@Test
public void testObtener() {
List<Cliente> resultado = null;
try {
resultado = clienteDAO.obtener();
assertTrue(resultado.size() > 0);
} catch(MyException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Test method for {@link co.edu.udea.iw.dao.impl.ClienteDAOImpl#obtener(java.lang.String)}.
* Probar que para una cedula dada, trae un cliente no nulo
*/
@Test
public void testObtenerString() {
Cliente cliente = null;
String cedulaTest = "19";
try {
cliente = clienteDAO.obtener(cedulaTest);
assertNotNull(cliente);
} catch (MyException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Test method for {@link co.edu.udea.iw.dao.impl.ClienteDAOImpl#guardar(co.edu.udea.iw.dto.Cliente)}.
* Probar que no se arrojen excepciones durante la creacion de una usuario
*/
@Test
@Rollback(false)
public void testGuardar() {
Cliente cliente = null;
Usuario usuario = null;
try {
/*Crear cliente y settear los atributos*/
cliente = new Cliente();
cliente.setCedula("10");
cliente.setNombres("Andres");
cliente.setApellidos("Ceballos Sanchez");
cliente.setEmail("ceballos@gmail.com");
/*Crear el usuario, solo necesito el login*/
usuario = new Usuario();
usuario.setLogin("elver");
cliente.setUsuarioCrea(usuario);
cliente.setFechaCreacion(new Date(Calendar.getInstance().getTimeInMillis()));
/*Guardar el cliente*/
clienteDAO.guardar(cliente);
} catch(MyException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
}
| true |
82746ee5265cc22fbfb8137418829c74cf11f625 | Java | saifulislamrajon/FeetMetersConverter | /app/src/main/java/com/example/saiful/feetmetersconverter/MainActivity.java | UTF-8 | 3,278 | 2.46875 | 2 | [] | no_license | package com.example.saiful.feetmetersconverter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button btnFeet, btnMeters, btnConvert;
EditText editText;
TextView tvFeet, tvMeters;
Toolbar toolbar;
int feet,meter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnFeet = (Button) findViewById(R.id.btnFeet);
btnMeters = (Button) findViewById(R.id.btnMeters);
btnConvert = (Button) findViewById(R.id.btnConvert);
editText = (EditText) findViewById(R.id.editText);
tvFeet = (TextView) findViewById(R.id.tvFeet);
tvMeters = (TextView) findViewById(R.id.tvMeters);
btnFeet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btnFeet.setEnabled(false);
tvMeters.setText(null);
btnMeters.setEnabled(true);
}
});
btnMeters.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btnMeters.setEnabled(false);
tvFeet.setText(null);
btnFeet.setEnabled(true);
}
});
btnConvert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (btnFeet.isEnabled() && btnMeters.isEnabled()) {
Toast.makeText(getApplicationContext(), "You have to disable any one fast", Toast.LENGTH_SHORT).show();
} else if (btnFeet.isEnabled()) {
try{
feet = Integer.parseInt(editText.getText().toString());
//double meter= (int) (0.305*feet);
double meter = 0.305 * feet;
// int r=Math.round(meter);
String m = Double.toString(Math.round(meter));
tvMeters.setText(m);
}catch (Exception e){
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Feet is empty",Toast.LENGTH_SHORT).show();
}
} else if (btnMeters.isEnabled()) {
try{
meter = Integer.parseInt(editText.getText().toString());
double feet = meter / 0.305;
String f = Double.toString(Math.round(feet));
tvFeet.setText(f);
}catch (Exception e){
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Meter is empty",Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
| true |
ee5f5b0582c2af46d3fe4c1e8e01cbcb24f4bb27 | Java | ThanhGT/MathFunctions | /src/main/java/com/mycompany/methods/Methods.java | UTF-8 | 13,867 | 3.890625 | 4 | [] | 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 com.mycompany.methods;
import java.util.Scanner;
/**
*
* @author THANH
*/
public class Methods {
/**
* Shows the main menu when called
*
* @return an int corresponding to the users selection
*/
public static int mainMenu() {
int select;
Scanner input = new Scanner(System.in);
int charLength = 15;
// for loop to create a seperator for the menu
for (int i = 0; i < charLength; i++) {
System.out.print("-");
}
System.out.println("\nMENU");
// for loop to create a seperator for the menu
for (int i = 0; i < charLength; i++) {
System.out.print("-");
}
System.out.println("\nWhat Math functions are you looking to use today?");
System.out.println("1. Trigonometric Functions");
System.out.println("2. Exponent Functions");
// for loop to create a seperator for the menu
for (int i = 0; i < charLength; i++) {
System.out.print("-");
}
System.out.print("\n");
select = input.nextInt();
return select;
}
/**
* method that runs the appropriate menu
*/
public static void run() {
int select = mainMenu();
switch (select) {
case 1:
trigFunctions();
break;
case 2:
exponentFunctions();
break;
default:
System.out.println("Selection is not valid. Program will terminate");
}
}
/**
* method that runs the menu for exponent functions
*
* @return an int corresponding to the users selection
*/
public static int exponentMenu() {
int select;
Scanner input = new Scanner(System.in);
int charLength = 25;
// for loop to create a seperator for the menu
for (int i = 0; i < charLength; i++) {
System.out.print("-");
}
System.out.println("\nEXPONENT FUNCTIONS");
// for loop to create a seperator for the menu
for (int i = 0; i < charLength; i++) {
System.out.print("-");
}
System.out.println("\nWhat exponent function would you like to apply?");
System.out.println("1. Exponent");
System.out.println("2. Logarithm");
System.out.println("3. Logarithm Base 10");
System.out.println("4. Power");
System.out.println("5. Square Root");
// for loop to create a seperator for the menu
for (int i = 0; i < charLength; i++) {
System.out.print("-");
}
System.out.println("\n");
select = input.nextInt();
return select;
}
/**
* method that runs the trigonometric menu
* @return int corresponding to the users input
*/
public static int trigMenu() {
int select;
Scanner input = new Scanner(System.in);
int charLength = 15;
// for loop to create a seperator for the menu
for (int i = 0; i < charLength; i++) {
System.out.print("-");
}
System.out.println("\nTRIGONOMETRIC FUNCTIONS");
// for loop to create a seperator for the menu
for (int i = 0; i < charLength; i++) {
System.out.print("-");
}
System.out.println("\nWhat trigonometric function would you like to apply?");
System.out.println("1. Sin");
System.out.println("2. Cos");
System.out.println("3. Tan");
System.out.println("4. aSin");
System.out.println("5. aCos");
System.out.println("6. aTan");
// for loop to create a seperator for the menu
for (int i = 0; i < charLength; i++) {
System.out.print("-");
}
System.out.println("\n");
select = input.nextInt();
return select;
}
/**
* method that runs the menu of rounding options
* @param result the answer from math functions
* @return rounded number calculated from calling a different method
*/
public static double roundingMenu(double result) {
int select;
Scanner input = new Scanner(System.in);
int charLength = 15;
// for loop to create a seperator for the menu
for (int i = 0; i < charLength; i++) {
System.out.print("-");
}
System.out.println("\nROUNDING NUMBERS");
// for loop to create a seperator for the menu
for (int i = 0; i < charLength; i++) {
System.out.print("-");
}
//the actual menu...
System.out.println("\nHow would like you like your answer?");
System.out.println("1. Round Up");
System.out.println("2. Round Down");
System.out.println("3. Nearest Integer");
System.out.println("4. Integer Conversion (32-bit");
System.out.println("5. Long Conversion (64-bit)");
// for loop to create a seperator for the menu
for (int i = 0; i < charLength; i++) {
System.out.print("-");
}
System.out.println("\n");
select = input.nextInt();
double roundedNum = roundingMethods(result, select);
return roundedNum;
}
/**
* method that rounds results to the desired user outcome
* @param result the answer from previous math functions
* @param select the selection the user made in the previous menu
* @return
*/
public static double roundingMethods(double result, int select) {
double retval = result;
// switch statement
switch (select) {
case 1:
retval = Math.ceil(result); // round up to the nearest value
break;
case 2:
retval = Math.floor(result); // round down to the nearest value
break;
case 3:
retval = Math.rint(result); // round to the nearest integer
break;
case 4:
retval = (int) result; // convert result to an int
break;
case 5:
retval = (long) result; // convert result to a long
break;
default:
System.out.print("No selection exists. Please try again.");
}
return retval;
}
/**
* a method that holds switch statement
*/
public static void trigFunctions() {
// while isRunning is true keep running the switch statement
Scanner input = new Scanner(System.in);
System.out.print("Enter a value: ");
double num = input.nextInt();
boolean isRunning = true;
while (isRunning) {
// select holds the value that mainMenu returns
int select = trigMenu();
// switch statement
switch (select) {
case 1:
double sinResult = Math.sin(num); // store answer for exponent algorithm
double roundedSinResult = roundingMenu(sinResult);
System.out.printf("The sin of %f is %1.2f. ", num, roundedSinResult);
isRunning = displayChoiceMenu();
break;
case 2:
double cosResult = Math.cos(num); // store result of log x into logResult
double roundedCosResult = roundingMenu(cosResult);
System.out.printf("The cos of %f is %1.2f.", num, roundedCosResult); // print result to user
isRunning = displayChoiceMenu();
break;
case 3:
double tanResult = Math.tan(num); // stores result of log base 10 of input into a10
double roundedTanResult = roundingMenu(tanResult);
System.out.printf("The tan of %f is %1.2f ", num, roundedTanResult); // print out output to the user
isRunning = displayChoiceMenu();
break;
case 4:
double aSinResult = Math.asin(num);
double roundedASinResult = roundingMenu(aSinResult);
System.out.printf("The aSin of %f is %1.2f ", num, roundedASinResult);
break;
case 5:
double aCosResult = Math.acos(num);
double roundedACosResult = roundingMenu(aCosResult);
System.out.printf("The acos of %f is %1.2f ", num, aCosResult);
break;
case 6:
double aTanResult = Math.atan(num);
double roundedATanResult = roundingMenu(aTanResult);
System.out.printf("The atan of %f is %1.2f ", num, aTanResult);
break;
default:
System.out.print("No selection exists. Please choose a valid selection.");
}
}
}
public static void exponentFunctions() {
// while isRunning is true keep running the switch statement
Scanner input = new Scanner(System.in);
System.out.print("Enter a value: ");
double num = input.nextInt();
boolean isRunning = true;
while (isRunning) {
// select holds the value that mainMenu returns
int select = exponentMenu();
// switch statement
switch (select) {
case 1:
double expResult = Math.exp(num); // store answer for exponent algorithm
double roundedExpResult = roundingMenu(expResult);
System.out.printf("%1.0f raised to the power of e results in %1.4f. ", num, roundedExpResult);
isRunning = displayChoiceMenu();
break;
case 2:
double logResult = Math.log(num); // store result of log x into logResult
double roundedLogResult = roundingMenu(logResult);
System.out.printf("The natural logarithm of %1.0f is %1.5f.", num, roundedLogResult); // print result to user
isRunning = displayChoiceMenu();
break;
case 3:
double baseLogResult = Math.log10(num); // stores result of log base 10 of input into a10
double roundedBaseLogResult = roundingMenu(baseLogResult);
System.out.printf("The 10 base logarithm of %1.0f is %f ", num, roundedBaseLogResult); // print out output to the user
isRunning = displayChoiceMenu();
break;
case 4:
System.out.print("Enter an exponent: ");
int n = input.nextInt();
int lastDigit = lastDigit(n);
//handle suffixes
String suffix;
if (lastDigit == 1) {
suffix = "st";
} else if (lastDigit == 2) {
suffix = "nd";
} else if (lastDigit == 3) {
suffix = "rd";
} else {
suffix = "th";
}
double powResult = Math.pow(num, n);
double roundedPowResult = roundingMenu(powResult);
System.out.printf("%1.0f to the %d%s power results in %1.0f: ", num, n, suffix, roundedPowResult);
isRunning = displayChoiceMenu();
break;
default:
System.out.print("No selection exists. Please choose a valid selection.");
}
}
}
/**
* method that determines the last digit value of the exponent the user entered
* @param n the exponent value the user entered
* @return the last digit of the power
*/
public static int lastDigit(int n) {
int lastDigit = n % 10;
return lastDigit;
}
/**
* method that asks user if they would like to rerun the menu again
* @return a boolean value depending on users choice
*/
public static boolean displayChoiceMenu() {
boolean retval = false;
System.out.println("\nWould you like to go back to the menu?");
System.out.println(" Y = Yes N = No");
Scanner in = new Scanner(System.in);
String sc = in.nextLine();
sc = sc.toUpperCase(); // convert user input to upper case
if (sc.equals("Y")) {
System.out.println("What menu would you like to go back to?");
System.out.println("1. Main Menu");
System.out.println("2. Previous Menu");
int menuChoice = in.nextInt();
switch (menuChoice) {
case 1:
run();
break;
case 2:
retval = true;
break;
}
} else if (sc.equals("N")) {
retval = false;
}
return retval;
}
/**
* main method; initializes program
* @param args
*/
public static void main(String[] args) {
run();
}
}
| true |
30c13634df3da9f13157a4582f46b86c7c099aca | Java | marcoucou/com.tinder | /src/com/google/gson/internal/a/c.java | UTF-8 | 2,557 | 2.015625 | 2 | [] | no_license | package com.google.gson.internal.a;
import com.google.gson.JsonSyntaxException;
import com.google.gson.b.a;
import com.google.gson.e;
import com.google.gson.r;
import com.google.gson.s;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public final class c
extends r<Date>
{
public static final s a = new s()
{
public <T> r<T> a(e paramAnonymouse, a<T> paramAnonymousa)
{
if (paramAnonymousa.a() == Date.class) {
return new c();
}
return null;
}
};
private final DateFormat b = DateFormat.getDateTimeInstance(2, 2, Locale.US);
private final DateFormat c = DateFormat.getDateTimeInstance(2, 2);
private final DateFormat d = a();
private static DateFormat a()
{
SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
localSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return localSimpleDateFormat;
}
private Date a(String paramString)
{
try
{
Date localDate1 = c.parse(paramString);
paramString = localDate1;
}
catch (ParseException localParseException1)
{
try
{
Date localDate2 = b.parse(paramString);
paramString = localDate2;
}
catch (ParseException localParseException2)
{
try
{
Date localDate3 = d.parse(paramString);
paramString = localDate3;
}
catch (ParseException localParseException3)
{
throw new JsonSyntaxException(paramString, localParseException3);
}
}
}
finally {}
return paramString;
}
public Date a(JsonReader paramJsonReader)
throws IOException
{
if (paramJsonReader.peek() == JsonToken.NULL)
{
paramJsonReader.nextNull();
return null;
}
return a(paramJsonReader.nextString());
}
public void a(JsonWriter paramJsonWriter, Date paramDate)
throws IOException
{
if (paramDate == null) {}
for (;;)
{
try
{
paramJsonWriter.nullValue();
return;
}
finally {}
paramJsonWriter.value(b.format(paramDate));
}
}
}
/* Location:
* Qualified Name: com.google.gson.internal.a.c
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
b8f1ac8af3f952b6afbada2286bc099993bc3b93 | Java | Favio88/UnionCanina | /app/src/main/java/com/favio/unioncanina/modelos/Fotografia.java | UTF-8 | 142 | 1.53125 | 2 | [] | no_license | package com.favio.unioncanina.modelos;
public class Fotografia {
private int id;
private int id_mascota;
private String foto;
} | true |
172b22eb54f688920cbe7451937114125891a26b | Java | HaugTest/Fire_Emblem_Recreation | /src/test/java/testEquippableItems/testAccessoryCreation/testShields.java | UTF-8 | 1,551 | 2.609375 | 3 | [] | no_license | package testEquippableItems.testAccessoryCreation;
import org.junit.Test;
import java.util.ArrayList;
import static testSetUpMethods.AccessoryCreationTestMethod.createAndTestAccessory;
public class testShields {
@Test
public void testLeatherShield() {
createAndTestAccessory("Leather_Shield", "Leather Shield", "Shield",
1,1, new int[9], new int[5], new ArrayList<String>(),
"A shield made of leather. Simple but sturdy.");
}
@Test
public void testIronShield() {
createAndTestAccessory("Iron_Shield", "Iron Shield", "Shield",
2,2, new int[9], new int[5], new ArrayList<String>(),
"A wrought-iron shield. The standard for defense.");
}
@Test
public void testSteelShield() {
createAndTestAccessory("Steel_Shield", "Steel Shield", "Shield",
3,3, new int[9], new int[5], new ArrayList<String>(),
"A weighty shield offering strong protection.");
}
@Test
public void testSilverShield() {
createAndTestAccessory("Silver_Shield", "Silver Shield", "Shield",
4,4, new int[9], new int[5], new ArrayList<String>(),
"A Shield made of shining silver.");
}
@Test
public void testHexlockShield() {
createAndTestAccessory("Hexlock_Shield", "Hexlock Shield", "Shield",
2,5, new int[]{0,0,0,0,0,0,0,4,0}, new int[5], new ArrayList<String>(),
"A Shield offering strong protection and resilience.");
}
}
| true |
0ecf15ca9116a6bc8474ccccfba76a393f06bde4 | Java | vedina/RESTNet | /restnet-userdb/src/main/java/net/idea/restnet/resources/Resources.java | UTF-8 | 948 | 1.515625 | 2 | [] | no_license | package net.idea.restnet.resources;
import net.idea.restnet.c.resource.TaskResource;
public class Resources {
public static final String project = "/project";
public static final String organisation = "/organisation";
public static final String user = "/user";
public static final String authors = "/authors";
public static final String myaccount = "/myaccount";
public static final String register = "/register";
public static final String confirm = "/confirm";
public static final String notify = "/notify";
public static final String task = TaskResource.resource;
public static final String alert = "/alert";
public static final String reset = "/reset";
public static final String policy = "/policy";
public static final String protocol = "/protocol";
public final static String AMBIT_LOCAL_USER = "aa.local.admin.name";
public final static String AMBIT_LOCAL_PWD = "aa.local.admin.pass";
}
| true |
472e96b5efc3df6880e12528cfb9a191605626bd | Java | mojavelinux/seam-faces | /api/src/main/java/org/jboss/seam/faces/context/conversation/ConversationBoundary.java | UTF-8 | 812 | 1.96875 | 2 | [] | no_license | package org.jboss.seam.faces.context.conversation;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;
/**
* Parent annotation for @{@link Begin} and @{@link End}
* <p>
* <b>Note:</b> This should never be used.
* <p>
* TODO: Should we warn at startup if @{@link Begin} and @{@link End} are used
* together on the same method?
*
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*/
@InterceptorBinding
@Inherited
@Target( { METHOD, TYPE })
@Retention(RUNTIME)
@interface ConversationBoundary
{
} | true |
b0a8c08dde25cdf1beaf1a0783aa1b1661cdc099 | Java | 791837060/qipai_huainanmajiang | /qipai_admin_facade/src/main/java/com/anbang/qipai/admin/plan/dao/shopdao/ScoreProductRecordDao.java | UTF-8 | 743 | 1.796875 | 2 | [] | no_license | package com.anbang.qipai.admin.plan.dao.shopdao;
import com.anbang.qipai.admin.plan.bean.shop.ScoreProductRecord;
import com.anbang.qipai.admin.web.query.ScoreRecordQuery;
import java.util.List;
public interface ScoreProductRecordDao {
void save(ScoreProductRecord record);
ScoreProductRecord findById(String id);
void updateStatusById(String id, String status);
void updateDeliverTimeById(String id, long deliverTime);
long countByMemberIdAndStatus(String memberId, String status);
List<ScoreProductRecord> findByMemberIdAndStatus(int page, int size, String memberId, String status);
List<ScoreProductRecord> findByQuery(int page, int size, ScoreRecordQuery recordQuery);
long countByQuery(ScoreRecordQuery recordQuery);
}
| true |