blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b89f21a782cc1064e657d4fe9245d772da6677ec | 3f2cb4668322822a717db64a01fb56dac7e193c8 | /usecase/src/main/java/de/cassisi/heartcapture/usecase/port/ReportFileGenerator.java | 5f0aaa4113f4c44283c67f796343a0c41e513c43 | [] | no_license | DomenicDev/heartcapture | 1e80c30274c9ab4246058687131b7f337814636b | f62f835f308193499b8c5d6ccb96e0b358f53f33 | refs/heads/master | 2023-03-05T15:37:27.854864 | 2021-02-15T16:30:01 | 2021-02-15T16:30:01 | 294,749,044 | 0 | 1 | null | 2021-02-01T11:10:43 | 2020-09-11T16:42:38 | Java | UTF-8 | Java | false | false | 300 | java | package de.cassisi.heartcapture.usecase.port;
import de.cassisi.heartcapture.entity.ReportData;
import de.cassisi.heartcapture.usecase.exception.ReportGenerationException;
public interface ReportFileGenerator {
byte[] generateReport(ReportData reportData) throws ReportGenerationException;
}
| [
"[email protected]"
] | |
e4d69f8243e8a0e400baf7b84d70973d32b7cd78 | 8654d804cb0f1df2689c9e670c1a5c050420b01f | /FOOL/src/it/unibo/FOOL/test/plus/MethodTest5.java | 82e5ff0cbc9ecd5561691a00476981a3ff90f773 | [
"CC0-1.0"
] | permissive | binghe/informatica-public | 9877f0c4dcf09f77f8d2b68bb10e0391da7da8b0 | 40b5623bf117059501b7c562a83e3efd1c6f3ea7 | refs/heads/master | 2023-01-13T01:47:40.743166 | 2023-01-02T03:16:51 | 2023-01-02T03:16:51 | 45,143,642 | 91 | 11 | null | null | null | null | UTF-8 | Java | false | false | 2,000 | java | /**
* An bytecode compiler and interpreter for FOOL+ language in Java/ANTLR
*
* Course project for COMPILATORI E INTERPRETI (ANALISI STATICA DI PROGRAMMI)
* Copyright(R) 2017 Chun Tian, University of Bologna
*/
package it.unibo.FOOL.test.plus;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import it.unibo.FOOL.test.*;
/*
* Method Test #4: chain of methods
*/
public final class MethodTest5 extends UnitTest {
@Test
public void testMethod5() {
prog = " class C = object end; \n"
+ "let C f(C o) o; \n"
+ " int g(C o) 1; \n"
+ "in (new C).f().g(); \n";
result = 1;
trace = true;
assertEquals(run(), result);
}
}
/** @formatter:off
3. Symbol Analysis:
base ID of class C is 1
defined class: class C(standard_object):{}
defined init function: <global.C_init():class C(standard_object):{}>
base ID of <f():class C(standard_object):{}> is 0
defined variable o in <f(C):class C(standard_object):{}>
defined function: <f(C):class C(standard_object):{}>
base ID of <g():int> is 0
defined variable o in <g(C):int>
defined function: <g(C):int>
locals: []
created new generic function: f
added new method f(C) into generic function f
created new generic function: g
added new method g(C) into generic function g
done.
4. Type Analysis:
type of prog is: int
5. Emit Bytecode:
defining function f(C) [nargs: 1(0 + 1), nlocals: 0]
defining function g(C) [nargs: 1(0 + 1), nlocals: 0]
nlocals for top-level LET: 0
done.
6. Disassemble Bytecode:
Disassembly:
.global 0
0000: br 26
0005: iconst 3
0010: load 0
0015: fstore 0
0020: load 0
0025: ret
0026: br 37
0031: load 0
0036: ret
0037: br 48
0042: iconst 1
0047: ret
0048: struct 1
0053: call #0:C_init()@5
0058: call #1:f(C)@31
0063: call #2:g(C)@42
0068: halt
7. Run Bytecode:
1
*/
| [
"[email protected]"
] | |
ce6c493b923994fbf19c42b944178cc306e5df5d | 778b224eb173e3c59008aceb9c48b99a04f9d473 | /mi-mall/src/main/java/com/time/demo/entity/User.java | 33c72f84fc727ab9b36a6032b22a74d3718bfa04 | [] | no_license | JieBaBaBa/sixsixsix | dda5c4e77e6fadd961e933cb288d789bb5f2943f | 722e35f8099e6b9cc2267e8092c24dabb48dfb09 | refs/heads/master | 2022-07-14T04:21:19.459515 | 2020-02-10T09:29:36 | 2020-02-10T09:30:36 | 239,472,552 | 0 | 0 | null | 2022-06-17T02:51:56 | 2020-02-10T09:24:22 | Java | UTF-8 | Java | false | false | 665 | java | package com.time.demo.entity;
import java.io.Serializable;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@Builder
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class User extends BaseRowModel implements Serializable {
private static final long serialVersionUID = 1L;
//用户编号
private Integer userid;
//用户昵称
private String nickname;
//用户名
private String username;
//密码
private String password;
//用户性别
private String sex;
} | [
"[email protected]"
] | |
1eb03747c97ac5499f82640229e7b94558c9fe7d | 1914fc49cafdb9ec2ba00b68cbb049dbe00fc652 | /src/com/starry/dao/IDepartmentImpl.java | 9ab471df86786a85bcabe41480d97ca1c1b33f74 | [] | no_license | F-eagle/Graduate | 090057371da5c78e57dadb8c44d15670cb2b7a9a | dca068a13022d94a7621335da9e0df1a5aef08a4 | refs/heads/master | 2021-01-20T04:12:23.649473 | 2017-04-26T11:33:12 | 2017-04-26T11:33:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,279 | java | package com.starry.dao;
import java.util.List;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;
import com.starry.entity.Department;
@Repository("departmentDao")
public class IDepartmentImpl extends SqlSessionDaoSupport implements IDepartmentDao {
@Resource
public void setSuperSessionFactory(SqlSessionFactory sessionFactory){
this.setSqlSessionFactory(sessionFactory);
}
@Override
public List<Department> getAll() {
return getSqlSession().selectList("getcla");
}
@Override
public int DeleteById(String id) {
int result = this.getSqlSession().delete("delById", id);
return result;
}
@Override
public List<Department> findName(String info) {
System.out.println(this.getSqlSession().selectList("getByName", info));
return this.getSqlSession().selectList("getByName", info);
}
@Override
public List<Department> findId(String info) {
System.out.println(this.getSqlSession().selectList("getById", info));
return this.getSqlSession().selectList("getById", info);
}
@Override
public void updateDepart(Department department) {
this.getSqlSession().update("updateById",department );
}
}
| [
"[email protected]"
] | |
927c341893a2e135fbdee491090c61f2769a7cb2 | 7ec45694dac23073aca16a3a3ae43a3d9033ad06 | /src/main/java/com/vastserver/classes/vastErrorHandling/VastRestExceptionHandler.java | 24f5f21ffd9bc5114c09d287af24f7f9133a71ec | [] | no_license | yossisp/VASTAdServer | 50ee3604324f33639370e4ba6ac825baaf3a85b4 | 4869b6e8a0bf5a5311a66b3cee7e5b2d70662265 | refs/heads/master | 2022-11-20T01:12:52.899074 | 2019-08-30T10:36:55 | 2019-08-30T10:36:55 | 205,361,128 | 1 | 0 | null | 2022-11-16T08:51:43 | 2019-08-30T10:37:38 | Java | UTF-8 | Java | false | false | 1,352 | java | package com.vastserver.classes.vastErrorHandling;
import com.vastserver.classes.VastLogger;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class VastRestExceptionHandler extends ResponseEntityExceptionHandler {
private Logger log = VastLogger.getLogger(VastRestExceptionHandler.class);
@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(
MissingServletRequestParameterException exception, HttpHeaders headers,
HttpStatus status, WebRequest request) {
log.warn("from handleMissingServletRequestParameter!");
String error = exception.getParameterName() + " parameter is missing";
ApiError apiError =
new ApiError(HttpStatus.BAD_REQUEST, exception.getLocalizedMessage(), error);
return new ResponseEntity<Object>(
apiError, new HttpHeaders(), apiError.getStatus());
}
} | [
"[email protected]"
] | |
1ab2a3fdd40110487971a71ac261a85a95c6267c | 312f02581cc9298b0375ae8b218b976a9779b113 | /dev/modules/native/aws-ec2/src/main/java/com/anttoolkit/aws/ec2/tasks/routetable/DeleteRouteTableTask.java | 5c6652137e6c90c6b07d927245d4140202804727 | [
"Apache-2.0"
] | permissive | irudyak/ant-toolkit | 2453611069fd5306e5a5b06908bbaa4b6afb760b | dcf6993c2aa7525557ea45ad560d1fed23a3cdc4 | refs/heads/master | 2021-01-15T09:03:32.519188 | 2016-09-14T20:58:36 | 2016-09-14T20:58:36 | 40,494,892 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 621 | java | package com.anttoolkit.aws.ec2.tasks.routetable;
import com.amazonaws.services.ec2.model.*;
import org.apache.tools.ant.*;
import com.anttoolkit.general.common.annotations.*;
import com.anttoolkit.aws.ec2.tasks.*;
public class DeleteRouteTableTask extends GenericEc2Task
{
@Required("Route table id should be specified")
private String tableId;
public void setTableId(String id)
{
tableId = id;
}
@Override
public void doWork() throws BuildException
{
DeleteRouteTableRequest request = new DeleteRouteTableRequest();
request.setRouteTableId(tableId);
getEc2Client().deleteRouteTable(request);
}
}
| [
"[email protected]"
] | |
85ce06dfe297a34f878e9037d447c0bb17ea6643 | 2a2ce22d3bd2319d3d6171f9b16bfe75399353b9 | /springcloud-feign/src/main/java/com/ytc/controller/UserController.java | 30e395d47b37855c2f75162db3b2d4c2e4ee0a77 | [] | no_license | qty0922/springcloud_marry | 6209c41597204e1d6b4a476f18b9eeba70864fff | 4bd553f373b39e78e5489afc558a0905e51644fe | refs/heads/master | 2023-03-09T04:07:15.321229 | 2021-03-02T08:38:53 | 2021-03-02T08:38:53 | 289,672,242 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,536 | java | /**
* Copyright (C), 2015-2020, XXX有限公司
* FileName: userController
* Author: 15065
* Date: 2020/8/23 15:42
* Description:
* History:
* qty <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package com.ytc.controller;
import com.ytc.model.User;
import com.ytc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
/**
* 〈一句话功能简述〉<br>
* 〈〉
*
* @author 15065
* @create 2020/8/23
* @since 1.0.0
*/
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("hello")
public String hello(){
return "hello";
}
@GetMapping("queryUserList")
public String queryUserList(Model model){
List<User> list = userService.queryUserList();
model.addAttribute("list",list);
System.out.println(list);
return "user/show";
}
@PostMapping("register")
public void register(User user){
user.setUserId(2);
user.setUserName("admin");
user.setUserPwd("admin");
userService.register(user);
System.out.println("注册成功");
}
}
| [
"[email protected]"
] | |
62497c5928609fd6ee2ad4296d16a36bf4722f85 | 3b55f578ef0891cbfa4931276450528d77a0610d | /C83-S2-Phjx-mvn-damai/src/main/java/com/yc/damai/dao/CartDao.java | bd6ca1c25f0c279355de5aaf0784751862cd147e | [] | no_license | hujuanxiu/maven | 4ca24f6b5302b7b1184c8fd491fe21718213ad5c | ef0bc285d527b4c47b5a29f88b1955cf4bf7decd | refs/heads/master | 2022-12-09T20:47:51.982674 | 2020-08-26T11:44:59 | 2020-08-26T11:44:59 | 285,169,631 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,189 | java | package com.yc.damai.dao;
import java.util.List;
import com.yc.damai.util.DBHelper;
public class CartDao {
/**
* 添加购物车商品
* @param uid
* @param pid
* @return
*/
public int add(String uid,String pid) {
String sql="insert into dm_cart values(null,?,?,1)";
return new DBHelper().update(sql, uid,pid);
}
/**
* 给某个用户的购物车商品数量+1
* @param uid
* @param pid
* @return 新增的记录数
*/
public int update(String uid,String pid) {
String sql="update dm_cart set count=count+1 where uid=? and pid=?";
return new DBHelper().update(sql, uid,pid);
}
public List<?> queryByUid(String uid){
String sql="select * from dm_cart a join dm_product b on a.pid=b.id where a.uid=?";
return new DBHelper().query(sql, uid);
}
public List<?> queryByPid(String Pid){
String sql="select * from dm_cart where pid=?";
return new DBHelper().query(sql, Pid);
}
public int deleteByUid(String uid) {
String sql="delete from dm_cart where uid=?";
return new DBHelper().update(sql, uid);
}
public int del(String pid) {
String sql="delete from dm_cart where pid=?";
return new DBHelper().update(sql, pid);
}
}
| [
"风吹来的小仙女@DESKTOP-S7B2RQ0"
] | 风吹来的小仙女@DESKTOP-S7B2RQ0 |
47270452347443db2b485f6d3c210456d6de2ca1 | 6071044b412f7fe6aa902f765738dfc818207d2b | /discovery/src/main/java/com/ibm/watson/developer_cloud/discovery/v1/model/environment/DeleteEnvironmentResponse.java | c93a3593696d4a67bb4a87b3686da25ba3f059ac | [
"Apache-2.0"
] | permissive | eugenso/java-sdk | e07690ee5b480e51b09e3a7e5575cb1fc242d8b0 | cbb1e9cbdddda8b9fe395ada6bdc4e4181cc497e | refs/heads/master | 2021-06-11T19:26:30.867872 | 2017-02-22T19:18:50 | 2017-02-22T19:18:50 | 82,702,052 | 0 | 0 | Apache-2.0 | 2021-06-04T02:57:49 | 2017-02-21T16:28:58 | Java | UTF-8 | Java | false | false | 1,278 | java | /*
* Copyright 2016 IBM Corp. 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.
*/
package com.ibm.watson.developer_cloud.discovery.v1.model.environment;
import com.google.gson.annotations.SerializedName;
import com.ibm.watson.developer_cloud.discovery.v1.model.common.Status;
import com.ibm.watson.developer_cloud.service.model.GenericModel;
/**
* Response from a {@link DeleteEnvironmentRequest}.
*/
public class DeleteEnvironmentResponse extends GenericModel {
@SerializedName(EnvironmentManager.ID)
private String environmentId;
@SerializedName(EnvironmentManager.STATUS)
private Status status;
public String getEnvironmentId() {
return environmentId;
}
public Status getStatus() {
return status;
}
}
| [
"[email protected]"
] | |
b972fe50d142bc313317bbfb93b5a0f8e1a75570 | 8862d4b402af9e02246705da465ed8048835ecdc | /src/org/omg/PortableInterceptor/InvalidSlotHelper.java | e49e93739735009d9f29c06b24aed9ab1e8de6cc | [] | no_license | YuanAaron/JavaSourcecodeLearning | c819cedbec5c44a5d053ee4478572ac2380fdb99 | e7b57768534ba80817c9c852461ab2e39b09fb42 | refs/heads/master | 2021-07-25T08:39:28.846718 | 2021-06-03T07:32:20 | 2021-06-03T07:32:20 | 250,476,919 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,268 | java | package org.omg.PortableInterceptor;
/**
* org/omg/PortableInterceptor/InvalidSlotHelper.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from /Users/java_re/workspace/8-2-build-macosx-x86_64/jdk8u231/13620/corba/src/share/classes/org/omg/PortableInterceptor/Interceptors.idl
* Saturday, October 5, 2019 3:17:54 AM PDT
*/
abstract public class InvalidSlotHelper
{
private static String _id = "IDL:omg.org/PortableInterceptor/InvalidSlot:1.0";
public static void insert (org.omg.CORBA.Any a, org.omg.PortableInterceptor.InvalidSlot that)
{
org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();
a.type (type ());
write (out, that);
a.read_value (out.create_input_stream (), type ());
}
public static org.omg.PortableInterceptor.InvalidSlot extract (org.omg.CORBA.Any a)
{
return read (a.create_input_stream ());
}
private static org.omg.CORBA.TypeCode __typeCode = null;
private static boolean __active = false;
synchronized public static org.omg.CORBA.TypeCode type ()
{
if (__typeCode == null)
{
synchronized (org.omg.CORBA.TypeCode.class)
{
if (__typeCode == null)
{
if (__active)
{
return org.omg.CORBA.ORB.init().create_recursive_tc ( _id );
}
__active = true;
org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [0];
org.omg.CORBA.TypeCode _tcOf_members0 = null;
__typeCode = org.omg.CORBA.ORB.init ().create_exception_tc (org.omg.PortableInterceptor.InvalidSlotHelper.id (), "InvalidSlot", _members0);
__active = false;
}
}
}
return __typeCode;
}
public static String id ()
{
return _id;
}
public static org.omg.PortableInterceptor.InvalidSlot read (org.omg.CORBA.portable.InputStream istream)
{
org.omg.PortableInterceptor.InvalidSlot value = new org.omg.PortableInterceptor.InvalidSlot ();
// read and discard the repository ID
istream.read_string ();
return value;
}
public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.PortableInterceptor.InvalidSlot value)
{
// write the repository ID
ostream.write_string (id ());
}
}
| [
"[email protected]"
] | |
f415374a375930a6d6aa643138238362e60a8ee1 | f512281ec0365bde867e9c97ed65738812655cc0 | /cloud-eureka-server7001/src/main/java/com/halation/springcloud/EurekaMain7001.java | bf7fe73f05325e71940c5527e582f285bb7a0f64 | [] | no_license | java-liang/wklcloud | 94cd3272e5e3aba0a2aa04f3102fd97508183e12 | 05418e9180736de9c5cc584ebb39c2a20e389453 | refs/heads/master | 2022-07-11T09:48:19.676846 | 2020-03-18T11:47:08 | 2020-03-18T11:47:08 | 248,215,872 | 0 | 0 | null | 2022-06-21T03:01:00 | 2020-03-18T11:42:15 | Java | UTF-8 | Java | false | false | 419 | java | package com.halation.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaMain7001 {
public static void main(String[] args) {
SpringApplication.run(EurekaMain7001.class, args);
}
}
| [
"[email protected]"
] | |
9ee99d976accb18148acd15f90760cb1f4f8596e | f92fc2fbbfde756ecdfda07b361285d2b0f4b4d8 | /src/main/java/designpattern/command/audioplayer/MacroCommand.java | ba33dfebf20e9041a6218df044e5c5fea986b54b | [] | no_license | blueaken/JianTestPlayGround | 9dbfde62273f9d8593e111bdc201b61ccfcfbfd9 | 02a962d17a6e7172b96807a785b16e7987fe3f1f | refs/heads/master | 2023-08-04T09:13:19.512764 | 2023-07-15T11:17:25 | 2023-07-15T11:17:25 | 19,551,504 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 327 | java | package designpattern.command.audioplayer;
import java.util.List;
import java.util.ArrayList;
/**
* Author: blueaken
* Date: 3/3/16 10:18 PM
*/
public interface MacroCommand extends Command {
List<Command> cmdList = new ArrayList<>();
public void add(Command command);
public void remove(Command command);
}
| [
"[email protected]"
] | |
deec30d29b7d46444e40e049b0c2ad6fd3e05876 | fb85aa6db8e297fc4a0ea9586957dd55bfadc8a6 | /src/main/java/services/UserService.java | a29b605184d8d17d7325b690d7824de9fa3f3085 | [] | no_license | fontys-luxemburg/EndUserApplication | 8e2ea39b210c90b98fce7247fb3be474d98875f3 | ed6f53c7a46b9f117c921a930107274f3406d957 | refs/heads/DEV | 2022-03-12T11:00:18.578790 | 2019-06-17T07:52:22 | 2019-06-17T07:52:22 | 181,638,915 | 0 | 0 | null | 2022-02-26T11:52:57 | 2019-04-16T07:36:13 | null | UTF-8 | Java | false | false | 321 | java | package services;
import Connector.UserConnector;
import models.Credentials;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
@ApplicationScoped
public class UserService {
@Inject
UserConnector userConnector;
public String login(Credentials c) {
return userConnector.login(c);
}
}
| [
"[email protected]"
] | |
6e0fe513689f8f3d184c48c1b17f6def238dec0c | 7b91092bb7197663775772a669b4cc8e210e9735 | /modules/wss4j/test/interop/TestSTScenario3.java | bde6b4ea30f7ada66de042a96752d4557a28b433 | [
"Apache-2.0",
"LicenseRef-scancode-unknown"
] | permissive | wso2/wso2-wss4j | e9786442796d37756e62675aaacfd49972ef8053 | bbd50534d56277981bbac9d18f1154ec328cd1b7 | refs/heads/master | 2023-09-05T02:47:21.212980 | 2023-02-24T06:32:44 | 2023-02-24T06:32:44 | 16,401,283 | 35 | 59 | Apache-2.0 | 2023-04-10T12:51:16 | 2014-01-31T06:23:25 | Java | UTF-8 | Java | false | false | 1,802 | java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package interop;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.ws.axis.oasis.STScenario3;
/**
* WS-Security Test Case
* <p/>
*
* @author Davanum Srinivas ([email protected])
*/
public class TestSTScenario3 extends TestCase {
/**
* TestScenario1 constructor
* <p/>
*
* @param name name of the test
*/
public TestSTScenario3(String name) {
super(name);
}
/**
* JUnit suite
* <p/>
*
* @return a junit test suite
*/
public static Test suite() {
return new TestSuite(TestSTScenario3.class);
}
/**
* Main method
* <p/>
*
* @param args command line args
*/
public static void main(String[] args) throws Exception {
STScenario3.main(args);
}
public void testSTScenario3() throws Exception {
STScenario3.main(new String[]{"-lhttp://localhost:8080/axis/services/STPing3"});
}
}
| [
"[email protected]"
] | |
68f3708b26cc99956055c420812f8aea98cdc021 | f0992aca114b595f57fe5e74a47ed3af0e26237b | /source/tools/jboss-v7-tool/src/main/java/com/uc4/ara/feature/jbossv7/schemas/Messaging.java | 11a8e4a951da958e4bead9d78e98c642ee00bc98 | [] | no_license | Automic-Community/red-hat-jboss-v7-action-pack | 3d7b1420245d2f4b88a7332139dc6b2c301f4d9a | 90fe8ae1483a6d124528aa76b371f4d0e069ef21 | refs/heads/master | 2023-01-12T21:59:27.809924 | 2020-11-20T13:01:26 | 2020-11-20T13:01:26 | 292,008,144 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,238 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.12.04 at 03:31:00 PM ICT
//
package com.uc4.ara.feature.jbossv7.schemas;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Messaging complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Messaging">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="hornetq-server" maxOccurs="unbounded" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="clustered" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="jmx-domain" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="version" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="management-address" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="jms-queues">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="jms-queue" type="{http://www.example.org/JBossV7SnapshotSchema}JmsQueue" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="jms-topics">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="jms-topic" type="{http://www.example.org/JBossV7SnapshotSchema}JmsTopic" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" default="Messaging Subsystem" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Messaging", propOrder = {
"hornetqServer"
})
public class Messaging {
@XmlElement(name = "hornetq-server", nillable = true)
protected List<Messaging.HornetqServer> hornetqServer;
@XmlAttribute
protected String name;
/**
* Gets the value of the hornetqServer property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the hornetqServer property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getHornetqServer().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Messaging.HornetqServer }
*
*
*/
public List<Messaging.HornetqServer> getHornetqServer() {
if (hornetqServer == null) {
hornetqServer = new ArrayList<Messaging.HornetqServer>();
}
return this.hornetqServer;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
if (name == null) {
return "Messaging Subsystem";
} else {
return name;
}
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="clustered" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="jmx-domain" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="version" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="management-address" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="jms-queues">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="jms-queue" type="{http://www.example.org/JBossV7SnapshotSchema}JmsQueue" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="jms-topics">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="jms-topic" type="{http://www.example.org/JBossV7SnapshotSchema}JmsTopic" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"clustered",
"jmxDomain",
"version",
"managementAddress",
"jmsQueues",
"jmsTopics"
})
public static class HornetqServer {
@XmlElement(required = true)
protected String clustered;
@XmlElement(name = "jmx-domain", required = true)
protected String jmxDomain;
@XmlElement(required = true)
protected String version;
@XmlElement(name = "management-address", required = true)
protected String managementAddress;
@XmlElement(name = "jms-queues", required = true)
protected Messaging.HornetqServer.JmsQueues jmsQueues;
@XmlElement(name = "jms-topics", required = true)
protected Messaging.HornetqServer.JmsTopics jmsTopics;
@XmlAttribute
protected String name;
/**
* Gets the value of the clustered property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClustered() {
return clustered;
}
/**
* Sets the value of the clustered property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClustered(String value) {
this.clustered = value;
}
/**
* Gets the value of the jmxDomain property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getJmxDomain() {
return jmxDomain;
}
/**
* Sets the value of the jmxDomain property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setJmxDomain(String value) {
this.jmxDomain = value;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
return version;
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersion(String value) {
this.version = value;
}
/**
* Gets the value of the managementAddress property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getManagementAddress() {
return managementAddress;
}
/**
* Sets the value of the managementAddress property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setManagementAddress(String value) {
this.managementAddress = value;
}
/**
* Gets the value of the jmsQueues property.
*
* @return
* possible object is
* {@link Messaging.HornetqServer.JmsQueues }
*
*/
public Messaging.HornetqServer.JmsQueues getJmsQueues() {
return jmsQueues;
}
/**
* Sets the value of the jmsQueues property.
*
* @param value
* allowed object is
* {@link Messaging.HornetqServer.JmsQueues }
*
*/
public void setJmsQueues(Messaging.HornetqServer.JmsQueues value) {
this.jmsQueues = value;
}
/**
* Gets the value of the jmsTopics property.
*
* @return
* possible object is
* {@link Messaging.HornetqServer.JmsTopics }
*
*/
public Messaging.HornetqServer.JmsTopics getJmsTopics() {
return jmsTopics;
}
/**
* Sets the value of the jmsTopics property.
*
* @param value
* allowed object is
* {@link Messaging.HornetqServer.JmsTopics }
*
*/
public void setJmsTopics(Messaging.HornetqServer.JmsTopics value) {
this.jmsTopics = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="jms-queue" type="{http://www.example.org/JBossV7SnapshotSchema}JmsQueue" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"jmsQueue"
})
public static class JmsQueues {
@XmlElement(name = "jms-queue", nillable = true)
protected List<JmsQueue> jmsQueue;
/**
* Gets the value of the jmsQueue property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the jmsQueue property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getJmsQueue().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link JmsQueue }
*
*
*/
public List<JmsQueue> getJmsQueue() {
if (jmsQueue == null) {
jmsQueue = new ArrayList<JmsQueue>();
}
return this.jmsQueue;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="jms-topic" type="{http://www.example.org/JBossV7SnapshotSchema}JmsTopic" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"jmsTopic"
})
public static class JmsTopics {
@XmlElement(name = "jms-topic", nillable = true)
protected List<JmsTopic> jmsTopic;
/**
* Gets the value of the jmsTopic property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the jmsTopic property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getJmsTopic().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link JmsTopic }
*
*
*/
public List<JmsTopic> getJmsTopic() {
if (jmsTopic == null) {
jmsTopic = new ArrayList<JmsTopic>();
}
return this.jmsTopic;
}
}
}
}
| [
"[email protected]"
] | |
edc03bf34e195549d4352895dd2e317b9963926b | ae5eb1a38b4d22c82dfd67c86db73592094edc4b | /project224/src/main/java/org/gradle/test/performance/largejavamultiproject/project224/p1123/Production22466.java | 65f14ec617173cbaa460f6ca451be482b508a17a | [] | no_license | big-guy/largeJavaMultiProject | 405cc7f55301e1fd87cee5878a165ec5d4a071aa | 1cd6a3f9c59e9b13dffa35ad27d911114f253c33 | refs/heads/main | 2023-03-17T10:59:53.226128 | 2021-03-04T01:01:39 | 2021-03-04T01:01:39 | 344,307,977 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,890 | java | package org.gradle.test.performance.largejavamultiproject.project224.p1123;
public class Production22466 {
private String property0;
public String getProperty0() {
return property0;
}
public void setProperty0(String value) {
property0 = value;
}
private String property1;
public String getProperty1() {
return property1;
}
public void setProperty1(String value) {
property1 = value;
}
private String property2;
public String getProperty2() {
return property2;
}
public void setProperty2(String value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
} | [
"[email protected]"
] | |
13050047fca85223e6a53bf290c97c32271d4544 | a052af7bc2330b68bde528c3f89aad228c979568 | /mylazyloadingfragment/src/test/java/com/gmm/www/mylazyloadingfragment/ExampleUnitTest.java | 63bf074644210a7be17bbcfa9d954ddacf28f024 | [] | no_license | LittleGentleman/practice | 8bcedca89ed551d893f4f02e740c0c81444fbab4 | 8aa1ef9ec156aeb6f9691614bf8f25ce7b2df8e1 | refs/heads/master | 2022-12-19T14:05:59.733538 | 2020-09-22T09:33:28 | 2020-09-22T09:33:28 | 255,034,843 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 394 | java | package com.gmm.www.mylazyloadingfragment;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
75fb3e327c843b755cda09d4db08d14ed2866feb | 0928abafc44e426900cae3f4931f6c725f509ee2 | /SprigToShoapIntegarationExample/src/main/java/com/sk/service/ProductServiceImpl.java | 1af693432fb2d8dfb36a122a20870eacd00d6d98 | [
"MIT"
] | permissive | skch1/soap-spring-intergaration | d790eb895719c54848c85947aba9f34add784a91 | 395634b6c34af8dd4ede12d9f6c39a49acd390e4 | refs/heads/master | 2021-01-15T19:52:29.388488 | 2017-08-09T17:56:20 | 2017-08-09T17:56:20 | 99,833,356 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 487 | java | package com.sk.service;
import com.sk.dao.ProductDAO;
import com.sk.domain.Product;
public class ProductServiceImpl implements ProductService {
public void setProductDAO(ProductDAO productDAO) {
this.productDAO = productDAO;
}
private ProductDAO productDAO;
@Override
public boolean registration(Product product) {
boolean flage=false;
int count=0;
count=productDAO.resiterProduct(product);
if(count>0) {
flage=true;
}
return flage;
}
}
| [
"[email protected]"
] | |
5518226ac25d99197e8ea6a09a0f397395350403 | 721bce391fa3b2afd02a9c2b61bf4276d6714d12 | /src/main/java/org/apache/lucene/queryparser/xml/builders/LikeThisQueryBuilder.java | 391be93054da7e45dceb0a94c773de85a0ec9a61 | [] | no_license | Sudhanshu127/Lucene-QueryParser-patched | 4f4ba7c51b2ee6c1be17d14c14cd160c1e9e667e | 11efb27e5caa6d64c8bee5b46cdb398dd2b6db7f | refs/heads/master | 2022-11-04T21:32:00.743344 | 2020-06-30T12:59:18 | 2020-06-30T12:59:18 | 275,168,039 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,243 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.queryparser.xml.builders;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.queries.mlt.MoreLikeThisQuery;
import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.w3c.dom.Element;
import org.apache.lucene.queryparser.xml.DOMUtils;
import org.apache.lucene.queryparser.xml.ParserException;
import org.apache.lucene.queryparser.xml.QueryBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
/**
* Builder for {@link MoreLikeThisQuery}
*/
public class LikeThisQueryBuilder implements QueryBuilder {
private static final int DEFAULT_MAX_QUERY_TERMS = 20;
private static final int DEFAULT_MIN_TERM_FREQUENCY = 1;
private static final float DEFAULT_PERCENT_TERMS_TO_MATCH = 30; //default is a 3rd of selected terms must match
private final Analyzer analyzer;
private final String defaultFieldNames[];
public LikeThisQueryBuilder(Analyzer analyzer, String[] defaultFieldNames) {
this.analyzer = analyzer;
this.defaultFieldNames = defaultFieldNames;
}
/* (non-Javadoc)
* @see org.apache.lucene.xmlparser.QueryObjectBuilder#process(org.w3c.dom.Element)
*/
@Override
public Query getQuery(Element e) throws ParserException {
String fieldsList = e.getAttribute("fieldNames"); //a comma-delimited list of fields
String fields[] = defaultFieldNames;
if ((fieldsList != null) && (fieldsList.trim().length() > 0)) {
fields = fieldsList.trim().split(",");
//trim the fieldnames
for (int i = 0; i < fields.length; i++) {
fields[i] = fields[i].trim();
}
}
//Parse any "stopWords" attribute
//TODO MoreLikeThis needs to ideally have per-field stopWords lists - until then
//I use all analyzers/fields to generate multi-field compatible stop list
String stopWords = e.getAttribute("stopWords");
Set<String> stopWordsSet = null;
if ((stopWords != null) && (fields != null)) {
stopWordsSet = new HashSet<>();
for (String field : fields) {
try (TokenStream ts = analyzer.tokenStream(field, stopWords)) {
CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
ts.reset();
while (ts.incrementToken()) {
stopWordsSet.add(termAtt.toString());
}
ts.end();
} catch (IOException ioe) {
throw new ParserException("IoException parsing stop words list in "
+ getClass().getName() + ":" + ioe.getLocalizedMessage());
}
}
}
MoreLikeThisQuery mlt = new MoreLikeThisQuery(DOMUtils.getText(e), fields, analyzer, fields[0]);
mlt.setMaxQueryTerms(DOMUtils.getAttribute(e, "maxQueryTerms", DEFAULT_MAX_QUERY_TERMS));
mlt.setMinTermFrequency(DOMUtils.getAttribute(e, "minTermFrequency", DEFAULT_MIN_TERM_FREQUENCY));
mlt.setPercentTermsToMatch(DOMUtils.getAttribute(e, "percentTermsToMatch", DEFAULT_PERCENT_TERMS_TO_MATCH) / 100);
mlt.setStopWords(stopWordsSet);
int minDocFreq = DOMUtils.getAttribute(e, "minDocFreq", -1);
if (minDocFreq >= 0) {
mlt.setMinDocFreq(minDocFreq);
}
Query q = mlt;
float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
if (boost != 1f) {
q = new BoostQuery(mlt, boost);
}
return q;
}
}
| [
"[email protected]"
] | |
cbf279663a650c914342d96c68842048debac483 | 13fad97d2f965bcc38fcaac33c24a69a591431fe | /Session11/src/com/auribises/threads/Synchronization.java | afd9f58f0f5d08eb3427343f391497c51014346b | [] | no_license | ishantk/JavaJ2EELPU1 | 2cbd8106c438e56d38a4129d8d3dfc41879d287f | ea63c2839076d073c0968f31825086466c296a14 | refs/heads/master | 2022-12-06T21:45:02.106296 | 2020-08-27T14:00:10 | 2020-08-27T14:00:10 | 286,752,644 | 9 | 5 | null | null | null | null | UTF-8 | Java | false | false | 3,097 | java | package com.auribises.threads;
class MovieTicket{
String title;
int seatNumber;
String email;
public MovieTicket() {
}
public MovieTicket(String title, int seatNumber) {
//email = ""; // by default lets make it empty
this.title = title;
this.seatNumber = seatNumber;
}
void blockMovieTicket(String email) {
this.email = email;
System.out.println("We have Blocked Ticket for You "+email);
}
void pay() {
System.out.println("Please Pay \u20b9"+200);
System.out.println("Thank You "+email+" Your Ticket has been Booked");
}
void showConfirmedTicket() {
System.out.println("Dear, "+email);
System.out.println("Your Confirmed Ticket Details: "+title+" "+seatNumber);
}
boolean isTicketAvailable() {
//return email.isEmpty();
return email == null;
}
}
// Whenever we have a long running operations we must put in a separate thread
class MovieTicketTransaction extends Thread{
String email;
MovieTicket ticket;
MovieTicketTransaction(String email, MovieTicket ticket){
this.email = email;
this.ticket = ticket;
}
public void run() {
// if any thread is using ticket object, it will be locked for the same thread, and all other threads must wait
// till sync block has not exited, no other thread can use the same ticket object :)
synchronized (ticket) {
// isTicketAvailable is a HACK
// Could be a case for n-number of users, isTicketAvailble may return true
if(ticket.isTicketAvailable()) {
try {
System.out.println("Validating User "+email+" for his account detials in the background");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticket.blockMovieTicket(email);
ticket.pay();
ticket.showConfirmedTicket();
}else {
System.out.println("Sorry, "+email+" ticket is booked :(");
}
}
}
}
class User{
String name;
String phone;
String email;
public User() {
}
public User(String name, String phone, String email) {
this.name = name;
this.phone = phone;
this.email = email;
}
void selectAndBookMovieTicket(MovieTicket ticket) {
MovieTicketTransaction transaction = new MovieTicketTransaction(email, ticket);
transaction.start();
}
}
public class Synchronization {
public static void main(String[] args) {
MovieTicket m1 = new MovieTicket("Avengers", 1);
MovieTicket m2 = new MovieTicket("Avengers", 2);
MovieTicket m3 = new MovieTicket("Avengers", 3);
MovieTicket m4 = new MovieTicket("Avengers", 4);
MovieTicket m5 = new MovieTicket("Avengers", 5);
//System.out.println("Is Seat Number #"+m1.seatNumber+" available: "+m1.isTicketAvailable());
User user1 = new User("John", "+91 99999 88888", "[email protected]");
User user2 = new User("Fionna", "+91 99999 11111", "[email protected]");
user1.selectAndBookMovieTicket(m1);
user2.selectAndBookMovieTicket(m1);
}
}
// Challenge: In a Multi Threaded Env, when Multiple Threads access the Same Object, we must sync them
// Assignment: Write a Program demonstrating the usage of synchorized method
| [
"[email protected]"
] | |
bc359224dc9c86717bb719e11965765b306cc4e9 | 4c8fb7dde1aed013fef99bb1d3d97f6b3e14e411 | /src/test/java/com/example/amynashamy/journeytracker/ExampleUnitTest.java | 360d94cd32e970c36480d307dade88a18fa8bc8a | [] | no_license | AmyNashh/Journey-Tracker | e32559bf3314fb8b2f7dc29e2d4822bd546352ab | 67bea7b30bb020bade7b61b31b7afee436fb32f8 | refs/heads/master | 2021-01-01T05:17:24.243309 | 2016-05-25T16:20:19 | 2016-05-25T16:20:19 | 59,599,591 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 330 | java | package com.example.amynashamy.journeytracker;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
294599b37a5aad464ff84b46bb8a8bc6bc47b245 | 5b538720b923d7c4171242d8057a1622429ae1ea | /src/main/java/com/tweedy/sboot/thymeleaf/entity/CarryoverRecordsWrapper.java | de36f8d89bd18e299cbc0de27ce538fb35b724e6 | [] | no_license | mbazhe01/attendance-tracking-v2 | 6220e2dcf5dd9e8d8de81e69ea5346691a9a6c94 | 51b7c334a08856bb830c925612685225ad666839 | refs/heads/master | 2023-03-23T00:53:23.828435 | 2021-03-17T19:22:48 | 2021-03-17T19:22:48 | 348,436,255 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,315 | java | package com.tweedy.sboot.thymeleaf.entity;
import java.util.List;
import lombok.Data;
@Data
public class CarryoverRecordsWrapper {
List<CarryoverRecord> carryovers;
public void addCarryoverRecord(CarryoverRecord carryOverRecord) {
// add on top of the list
this.carryovers.add(0, carryOverRecord);
}
public CarryoverRecordsWrapper(List<CarryoverRecord> carryOvers) {
this.carryovers = carryOvers;
}
// utility function
public int getEmployeeId() {
int emplId = -1;
if (carryovers != null && carryovers.size() > 0) {
for (CarryoverRecord c : carryovers) {
emplId = c.getEmplId();
}
}
return emplId;
}
// non field constructor
public CarryoverRecordsWrapper() {
}
public int deleteCarryOver(int id) {
int removedYear = 0;
if (carryovers != null) {
int index = -1;
for (int i = 0; i < carryovers.size(); i++) {
if (carryovers.get(i).getId() == id) {
index = i;
removedYear = carryovers.get(i).getVacationYear();
break;
}
}
if (index != -1) {
carryovers.remove(index);
}
}
return removedYear;
}// eof
public boolean contains(CarryoverRecord c) {
if (carryovers.contains(c))
return true;
else
return false;
}
}
| [
"[email protected]"
] | |
fdd74be6e75c8d0214aebc018a40d3b87a941b8b | f8ff1a3bde1492d2853f2748b2de60680400cb7f | /src/main/java/kr/withanimal/board/vo/BoardVO.java | 403a712636af2f818fcd4d5f06e1f815d02df812 | [] | no_license | ymi316/WithAnimal | d7c07894a27e575dd065824436e9eb22105b33e9 | c8ae4143f4a3d449d73f98756c7ed704623f5255 | refs/heads/master | 2020-12-15T06:45:02.719512 | 2020-01-20T00:38:20 | 2020-01-20T00:38:20 | 235,024,525 | 0 | 0 | null | 2020-01-20T05:19:47 | 2020-01-20T05:19:46 | null | UTF-8 | Java | false | false | 771 | java | package kr.withanimal.board.vo;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/*
CREATE TABLE withanimal_lost(
content_idx NUMBER PRIMARY KEY NOT NULL,
u_id VARCHAR2(50) NOT NULL,
u_pw VARCHAR2(50) NOT NULL,
u_name VARCHAR2(50) NOT NULL,
content VARCHAR2(500) NULL,
content_regdate TIMESTAMP NULL
);
*/
@XmlRootElement
@AllArgsConstructor
@NoArgsConstructor
@Data
public class BoardVO {
private int content_idx;
private String u_id;
private String u_pw;
private String u_name;
private String subject;
private String content;
private Date content_regdate;
private String ip;
}
| [
"Green_Computer@DESKTOP-912HOCH"
] | Green_Computer@DESKTOP-912HOCH |
6b89bfe4c744a54a55e01d88a8b35fcd3822638f | 8f0d58b0256f270e9ef4c7305d2b65ac4a3e4852 | /src/main/java/com/CursoEducaWeb/course/entities/User.java | b89e9af4c94be88498120676ac12ac9f9127e4d7 | [] | no_license | PauloMiron/course-springboot-2-java-11 | b1ad864804ac548bb290760389c20ce68a61813f | d06ea128b9efa26bb45c62ecb16fc1b38a0caec9 | refs/heads/master | 2023-03-31T14:32:06.587497 | 2021-03-26T16:57:36 | 2021-03-26T16:57:36 | 351,093,263 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,919 | java | package com.CursoEducaWeb.course.entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "tb_user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private String phone;
private String password;
@JsonIgnore
@OneToMany(mappedBy = "client")
private List<Order> orders = new ArrayList<>();
public User(){
}
public User(Long id, String name, String email,String phone, String password) {
this.id = id;
this.name = name;
this.email = email;
this.phone = phone;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public List<Order> getOrders() {
return orders;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
| [
"[email protected]"
] | |
eefc67970eafbf9393e703f1507f394e76612080 | 5d13845c8e26e16c462af281b25aba57f7b04c36 | /poo_1/src/vista/frm_empleado.java | 0d5a54611cb19a48e330140bdd9b9514308a92e3 | [] | no_license | Oliver450F/frm_puestos | 9cd90af6d9033c875d4120676b02485402077eec | 91ac5d4cab0c4eabd11a1ee3f3e15dd8e35f4a21 | refs/heads/main | 2023-07-17T05:47:50.729387 | 2021-09-02T02:50:47 | 2021-09-02T02:50:47 | 402,268,936 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 20,254 | java | /*
* 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 vista;
import modelo.Empleado;
import javax.swing.JOptionPane;
import modelo.Conexion;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author olive
*/
public class frm_empleado extends javax.swing.JFrame {
/**
* Creates new form frm_empleado
*/
Empleado obj_Empleado;
DefaultTableModel t_empleado;
public frm_empleado() {
initComponents();
obj_Empleado = new Empleado();
tbl_Empleado.setModel(obj_Empleado.leer());
cmb_puesto.addItem("Gerente");
cmb_puesto.addItem("Jefe");
cmb_puesto.addItem("Cajero");
t_empleado = new DefaultTableModel();
String encabezado []={"id","Codigo","Nombres","Apellidos","Direccion","Telefono","Nacimiento","id_Puesto"};
t_empleado.setColumnIdentifiers(encabezado);
tbl_Empleado.setModel(t_empleado);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
txt_codigo = new javax.swing.JTextField();
txt_nombres = new javax.swing.JTextField();
txt_apellidos = new javax.swing.JTextField();
txt_direccion = new javax.swing.JTextField();
txt_telefono = new javax.swing.JTextField();
txt_fn1 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
btn_aceptar = new javax.swing.JButton();
btn_modificar = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tbl_Empleado = new javax.swing.JTable();
cmb_puesto = new javax.swing.JComboBox<>();
lbl_puesto = new javax.swing.JLabel();
btn_eliminar = new javax.swing.JButton();
lbl_id = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Codigo");
jLabel2.setText("Nombres");
jLabel3.setText("Apellidos");
jLabel4.setText("Direccion");
jLabel5.setText("Telefono");
jLabel7.setText("Fecha Nacimiento");
btn_aceptar.setText("Aceptar");
btn_aceptar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_aceptarActionPerformed(evt);
}
});
btn_modificar.setText("Modificar");
btn_modificar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_modificarActionPerformed(evt);
}
});
jButton1.setText("Conexion");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jScrollPane1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jScrollPane1MouseClicked(evt);
}
});
jScrollPane1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jScrollPane1KeyReleased(evt);
}
});
tbl_Empleado.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tbl_Empleado.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tbl_EmpleadoMouseClicked(evt);
}
});
tbl_Empleado.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
tbl_EmpleadoKeyReleased(evt);
}
});
jScrollPane1.setViewportView(tbl_Empleado);
cmb_puesto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmb_puestoActionPerformed(evt);
}
});
lbl_puesto.setText("Puesto");
btn_eliminar.setText("Eliminar");
btn_eliminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_eliminarActionPerformed(evt);
}
});
lbl_id.setText("0");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(77, 77, 77)
.addComponent(txt_fn1, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txt_nombres)
.addComponent(txt_apellidos)
.addComponent(txt_direccion, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE)
.addComponent(txt_telefono, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbl_puesto, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(cmb_puesto, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(40, 40, 40)
.addComponent(txt_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(92, 92, 92)
.addComponent(lbl_id, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jButton1)
.addGap(40, 40, 40)
.addComponent(btn_aceptar)
.addGap(37, 37, 37)
.addComponent(btn_modificar)
.addGap(18, 18, 18)
.addComponent(btn_eliminar)
.addGap(0, 0, Short.MAX_VALUE)))
.addGap(55, 55, 55))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 623, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)))
.addComponent(lbl_id, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_nombres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txt_apellidos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_direccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_telefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)))
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmb_puesto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_puesto))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_fn1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_aceptar)
.addComponent(btn_modificar)
.addComponent(jButton1)
.addComponent(btn_eliminar))
.addGap(30, 30, 30))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btn_aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_aceptarActionPerformed
// TODO add your handling code here:
obj_Empleado = new Empleado(0,txt_codigo.getText(),txt_nombres.getText(),txt_apellidos.getText(),txt_direccion.getText(),txt_telefono.getText(),txt_fn1.getText());
obj_Empleado.agregar();
tbl_Empleado.setModel(obj_Empleado.leer());
}//GEN-LAST:event_btn_aceptarActionPerformed
private void btn_modificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_modificarActionPerformed
// TODO add your handling code here:
obj_Empleado = new Empleado(Integer.valueOf(lbl_id.getText()),txt_codigo.getText(),txt_nombres.getText(),txt_apellidos.getText(),txt_direccion.getText(),txt_telefono.getText(),txt_fn1.getText());
obj_Empleado.modificar();
tbl_Empleado.setModel(obj_Empleado.leer());
/* obj_Empleado.setCodigo(txt_codigo.getText());
obj_Empleado.setNombres(txt_nombres.getText());
obj_Empleado.setApellidos(txt_apellidos.getText());
obj_Empleado.setDireccion(txt_direccion.getText());
obj_Empleado.setTelefono(txt_telefono.getText());
//obj_Empleado.setFecha_nacimiento(txt_fn1.getText());
obj_Empleado.agregar();*/
}//GEN-LAST:event_btn_modificarActionPerformed
public void select_datos(){
int fila =tbl_Empleado.getSelectedRow();
lbl_id.setText(tbl_Empleado.getValueAt(fila,0).toString());
txt_codigo.setText(tbl_Empleado.getValueAt(fila,1).toString());
txt_nombres.setText(tbl_Empleado.getValueAt(fila,2).toString());
txt_apellidos.setText(tbl_Empleado.getValueAt(fila,3).toString());
txt_direccion.setText(tbl_Empleado.getValueAt(fila,4).toString());
txt_telefono.setText(tbl_Empleado.getValueAt(fila,5).toString());
txt_fn1.setText(tbl_Empleado.getValueAt(fila,6).toString());
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
// Conexion cn=new Conexion();
//cn.abrir_conexion();
// cn.cerrar_conexion()
}//GEN-LAST:event_jButton1ActionPerformed
private void cmb_puestoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmb_puestoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cmb_puestoActionPerformed
private void jScrollPane1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jScrollPane1MouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_jScrollPane1MouseClicked
private void jScrollPane1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jScrollPane1KeyReleased
// TODO add your handling code here:
}//GEN-LAST:event_jScrollPane1KeyReleased
private void tbl_EmpleadoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_EmpleadoMouseClicked
// TODO add your handling code here:
select_datos();
}//GEN-LAST:event_tbl_EmpleadoMouseClicked
private void tbl_EmpleadoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbl_EmpleadoKeyReleased
// TODO add your handling code here:
select_datos();
}//GEN-LAST:event_tbl_EmpleadoKeyReleased
private void btn_eliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_eliminarActionPerformed
// TODO add your handling code here:
int opcion =JOptionPane.showConfirmDialog(null, "¿Desea eliminar el registro?","opcion",JOptionPane.YES_OPTION);
if(opcion==0){
obj_Empleado = new Empleado();
obj_Empleado.setId(Integer.valueOf(lbl_id.getText()));
obj_Empleado.eliminar();
tbl_Empleado.setModel(obj_Empleado.leer());
}//GEN-LAST:event_btn_eliminarActionPerformed
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(frm_empleado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(frm_empleado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(frm_empleado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(frm_empleado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new frm_empleado().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_aceptar;
private javax.swing.JButton btn_eliminar;
private javax.swing.JButton btn_modificar;
private javax.swing.JComboBox<String> cmb_puesto;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel7;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lbl_id;
private javax.swing.JLabel lbl_puesto;
private javax.swing.JTable tbl_Empleado;
private javax.swing.JTextField txt_apellidos;
private javax.swing.JTextField txt_codigo;
private javax.swing.JTextField txt_direccion;
private javax.swing.JTextField txt_fn1;
private javax.swing.JTextField txt_nombres;
private javax.swing.JTextField txt_telefono;
// End of variables declaration//GEN-END:variables
}
| [
"oliver450F"
] | oliver450F |
1016785a29d1fbd70f301106fd07e87e3881fe25 | 5582e7b84b2331a623f483b3b8f53ded9a2e7ed2 | /tucao/src/main/java/com/aibabel/tucao/utils/MyScrollview.java | f9b3aef68f2e9f8653fd7bb47088d148a53dd782 | [] | no_license | 571034884/zhuner | 451fc9b2ecae06d83ed32b20e4ddb780095b5582 | 6879d978f0c55fe33a46b46117a097131e3b1b65 | refs/heads/master | 2022-01-14T07:08:13.537239 | 2019-03-26T07:09:44 | 2019-03-26T07:09:44 | 189,947,004 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,289 | java | package com.aibabel.tucao.utils;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.widget.ScrollView;
/**
* Created by zhb on 2017/6/14.
* 嵌套recyclerview,滑动惯性问题
*/
public class MyScrollview extends ScrollView {
private int downX;
private int downY;
private int mTouchSlop;
public MyScrollview(Context context) {
super(context);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
public MyScrollview(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
public MyScrollview(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
int action = e.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downX = (int) e.getRawX();
downY = (int) e.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int moveY = (int) e.getRawY();
if (Math.abs(moveY - downY) > mTouchSlop) {
return true;
}
}
return super.onInterceptTouchEvent(e);
}
} | [
"[email protected]"
] | |
9951e3e08840d5e8d398bb726cd86f9b7fd727a8 | 4eecf8fe956a6bd4cb429cf09382cc89a914d605 | /app/src/main/java/com/lqr/wechat/utils/StringUtils.java | ecda13d60a447e800719c9e3a04d63f86f59f589 | [] | no_license | MiloMallo/HeartFollow-master | 3be6c5c0c9b63b42a27e5e52f8f751020fa15c26 | 32b4d8d9fa1e01887154b7cca4a6e904bd055967 | refs/heads/master | 2021-06-20T19:04:22.679551 | 2017-08-12T04:28:42 | 2017-08-12T04:28:42 | 91,869,054 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,722 | java | package com.lqr.wechat.utils;
import java.util.List;
/**
* @创建者 CSDN_LQR
* @描述 字符串工具类
*/
public class StringUtils {
/**
* 得到不为空的字符串
*
* @param o
* @return
*/
public static String getNotNULLStr(Object o) {
return o == null ? "" : o.toString();
}
/**
* 判断字符串或集合是否为空
*
* @param o
* @return
*/
public static boolean isEmpty(Object o) {
if (o instanceof List)
return ((List) o).size() == 0;
return o == null || o.toString().equals("");
}
/**
* 判断字符串是否为空(空格字符串也是blank)
*
* @param s
* @return
*/
public static boolean isBlank(final CharSequence s) {
if (s == null) {
return true;
}
for (int i = 0; i < s.length(); i++) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
/**
* 函数传入汉字的Unicode编码字符串,返回相应的汉字字符串
*
* @return
*/
public static String decodeUnicode(final String utfString) {
StringBuilder sb = new StringBuilder();
int i = -1;
int pos = 0;
while ((i = utfString.indexOf("\\u", pos)) != -1) {
sb.append(utfString.substring(pos, i));
if (i + 5 < utfString.length()) {
pos = i + 6;
sb.append((char) Integer.parseInt(utfString.substring(i + 2, i + 6), 16));
}
}
sb.append(utfString.substring(pos, utfString.length()));
return sb.toString();
}
}
| [
"[email protected]"
] | |
7a945ae61baeadd8a43b116e6bc3ee915718ded9 | 3771b97a96f67ec0c8967cd601f25cdd47ff80aa | /app/src/main/java/com/yitong/requestframe/download/DownloadListener.java | c95f993f41943274ef7ab83b54f317789291c2c0 | [] | no_license | hejinyi23/RequestFrame | 89e291838aece7cdb4333667c8d3fac82c663abb | adb8c993f979883380e7be9a361ba230cf0a5489 | refs/heads/master | 2020-05-22T15:11:02.789193 | 2019-03-08T12:48:43 | 2019-03-08T12:48:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 242 | java | package com.yitong.requestframe.download;
/**
* @Author Daniel Zhang
* @Time 2019/2/26 22:44
* @E-Mail [email protected]
* @Description
*/
public interface DownloadListener {
void onProgress(long total, long current);
}
| [
"[email protected]"
] | |
4fa1bbce4ec2c3bfead7815b768c01d573a398cb | c1a068aa5b52792b39a4c9000000422f9db6459f | /MainActivity.java | a7436668f68861fb40d900f0479269308d2a6629 | [] | no_license | gitrexhugh/swipe_view | ac055931db1f6e1901aa309227a997fbafdceea2 | 1a7f4e77336bc72e60076297d68fa19251116ce5 | refs/heads/master | 2020-03-29T08:42:03.438846 | 2018-09-21T07:22:53 | 2018-09-21T07:22:53 | 149,723,933 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,565 | java | package com.example.hugh.swipe_view_t01;
//reference:https://medium.com/@droidbyme/android-material-design-tabs-tab-layout-with-swipe-884085ae80ff
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
//-----
public class MainActivity extends AppCompatActivity {
private TabAdapter adapter;
private TabLayout tabLayout;
private ViewPager viewPager;
private int test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();//隱藏預設標題(繼承AppCompatActivity時可用)
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
adapter = new TabAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1Fragment(), "Tab 1");
adapter.addFragment(new Tab2Fragment(), "Tab 2");
adapter.addFragment(new Tab3Fragment(), "Tab 3");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
int[] tabIcons = {
R.drawable.backlight1_xxxhdpi,
R.drawable.backlight_camera1_xxxhdpi,
R.drawable.screenlight_camera1_xxxhdpi
};
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
}
| [
"[email protected]"
] | |
e12440963eec141369483ff03b5c45c5f8d476fa | f72cb55daa5ad2d90fb038e78075eaf6691c32af | /modules/global/src/com/company/facilitymanagement/service/AppointmentService.java | 52fc623521b3f21667c141a22ddb7c660df06cef | [] | no_license | prernarai/FacilityManagement | 20e4766be8c4683db62b898afdbf6551e79752b6 | d8cf8245cffd561c83ec11ff9781f5f3fc99e78e | refs/heads/master | 2020-09-24T02:38:48.251906 | 2019-12-06T06:53:48 | 2019-12-06T06:53:48 | 225,641,593 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 445 | java | package com.company.facilitymanagement.service;
import com.company.facilitymanagement.entity.ComplaintModel.Complaint;
import com.company.facilitymanagement.entity.ScheduleMgmt.Appointment;
import com.haulmont.cuba.core.global.DataManager;
import javax.inject.Inject;
import java.util.List;
public interface AppointmentService {
String NAME = "facilitymanagement_AppointmentService";
public List<Appointment> getAppointmentList();
} | [
"[email protected]"
] | |
f87a70c7ac7460738ab8b32dfa9d02729638df4b | ce719d08d68de247896e718e4c3ab5c7640a8a8f | /springboot/social-multiplication/src/main/java/microservices/book/socialmultiplication/domain/Multiplication.java | b4958072e5616b54b6ec65e10ee6c9755218f47e | [] | no_license | Uenderley/estudo | 0c82abee2a3b5cb4eb9fb51ff32539adda987bf4 | 1d15c39bc927b77a4b362d898c018527e6f20721 | refs/heads/master | 2023-01-12T17:08:53.559913 | 2021-03-26T04:07:18 | 2021-03-26T04:07:18 | 110,310,947 | 0 | 1 | null | 2023-01-07T11:54:32 | 2017-11-11T02:16:42 | Java | UTF-8 | Java | false | false | 741 | java | package microservices.book.socialmultiplication.domain;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* This class represents a Multiplication (a * b).
*/
@RequiredArgsConstructor
@Getter
@ToString
@EqualsAndHashCode
@Entity
public final class Multiplication {
@Id
@GeneratedValue
@Column(name = "MULTIPLICATION_ID")
private Long id;
// Both factors
private final int factorA;
private final int factorB;
// Empty constructor for JSON/JPA
Multiplication() {
this(0, 0);
}
} | [
"[email protected]"
] | |
589b122ba4c9f7b52d23d30c6b59a699d89460e1 | 22c93d9ba57be6a3d5caee390dfe5e2627273011 | /src/glslplugin/lang/elements/statements/GLSLBreakStatement.java | 16b7a6b3d495384ebdeeb4513e15095550cabd0c | [] | no_license | TheRealSpaceShip/glsl4idea | 363420b3e8b8daa013d2e06532a5b1fff42cffcf | ff9b13b5b35f8b34e1065ebcf4ec5f50288ae28a | refs/heads/master | 2016-08-12T11:02:58.579417 | 2013-05-03T11:06:06 | 2013-05-03T11:06:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,332 | java | /*
* Copyright 2010 Jean-Paul Balabanian and Yngve Devik Hammersland
*
* This file is part of glsl4idea.
*
* Glsl4idea is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* Glsl4idea 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with glsl4idea. If not, see <http://www.gnu.org/licenses/>.
*/
package glslplugin.lang.elements.statements;
import com.intellij.lang.ASTNode;
import org.jetbrains.annotations.NotNull;
/**
* GLSLDeclarationStatement is ...
*
* @author Yngve Devik Hammersland
* Date: Jan 28, 2009
* Time: 6:13:58 PM
*/
public class GLSLBreakStatement extends GLSLStatement {
public GLSLBreakStatement(@NotNull ASTNode astNode) {
super(astNode);
}
// TODO: Implement
@Override
public String toString() {
return "Break Statement";
}
} | [
"[email protected]"
] | |
4b8dbacca037af436ba69ba19f0b48deed3dd1bb | ce6a305a23a786616163f50e730473488185771e | /CompoundIT.java | 294288d115732197aaf1dbb1781f3801dfa7dd00 | [] | no_license | rakeshkamble826/javaprogram | bed72377c8c048af270e8f344bbb23d11e3b94b0 | 2d5062214b02a16ce68ab6d441e85c02194a17fb | refs/heads/master | 2022-12-10T04:22:11.500001 | 2020-08-29T09:31:04 | 2020-08-29T09:31:04 | 290,171,305 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 864 | java | import java.util.Scanner;
public class CompoundIT {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the principal:");
double principal=sc.nextDouble();
System.out.println("Enter the rate:");
double rate=sc.nextDouble();
System.out.println("Enter the time:");
double time=sc.nextDouble();
System.out.println("Enter number of times interst is compounded:");
int number=sc.nextInt();
double interest=principal*(Math.pow((1+rate/100),(time*number)))-principal;
System.out.println(" principal:"+principal);
System.out.println(" Interest Rate:"+rate);
System.out.println(" Time Duration:"+time);
System.out.println(" Number of Time interest Compouded:"+number);
System.out.println(" Compoud Interest:"+interest);
}
}
| [
"[email protected]"
] | |
53ceb09cd2ae7f702ce47ec79d294fac4f2335b3 | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/serge-rider--dbeaver/5879593f44c6a11dd22c0c56f1e2ee4f45ece200/after/DBeaverCore.java | 9eb92a4e14d73ef450819c7c07632f7baea58862 | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,328 | java | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2015 Serge Rieder ([email protected])
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (version 2)
* 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 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.jkiss.dbeaver.core;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.DBPApplication;
import org.jkiss.dbeaver.model.DBPPreferenceStore;
import org.jkiss.dbeaver.model.DBPProjectManager;
import org.jkiss.dbeaver.model.data.DBDValueHandlerRegistry;
import org.jkiss.dbeaver.model.qm.QMUtils;
import org.jkiss.dbeaver.registry.DataTypeProviderRegistry;
import org.jkiss.dbeaver.registry.PluginServiceRegistry;
import org.jkiss.dbeaver.runtime.IPluginService;
import org.jkiss.dbeaver.runtime.net.GlobalProxyAuthenticator;
import org.jkiss.dbeaver.runtime.net.GlobalProxySelector;
import org.jkiss.dbeaver.model.navigator.DBNModel;
import org.jkiss.dbeaver.model.qm.QMController;
import org.jkiss.dbeaver.registry.DataSourceProviderRegistry;
import org.jkiss.dbeaver.model.runtime.OSDescriptor;
import org.jkiss.dbeaver.registry.ProjectRegistry;
import org.jkiss.dbeaver.runtime.qm.QMControllerImpl;
import org.jkiss.dbeaver.runtime.qm.QMLogFileWriter;
import org.osgi.framework.Bundle;
import org.osgi.framework.Version;
import java.io.File;
import java.io.IOException;
import java.net.Authenticator;
import java.net.ProxySelector;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
/**
* DBeaverCore
*/
public class DBeaverCore implements DBPApplication {
static final Log log = Log.getLog(DBeaverCore.class);
private static final String LOB_DIR = ".lob"; //$NON-NLS-1$
public static final String TEMP_PROJECT_NAME = ".dbeaver-temp"; //$NON-NLS-1$
static DBeaverCore instance;
private static boolean standalone = false;
private static volatile boolean isClosing = false;
private IWorkspace workspace;
private IProject tempProject;
private OSDescriptor localSystem;
private DBNModel navigatorModel;
private QMControllerImpl queryManager;
private QMLogFileWriter qmLogWriter;
private ProjectRegistry projectRegistry;
private final List<IPluginService> activatedServices = new ArrayList<IPluginService>();
private static boolean disposed = false;
public static DBeaverCore getInstance()
{
if (instance == null) {
synchronized (DBeaverCore.class) {
if (disposed) {
throw new IllegalStateException("DBeaver core already disposed");
}
if (instance == null) {
// Initialize DBeaver Core
DBeaverCore.createInstance();
}
}
}
return instance;
}
private static DBeaverCore createInstance()
{
log.debug("Initializing " + getProductTitle());
if (Platform.getProduct() != null) {
Bundle definingBundle = Platform.getProduct().getDefiningBundle();
if (definingBundle != null) {
log.debug("Host plugin: " + definingBundle.getSymbolicName() + " " + definingBundle.getVersion());
}
}
try {
instance = new DBeaverCore();
instance.initialize();
return instance;
} catch (Throwable e) {
log.error("Error initializing DBeaverCore", e);
throw new IllegalStateException("Error initializing DBeaverCore", e);
}
}
public static String getCorePluginID()
{
return DBeaverActivator.getInstance().getBundle().getSymbolicName();
}
public static boolean isStandalone()
{
return standalone;
}
public static void setStandalone(boolean flag)
{
standalone = flag;
}
public static boolean isClosing()
{
return isClosing;
}
public static void setClosing(boolean closing)
{
isClosing = closing;
}
public static Version getVersion()
{
return DBeaverActivator.getInstance().getBundle().getVersion();
}
public static String getProductTitle()
{
return Platform.getProduct().getName() + " " + getVersion();
}
public static DBPPreferenceStore getGlobalPreferenceStore()
{
return DBeaverActivator.getInstance().getPreferences();
}
DBeaverCore()
{
}
private void initialize()
{
// Register properties adapter
this.workspace = ResourcesPlugin.getWorkspace();
this.localSystem = new OSDescriptor(Platform.getOS(), Platform.getOSArch());
QMUtils.initApplication(this);
this.queryManager = new QMControllerImpl();
this.qmLogWriter = new QMLogFileWriter();
this.queryManager.registerMetaListener(qmLogWriter);
// Init default network settings
Authenticator.setDefault(new GlobalProxyAuthenticator());
ProxySelector.setDefault(new GlobalProxySelector(ProxySelector.getDefault()));
// Init project registry
this.projectRegistry = new ProjectRegistry(workspace);
// Projects registry
initializeProjects();
// Navigator model
this.navigatorModel = new DBNModel(this);
this.navigatorModel.initialize();
// Activate plugin services
for (IPluginService pluginService : PluginServiceRegistry.getInstance().getServices()) {
try {
pluginService.activateService();
activatedServices.add(pluginService);
} catch (Throwable e) {
log.error("Error activating plugin service", e);
}
}
}
private void initializeProjects()
{
final IProgressMonitor monitor = new NullProgressMonitor();
try {
projectRegistry.loadProjects(monitor);
} catch (DBException e) {
log.error("Error loading projects", e);
}
try {
// Temp project
tempProject = workspace.getRoot().getProject(TEMP_PROJECT_NAME);
if (tempProject.exists()) {
try {
tempProject.delete(true, true, monitor);
} catch (CoreException e) {
log.error("Can't delete temp project", e);
}
}
IProjectDescription description = workspace.newProjectDescription(TEMP_PROJECT_NAME);
description.setName(TEMP_PROJECT_NAME);
description.setComment("Project for DBeaver temporary content");
try {
tempProject.create(description, IProject.HIDDEN, monitor);
} catch (CoreException e) {
log.error("Can't create temp project", e);
}
tempProject.open(monitor);
} catch (Throwable e) {
log.error("Cannot open temp project", e); //$NON-NLS-1$
}
}
public synchronized void dispose()
{
log.debug("Shutdown initiated");
long startTime = System.currentTimeMillis();
DBeaverCore.setClosing(true);
// Deactivate plugin services
for (IPluginService pluginService : activatedServices) {
try {
pluginService.deactivateService();
} catch (Exception e) {
log.error("Error deactivating plugin service", e);
}
}
activatedServices.clear();
// Dispose navigator model first
// It is a part of UI
if (this.navigatorModel != null) {
this.navigatorModel.dispose();
//this.navigatorModel = null;
}
// Dispose project registry
// It will close all open connections
if (this.projectRegistry != null) {
this.projectRegistry.dispose();
this.projectRegistry = null;
}
// Cleanup temp project
IProgressMonitor monitor = new NullProgressMonitor();
if (workspace != null) {
if (tempProject != null && tempProject.exists()) {
try {
tempProject.delete(true, true, monitor);
} catch (CoreException e) {
log.warn("Can't cleanup temp project", e);
}
}
}
if (this.qmLogWriter != null) {
this.queryManager.unregisterMetaListener(qmLogWriter);
this.qmLogWriter.dispose();
this.qmLogWriter = null;
}
if (this.queryManager != null) {
this.queryManager.dispose();
//queryManager = null;
}
DataSourceProviderRegistry.getInstance().dispose();
if (isStandalone() && workspace != null) {
try {
workspace.save(true, monitor);
} catch (CoreException ex) {
log.error("Can't save workspace", ex); //$NON-NLS-1$
}
}
DBeaverCore.instance = null;
DBeaverCore.disposed = true;
log.debug("Shutdown completed in " + (System.currentTimeMillis() - startTime) + "ms");
}
@Override
public IWorkspace getWorkspace()
{
return workspace;
}
@Override
public DBPProjectManager getProjectManager() {
return getProjectRegistry();
}
/**
* Returns configuration file
*/
public File getConfigurationFile(String fileName, boolean read)
{
File configFile = new File(DBeaverActivator.getInstance().getStateLocation().toFile(), fileName);
if (!configFile.exists() && read) {
// [Compatibility with DBeaver 1.x]
configFile = new File(Platform.getLocation().toFile(), fileName);
}
return configFile;
}
public OSDescriptor getLocalSystem()
{
return localSystem;
}
@NotNull
@Override
public DBNModel getNavigatorModel()
{
return navigatorModel;
}
public QMController getQueryManager()
{
return queryManager;
}
@Override
public DBDValueHandlerRegistry getValueHandlerRegistry() {
return DataTypeProviderRegistry.getInstance();
}
@Override
public DBPPreferenceStore getPreferenceStore() {
return getGlobalPreferenceStore();
}
public ProjectRegistry getProjectRegistry()
{
return projectRegistry;
}
public IProject getTempProject() {
return tempProject;
}
public IFolder getLobFolder(IProgressMonitor monitor)
throws IOException
{
return getTempFolder(monitor, LOB_DIR);
}
private IFolder getTempFolder(IProgressMonitor monitor, String name)
throws IOException
{
if (tempProject == null) {
throw new IOException("Temp project wasn't initialized properly");
}
IPath tempPath = tempProject.getProjectRelativePath().append(name);
IFolder tempFolder = tempProject.getFolder(tempPath);
if (!tempFolder.exists()) {
try {
tempFolder.create(true, true, monitor);
tempFolder.setHidden(true);
} catch (CoreException ex) {
throw new IOException(MessageFormat.format(CoreMessages.DBeaverCore_error_can_create_temp_dir, tempFolder.toString()), ex);
}
}
return tempFolder;
}
public List<IProject> getLiveProjects()
{
List<IProject> result = new ArrayList<IProject>();
for (IProject project : workspace.getRoot().getProjects()) {
if (project.exists() && !project.isHidden()) {
result.add(project);
}
}
return result;
}
} | [
"[email protected]"
] | |
b1aa41ec837fc3805344a0d56908b01d24d075c2 | 42d098e6001c2fed6e86f754b667c5a886d9f406 | /src/J03Encapsulation/Encapsulation22.java | bcc6cadbbb1a31fe0e5e2e58f9deb50733c5e988 | [] | no_license | Caoanhtu/JavaOOPCodeLearnIO | a0194c68c5176f5812534d1e6473bcf79dffe013 | 10d7d5e70af81fdcd48eb1c4d057898a4d0d2a4c | refs/heads/master | 2022-11-17T18:27:19.723668 | 2020-07-18T02:52:24 | 2020-07-18T02:52:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,331 | java | package J03Encapsulation;
/*
Rectangle
-length: double
-width: double
+Rectangle
+Rectangle(length: double, width: double)
+setLength(length: double): void
+getLength(): double
+setWidth(width: double): void
+getWidth(): double
+getArea(): double
+getPerimeter(): double
*/
public class Encapsulation22 {
public static void main(String[] args) {
Rectangle r = new Rectangle(4, 5);
System.out.println("Area: " + r.getArea());
System.out.println("Perimeter: " + r.getPerimeter());
r.setLength(2);
r.setWidth(3);
System.out.println("Area: " + r.getArea());
System.out.println("Perimeter: " + r.getPerimeter());
}
}
class Rectangle {
private double length;
private double width;
public Rectangle() {
}
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public void setLength(double length) {
this.length = length;
}
public double getLength() {
return length;
}
public void setWidth(double width) {
this.width = width;
}
public double getWidth() {
return width;
}
public double getArea() {
return length * width;
}
public double getPerimeter() {
return (length + width) * 2;
}
} | [
"[email protected]"
] | |
99be43afa911dd9c6b216e8bd76b54a194493957 | 1627f39bdce9c3fe5bfa34e68c276faa4568bc35 | /src/implementation/Boj10539.java | ca3ceb40ebe88d02036d8ca97d830c7b0245cfb5 | [
"Apache-2.0"
] | permissive | minuk8932/Algorithm_BaekJoon | 9ebb556f5055b89a5e5c8d885b77738f1e660e4d | a4a46b5e22e0ed0bb1b23bf1e63b78d542aa5557 | refs/heads/master | 2022-10-23T20:08:19.968211 | 2022-10-02T06:55:53 | 2022-10-02T06:55:53 | 84,549,122 | 3 | 3 | null | null | null | null | UTF-8 | Java | false | false | 854 | java | package implementation;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Boj10539 {
public static final String SPACE = " ";
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int N = Integer.parseInt(br.readLine());
int[] A = new int[N];
int chk = 0;
int[] sum = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
for(int i = 0; i < N; i++){
A[i] = Integer.parseInt(st.nextToken());
if(i >= 1){
sum[i] = ((i+1) * A[i]) - chk;
} else {
sum[i] = A[0];
}
chk += sum[i];
sb.append(sum[i]).append(SPACE);
}
System.out.println(sb.toString());
}
}
| [
"[email protected]"
] | |
d205430fe96f5287c6950a277ac756a191cdad58 | ec47ec572bc5eba858c055e2bd4a0e1aa8137619 | /ly-item/ly-item-interface/src/main/java/com/leyou/item/pojo/SpuBo.java | 0e7fe8f78aa06c9776fb17ccfcede29a166397fc | [] | no_license | lingkuraki/leyou | aeb9faa66a30c784a275322570200d89884f96b7 | 07df782f480053e408e77fb0eb20cfe4fbb211c8 | refs/heads/master | 2020-04-29T18:05:56.743616 | 2019-03-18T15:15:56 | 2019-03-18T15:15:56 | 176,291,381 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,226 | java | package com.leyou.item.pojo;
import javax.persistence.Transient;
import java.util.List;
public class SpuBo extends Spu {
// 商品分类名称
@Transient
private String cname;
// 品牌名称
@Transient
private String bname;
// 商品详情
@Transient
private SpuDetail spuDetail;
// sku列表
@Transient
private List<Sku> skus;
public SpuDetail getSpuDetail() {
return spuDetail;
}
public void setSpuDetail(SpuDetail spuDetail) {
this.spuDetail = spuDetail;
}
public List<Sku> getSkus() {
return skus;
}
public void setSkus(List<Sku> skus) {
this.skus = skus;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
@Override
public String toString() {
return "SpuBo{" +
"cname='" + cname + '\'' +
", bname='" + bname + '\'' +
", spuDetail=" + spuDetail +
", skus=" + skus +
'}';
}
}
| [
"[email protected]"
] | |
9aedc5c81d09b647c8cc762b3c9f831a17ab6887 | af7c55c0f260a0060c1acf5f60f169839f6e389d | /src/main/java/moa/streams/filters/HashingTrickFilterBinary.java | 6177dd614f27c58f06d1807dde1ea2686c628d0d | [] | no_license | marouabahri/CS-ARF | 6be73a351c104f779e50764e565b5a33e88fa0f4 | 523667cb1cd1bc8199d0ddc70976e0d98941f5ba | refs/heads/master | 2021-04-17T16:12:25.463026 | 2020-03-24T15:59:40 | 2020-03-24T15:59:40 | 249,458,280 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,747 | java |
package moa.streams.filters;
import com.github.javacliparser.IntOption;
import com.google.common.hash.Hashing;
import com.yahoo.labs.samoa.instances.Attribute;
import com.yahoo.labs.samoa.instances.DenseInstance;
import com.yahoo.labs.samoa.instances.Instance;
import com.yahoo.labs.samoa.instances.Instances;
import com.yahoo.labs.samoa.instances.InstancesHeader;
import java.util.Arrays;
import moa.core.FastVector;
import moa.core.InstanceExample;
import moa.streams.InstanceStream;
/**
* Filter to perform feature hashing, to reduce the number of attributes. It applies
* a hash function to the features and using their hash values as indices directly,
* rather than looking the indices up in an associative array.
*
* @author Maroua Bahri
*/
public class HashingTrickFilterBinary extends AbstractStreamFilter {
private static final long serialVersionUID = 1L;
public IntOption dim = new IntOption("FeatureDimension", 'd',
"the target feature dimension.", 10);
protected InstancesHeader streamHeader;
protected FastVector attributes;
@Override
protected void restartImpl() {
this.streamHeader = null;
}
@Override
public InstancesHeader getHeader() {
return this.streamHeader;
}
@Override
public InstanceExample nextInstance() {
Instance sparseInstance = (Instance) this.inputStream.nextInstance().getData();
if (streamHeader == null) {
//Create a new header
this.attributes = new FastVector();
String [] attribut = new String []{"0","1"} ;
for (int i = 0; i < this.dim.getValue(); i++) {
attributes.addElement(new Attribute("nominal" + (i + 1),
Arrays.asList(attribut)));
}
this.attributes.addElement(sparseInstance.classAttribute());
this.streamHeader = new InstancesHeader(new Instances(
getCLICreationString(InstanceStream.class), this.attributes, 0));
this.streamHeader.setClassIndex(this.streamHeader.numAttributes() - 1);
}
int [] hashVal = hashVector(sparseInstance,this.dim.getValue(), Hashing.murmur3_128());
return new InstanceExample(transformedInstance(sparseInstance, Arrays.stream(hashVal).asDoubleStream().toArray()));
}
public DenseInstance transformedInstance(Instance sparseInst, double [] hashVal) {
Instances header = this.streamHeader;
double[] attributeValues = new double[header.numAttributes()];
for(int i = 0 ; i < header.numAttributes()-1 ; i++) {
attributeValues[i] = hashVal[i];
}
attributeValues[attributeValues.length-1] = sparseInst.classValue();
DenseInstance newInstance = new DenseInstance(1.0, attributeValues);
newInstance.setDataset(header);
header.add(newInstance);
return newInstance;
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
public int[] hashVector(Instance instance, int n,
com.google.common.hash.HashFunction hashFunction) {
int [] denseValues = new int [n];
for (int i = 0 ; i < n ; i++) {
denseValues[i] = 0;
}
for (int i = 0; i < instance.numAttributes()-1 ; i++){
double diff = Math.abs(instance.value(i));
if( diff > Double.MIN_NORMAL) {
int hash = hashFunction.hashInt(i).asInt();
int bucket = Math.abs(hash) % n;
denseValues[bucket] = (1);
}
}
return denseValues;
}
} | [
"[email protected]"
] | |
636ee7c4469dd894f8725bedfe0a9e43b625082a | 0e02f3767acc23b9e5ab742e152688af4c42dd9e | /ArrayLists/BasicArraylists3.java | 1c9dd6e843ca14125231a26d06113274862eb924 | [] | no_license | parkkeonhee/ProgrammingByDoing-Solutions | e08acc6068153b7eb31d99cca1d418926f4da1b7 | c0c1bbc43b5c053705241dee7fe2717d2bc5f0e4 | refs/heads/master | 2020-08-12T19:32:27.830909 | 2017-01-01T04:37:24 | 2017-01-01T04:37:24 | 73,526,532 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 741 | java |
/*
* Author: Keon Hee Park
* Assignment: http://programmingbydoing.com/a/basic-arraylists-3.html
* Completed: December 30, 2016
*/
import java.util.ArrayList;
import java.util.Random;
public class BasicArraylists3 {
public static void main(String[] args) {
Random generator = new Random();
ArrayList<Integer> list = new ArrayList<Integer>();
int max = 1000;
for (int i = 0; i < max; i++) {
list.add(generator.nextInt(90) + 10);
if (i % 20 == 0 && i != 0) {
System.out.println();
}
if (i == 0) {
System.out.print("[" + list.get(i) + ", ");
} else if (i != 0 && i != max - 1) {
System.out.print(list.get(i) + ", ");
} else if (i == max - 1) {
System.out.print(list.get(i) + "]");
}
}
}
} | [
"[email protected]"
] | |
7717824c27c0854543b6fcc7398bd6c8da0a8e2b | 1227175c8cab4215e116cfcffe006e322e3fee61 | /src/main/java/com/example/Authentication/RatingConsumerConfig.java | bd7e4ac9f29965f2e3852a720b661bb5ad478d84 | [] | no_license | ritikshuklacse/Authentication-MicroService | ff304f652a035490490a86412d7ee649d86c77c7 | 3ca3b358d30ea4126fdc67593645274e49ea77be | refs/heads/main | 2023-02-19T08:22:31.684100 | 2021-01-20T13:58:58 | 2021-01-20T13:58:58 | 331,327,373 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,638 | java | package com.example.Authentication;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import java.util.HashMap;
import java.util.Map;
@EnableKafka
@Configuration
public class RatingConsumerConfig {
@Bean
public ConsumerFactory<String, String> consumerFactory() {
Map<String, Object> props = new HashMap<>();
props.put(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
"http://10.177.1.254:9092");
props.put(
ConsumerConfig.GROUP_ID_CONFIG,
"abc");
props.put(
ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
StringDeserializer.class);
props.put(
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
StringDeserializer.class);
return new DefaultKafkaConsumerFactory<>(props);
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, String>
kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory =
new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
return factory;
}
}
| [
"[email protected]"
] | |
8054ac2cee5161f6f026ad8610fcde2885a8cefa | a1014298e6976103434a6124d7b2ff219d7f5d18 | /RISCV_final_project/mars/venus/FileDumpMemoryAction.java | 3a4a339c6698256265c71dffac4da858b259841c | [
"MIT"
] | permissive | MAYAPERETZ/Project | bd593a136361bb1ede21a9b92b9d0399a813c601 | 3be9e361582576801646d58806ff679d45a62c1d | refs/heads/master | 2020-06-25T01:37:29.970604 | 2019-11-19T18:57:55 | 2019-11-19T18:57:55 | 199,156,101 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,308 | java | package mars.venus;
import mars.*;
import mars.util.GenMath;
import mars.util.*;
import mars.riscv.dump.*;
import mars.riscv.hardware.*;
import mars.riscv.hardware.memory.Memory;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;
import java.util.*;
import javax.swing.plaf.basic.*;
/*
Copyright (c) 2003-2008, Pete Sanderson and Kenneth Vollmar
Developed by Pete Sanderson ([email protected])
and Kenneth Vollmar ([email protected])
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject
to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(MIT license, http://www.opensource.org/licenses/mit-license.html)
*/
/**
* Action for the File -> Save For Dump Memory menu item
*/
public class FileDumpMemoryAction extends GuiAction {
private JDialog dumpDialog;
private static final String title = "Dump Memory To File";
private Number[] segmentListBaseArray;
private Number[] segmentListHighArray;
private JComboBox segmentListSelector;
private JComboBox formatListSelector;
public FileDumpMemoryAction(String name, Icon icon, String descrip,
Integer mnemonic, KeyStroke accel, GUI mainUI) {
super(name, icon, descrip, mnemonic, accel, mainUI);
}
public void actionPerformed(ActionEvent e){
dumpMemory();
}
/* Save the memory segment in a supported format.*/
private void dumpMemory() {
dumpDialog = createDumpDialog();
dumpDialog.pack();
dumpDialog.setLocationRelativeTo(Globals.getGui());
dumpDialog.setVisible(true);
}
// The dump dialog that appears when menu item is selected.
private JDialog createDumpDialog() {
JDialog dumpDialog = new JDialog(Globals.getGui(), title, true);
dumpDialog.setContentPane(buildDialogPanel());
dumpDialog.setDefaultCloseOperation(
JDialog.DO_NOTHING_ON_CLOSE);
dumpDialog.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent we) {
closeDialog();
}
});
return dumpDialog;
}
// Set contents of dump dialog.
private JPanel buildDialogPanel() {
JPanel contents = new JPanel(new BorderLayout(20,20));
contents.setBorder(new EmptyBorder(10,10,10,10));
// A series of parallel arrays representing the memory segments that can be dumped.
String[] segmentArray = MemoryDump.getSegmentNames();
Number[] baseAddressArray = MemoryDump.getBaseAddresses();
Number[] limitAddressArray = MemoryDump.getLimitAddresses(segmentArray);
Number[] highAddressArray = new Number[segmentArray.length];
// These three are allocated and filled by buildDialogPanel() and used by action listeners.
String[] segmentListArray = new String[segmentArray.length];
segmentListBaseArray = new Number[segmentArray.length];
segmentListHighArray = new Number[segmentArray.length];
// Calculate the actual highest address to be dumped. For text segment, this depends on the
// program length (number of machine code instructions). For data segment, this depends on
// how many MARS 4K word blocks have been referenced during assembly and/or execution.
// Then generate label from concatentation of segmentArray[i], baseAddressArray[i]
// and highAddressArray[i]. This lets user know exactly what range will be dumped. Initially not
// editable but maybe add this later.
// If there is nothing to dump (e.g. address of first null == base address), then
// the segment will not be listed.
int segmentCount = 0;
for (int i = 0; i< segmentArray.length; i++) {
try {
highAddressArray[i] = GenMath.sub(Globals.memory.getAddressOfFirstNull(
baseAddressArray[i], limitAddressArray[i]), Memory.WORD_LENGTH_BYTES);
} // Exception will not happen since the Memory base and limit addresses are on word boundaries!
catch (AddressErrorException aee) {
highAddressArray[i] = GenMath.sub(baseAddressArray[i], Memory.WORD_LENGTH_BYTES);
}
if (!Math2.isLt(highAddressArray[i], baseAddressArray[i])) {
segmentListBaseArray[segmentCount] = baseAddressArray[i];
segmentListHighArray[segmentCount] = highAddressArray[i];
segmentListArray[segmentCount] =
segmentArray[i] + " (" + Binary.currentNumToHexString(baseAddressArray[i]) +
" - " + Binary.currentNumToHexString(highAddressArray[i]) + ")";
segmentCount++;
}
}
// It is highly unlikely that no segments remain after the null check, since
// there will always be at least one instruction (.text segment has one non-null).
// But just in case...
if (segmentCount == 0) {
contents.add(new Label("There is nothing to dump!"), BorderLayout.NORTH);
JButton OKButton = new JButton("OK");
OKButton.addActionListener(e -> closeDialog());
contents.add(OKButton, BorderLayout.SOUTH);
return contents;
}
// This is needed to assure no null array elements in ComboBox list.
if (segmentCount < segmentListArray.length) {
String[] tempArray = new String[segmentCount];
System.arraycopy(segmentListArray, 0, tempArray, 0, segmentCount);
segmentListArray = tempArray;
}
// Create segment selector. First element selected by default.
segmentListSelector = new JComboBox(segmentListArray);
segmentListSelector.setSelectedIndex(0);
JPanel segmentPanel = new JPanel(new BorderLayout());
segmentPanel.add(new Label("Memory Segment"), BorderLayout.NORTH);
segmentPanel.add(segmentListSelector);
contents.add(segmentPanel, BorderLayout.WEST);
// Next, create list of all available dump formats.
ArrayList dumpFormats = (new DumpFormatLoader()).loadDumpFormats();
formatListSelector = new JComboBox(dumpFormats.toArray());
formatListSelector.setRenderer(new DumpFormatComboBoxRenderer(formatListSelector));
formatListSelector.setSelectedIndex(0);
JPanel formatPanel = new JPanel(new BorderLayout());
formatPanel.add(new Label("Dump Format"), BorderLayout.NORTH);
formatPanel.add(formatListSelector);
contents.add(formatPanel, BorderLayout.EAST);
// Bottom row - the control buttons for Dump and Cancel
Box controlPanel = Box.createHorizontalBox();
JButton dumpButton = new JButton("Dump To File...");
dumpButton.addActionListener(
e -> {
if (performDump(segmentListBaseArray[segmentListSelector.getSelectedIndex()],
segmentListHighArray[segmentListSelector.getSelectedIndex()],
(DumpFormat)formatListSelector.getSelectedItem())) {
closeDialog();
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(
e -> closeDialog());
controlPanel.add(Box.createHorizontalGlue());
controlPanel.add(dumpButton);
controlPanel.add(Box.createHorizontalGlue());
controlPanel.add(cancelButton);
controlPanel.add(Box.createHorizontalGlue());
contents.add(controlPanel,BorderLayout.SOUTH);
return contents;
}
// User has clicked "Dump" button, so launch a file chooser then get
// segment (memory range) and format selections and save to the file.
private boolean performDump(Number firstAddress, Number lastAddress, DumpFormat format) {
File theFile;
JFileChooser saveDialog;
boolean operationOK = false;
saveDialog = new JFileChooser(mainUI.getEditor().getCurrentSaveDirectory());
saveDialog.setDialogTitle(title);
while (!operationOK) {
int decision = saveDialog.showSaveDialog(mainUI);
if (decision != JFileChooser.APPROVE_OPTION)
return false;
theFile = saveDialog.getSelectedFile();
operationOK = true;
if (theFile.exists()) {
int overwrite = JOptionPane.showConfirmDialog(mainUI,
"File "+theFile.getName()+" already exists. Do you wish to overwrite it?",
"Overwrite existing file?",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
switch (overwrite) {
case JOptionPane.YES_OPTION :
operationOK = true;
break;
case JOptionPane.NO_OPTION :
operationOK = false;
break;
case JOptionPane.CANCEL_OPTION :
return false;
default : // should never occur
return false;
}
}
if (operationOK) {
try {
format.dumpMemoryRange(theFile, firstAddress, lastAddress);
}
catch (AddressErrorException | IOException ignored) { }
}
}
return true;
}
// We're finished with this modal dialog.
private void closeDialog() {
dumpDialog.setVisible(false);
dumpDialog.dispose();
}
// Display tool tip for dump format list items. Got the technique from
// http://forum.java.sun.com/thread.jspa?threadID=488762&messageID=2292482
private class DumpFormatComboBoxRenderer extends BasicComboBoxRenderer {
private JComboBox myMaster;
public DumpFormatComboBoxRenderer(JComboBox myMaster) {
super();
this.myMaster = myMaster;
}
public Component getListCellRendererComponent( JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
setToolTipText(value.toString());
if (index >=0 && ((DumpFormat)(myMaster.getItemAt(index))).getDescription() != null) {
setToolTipText(((DumpFormat)(myMaster.getItemAt(index))).getDescription());
}
return this;
}
}
} | [
"[email protected]"
] | |
e183bedbd5b02a76a014ced2324355dd4c233bba | 4ae57006210072f8532200f776947af768e2f713 | /app/src/main/java/com/example/kev/revanotes/SubmitNotes.java | 47998aebcc8dd9c3326a2a3369b4ab93439168ac | [] | no_license | KevinGThomas/RevaNotes | 530ede25f446a097ad0a36553c938b1d0d888a6d | 6a645eb7e7383023d185ef647887805be42136e8 | refs/heads/master | 2021-06-17T19:40:58.673553 | 2019-10-18T04:58:21 | 2019-10-18T04:58:21 | 149,141,472 | 1 | 1 | null | 2018-09-19T12:13:37 | 2018-09-17T14:51:13 | Java | UTF-8 | Java | false | false | 5,207 | java | package com.example.kev.revanotes;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
public class SubmitNotes extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_submit_notes);
Toolbar toolbar = (Toolbar) findViewById(R.id.submitToolbarTab);
final EditText et = (EditText) findViewById(R.id.etSubmit);
final EditText et1 = (EditText) findViewById(R.id.et1Submit);
final EditText et2 = (EditText) findViewById(R.id.et2Submit);
Button bt= (Button) findViewById(R.id.btSubmit);
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
RelativeLayout relativeLayout = findViewById(R.id.relativeDisplayTab);
ScrollView scrollView = findViewById(R.id.scrollSubmit);
if (Selection.branch.equals(getString(R.string.CS))) {
//relativeLayout.setBackgroundResource(R.drawable.background_cs);
scrollView.setBackgroundResource(R.drawable.background_cs);
int dark = ColorUtil.darken(this.getResources().getColor(R.color.CS), 12);
bt.setBackgroundColor(this.getResources().getColor(R.color.CS));
window.setStatusBarColor(dark);
} else if (Selection.branch.equals(getString(R.string.Mech))) {
//relativeLayout.setBackgroundResource(R.drawable.background_mech);
scrollView.setBackgroundResource(R.drawable.background_mech);
bt.setBackgroundColor(this.getResources().getColor(R.color.Mech));
int dark = ColorUtil.darken(this.getResources().getColor(R.color.Mech), 12);
window.setStatusBarColor(dark);
} else if (Selection.branch.equals(getString(R.string.EE))) {
//relativeLayout.setBackgroundResource(R.drawable.background_ee);
scrollView.setBackgroundResource(R.drawable.background_ee);
bt.setBackgroundColor(this.getResources().getColor(R.color.EE));
int dark = ColorUtil.darken(this.getResources().getColor(R.color.EE), 12);
window.setStatusBarColor(dark);
} else if (Selection.branch.equals(getString(R.string.EC))) {
//relativeLayout.setBackgroundResource(R.drawable.background_ec);
scrollView.setBackgroundResource(R.drawable.background_ec);
bt.setBackgroundColor(this.getResources().getColor(R.color.EC));
int dark = ColorUtil.darken(this.getResources().getColor(R.color.EC), 12);
window.setStatusBarColor(dark);
} else if (Selection.branch.equals(getString(R.string.Civil))) {
//relativeLayout.setBackgroundResource(R.drawable.background_civil);
scrollView.setBackgroundResource(R.drawable.background_civil);
bt.setBackgroundColor(this.getResources().getColor(R.color.Civil));
int dark = ColorUtil.darken(this.getResources().getColor(R.color.Civil), 12);
window.setStatusBarColor(dark);
}
toolbar.setTitle("");
//toolbar.setTitle(Selection.subject);
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// back button pressed
finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
});
et.setText("Branch: "+Selection.branch+"\nSemester: "+Selection.semester+"\nSubject: "+Selection.subject);
et.setBackgroundResource(R.drawable.edittextline);
et1.setBackgroundResource(R.drawable.edittextline);
et2.setBackgroundResource(R.drawable.edittextline);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String message="NOTES FOR VALIDATION:\n"+et.getText().toString()+"\n"+et1.getText().toString()+"\n"+et2.getText().toString()
+"\n"+"Please find the Notes attached below.";
String text="https://wa.me/918088542610?text="+message;
Uri uri = Uri.parse(text)
.buildUpon()
.appendQueryParameter("key", "val")
.build();
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setPackage("com.whatsapp");
startActivity(intent);
}
});
}
@Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
}
| [
"[email protected]"
] | |
2be4ebe2339913fee8c892f8067e639d452e4b50 | da0e99192662fecbb951a032e4b9a7a9c39348d7 | /asaimagelibrary/src/main/java/technited/minds/asaimagelibrary/MediaLoader.java | 577b001c3b0813d8dfe5f0e6c6a540fa736a7ae2 | [] | no_license | sahuadarsh0/BigBannerIndiaApp | 7aff246f9b0aeed61c9230bb4fc1d0c9b39a076c | 75909403bd1e382334426a3b5e09fb4e66814bd9 | refs/heads/master | 2023-06-08T01:21:29.631721 | 2021-06-27T01:30:59 | 2021-06-27T01:30:59 | 249,540,379 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 317 | java | package technited.minds.asaimagelibrary;
import android.content.Context;
import android.widget.ImageView;
public interface MediaLoader {
boolean isImage();
void loadMedia(Context context, ImageView imageView, SuccessCallback callback);
interface SuccessCallback {
void onSuccess();
}
} | [
"[email protected]"
] | |
f162baba7549b8cd9b140bf0aaf4302784dc619b | 54a7300afab27530225d1b0d97edc3b98559a191 | /src/oliver/neuron/distortedletters/DistortedLettersChoice.java | 1638525f3f730f75d720a3a81f8ac87520db1279 | [] | no_license | olivermcccarthy/neuralnetworks | cc99f3c1e58cf4f672d78dbb48b3c663f603be6f | fd500bf6c951c36a7365c8b162e415d852fc0b16 | refs/heads/master | 2020-04-17T08:22:42.450088 | 2019-03-29T13:48:34 | 2019-03-29T13:48:34 | 166,409,710 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,213 | java | package oliver.neuron.distortedletters;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import oliver.neuron.Cost;
import oliver.neuron.ui.DrawNeuralNetwork;
/**
* Display a Distorted(Distorted) Letter and ask user to select which Letter it is
*/
public class DistortedLettersChoice extends JPanel {
/**
*
*/
private static final long serialVersionUID = -985471666659201980L;
/**
* Choice of letters
*/
static String[] LETTERS = new String[] { "E", "F", "H" };
/**
* Wait for user to choose
*/
Object waitForMe = "";
/**
* Group of buttons ( User Choose the letter)
*/
ButtonGroup group = new ButtonGroup();
/**
* Panel displaying the distorted Letter
*/
DistortedLetters innerPanel = new DistortedLetters();
//JTextPane resultPane = new JTextPane();
/**
* Which Letter did the user choose
*/
int selectedCoice = -1;
/**
* Preferred width of this panel
*/
static int preferedWidth = 200;
public DistortedLettersChoice() {
this.setLayout(null);
this.add(innerPanel);
this.setPreferredSize(new Dimension(preferedWidth, 280));
this.setLayout(null);
int w = 0;
int id = 0;
for (String letter : LETTERS) {
JButton but = new JButton(letter);
final int oID = id;
but.setBounds(w, 230, 50, 30);
this.add(but);
group.add(but);
but.addActionListener(new ActionListener() {
int ourID = oID;
@Override
public void actionPerformed(ActionEvent e) {
synchronized (waitForMe) {
waitForMe.notifyAll();
selectedCoice = ourID;
}
}
});
id++;
w += 50;
}
innerPanel.setBounds(0, 0, preferedWidth, 200);
}
/**
* User agrees we set expected[neuronChoce] to 1 and all others to 0 User
* changes choice we set expected[userChoice] to 1 and all others to 0 User does
* nothing we set expected to in for all values and nothing is learned
*
* @param overallPanel
* @param in
* @return
*/
public double[] like(Cost theCost,DistortedLetterTrial trial, DrawNeuralNetwork overallPanel, double[] in) {
//resultPane.setBackground(this.getBackground());
double[] expected = new double[in.length];
int neuronChoice = -1;
double max = 0;
for (int x = 0; x < in.length; x++) {
if (in[x] > max) {
max = in[x];
neuronChoice = x;
}
}
String gotLetter = LETTERS[neuronChoice];
//this.resultPane.setText(text);
//this.resultPane.setFont(this.resultPane.getFont().deriveFont(18.0f));
selectedCoice = -1;
synchronized (waitForMe) {
try {
waitForMe.wait(overallPanel.controlPanel.getSleepTime());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (selectedCoice != -1) {
if(selectedCoice == -2) {
this.selectedCoice= neuronChoice;
}
if (this.selectedCoice != neuronChoice) {
theCost.incNumWrong();
}
neuronChoice = this.selectedCoice;
for (int x = 0; x < in.length; x++) {
expected[x] = 0;
if (x == neuronChoice) {
expected[x] = 1;
}
}
} else {
// No choice nothing to learn
for (int x = 0; x < in.length; x++) {
expected[x] = in[x];
}
}
String expectedLetter = LETTERS[neuronChoice];
overallPanel.waitForUserClick(trial, String.format("%s, %s", expectedLetter,gotLetter),false,true);
return expected;
}
protected void newLetter() {
this.innerPanel.newLetter();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
public static void main(String[] args) {
JFrame frame = new JFrame("test");
frame.setSize(200, 200);
DistortedLettersChoice panel = new DistortedLettersChoice();
frame.add(panel);
frame.setVisible(true);
}
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
Enumeration<AbstractButton> enumk =group.getElements();
while (enumk.hasMoreElements()) {
enumk.nextElement().setEnabled(enabled);
}
}
}
| [
"[email protected]"
] | |
a54b693dc26a23e1c6666aefae7986c5be650343 | ab37af792507e7fb65b1d482293ae9086f83a56e | /src/com/crypto/classes/Listener.java | 57e801bb6542880f30f7cf1e1c3a6c72f7d4672a | [] | no_license | seyitaliyaman/observer-pattern-encryption-algorithms | b0ecd11d556b16d06109c05ae2f210d0d6142fa1 | 7345c74456e0451abd5d4241a2b76349c42a7075 | refs/heads/master | 2023-02-02T15:29:31.979908 | 2020-12-25T15:09:20 | 2020-12-25T15:09:20 | 324,383,757 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 96 | java | package com.crypto.classes;
public interface Listener {
void update(String s, byte key);
}
| [
"[email protected]"
] | |
f24daaa0674057d4be02b6e31d14e5a492e128c5 | a69922d3f552ac5a22e5a92bfcb8a6a27a97b8a4 | /src/test/java/com/renz/amaysim/cart/service/UserShoppingCartTest.java | 7a47d5952a3fb481c3fb07b3ce6d3bf3e7860bb5 | [] | no_license | renzrollon/shopping-cart | 63ffbcfc67207ece8073c1f407694af461f7c691 | 9a864081b48b62e4f822d272c1058622c3c56e74 | refs/heads/master | 2021-07-12T19:23:26.867997 | 2021-03-07T05:40:22 | 2021-03-07T05:40:22 | 73,008,175 | 0 | 0 | null | 2021-03-07T05:40:39 | 2016-11-06T17:49:27 | Java | UTF-8 | Java | false | false | 3,880 | java | package com.renz.amaysim.cart.service;
import com.renz.amaysim.cart.decorator.*;
import com.renz.amaysim.cart.domain.Product;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertEquals;
/**
* Created by renz on 11/6/16.
*/
@RunWith(BlockJUnit4ClassRunner.class)
public class UserShoppingCartTest {
private UserShoppingCart shoppingCart;
private final String USER_ID = "helloWorldUser";
@Before
public void setup() {
shoppingCart = new UserShoppingCart(USER_ID);
Set<ShoppingCartDecorator> decoratorList = new HashSet<>();
decoratorList.add(UnliSmall3For2DealDecorator.getInstance());
decoratorList.add(UnliLargeBulkDiscountDecorator.getInstance());
decoratorList.add(Free1GBDataDecorator.getInstance());
decoratorList.add(PromoCode10PercentDiscountDecorator.getInstance());
shoppingCart.setPriceDecorators(decoratorList);
}
@Test
public void unliSmallTotal() {
shoppingCart.add(Product.getUnliSmallInstance());
BigDecimal expected = Product.UNLI_SMALL_PRICE;
BigDecimal actual = shoppingCart.total();
assertEquals(expected, actual);
}
@Test
public void unliSmallMediumLargeAnd1GBTotal() {
shoppingCart.add(Product.getUnliSmallInstance());
shoppingCart.add(Product.getUnliMediumInstance());
shoppingCart.add(Product.getUnliLargeInstance());
shoppingCart.add(Product.get1GbDataPackInstance());
BigDecimal expected = Product.UNLI_SMALL_PRICE
.add(Product.UNLI_MEDIUM_PRICE)
.add(Product.UNLI_LARGE_PRICE)
.add(Product._1GB_DATA_PACK_PRICE);
BigDecimal actual = shoppingCart.total();
assertEquals(expected, actual);
}
@Test
public void scenario1Total() {
shoppingCart.add(Product.getUnliSmallInstance());
shoppingCart.add(Product.getUnliSmallInstance());
shoppingCart.add(Product.getUnliSmallInstance());
shoppingCart.add(Product.getUnliLargeInstance());
BigDecimal expected = new BigDecimal("94.70");
BigDecimal actual = shoppingCart.total();
assertEquals(expected, actual);
}
@Test
public void scenario2Total() {
shoppingCart.add(Product.getUnliSmallInstance());
shoppingCart.add(Product.getUnliSmallInstance());
shoppingCart.add(Product.getUnliLargeInstance());
shoppingCart.add(Product.getUnliLargeInstance());
shoppingCart.add(Product.getUnliLargeInstance());
shoppingCart.add(Product.getUnliLargeInstance());
BigDecimal expected = new BigDecimal("209.40");
BigDecimal actual = shoppingCart.total();
assertEquals(expected, actual);
}
@Test
public void scenario3Total() {
shoppingCart.add(Product.getUnliSmallInstance());
shoppingCart.add(Product.getUnliMediumInstance());
shoppingCart.add(Product.getUnliMediumInstance());
BigDecimal expectedPrice = new BigDecimal("84.70");
BigDecimal actualPrice = shoppingCart.total();
assertEquals(expectedPrice, actualPrice);
int expectedItemSize = 5;
int actualItemSize = shoppingCart.items().size();
assertEquals(expectedItemSize, actualItemSize);
}
@Test
public void scenario4Total() {
String discountCode = "I<3AMAYSIM";
shoppingCart.add(Product.getUnliSmallInstance());
shoppingCart.add(Product.get1GbDataPackInstance(), discountCode);
BigDecimal expectedPrice = new BigDecimal("31.32");
BigDecimal actualPrice = shoppingCart.total();
assertEquals(expectedPrice, actualPrice);
}
}
| [
"[email protected]"
] | |
35a4eb95b781f86e7a515ed8fa9948897d05165e | fe41525f02cef0ae15ec458a4eeff150b3245790 | /molecularDynamics/Brown.java | c05f9af2c20d3e19603a3b13223b285352ceb21f | [] | no_license | mkadlof/mm2 | ad11f7e95a92b7ce2a6a30d3b38abf46a225cae2 | 8e9af62fd405a84523350eef56b08c13b2c3f92c | refs/heads/master | 2020-04-16T15:22:56.670510 | 2015-05-12T07:39:29 | 2015-05-12T07:39:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 851 | java | import java.util.Random;
public class Brown extends Integrator {
private double dt;
private double gamma;
private double T;
private Random rGen;
public Brown(double dt, double gamma, double T) {
this.dt = dt;
this.gamma = gamma;
this.T = T;
rGen = new Random();
}
public void step(TheSystem system, ForceField ff) {
// calkowanie
Atom[] atoms = system.getAtoms();
VecNd tmp = new VecNd();
double e_GammaDt = Math.exp(-gamma*dt);
double sigmaR2 = dt*T/gamma * (2-(3-4*e_GammaDt+e_GammaDt*e_GammaDt)/gamma/dt);
for( Atom a : atoms ) {
VecNd currX = a.getX();
VecNd currV = a.getV();
VecNd currA = a.getA();
VecNd newX = new VecNd();
// newX := currX + currA*dt/gamma + rand
tmp.mult(dt/gamma,currA);
tmp.add( VecNd.gaussian(rGen,0,sigmaR2) );
newX.add(currX,tmp);
a.updateX(newX);
}
}
}
| [
"[email protected]"
] | |
300e824d59530ee1a9776a0ffb444f9a0a4dbb7d | 436e88127327f6511ae03327b4924f6eeaa5ea45 | /common/src/main/java/com/easycompany/trappd/cache/StateCache.java | 2a14bc3e75063df5417ba8b417f106604d9266c9 | [] | no_license | princebansal/trappd | 11d35b4d022bba7f893e7e3d0b82d5d8b8d0848f | 58dce86a03c6dbcb2843ec9779f94f15cf2ef5c3 | refs/heads/master | 2021-05-25T15:20:50.096853 | 2020-04-20T16:14:54 | 2020-04-20T16:14:54 | 253,805,561 | 1 | 0 | null | 2020-04-19T14:32:16 | 2020-04-07T13:44:31 | Java | UTF-8 | Java | false | false | 1,570 | java | package com.easycompany.trappd.cache;
import com.easycompany.trappd.model.entity.StateEntity;
import com.easycompany.trappd.repository.StateRepository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
public final class StateCache {
private static Map<String, StateEntity> stateCodeToStateEntityMap = new HashMap<>();
private final StateRepository stateRepository;
@Autowired
public StateCache(StateRepository stateRepository) {
this.stateRepository = stateRepository;
}
@PostConstruct
public void init() {
List<StateEntity> stateEntityList = stateRepository.findAll();
stateCodeToStateEntityMap =
stateEntityList.stream()
.collect(
Collectors.toMap(
stateEntity -> stateEntity.getCode().toLowerCase(),
stateEntity -> stateEntity));
}
public Optional<StateEntity> getStateEntity(String code) {
if (stateCodeToStateEntityMap.containsKey(code.toLowerCase())) {
return Optional.ofNullable(stateCodeToStateEntityMap.get(code.toLowerCase()));
} else {
return Optional.empty();
}
}
public StateEntity getStateEntity(String code1, String code2) {
return getStateEntity(code1).orElseGet(() -> getStateEntity(code2).orElse(null));
}
}
| [
"[email protected]"
] | |
b2ee05f923c9613b77bd8136118a23952e1073f8 | 4f8dfcdd6f1494b59684438b8592c6c5c2e63829 | /DiffTGen-result/output/patch1-Lang-45-Jaid-plausible/Lang_45_1-plausible_jaid/target/0/25/evosuite-tests/org/apache/commons/lang/WordUtils_ESTest_scaffolding.java | 70cdc38c1f33ec694ce2febaf47dca91c8801c24 | [] | no_license | IntHelloWorld/Ddifferent-study | fa76c35ff48bf7a240dbe7a8b55dc5a3d2594a3b | 9782867d9480e5d68adef635b0141d66ceb81a7e | refs/heads/master | 2021-04-17T11:40:12.749992 | 2020-03-31T23:58:19 | 2020-03-31T23:58:19 | 249,439,516 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,441 | java | /**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Mon Mar 30 02:49:04 GMT 2020
*/
package org.apache.commons.lang;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
import org.junit.AfterClass;
import org.evosuite.runtime.sandbox.Sandbox;
import org.evosuite.runtime.sandbox.Sandbox.SandboxMode;
@EvoSuiteClassExclude
public class WordUtils_ESTest_scaffolding {
@org.junit.Rule
public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule();
private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone();
private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000);
@BeforeClass
public static void initEvoSuiteFramework() {
org.evosuite.runtime.RuntimeSettings.className = "org.apache.commons.lang.WordUtils";
org.evosuite.runtime.GuiSupport.initialize();
org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100;
org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000;
org.evosuite.runtime.RuntimeSettings.mockSystemIn = true;
org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED;
org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT();
org.evosuite.runtime.classhandling.JDKClassResetter.init();
setSystemProperties();
initializeClasses();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
}
@AfterClass
public static void clearEvoSuiteFramework(){
Sandbox.resetDefaultSecurityManager();
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
}
@Before
public void initTestCase(){
threadStopper.storeCurrentThreads();
threadStopper.startRecordingTime();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler();
org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode();
setSystemProperties();
org.evosuite.runtime.GuiSupport.setHeadless();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
org.evosuite.runtime.agent.InstrumentingAgent.activate();
}
@After
public void doneWithTestCase(){
threadStopper.killAndJoinClientThreads();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks();
org.evosuite.runtime.classhandling.JDKClassResetter.reset();
resetClasses();
org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode();
org.evosuite.runtime.agent.InstrumentingAgent.deactivate();
org.evosuite.runtime.GuiSupport.restoreHeadlessMode();
}
public static void setSystemProperties() {
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
java.lang.System.setProperty("file.encoding", "UTF-8");
java.lang.System.setProperty("java.awt.headless", "true");
java.lang.System.setProperty("java.io.tmpdir", "/tmp");
java.lang.System.setProperty("user.country", "US");
java.lang.System.setProperty("user.dir", "/home/hewitt/work/DiffTGen-master/output/patch1-Lang-45-Jaid-plausible/Lang_45_1-plausible_jaid/target/0/25");
java.lang.System.setProperty("user.home", "/home/hewitt");
java.lang.System.setProperty("user.language", "en");
java.lang.System.setProperty("user.name", "hewitt");
java.lang.System.setProperty("user.timezone", "Asia/Chongqing");
}
private static void initializeClasses() {
org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(WordUtils_ESTest_scaffolding.class.getClassLoader() ,
"org.apache.commons.lang.StringUtils",
"org.apache.commons.lang.SystemUtils",
"org.apache.commons.lang.WordUtils"
);
}
private static void resetClasses() {
org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(WordUtils_ESTest_scaffolding.class.getClassLoader());
org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses(
"org.apache.commons.lang.WordUtils",
"org.apache.commons.lang.SystemUtils",
"org.apache.commons.lang.StringUtils"
);
}
}
| [
"[email protected]"
] | |
bd43f6e5a9115163219bef057d71b88d3198923f | 2bbef9d5ae067c0327d915e7cd9ca0bf8d1a3108 | /src/main/java/View/HelpInfo/StartInfo.java | 1eb2aed29a48e711e542320ae466804e1116875d | [] | no_license | memphis8/w_info | 63c56dff0d29972f309ae02962007f0fe8b7ce13 | de5805f0c02f5fead4e29de71a6cfe31ba54852e | refs/heads/master | 2022-06-25T13:44:49.669347 | 2019-06-21T09:14:09 | 2019-06-21T09:14:09 | 193,065,261 | 1 | 0 | null | 2022-06-20T22:42:59 | 2019-06-21T08:54:41 | Java | UTF-8 | Java | false | false | 2,116 | java | package View.HelpInfo;
public class StartInfo {
public static void showStartInfo(){
System.out.println(" .----------------. .----------------. .-----------------. .----------------. .----------------. \n" +
"| .--------------. || .--------------. || .--------------. || .--------------. || .--------------. |\n" +
"| | _____ _____ | || | _____ | || | ____ _____ | || | _________ | || | ____ | |\n" +
"| ||_ _||_ _|| || | |_ _| | || ||_ \\|_ _| | || | |_ ___ | | || | .' `. | |\n" +
"| | | | /\\ | | | || | | | | || | | \\ | | | || | | |_ \\_| | || | / .--. \\ | |\n" +
"| | | |/ \\| | | || | | | | || | | |\\ \\| | | || | | _| | || | | | | | | |\n" +
"| | | /\\ | | || | _| |_ | || | _| |_\\ |_ | || | _| |_ | || | \\ `--' / | |\n" +
"| | |__/ \\__| | || | |_____| | || ||_____|\\____| | || | |_____| | || | `.____.' | |\n" +
"| | | || | | || | | || | | || | v1.0 | |\n" +
"| '--------------' || '--------------' || '--------------' || '--------------' || '--------------' |\n" +
" '----------------' '----------------' '----------------' '----------------' '----------------' ");
System.out.println("====================================================================================================");
System.out.println("☼ Welcome to weather application winfo !");
System.out.println("☼ Current weather : \"winfo -c YourCity\"");
System.out.println("☼ Weather forecast for 5 days : \"winfo -f YourCity\"");
System.out.println("☼ All weather info : \"winfo -a YourCity\"");
System.out.println("☼ Help information : \"winfo -h\"");
System.out.println("====================================================================================================");
}
}
| [
"[email protected]"
] | |
f734dca3dd1d29e4c1b384c1de60b60baae55b6e | c2e7f3b27536240cafcb4bef59d02292daadaf73 | /src/main/java/com/springapp/mvc/service/PetStateService.java | 2f022f4ab9c9b4bb35cca74da366e561d9af64e3 | [] | no_license | AlyonaV/PetMonitor | e73e81b287638463902d87054c2eadc11ea77c83 | bbc9ef811cf4688d5b1c0d51bd09471d7f9cbc3b | refs/heads/master | 2021-01-19T04:33:27.906754 | 2016-06-01T13:22:29 | 2016-06-01T13:22:29 | 60,178,794 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 277 | java | package com.springapp.mvc.service;
import com.springapp.mvc.persistence.model.PetState;
/**
* Created by Alona on 22.05.2016.
*/
public interface PetStateService {
PetState getById(Integer id);
void save(PetState petState);
void update(PetState petState);
}
| [
"Alona Vit"
] | Alona Vit |
773cf2d3901b7325b4cc95c7f065089cf15fbe8c | 1a86e57ccafc65ec3bf74d497d867eb456996058 | /TAS/src/main/java/info/smartkit/tas/controller/TASController.java | a1ff78448ed716dfe14abb0889c085e8cc583ca7 | [
"Unlicense"
] | permissive | smartkit/COVITAS | cad15ba881b40d19cc0c19f7a20232ba86936e41 | 99062d807cc50a50fb346ddaaad764f80ed1f34b | refs/heads/master | 2023-03-10T15:36:03.307181 | 2023-02-23T00:36:17 | 2023-02-23T00:36:17 | 89,655,588 | 0 | 1 | Unlicense | 2023-02-23T00:36:19 | 2017-04-28T01:35:06 | JavaScript | UTF-8 | Java | false | false | 3,029 | java | package info.smartkit.tas.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import info.smartkit.tas.pojo.*;
import info.smartkit.tas.service.ITASServices;
import info.smartkit.tas.service.impl.TASService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.Date;
/**
* Created by smartkit on 28/04/2017.
*/
@RestController
@RequestMapping("/tas")
public class TASController {
private static final Logger LOG = LoggerFactory.getLogger(TASController.class);
@Autowired
private ITASServices tasService;
@RequestMapping(method = RequestMethod.GET, value="pf/{chatBotID}/{message}")
public MessageResponse simplePFMessage(@PathVariable int chatBotID, @PathVariable String message) throws JsonProcessingException,IOException {
int timeStampInt = (int) (System.currentTimeMillis() / 1000L);
LOG.info("simplePFMessage called at:"+timeStampInt);
PFMessage pfMessage = new PFMessage();
Message messageObj = new Message();
messageObj.setChatBotID(chatBotID);
messageObj.setTimestamp(timeStampInt);
messageObj.setMessage(message);
//default User
User userObj = new User();
userObj.setExternalID("abc-639184572");
userObj.setFirstName("Tugger");
userObj.setLastName("Sufani");
userObj.setGender("m");
pfMessage.setMessage(messageObj);
pfMessage.setUser(userObj);
return tasService.personalityForge(pfMessage);
}
@RequestMapping(method = RequestMethod.POST,value = "/pf")
public MessageResponse securePfMessage(@RequestBody PFMessage pfMessage) throws JsonProcessingException,IOException {
return tasService.personalityForge(pfMessage);
}
// @RequestMapping(value = "/pf", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
// @ResponseBody
// public Resource<Object> getArtist(@RequestBody PFMessage message) throws JsonProcessingException {
// Object a = tasService.personalityForge(message);
// Resource<Object> resource = new Resource(a);
// resource.add(linkTo(methodOn(ArtistController.class).getArtist(id)).withSelfRel());
// return a;
// }
// private Resource<Album> getAlbumResource(Album album) {
// Resource<Album> resource = new Resource<Album>(album);
//
// // Link to Album
// resource.add(linkTo(methodOn(AlbumController.class).getAlbum(album.getId())).withSelfRel());
// // Link to Artist
// resource.add(linkTo(methodOn(ArtistController.class).getArtist(album.getArtist().getId())).withRel("artist"));
// // Option to purchase Album
// if (album.getStockLevel() > 0) {
// resource.add(linkTo(methodOn(AlbumController.class).purchaseAlbum(album.getId())).withRel("album.purchase"));
// }
// return resource;
// }
} | [
"[email protected]"
] | |
bc71191a8c360331a32b6d8e1e62865e38011212 | 127140ce7439c3aec962e13ded2183c2d1a644d8 | /src/main/java/com/music/app/constraint/PasswordConstraint.java | e51eb9dce588fd19cdf4209f12d3b55becf060e5 | [] | no_license | PinkFuryAlpha/Licenta | c54ec40e04dd21d3c2f2a63e5b1797e14a779273 | 5af16e5e6e384aafc755844aae1f04e3f18641b5 | refs/heads/main | 2023-05-30T04:05:46.511807 | 2021-06-26T16:14:30 | 2021-06-26T16:14:30 | 342,834,534 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 795 | java | package com.music.app.constraint;
import com.music.app.validators.PasswordValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Constraint(validatedBy = PasswordValidator.class)
@Target({ElementType.METHOD,ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface PasswordConstraint {
String message() default "Invalid password. It should contain one special character, one upper case letter, one number at least.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
| [
"[email protected]"
] | |
a4add1f865275ce0865fae5a9479192b3431aa45 | 2254def0c4f67f53e46d1e7fa17c58a59b507e13 | /app/src/main/java/com/util/ActionBarUtil.java | 4c4e786d3b232aa19d83193b202d9843fa74ce09 | [] | no_license | PurpleFrontPvtLtd/Kriddr_Pet_Parent_Share | 77e535d187050259837323eeaba1ede0092c9de8 | 3d0786ec0f9ab825872d8be0bde6e23e011905b3 | refs/heads/master | 2020-03-29T19:21:39.635382 | 2018-09-25T12:11:39 | 2018-09-25T12:11:39 | 150,259,077 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,792 | java | package com.util;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import purplefront.com.kriddrpetparent.R;
/**
* Created by Niranjan Reddy on 12-02-2018.
*/
public class ActionBarUtil {
AppCompatActivity CallActivity;
ImageView imgBack, imgSettings, imgSearch,imgNotify,imgSharePet;
TextView txtTitle;
EditText edtSearch;
ActionBar actionBar;
public ActionBarUtil(AppCompatActivity activity) {
CallActivity = activity;
actionBar = CallActivity.getSupportActionBar();
SetView();
setViewInvisible();
}
public void setViewInvisible(){
imgSettings.setVisibility(View.INVISIBLE);
imgBack.setVisibility(View.INVISIBLE);
imgSearch.setVisibility(View.INVISIBLE);
imgNotify.setVisibility(View.INVISIBLE);
edtSearch.setVisibility(View.INVISIBLE);
txtTitle.setVisibility(View.INVISIBLE);
imgSharePet.setVisibility(View.INVISIBLE);
edtSearch.setText("");
txtTitle.setClickable(false);
txtTitle.setGravity(Gravity.CENTER_VERTICAL);
}
public void setActionBarVisible() {
actionBar.show();
}
public void SetActionBarHide() {
actionBar.hide();
}
public void SetView() {
actionBar.setCustomView(R.layout.actionbar_view);
actionBar.setDisplayShowCustomEnabled(true);
View v = actionBar.getCustomView();
txtTitle = (TextView) v.findViewById(R.id.textBarTitle);
imgBack = (ImageView) v.findViewById(R.id.img_actionBarBack);
imgSettings = (ImageView) v.findViewById(R.id.img_settings_menu);
edtSearch = (EditText) v.findViewById(R.id.edtSearchText);
imgSearch = (ImageView) v.findViewById(R.id.imgSearch);
imgNotify= (ImageView) v.findViewById(R.id.img_Notify);
imgSharePet=(ImageView)v.findViewById(R.id.imgSharePet);
edtSearch.addTextChangedListener(new PhoneNumberFormattingTextWatcher("US"));
}
public void setTitle(String title) {
txtTitle.setText(title);
}
public EditText getEdtSearch(){
return edtSearch;
}
public TextView getTitle(){
return txtTitle;
}
public ImageView getImgBack() {
return imgBack;
}
public ImageView getImgSharePet(){
return imgSharePet;
}
public ImageView getImgSettings() {
return imgSettings;
}
public ImageView getImgNotify(){
return imgNotify;
}
public ImageView getImgSearch() {
return imgSearch;
}
}
| [
"[email protected]"
] | |
301df9b366fe66c5f0544d96d0bfe668d967a8d5 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/28/28_7f51db0d946c9b46c8efd673cb3ff8e6eb3f2b85/Pattern/28_7f51db0d946c9b46c8efd673cb3ff8e6eb3f2b85_Pattern_t.java | c17b4eff44ff0461c718dd68205b21d7ed999d99 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 11,415 | java | package org.freeplane.features.mindmapnode.pattern;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import org.freeplane.core.util.LogTool;
import org.freeplane.n3.nanoxml.IXMLParser;
import org.freeplane.n3.nanoxml.IXMLReader;
import org.freeplane.n3.nanoxml.StdXMLReader;
import org.freeplane.n3.nanoxml.XMLElement;
import org.freeplane.n3.nanoxml.XMLException;
import org.freeplane.n3.nanoxml.XMLParserFactory;
import org.freeplane.n3.nanoxml.XMLWriter;
public class Pattern implements Cloneable {
public static Pattern unMarshall(final String patternString) {
try {
final IXMLParser parser = XMLParserFactory.createDefaultXMLParser();
final IXMLReader xmlReader = new StdXMLReader(new StringReader(patternString));
parser.setReader(xmlReader);
final XMLElement xml = (XMLElement) parser.parse();
return Pattern.unMarshall(xml);
}
catch (final XMLException e) {
LogTool.severe(e);
return null;
}
}
public static Pattern unMarshall(final XMLElement xmlPattern) {
final Pattern pattern = new Pattern();
pattern.unMarshallImpl(xmlPattern);
return pattern;
}
private String name;
private PatternProperty patternChild;
private PatternProperty patternCloud;
private PatternProperty patternCloudColor;
private PatternProperty patternEdgeColor;
private PatternProperty patternEdgeStyle;
private PatternProperty patternEdgeWidth;
private PatternProperty patternIcon;
private PatternProperty patternNodeBackgroundColor;
private PatternProperty patternNodeColor;
private PatternProperty patternNodeFontBold;
private PatternProperty patternNodeFontItalic;
private PatternProperty patternNodeFontName;
private PatternProperty patternNodeFontSize;
private PatternProperty patternNodeStyle;
private PatternProperty patternNodeText;
private PatternProperty patternScript;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public String getName() {
return name;
}
public PatternProperty getPatternChild() {
return patternChild;
}
public PatternProperty getPatternCloud() {
return patternCloud;
}
public PatternProperty getPatternCloudColor() {
return patternCloudColor;
}
public PatternProperty getPatternEdgeColor() {
return patternEdgeColor;
}
public PatternProperty getPatternEdgeStyle() {
return patternEdgeStyle;
}
public PatternProperty getPatternEdgeWidth() {
return patternEdgeWidth;
}
public PatternProperty getPatternIcon() {
return patternIcon;
}
public PatternProperty getPatternNodeBackgroundColor() {
return patternNodeBackgroundColor;
}
public PatternProperty getPatternNodeColor() {
return patternNodeColor;
}
public PatternProperty getPatternNodeFontBold() {
return patternNodeFontBold;
}
public PatternProperty getPatternNodeFontItalic() {
return patternNodeFontItalic;
}
public PatternProperty getPatternNodeFontName() {
return patternNodeFontName;
}
public PatternProperty getPatternNodeFontSize() {
return patternNodeFontSize;
}
public PatternProperty getPatternNodeStyle() {
return patternNodeStyle;
}
public PatternProperty getPatternNodeText() {
return patternNodeText;
}
public PatternProperty getPatternScript() {
return patternScript;
}
private void marschall(final XMLElement xml, final String string, final PatternProperty pattern) {
if (pattern == null) {
return;
}
final XMLElement property = new XMLElement(string);
final String value = pattern.getValue();
if (value != null) {
property.setAttribute("value", value);
}
xml.addChild(property);
}
public String marshall() {
final XMLElement xml = new XMLElement("pattern");
xml.setAttribute("name", name);
marschall(xml, "pattern_node_background_color", patternNodeBackgroundColor);
marschall(xml, "pattern_node_color", patternNodeColor);
marschall(xml, "pattern_node_style", patternNodeStyle);
marschall(xml, "pattern_node_text", patternNodeText);
marschall(xml, "pattern_node_font_name", patternNodeFontName);
marschall(xml, "pattern_node_font_bold", patternNodeFontBold);
marschall(xml, "pattern_node_font_italic", patternNodeFontItalic);
marschall(xml, "pattern_node_font_size", patternNodeFontSize);
marschall(xml, "pattern_icon", patternIcon);
marschall(xml, "pattern_cloud", patternCloud);
marschall(xml, "pattern_cloud_color", patternCloudColor);
marschall(xml, "pattern_edge_color", patternEdgeColor);
marschall(xml, "pattern_edge_style", patternEdgeStyle);
marschall(xml, "pattern_edge_width", patternEdgeWidth);
marschall(xml, "pattern_child", patternChild);
marschall(xml, "pattern_script", patternScript);
final StringWriter string = new StringWriter();
final XMLWriter writer = new XMLWriter(string);
try {
writer.write(xml, true);
return string.toString();
}
catch (final IOException e) {
LogTool.severe(e);
return null;
}
}
public void setName(final String name) {
this.name = name;
}
public void setPatternChild(final PatternProperty patternChild) {
this.patternChild = patternChild;
}
public void setPatternEdgeColor(final PatternProperty patternEdgeColor) {
this.patternEdgeColor = patternEdgeColor;
}
public void setPatternCloud(final PatternProperty patternCloud) {
this.patternCloud = patternCloud;
}
public void setPatternCloudColor(final PatternProperty patternEdgeColor) {
this.patternCloudColor = patternEdgeColor;
}
public void setPatternEdgeStyle(final PatternProperty patternEdgeStyle) {
this.patternEdgeStyle = patternEdgeStyle;
}
public void setPatternEdgeWidth(final PatternProperty patternEdgeWidth) {
this.patternEdgeWidth = patternEdgeWidth;
}
public void setPatternIcon(final PatternProperty patternIcon) {
this.patternIcon = patternIcon;
}
public void setPatternNodeBackgroundColor(final PatternProperty patternNodeBackgroundColor) {
this.patternNodeBackgroundColor = patternNodeBackgroundColor;
}
public void setPatternNodeColor(final PatternProperty patternNodeColor) {
this.patternNodeColor = patternNodeColor;
}
public void setPatternNodeFontBold(final PatternProperty patternNodeFontBold) {
this.patternNodeFontBold = patternNodeFontBold;
}
public void setPatternNodeFontItalic(final PatternProperty patternNodeFontItalic) {
this.patternNodeFontItalic = patternNodeFontItalic;
}
public void setPatternNodeFontName(final PatternProperty patternNodeFontName) {
this.patternNodeFontName = patternNodeFontName;
}
public void setPatternNodeFontSize(final PatternProperty patternNodeFontSize) {
this.patternNodeFontSize = patternNodeFontSize;
}
public void setPatternNodeStyle(final PatternProperty patternNodeStyle) {
this.patternNodeStyle = patternNodeStyle;
}
public void setPatternNodeText(final PatternProperty patternNodeText) {
this.patternNodeText = patternNodeText;
}
public void setPatternScript(final PatternProperty patternScript) {
this.patternScript = patternScript;
}
private void unMarshallImpl(final XMLElement xmlPattern) {
name = xmlPattern.getAttribute("name", null);
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_node_background_color");
if (xmlProperty != null) {
patternNodeBackgroundColor = new PatternProperty();
patternNodeBackgroundColor.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_node_color");
if (xmlProperty != null) {
patternNodeColor = new PatternProperty();
patternNodeColor.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_node_style");
if (xmlProperty != null) {
patternNodeStyle = new PatternProperty();
patternNodeStyle.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_node_text");
if (xmlProperty != null) {
patternNodeText = new PatternProperty();
patternNodeText.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_node_font_name");
if (xmlProperty != null) {
patternNodeFontName = new PatternProperty();
patternNodeFontName.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_node_font_bold");
if (xmlProperty != null) {
patternNodeFontBold = new PatternProperty();
patternNodeFontBold.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_node_font_italic");
if (xmlProperty != null) {
patternNodeFontItalic = new PatternProperty();
patternNodeFontItalic.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_node_font_size");
if (xmlProperty != null) {
patternNodeFontSize = new PatternProperty();
patternNodeFontSize.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_icon");
if (xmlProperty != null) {
patternIcon = new PatternProperty();
patternIcon.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_cloud");
if (xmlProperty != null) {
patternCloud = new PatternProperty();
patternCloud.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_cloud_color");
if (xmlProperty != null) {
patternCloudColor = new PatternProperty();
patternCloudColor.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_edge_color");
if (xmlProperty != null) {
patternEdgeColor = new PatternProperty();
patternEdgeColor.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_edge_style");
if (xmlProperty != null) {
patternEdgeStyle = new PatternProperty();
patternEdgeStyle.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_edge_width");
if (xmlProperty != null) {
patternEdgeWidth = new PatternProperty();
patternEdgeWidth.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_child");
if (xmlProperty != null) {
patternChild = new PatternProperty();
patternChild.value = xmlProperty.getAttribute("value", null);
}
}
{
final XMLElement xmlProperty = xmlPattern.getFirstChildNamed("pattern_script");
if (xmlProperty != null) {
patternScript = new PatternProperty();
patternScript.value = xmlProperty.getAttribute("value", null);
}
}
}
}
| [
"[email protected]"
] | |
52cae68efd39ea78a25395076f374b0c240c734a | 5ed389c1f3fc175aa73478fc3dcba4101520b80b | /java/src/main/java/com/spoonacular/client/ProgressResponseBody.java | fd9baf8e16ab0d8f09ae63c60a15b1b1cc4c194d | [
"MIT"
] | permissive | jvenlin/spoonacular-api-clients | fae17091722085017cae5d84215d3b4af09082aa | 63f955ceb2c356fefdd48ec634deb3c3e16a6ae7 | refs/heads/master | 2023-08-04T01:51:19.615572 | 2021-10-03T13:30:26 | 2021-10-03T13:30:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,938 | java | /*
* spoonacular API
* The spoonacular Nutrition, Recipe, and Food API allows you to access over 380,000 recipes, thousands of ingredients, 800,000 food products, and 100,000 menu items. Our food ontology and semantic recipe search engine makes it possible to search for recipes using natural language queries, such as \"gluten free brownies without sugar\" or \"low fat vegan cupcakes.\" You can automatically calculate the nutritional information for any recipe, analyze recipe costs, visualize ingredient lists, find recipes for what's in your fridge, find recipes based on special diets, nutritional requirements, or favorite ingredients, classify recipes into types and cuisines, convert ingredient amounts, or even compute an entire meal plan. With our powerful API, you can create many kinds of food and especially nutrition apps. Special diets/dietary requirements currently available include: vegan, vegetarian, pescetarian, gluten free, grain free, dairy free, high protein, whole 30, low sodium, low carb, Paleo, ketogenic, FODMAP, and Primal.
*
* The version of the OpenAPI document: 1.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.spoonacular.client;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import java.io.IOException;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;
public class ProgressResponseBody extends ResponseBody {
private final ResponseBody responseBody;
private final ApiCallback callback;
private BufferedSource bufferedSource;
public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) {
this.responseBody = responseBody;
this.callback = callback;
}
@Override
public MediaType contentType() {
return responseBody.contentType();
}
@Override
public long contentLength() {
return responseBody.contentLength();
}
@Override
public BufferedSource source() {
if (bufferedSource == null) {
bufferedSource = Okio.buffer(source(responseBody.source()));
}
return bufferedSource;
}
private Source source(Source source) {
return new ForwardingSource(source) {
long totalBytesRead = 0L;
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
// read() returns the number of bytes read, or -1 if this source is exhausted.
totalBytesRead += bytesRead != -1 ? bytesRead : 0;
callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
return bytesRead;
}
};
}
}
| [
"[email protected]"
] | |
4145a5a129ffb068da0b5e043c361dcd050cdd0a | 4fa264697620bcb1bba06a0cff1c2b4ed4bb1ec4 | /Care.Android/app/src/androidTest/java/com/example/care/ApplicationTest.java | 2ae047e37bfb1d8d3a9585a0524dcc894d3ee9d3 | [] | no_license | Akshshr/care | c4b16d509592256634fc1f59c8b0eb4b13405596 | f322efcf71460c9e26170914d48710f8c32f2bb4 | refs/heads/master | 2021-01-24T23:11:29.477236 | 2015-06-27T14:30:56 | 2015-06-27T14:30:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 347 | java | package com.example.care;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"[email protected]"
] | |
c9a0836c04ea0429ffe1b7093c435e7a30d3d433 | c2fa8970c5b0295bcbecb903175057d588311a2f | /src/main/java/SeleniumMethods/LanchBrowserConcept.java | ac048475a92d36532829d049801c4b687633ec80 | [] | no_license | ademkaragoz/SeleniumCodeStudies | 95cc95a23edbc1acd20dfee3ab64edd3a3d388b1 | 1da50ba00d72b52bc2d0d2695168b56f83ba8e0e | refs/heads/master | 2023-04-16T16:34:36.007628 | 2020-07-25T07:31:39 | 2020-07-25T07:31:39 | 282,394,047 | 0 | 0 | null | 2021-04-26T20:31:26 | 2020-07-25T07:27:58 | Java | UTF-8 | Java | false | false | 1,035 | java | package SeleniumMethods;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class LanchBrowserConcept {
public static WebDriver driver;
public static void main(String[] args) {
String browser = "chrome";
if (browser.equals("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
}else if(browser.equals("firefox")){
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}else if (browser.equals("IE")) {
WebDriverManager.iedriver().setup();
driver = new InternetExplorerDriver();
} else if(browser.equals("opera")) {
WebDriverManager.operadriver().setup();
driver = new OperaDriver();
}else {
System.out.println("no defined browser");
}
driver.get("https://learnsdet.com/");
}
}
| [
"[email protected]"
] | |
e48dd16fd5df4e78213fa3535c26fb66febc20ce | 0715559d773bba23c1376a7217a6f8c5dce36c65 | /Plugins/TNT-TAG/src/main/java/org/jpwilliamson/sumoarena/ArenaPlugin.java | cd416f8ae0b6ab836dcad7e20c09764c26fd37dc | [] | no_license | kaushal-gawri9899/Advanced_MC_Plugins | df3d87b99550930129ef7ddb61303cb7e245d32b | bac456f4fb91a3f4822126ba429bc151e893ca04 | refs/heads/main | 2023-02-13T22:56:58.287525 | 2020-12-30T14:00:51 | 2020-12-30T14:00:51 | 324,824,559 | 0 | 0 | null | 2020-12-30T13:56:52 | 2020-12-27T18:33:13 | null | UTF-8 | Java | false | false | 3,604 | java | package org.jpwilliamson.sumoarena;
import lombok.Getter;
import org.jpwilliamson.sumoarena.command.ArenaCommandGroup;
import org.jpwilliamson.sumoarena.model.*;
import org.jpwilliamson.sumoarena.model.TestArena.TestArena;
import org.jpwilliamson.sumoarena.model.dm.DeathmatchArena;
import org.jpwilliamson.sumoarena.model.eggwars.EggWarsArena;
//import org.jpwilliamson.sumoarena.model.hideAndSeek.HideAndSeekArena;
import org.jpwilliamson.sumoarena.model.monster.MobArena;
import org.jpwilliamson.sumoarena.model.sumo.SumoArena;
import org.jpwilliamson.sumoarena.model.survival.SurvivalArena;
import org.jpwilliamson.sumoarena.model.team.ctf.CaptureTheFlagArena;
import org.jpwilliamson.sumoarena.model.team.tdm.TeamDeathmatchArena;
import org.jpwilliamson.sumoarena.model.tnt.TntTagArena;
import org.jpwilliamson.sumoarena.settings.Settings;
import org.jpwilliamson.sumoarena.task.EscapeTask;
import org.mineacademy.fo.Common;
import org.mineacademy.fo.command.SimpleCommand;
import org.mineacademy.fo.command.SimpleCommandGroup;
import org.mineacademy.fo.plugin.SimplePlugin;
import org.mineacademy.fo.settings.YamlStaticConfig;
import java.util.Arrays;
import java.util.List;
/**
* The core plugin class for Arena
*/
public final class ArenaPlugin extends SimplePlugin {
/**
* The main arena command
*/
@Getter
private final SimpleCommandGroup mainCommand = new ArenaCommandGroup();
/**
* Register arena types early
*/
@Override
protected void onPluginPreStart() {
// Register our arenas
ArenaManager.registerArenaType(MobArena.class);
ArenaManager.registerArenaType(DeathmatchArena.class);
ArenaManager.registerArenaType(TeamDeathmatchArena.class);
ArenaManager.registerArenaType(CaptureTheFlagArena.class);
ArenaManager.registerArenaType(EggWarsArena.class);
ArenaManager.registerArenaType(SumoArena.class);
//ArenaManager.registerArenaType(HideAndSeekArena.class);
ArenaManager.registerArenaType(SurvivalArena.class);
ArenaManager.registerArenaType(TntTagArena.class);
ArenaManager.registerArenaType(TestArena.class);
}
/**
* Load the plugin and its configuration
*/
@Override
protected void onPluginStart() {
// Connect to MySQL
// ArenaDatabase.start("mysql57.websupport.sk", 3311, "projectorion", "projectorion", "Te7=cXvxQI");
// Enable messages prefix
Common.ADD_TELL_PREFIX = true;
// Use themed messages in commands
SimpleCommand.USE_MESSENGER = true;
Common.runLater(() -> ArenaManager.loadArenas()); // Uncomment this line if your arena world is loaded by a third party plugin such as Multiverse
}
/**
* Called on startup and reload, load arenas
*/
@Override
protected void onReloadablesStart() {
//ArenaManager.loadArenas(); // Comment this line if your arena world is loaded by a third party plugin such as Multiverse
ArenaClass.loadClasses();
ArenaTeam.loadTeams();
ArenaReward.getInstance(); // Loads the file
ArenaPlayer.clearAllData();
registerEvents(new ArenaListener());
Common.runTimer(20, new EscapeTask());
}
/**
* Stop arenas on server stop
*/
@Override
protected void onPluginStop() {
ArenaManager.stopArenas(ArenaStopReason.PLUGIN);
}
/**
* Stop arenas on reload
*/
@Override
protected void onPluginReload() {
ArenaManager.stopArenas(ArenaStopReason.RELOAD);
ArenaManager.loadArenas(); // Uncomment this line if your arena world is loaded by a third party plugin such as Multiverse
}
/**
* Load the global settings classes
*/
@Override
public List<Class<? extends YamlStaticConfig>> getSettings() {
return Arrays.asList(Settings.class);
}
}
| [
"[email protected]"
] | |
454b1d19e9f62703b797dab350124191492aa533 | bbe560f89d40bbcedf97d744e115d699fecf9af8 | /ViaThinkSoft Distributed/src/de/viathinksoft/marschall/raumplan/formula/InvalidValException.java | e81e5810c852ee15d4680c91ad8eda29a6a195d2 | [] | no_license | danielmarschall/distributed | fde861b299744e21c0098075dfb75cc7a61aa9f6 | 342512bcb3fb91178c572cd4dea10cbd8233522e | refs/heads/master | 2022-11-30T04:00:03.521247 | 2010-12-13T20:28:52 | 2010-12-13T20:28:52 | 287,919,118 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 185 | java | package de.viathinksoft.marschall.raumplan.formula;
public class InvalidValException extends Exception {
private static final long serialVersionUID = 7819713196701732155L;
}
| [
"[email protected]"
] | |
5baab3adaad612c779900e4ff92a4d9c92f63454 | 22d8379d28e037f537b27f598f79564b93d9163f | /sample-facade/src/main/java/in/hocg/sample/facade/api/IndexController.java | 2891a921783568ca54c9e33dcb3e27b3f2abe9b7 | [] | no_license | service-mesh-projects/spring-cloud-sample | dac9d65c21b6117736a995bf583357509bdd1e9f | ce41775515eac026b3cac66df4c3d54103cb0406 | refs/heads/master | 2022-06-26T20:58:23.504469 | 2019-06-09T01:56:17 | 2019-06-09T01:56:17 | 190,943,910 | 0 | 0 | null | 2022-06-17T02:12:34 | 2019-06-08T23:16:01 | Java | UTF-8 | Java | false | false | 367 | java | package in.hocg.sample.facade.api;
import in.hocg.sample.facade.domain.Example;
import java.util.List;
/**
* Created by hocgin on 2019/6/9.
* email: [email protected]
*
* @author hocgin
*/
public interface IndexController {
/**
* Hi
*/
void hi();
void insert();
Example queryOne();
List<Example> queryAll();
}
| [
"[email protected]"
] | |
967caa4b8401d7cf7c9299b7ccb79a9ef58cc035 | 54c8cdd8c9a998a7769ebce175ec6c21dc8a0f6c | /GoGreen CustomerApp v1.1/app/src/main/java/com/cscodetech/supermarket/model/Register.java | 5bb062ea522fe2cbc1d10625a1f3097c1be3f779 | [] | no_license | luuuuuuuul/BytmCustomerApp | 53a16b892cf5e8c7007470989aa7339c3a7f14d3 | 7a0a15dec34561d48b8a633dafc44a7a054ca562 | refs/heads/main | 2023-01-28T14:08:59.449464 | 2020-12-10T14:57:40 | 2020-12-10T14:57:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,030 | java |
package com.cscodetech.supermarket.model;
import com.google.gson.annotations.SerializedName;
@SuppressWarnings("unused")
public class Register {
@SerializedName("userid")
private String userid;
@SerializedName("ResponseCode")
private String mResponseCode;
@SerializedName("ResponseMsg")
private String mResponseMsg;
@SerializedName("Result")
private String mResult;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getResponseCode() {
return mResponseCode;
}
public void setResponseCode(String responseCode) {
mResponseCode = responseCode;
}
public String getResponseMsg() {
return mResponseMsg;
}
public void setResponseMsg(String responseMsg) {
mResponseMsg = responseMsg;
}
public String getResult() {
return mResult;
}
public void setResult(String result) {
mResult = result;
}
}
| [
"[email protected]"
] | |
e6b248e9edd561381f7592ada76d33c14bdbbcdb | 0dea2f104f1b0b01149ba5e25ca8e125d1fe8404 | /codeforces/1519/D.java | cc6cacfa35c4f4b92821e38b94dbebf82feb3faa | [] | no_license | sudhanshu-mallick/All-My-Submissions | d14f82c38515d6140338daf5b77bdf2675c8aab6 | 68a97691fad0368a4ba4c39576e45ba8462ad3ae | refs/heads/master | 2023-06-22T16:01:20.872407 | 2021-07-03T13:07:00 | 2021-07-26T08:25:14 | 377,220,272 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,053 | java | import java.util.*;
import java.io.*;
public class Maximum_Sum_Of_Products {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void shuffle(int[] a) {
Random r = new Random();
for (int i = 0; i <= a.length - 2; i++) {
int j = i + r.nextInt(a.length - i);
swap(a, i, j);
}
Arrays.sort(a);
}
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
FastReader t = new FastReader();
PrintWriter o = new PrintWriter(System.out);
int n = t.nextInt();
long[] a = new long[n];
long[] b = new long[n];
long max = 0, total = 0;
for (int i = 0; i < n; ++i)
a[i] = t.nextLong();
for (int i = 0; i < n; ++i) {
b[i] = t.nextLong();
total += a[i] * b[i];
}
max = total;
for (int i = 0; i < n; ++i) {
int x = i - 1, y = i + 1;
long cur = total;
while (x >= 0 && y < n) {
cur = cur - a[x] * b[x] - a[y] * b[y] + a[x] * b[y] + a[y] * b[x];
--x;
++y;
max = Math.max(max, cur);
}
}
for (int i = 0; i < n; ++i) {
long cur = total;
int x = i, y = i + 1;
while (x >= 0 && y < n) {
cur = cur - a[x] * b[x] - a[y] * b[y] + a[x] * b[y] + a[y] * b[x];
--x;
++y;
max = Math.max(max, cur);
}
}
o.println(max);
o.flush();
o.close();
}
} | [
"[email protected]"
] | |
0dd858f75d12cc92ea1e2d71568db5079297ba0d | e23e239b54b9d3aa227ba5ef0e3d56c8bc24c0d2 | /src/test/java/com/catalystone/mbs/controller/AdminControllerTest.java | 6765956c00f7f28e87b6dc36bde0c13bbd18ae52 | [] | no_license | sdhawan27/mbs | f744236fa2239f9b12b049e8dc59f0221d75e7d8 | 617064412663d9b38a872c24ef910ed50bd003ff | refs/heads/master | 2020-06-29T01:50:18.114845 | 2019-08-04T16:29:39 | 2019-08-04T16:29:39 | 200,339,076 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,039 | java | package com.catalystone.mbs.controller;
import com.catalystone.mbs.entity.Theater;
import com.catalystone.mbs.exception.AdminException;
import com.catalystone.mbs.repository.TheaterRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class AdminControllerTest {
@Mock
TheaterRepository trepo;
@InjectMocks
AdminController controller;
@Test(expected= AdminException.class)
public void testDeleteTheaterWithException() throws AdminException {
controller.deleteTheater(new String("1"));
Mockito.when(trepo.findByTid(1L)).thenReturn(null);
}
@Test
public void testDeleteTheater() throws AdminException{
Theater t = new Theater();
Mockito.when(trepo.findByTid(1L)).thenReturn(t);
controller.deleteTheater(new String("1"));
Mockito.verify(trepo).delete(t);
}
}
| [
"[email protected]"
] | |
557d1f2a057e1f550b89ad92e0e979aa4eabba3e | 2d66a5012b7f7763eb58bd93e9a71241614123c8 | /ezcloud-wechat/src/main/java/com/ezcloud/framework/weixin/service/BaseWeiXinProcessWervice.java | d889f062078c6242d8025bcf431c0fd089692714 | [] | no_license | javakaka/ezcloud-dev | 98c8f1e6fc9125fce597ad52e6c24ce11d933e03 | e67643aa609c0f095825881bff7a27afa9a919f0 | refs/heads/master | 2020-04-12T09:35:16.702707 | 2017-01-27T05:20:09 | 2017-01-27T05:20:09 | 62,430,591 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,820 | java | package com.ezcloud.framework.weixin.service;
import com.ezcloud.framework.weixin.model.Message;
import com.ezcloud.framework.weixin.model.OutMessage;
public abstract class BaseWeiXinProcessWervice {
/**
* 对微信请求进行业务处理
* @author Administrator
*/
/****接收微信发来的请求消息类型**/
//接收的文本消息
public static final String REQUEST_MSG_TYPE_TEXT ="text";
//接收的图片消息
public static final String REQUEST_MSG_TYPE_IMAGE ="image";
//接收的语音消息
public static final String REQUEST_MSG_TYPE_VOICE ="voice";
//接收的语音识别消息
public static final String REQUEST_MSG_TYPE_VOICE_RECOGNITION ="voice_recognition";
//接收的视频消息
public static final String REQUEST_MSG_TYPE_VIDEO ="video";
//接收的地理位置消息
public static final String REQUEST_MSG_TYPE_LOCATION ="location";
//接收的链接消息
public static final String REQUEST_MSG_TYPE_LINK ="link";
//接收的事件消息
public static final String REQUEST_MSG_TYPE_EVENT ="event";
//接收的关注事件消息
public static final String REQUEST_MSG_TYPE_EVENT_SUBSCRIBE ="subscribe";
//接收的取消关注事件消息
public static final String REQUEST_MSG_TYPE_EVENT_UNSUBSCRIBE ="unsubscribe";
//接收的未关注时扫描二维码消息
public static final String REQUEST_MSG_TYPE_EVENT_SCAN_UNSUBSCRIBE ="scan_unsubscribe";
//接收的已关注公众号时扫描二维码的消息
public static final String REQUEST_MSG_TYPE_EVENT_SCAN_SUBSCRIBE ="scan_subscribe";
//接收的上报地理位置事件消息
public static final String REQUEST_MSG_TYPE_EVENT_LOCATION ="LOCATION";
//接收的用户点击事件消息
public static final String REQUEST_MSG_TYPE_EVENT_CLICK ="CLICK";
//接收用户的自定义菜单点击事件消息
public static final String REQUEST_MSG_TYPE_EVENT_VIEW ="VIEW";
//接收用户的自定义菜单点击 scancode_push:扫码推事件的事件推送
public static final String REQUEST_MSG_TYPE_EVENT_SCANCODE_PUSH ="scancode_push";
//接收用户的自定义菜单点击 scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框的事件推送
public static final String REQUEST_MSG_TYPE_EVENT_SCANCODE_WAITMSG ="scancode_waitmsg";
//自定义菜单点击 pic_sysphoto:弹出系统拍照发图的事件推送
public static final String REQUEST_MSG_TYPE_EVENT_PIC_SYSPHOTO ="pic_sysphoto";
//自定义菜单点击 pic_photo_or_album:弹出拍照或者相册发图的事件推送
public static final String REQUEST_MSG_TYPE_EVENT_PIC_PHOTO_OR_ALBUM ="pic_photo_or_album";
//自定义菜单点击 pic_weixin:弹出微信相册发图器的事件推送
public static final String REQUEST_MSG_TYPE_EVENT_PIC_WEIXIN ="pic_weixin";
//自定义菜单点击 location_select:弹出地理位置选择器的事件推送
public static final String REQUEST_MSG_TYPE_EVENT_LOCATION_SELECT ="location_select";
/***返回的被动响应消息类型**/
//返回文本消息
public static final String RESPONSE_MESSAGE_TYPE_TEXT = "text";
//返回图片消息
public static final String RESPONSE_MESSAGE_TYPE_IMAGE = "image";
//返回语音消息
public static final String RESPONSE_MESSAGE_TYPE_VOICE = "voice";
//返回视频消息
public static final String RESPONSE_MESSAGE_TYPE_VIDEO = "video";
//返回音乐消息
public static final String RESPONSE_MESSAGE_TYPE_MUSIC = "music";
//返回图文消息
public static final String RESPONSE_MESSAGE_TYPE_NEWS = "news";
/***返回的客服消息类型**/
//客服文本消息
public static final String RESPONSE_CUSTOM_MESSAGE_TYPE_TEXT = "text";
//客服图片消息
public static final String RESPONSE_CUSTOM_MESSAGE_TYPE_IMAGE = "image";
//客服语音消息
public static final String RESPONSE_CUSTOM_MESSAGE_TYPE_VOICE = "voice";
//客服视频消息
public static final String RESPONSE_CUSTOM_MESSAGE_TYPE_VIDEO = "video";
//客服音乐消息
public static final String RESPONSE_CUSTOM_MESSAGE_TYPE_MUSIC = "music";
//客服图文消息
public static final String RESPONSE_CUSTOM_MESSAGE_TYPE_NEWS = "news";
private Message outMsg;
//处理文本请求
public abstract OutMessage handleTextMsgRequest(Object msg);
//处理图片请求
public abstract OutMessage handleImageMsgRequest(Object msg);
//处理普通语音请求
public abstract OutMessage handleVoiceMsgRequest(Object msg);
//处理普通语音请求
public abstract OutMessage handleVoiceRecognitionMsgRequest(Object msg);
//处理视频请求
public abstract OutMessage handleVideoMsgRequest(Object msg);
//处理位置信息请求
public abstract OutMessage handleLocationMsgRequest(Object msg);
//处理链接信息请求
public abstract OutMessage handleLinkMsgRequest(Object msg);
//处理事件
public abstract OutMessage handleEventMsgRequest(Object msg);
//已关注时扫描二维码事件
public abstract OutMessage handleScanSubscribeEventMsgRequest(Object msg);
//未关注时扫描二维码事件
public abstract OutMessage handleScanUnSubscribeEventMsgRequest(Object msg);
//处理上报地理位置事件
public abstract OutMessage handleLocationEventMsgRequest(Object msg);
//处理自定义菜单点击拉取消息事件
public abstract OutMessage handleClickEventMsgRequest(Object msg);
//处理自定义菜单点击拉取消息事件
public abstract OutMessage handleClickViewEventMsgRequest(Object msg);
//处理自定义菜单点击拉取消息事件
public abstract OutMessage handleClickScancodePushEventMsgRequest(Object msg);
//自定义菜单点击 scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框的事件推送
public abstract OutMessage handleClickScancodeWaitmsgEventMsgRequest(Object msg);
//自定义菜单点击 pic_sysphoto:弹出系统拍照发图的事件推送
public abstract OutMessage handleClickPicSysphotoEventMsgRequest(Object msg);
//自定义菜单点击 pic_photo_or_album:弹出拍照或者相册发图的事件推送
public abstract OutMessage handleClickPicPhotoOrAlbumEventMsgRequest(Object msg);
//自定义菜单点击 pic_weixin:弹出微信相册发图器的事件推送
public abstract OutMessage handleClickPicWeixinEventMsgRequest(Object msg);
//自定义菜单点击 location_select:弹出地理位置选择器的事件推送
public abstract OutMessage handleClickLocationSelectEventMsgRequest(Object msg);
//处理关注事件
public abstract OutMessage handleSubscribeEventMsgRequest(Object msg);
//处理取消关注事件
public abstract OutMessage handleUnSubscribeEventMsgRequest(Object msg);
} | [
"[email protected]"
] | |
fd22018ed17b79a68b86660df00c13accd15a61b | ccaa535498e3daa911985bc3fc0e396eaf56e226 | /spider-55haitao-realtime/src/main/java/com/haitao55/spider/realtime/service/impl/RealtimeStatisticsServiceImpl.java | a82cefa0bba3f52014be4fd68cb608412903e895 | [] | no_license | github4n/spider-55ht | d871aad6e51f7cf800032351137b4b3f12d6e86e | 7c59cda6b5b514139bd69cff2b914e0815f53cd6 | refs/heads/master | 2020-03-29T22:44:38.527732 | 2018-02-01T07:53:30 | 2018-02-01T07:53:30 | 150,438,349 | 1 | 0 | null | 2018-09-26T14:19:14 | 2018-09-26T14:19:14 | null | UTF-8 | Java | false | false | 1,969 | java | package com.haitao55.spider.realtime.service.impl;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.haitao55.spider.common.dao.RealtimeStatisticsDAO;
import com.haitao55.spider.common.dos.RealtimeStatisticsDO;
import com.haitao55.spider.common.service.impl.BaseService;
import com.haitao55.spider.realtime.service.RealtimeStatisticsService;
/**
* RealtimeStatistics Service 实现类
* Title:
* Description:
* Company: 55海淘
* @author zhaoxl
* @date 2017年1月19日 下午2:23:55
* @version 1.0
*/
@Service("realtimeStatisticsService")
public class RealtimeStatisticsServiceImpl extends BaseService<RealtimeStatisticsDO> implements RealtimeStatisticsService {
@Autowired
private RealtimeStatisticsDAO realtimeStatisticsDAO;
/**
* save or update
*/
@Override
public void saveOrUpdate(RealtimeStatisticsDO realtimeStatisticsDO) {
String realtimeTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
realtimeStatisticsDO.setRealtimeTime(realtimeTime);
RealtimeStatisticsDO selectByKey = realtimeStatisticsDAO.findByPrimaryKey(realtimeStatisticsDO.getTaskId(),realtimeTime);
if(null == selectByKey){
this.save(realtimeStatisticsDO);
}else{
int crawler = selectByKey.getCrawler();
if(0 != realtimeStatisticsDO.getCrawler()){
crawler = crawler +1;
}
int mongo = selectByKey.getMongo();
if(0 != realtimeStatisticsDO.getMongo()){
mongo = mongo+1;
}
int redis = selectByKey.getRedis();
if(0 != realtimeStatisticsDO.getRedis()){
redis = redis+1;
}
int exception = selectByKey.getException();
if(0 != realtimeStatisticsDO.getException()){
exception = exception+1;
}
selectByKey.setCrawler(crawler);
selectByKey.setMongo(mongo);
selectByKey.setRedis(redis);
selectByKey.setException(exception);
this.updateNotNull(selectByKey);
}
}
}
| [
"[email protected]"
] | |
88574fc895ab48766df75d7f4f81ab05148c1e80 | 1dd24d92fc733f2a0fb2ff52d2e86e4d0d0c590c | /javaOOP/TP3_5/src/MyDateTime/Question5.java | 53bc603f0c552b0bd85b03a9c5d1ecb024c5014c | [] | no_license | QuynhHoaNguyen/Java | 507c3ac4be5c166ad82a866d9437e3114a538894 | 060f342b3e385bb30b828a6bb45128d67264de2c | refs/heads/master | 2022-12-24T17:33:31.687896 | 2020-10-06T11:50:31 | 2020-10-06T11:50:31 | 262,301,491 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 1,320 | java | package MyDateTime;
//import java.util.Scanner;
public class Question5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyDate date = new MyDate();
MyDate d1 = new MyDate(28, 12, 2019);
MyDate d2 = new MyDate(10, 04, 2020);
System.out.println("Le jour 1: " + d1);
System.out.println("Le jour 2: " + d2 + "\n");
System.out.println("2. Comparez deux objets MyDate");
if (date.comparez(d1, d2) == 1) {
System.out.println("Le jour 1 est avant le jour 2.\n");
}
if (date.comparez(d1, d2) == -1) {
System.out.println("Le jour 1 est après le jour 2.\n");
}
if (date.comparez(d1, d2) == 0) {
System.out.println("Est un jour.\n");
}
System.out.println("3. Vérifiez si une date est valide.");
if(date.checkDate(d1) == false) {
System.out.println("La date n'est pas valide.\n");
}
else {
System.out.println("valide.\n");
}
System.out.println("4. Calculez la distance entre deux dates générées à partir de MyDate.");
System.out.println("La distance entre les deux dates est " + date.distance(d1, d2) + " jours.\n");
System.out.println("6. Affichage de la date");
System.out.println(date.toString("02/11/1998"));
System.out.println(date.toString("01/10/97"));
System.out.println(date.toString("3030-12-24"));
}
}
| [
"[email protected]"
] | |
57e747a43b179515bb0779a1ab77b085bfffbcfe | 3c934c99c8e90e6ce901372bfb64bca583f60170 | /Part01_11.VariousVariables/src/main/java/VariousVariables.java | 15f05a71312d856905ce96cf02bad8fcb154955f | [] | no_license | aomer3/Java_1_MOOC_2020 | f728b1ae7b9323dbc7163e1de55c15050c43db0d | 47e6b955d2ec4f66dfe3aee70179490058db6d51 | refs/heads/main | 2023-02-08T21:31:43.125231 | 2020-12-26T22:24:19 | 2020-12-26T22:24:19 | 323,102,793 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 941 | java | /*
The exercise template contains a program that prints the following:
Chicken:
3
Bacon (kg):
5.5
Tractor:
None!
And finally, a summary:
3
5.5
None!
*/
public class VariousVariables {
public static void main(String[] args) {
// MODIFY THESE
int numberOfChicken = 9000;
double baconWeight = 0.1;
String tractor = "Zetor";
// DON'T MODIFY THESE:
//These tasks output messages onto the screen, using the created variables.
System.out.println("Chicken:");
System.out.println(numberOfChicken);
System.out.println("Bacon (kg):");
System.out.println(baconWeight);
System.out.println("Tractor:");
System.out.println(tractor);
System.out.println("");
System.out.println("And finally, a summary:");
System.out.println(numberOfChicken);
System.out.println(baconWeight);
System.out.println(tractor);
}
}
| [
"[email protected]"
] | |
093b75e2c479bc11c026c071ccc1218494da1323 | 145071f8d7e82d12fc12f857888c8d4ce024966c | /ODE_Metamodel/ode.concept.deis/src/artifact/util/Artifact_Switch.java | d69ffca8b79f4d995f18793c2ec3695e88ad959a | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | declan-whiting/DDI-Scripting-Tools | dd65032caf9bb579176218a85c7ea100858bcd63 | 90464c02f64c00ea0a77a158bebca14e7cb4f12b | refs/heads/master | 2020-08-22T10:11:27.005879 | 2019-05-17T23:04:21 | 2019-05-17T23:04:21 | 216,372,168 | 1 | 0 | MIT | 2019-10-20T14:10:21 | 2019-10-20T14:10:21 | null | UTF-8 | Java | false | false | 18,952 | java | /**
*/
package artifact.util;
import artifact.*;
import base.ArtifactElement;
import base.Element;
import base.ModelElement;
import base.SACMElement;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.util.Switch;
/**
* <!-- begin-user-doc -->
* The <b>Switch</b> for the model's inheritance hierarchy.
* It supports the call {@link #doSwitch(EObject) doSwitch(object)}
* to invoke the <code>caseXXX</code> method for each class of the model,
* starting with the actual class of the object
* and proceeding up the inheritance hierarchy
* until a non-null result is returned,
* which is the result of the switch.
* <!-- end-user-doc -->
* @see artifact.Artifact_Package
* @generated
*/
public class Artifact_Switch<T> extends Switch<T> {
/**
* The cached model package
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static Artifact_Package modelPackage;
/**
* Creates an instance of the switch.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Artifact_Switch() {
if (modelPackage == null) {
modelPackage = Artifact_Package.eINSTANCE;
}
}
/**
* Checks whether this is a switch for the given package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param ePackage the package in question.
* @return whether this is a switch for the given package.
* @generated
*/
@Override
protected boolean isSwitchFor(EPackage ePackage) {
return ePackage == modelPackage;
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
@Override
protected T doSwitch(int classifierID, EObject theEObject) {
switch (classifierID) {
case Artifact_Package.ARTIFACT_GROUP: {
ArtifactGroup artifactGroup = (ArtifactGroup)theEObject;
T result = caseArtifactGroup(artifactGroup);
if (result == null) result = caseArtifactElement(artifactGroup);
if (result == null) result = caseModelElement(artifactGroup);
if (result == null) result = caseSACMElement(artifactGroup);
if (result == null) result = caseElement(artifactGroup);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Artifact_Package.ARTIFACT_PACKAGE: {
ArtifactPackage artifactPackage = (ArtifactPackage)theEObject;
T result = caseArtifactPackage(artifactPackage);
if (result == null) result = caseArtifactElement(artifactPackage);
if (result == null) result = caseModelElement(artifactPackage);
if (result == null) result = caseSACMElement(artifactPackage);
if (result == null) result = caseElement(artifactPackage);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Artifact_Package.ARTIFACT_PACKAGE_BINDING: {
ArtifactPackageBinding artifactPackageBinding = (ArtifactPackageBinding)theEObject;
T result = caseArtifactPackageBinding(artifactPackageBinding);
if (result == null) result = caseArtifactPackage(artifactPackageBinding);
if (result == null) result = caseArtifactElement(artifactPackageBinding);
if (result == null) result = caseModelElement(artifactPackageBinding);
if (result == null) result = caseSACMElement(artifactPackageBinding);
if (result == null) result = caseElement(artifactPackageBinding);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Artifact_Package.ARTIFACT_PACKAGE_INTERFACE: {
ArtifactPackageInterface artifactPackageInterface = (ArtifactPackageInterface)theEObject;
T result = caseArtifactPackageInterface(artifactPackageInterface);
if (result == null) result = caseArtifactPackage(artifactPackageInterface);
if (result == null) result = caseArtifactElement(artifactPackageInterface);
if (result == null) result = caseModelElement(artifactPackageInterface);
if (result == null) result = caseSACMElement(artifactPackageInterface);
if (result == null) result = caseElement(artifactPackageInterface);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Artifact_Package.ARTIFACT_ASSET: {
ArtifactAsset artifactAsset = (ArtifactAsset)theEObject;
T result = caseArtifactAsset(artifactAsset);
if (result == null) result = caseArtifactElement(artifactAsset);
if (result == null) result = caseModelElement(artifactAsset);
if (result == null) result = caseSACMElement(artifactAsset);
if (result == null) result = caseElement(artifactAsset);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Artifact_Package.PROPERTY: {
Property property = (Property)theEObject;
T result = caseProperty(property);
if (result == null) result = caseArtifactAsset(property);
if (result == null) result = caseArtifactElement(property);
if (result == null) result = caseModelElement(property);
if (result == null) result = caseSACMElement(property);
if (result == null) result = caseElement(property);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Artifact_Package.TECHNIQUE: {
Technique technique = (Technique)theEObject;
T result = caseTechnique(technique);
if (result == null) result = caseArtifactAsset(technique);
if (result == null) result = caseArtifactElement(technique);
if (result == null) result = caseModelElement(technique);
if (result == null) result = caseSACMElement(technique);
if (result == null) result = caseElement(technique);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Artifact_Package.PARTICIPANT: {
Participant participant = (Participant)theEObject;
T result = caseParticipant(participant);
if (result == null) result = caseArtifactAsset(participant);
if (result == null) result = caseArtifactElement(participant);
if (result == null) result = caseModelElement(participant);
if (result == null) result = caseSACMElement(participant);
if (result == null) result = caseElement(participant);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Artifact_Package.ACTIVITY: {
Activity activity = (Activity)theEObject;
T result = caseActivity(activity);
if (result == null) result = caseArtifactAsset(activity);
if (result == null) result = caseArtifactElement(activity);
if (result == null) result = caseModelElement(activity);
if (result == null) result = caseSACMElement(activity);
if (result == null) result = caseElement(activity);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Artifact_Package.EVENT: {
Event event = (Event)theEObject;
T result = caseEvent(event);
if (result == null) result = caseArtifactAsset(event);
if (result == null) result = caseArtifactElement(event);
if (result == null) result = caseModelElement(event);
if (result == null) result = caseSACMElement(event);
if (result == null) result = caseElement(event);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Artifact_Package.RESOURCE: {
Resource resource = (Resource)theEObject;
T result = caseResource(resource);
if (result == null) result = caseArtifactAsset(resource);
if (result == null) result = caseArtifactElement(resource);
if (result == null) result = caseModelElement(resource);
if (result == null) result = caseSACMElement(resource);
if (result == null) result = caseElement(resource);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Artifact_Package.ARTIFACT: {
Artifact artifact = (Artifact)theEObject;
T result = caseArtifact(artifact);
if (result == null) result = caseArtifactAsset(artifact);
if (result == null) result = caseArtifactElement(artifact);
if (result == null) result = caseModelElement(artifact);
if (result == null) result = caseSACMElement(artifact);
if (result == null) result = caseElement(artifact);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Artifact_Package.ARTIFACT_ASSET_RELATIONSHIP: {
ArtifactAssetRelationship artifactAssetRelationship = (ArtifactAssetRelationship)theEObject;
T result = caseArtifactAssetRelationship(artifactAssetRelationship);
if (result == null) result = caseArtifactAsset(artifactAssetRelationship);
if (result == null) result = caseArtifactElement(artifactAssetRelationship);
if (result == null) result = caseModelElement(artifactAssetRelationship);
if (result == null) result = caseSACMElement(artifactAssetRelationship);
if (result == null) result = caseElement(artifactAssetRelationship);
if (result == null) result = defaultCase(theEObject);
return result;
}
default: return defaultCase(theEObject);
}
}
/**
* Returns the result of interpreting the object as an instance of '<em>Artifact Group</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Artifact Group</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseArtifactGroup(ArtifactGroup object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Artifact Package</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Artifact Package</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseArtifactPackage(ArtifactPackage object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Artifact Package Binding</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Artifact Package Binding</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseArtifactPackageBinding(ArtifactPackageBinding object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Artifact Package Interface</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Artifact Package Interface</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseArtifactPackageInterface(ArtifactPackageInterface object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Artifact Asset</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Artifact Asset</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseArtifactAsset(ArtifactAsset object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Property</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Property</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseProperty(Property object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Technique</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Technique</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseTechnique(Technique object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Participant</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Participant</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseParticipant(Participant object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Activity</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Activity</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseActivity(Activity object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Event</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Event</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseEvent(Event object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Resource</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Resource</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseResource(Resource object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Artifact</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Artifact</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseArtifact(Artifact object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Artifact Asset Relationship</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Artifact Asset Relationship</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseArtifactAssetRelationship(ArtifactAssetRelationship object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Element</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Element</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseElement(Element object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>SACM Element</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>SACM Element</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseSACMElement(SACMElement object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Model Element</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Model Element</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseModelElement(ModelElement object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Artifact Element</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Artifact Element</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseArtifactElement(ArtifactElement object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>EObject</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch, but this is the last case anyway.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>EObject</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject)
* @generated
*/
@Override
public T defaultCase(EObject object) {
return null;
}
} //Artifact_Switch
| [
"[email protected]"
] | |
28c1ee4fcce13998ec189951db191b4e87955d88 | 6be09f2a0e021e5834af02a5235ae9ccceff06a4 | /SIGCP/src/pe/com/pacasmayo/sgcp/bean/factory/BeanFactory.java | d23bc1e564f1a3f7f6b165fb205bbcdbfcdc4644 | [] | no_license | fbngeldres/sigcp | 60e4f556c0c5555c136639a06bea85f0b1cad744 | fc7d94c1e0d5b6abb5004d92a031355941884718 | refs/heads/master | 2021-01-11T22:33:13.669537 | 2017-03-07T16:19:41 | 2017-03-07T16:20:14 | 78,987,468 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 44,857 | java | package pe.com.pacasmayo.sgcp.bean.factory;
/*
* SGCP (Sistema de Gestión y Control de la Producción)
* Archivo: BeanFactory.java
* Modificado: Mar 17, 2010 10:13:34 AM
* Autor: andy.nunez
*
* Copyright (C) DBAccess, 2010. All rights reserved.
*
* Developed by: DBAccess. http://www.dbaccess.com
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import pe.com.pacasmayo.sgcp.bean.*;
import pe.com.pacasmayo.sgcp.excepciones.AplicacionException;
import pe.com.pacasmayo.sgcp.excepciones.LogicaException;
import pe.com.pacasmayo.sgcp.persistencia.dataObjects.*;
public interface BeanFactory {
/**
* @param actividades
* @return
*/
public abstract List<ActividadBean> transformarListaActividad(
List<Actividad> actividades);
public abstract List<ActividadBean> transformarListaActividadBasico(
List<Actividad> actividades);
/**
* @param actividad
* @return
*/
public abstract ActividadBean transformarActividad(Actividad actividad);
/**
* @param actividad
* @return
*/
public abstract ActividadBean transformarActividadBasico(Actividad actividad);
/**
* @param almacen
* @return
*/
public abstract AlmacenBean transformarAlmacen(Almacen almacen);
/**
* @param almacenes
* @return
*/
public abstract List<AlmacenBean> transformarListaAlmacen(
List<Almacen> almacenes);
/**
* @param clasificacionTipoMovimiento
* @return
*/
public abstract ClasificacionTipoMovimientoBean transformarClasificacionTipoMovimiento(
Clasificaciontipomovimiento clasificacionTipoMovimiento);
/**
* @param listaClasificacionTipoMovimiento
* @return
*/
public abstract List<ClasificacionTipoMovimientoBean> transformarListaClasificacionTipoMovimiento(
List<Clasificaciontipomovimiento> listaClasificacionTipoMovimiento);
/**
* @param componente
* @return
*/
public abstract ComponenteBean transformarComponente(Componente componente);
/**
* Método para tranformar un componente sin tomar en cuenta el factor de
* dosificacion
*
* @param componente
* Componente a transformar
* @return Componente Bean
*/
public abstract ComponenteBean transformarComponenteSinFactorDosificacion(
Componente componente);
/**
* @param componenteLista
* @return
*/
public abstract List<ComponenteBean> transformarListaComponente(
List<Componente> componenteLista);
/**
* @param division
* @return
*/
public abstract DivisionBean transformarDivision(Division division);
/**
* @param divisionBeans
* @return
*/
public abstract List<DivisionBean> transformarListaDivision(
List<Division> divisionBeans);
/**
* @param listaEstadoActividad
* @return
*/
public abstract List<EstadoActividadBean> transformarListaEstadoActividad(
List<Estadoactividad> listaEstadoActividad);
public abstract List<EstadoPrivilegioBean> transformarListaEstadoPrivilegio(
List<Estadoprivilegio> listaEstadoPrivilegio);
/**
* @param estadoActividad
* @return
*/
public abstract EstadoActividadBean transformarEstadoActividad(
Estadoactividad estadoActividad);
/**
* @param estadoNotificacion
* @return
*/
public abstract EstadoNotificacionBean transformarEstadoNotificacion(
Estadonotificacion estadoNotificacion);
/**
* @param listaEstadoNotificacion
* @return
*/
public abstract List<EstadoNotificacionBean> transformarListaEstadoNotificacion(
List<Estadonotificacion> listaEstadoNotificacion);
/**
* @param estadoHohaRuta
* @return
*/
public abstract EstadoHojaRutaBean transformarEstadoHojaRuta(
Estadohojaruta estadoHohaRuta);
/**
* @param listaEstadosHojaRuta
* @return
*/
public abstract List<EstadoHojaRutaBean> transformarListaEstadoHojaRuta(
List<Estadohojaruta> listaEstadosHojaRuta);
/**
* @param estadoProductoBeans
* @return
*/
public abstract List<EstadoProductoBean> transformarListaEstadoProducto(
List<Estadoproducto> estadoProductoBeans);
/**
* @param estadoProducto
* @return
*/
public abstract EstadoProductoBean transformarEstadoProducto(
Estadoproducto estadoProducto);
/**
* @param estadoPuestoTrabajos
* @return
*/
public abstract List<EstadoPuestoTrabajoBean> transformarListaEstadoPuestoTrabajo(
List<Estadopuestotrabajo> estadoPuestoTrabajos);
/**
* @param estadoPuestoTrabajo
* @return
*/
public abstract EstadoPuestoTrabajoBean transformarEstadoPuestoTrabajo(
Estadopuestotrabajo estadoPuestoTrabajo);
/**
* @param estadoUsuario
* @return
*/
public abstract EstadoUsuarioBean transformarEstadoUsuario(
Estadousuario estadoUsuario);
/**
* @param estadoPrivilegio
* @return
*/
public abstract EstadoPrivilegioBean transformarEstadoPrivilegio(
Estadoprivilegio estadoPrivilegio);
/**
* @param grupousuario
* @param agregarGrupoPrivilegios
* @return
*/
public abstract GrupoUsuarioBean transformarGrupoUsuario(
Grupousuario grupousuario, boolean agregarGrupoPrivilegios);
/**
* @param usuariogrupousuario
* @return
*/
public abstract UsuarioGrupoUsuarioBean transformarUsuarioGrupoUsuario(
Usuariogrupousuario usuariogrupousuario);
/**
* @param accion
* @return
*/
public abstract AccionBean transformarAccion(Accion accion);
/**
* @param opcion
* @return
*/
public abstract OpcionBean transformarOpcion(Opcion opcion);
public abstract List<OpcionBean> transformarListaOpcionParaCombo(
List<Opcion> opcionList);
public abstract OpcionAccionBean transformarOpcionAccion(
Opcionaccion opcionaccion);
public abstract List<OpcionAccionBean> transformarListaOpcionAccionParaCombo(
List<Opcionaccion> opcionaccionList);
/**
* @param nivelCargo
* @return
*/
public abstract NivelCargoBean transformarNivelCargo(Nivelcargo nivelCargo);
public abstract List<NivelCargoBean> transformarListaNivelCargo(
List<Nivelcargo> listaNivelCargo);
/**
* @param privilegio
* @return
*/
public abstract PrivilegioBean transformarPrivilegio(Privilegio privilegio);
public abstract List<PrivilegioBean> transformarListaPrivilegios(
List<Privilegio> listaPrivilegio);
public abstract NivelMenuBean transformarNivelMenu(Nivelmenu nivelmenu);
public abstract List<NivelMenuBean> transformarListaNivelMenu(
List<Nivelmenu> nivelesMenu);
/**
* @param grupoUsuarioPrivilegioList
* @return
*/
public abstract List<GrupoUsuarioPrivilegioBean> transformarListaGrupoUsuarioPrivilegio(
Set<Grupousuarioprivilegio> grupoUsuarioPrivilegioList);
/**
* @param grupoUsuarioPrivilegioList
* @return
*/
public abstract List<GrupoUsuarioPrivilegioBean> transformarListaGrupoUsuarioPrivilegio(
List<Grupousuarioprivilegio> grupoUsuarioPrivilegioList);
/**
* @param menu
* @param nivel
* @return
*/
public abstract MenuBean transformarMenu(Menu menu, Short nivel);
public abstract List<MenuBean> transformarListaMenu(List<Menu> menuList,
Short nivel);
public abstract MenuBean transformarMenuMantenimiento(Menu menu);
/**
* @param unidadCargo
* @return
*/
public abstract UnidadCargoBean transformarUnidadCargo(
Unidadcargo unidadCargo);
/**
* @param unidadCargoList
* @return
*/
public abstract List<UnidadBean> transformarListaUnidadCargo(
Set<Unidadcargo> unidadCargoList);
/**
* @param divisionCargo
* @return
*/
public abstract DivisionCargoBean transformarDivisionCargo(
Divisioncargo divisionCargo);
/**
* @param divisionCargoList
* @return
*/
public abstract List<DivisionBean> transformarListaDivisionCargo(
Set<Divisioncargo> divisionCargoList);
/**
* @param sociedadCargo
* @return
*/
public abstract SociedadCargoBean transformarSociedadCargo(
Sociedadcargo sociedadCargo);
/**
* @param sociedadCargoList
* @return
*/
public abstract List<SociedadBean> transformarListaSociedadCargo(
Set<Sociedadcargo> sociedadCargoList);
/**
* @param cargo
* @return
*/
public abstract CargoBean transformarCargo(Cargo cargo);
/**
* @param grupousuarioprivilegio
* @return
*/
public abstract GrupoUsuarioPrivilegioBean transformarGrupoUsuarioPrivilegio(
Grupousuarioprivilegio grupousuarioprivilegio);
/**
* @param factorDosificacion
* @return
*/
public abstract FactorDosificacionBean transformarFactordosificacion(
Factordosificacion factorDosificacion);
/**
* @param listaFactorDosificacion
* @return
*/
public abstract List<FactorDosificacionBean> transformarListaFactordosificacionParaConsulta(
List<Factordosificacion> listaFactorDosificacion);
/**
* @param factorDosificacionBeans
* @return
*/
public abstract List<FactorDosificacionBean> transformarListaFactordosificacion(
List<Factordosificacion> factorDosificacionBeans);
/**
* @param factorDosificacionBeans
* @return
*/
public abstract List<FactorDosificacionBean> transformarListaFactordosificacion(
Set<Factordosificacion> factorDosificacionBeans);
/**
* @param factorDosificacionRegistroMensual
* @return
*/
public abstract FactorDosificacionRegistroMensualBean transformarFactordosificacionregistromensu(
Factordosificacionregistromensu factorDosificacionRegistroMensual);
/**
* @param factorDosificacionRegistroMensualBeans
* @return
*/
public abstract List<FactorDosificacionRegistroMensualBean> transformarListaFactordosificacionregistromensu(
List<Factordosificacionregistromensu> factorDosificacionRegistroMensualBeans);
/**
* @param factorDosificacionRegistroMensualBeans
* @return
*/
public abstract FactorDosificacionRegistroMensualBean[] transformarListaFactorDosificacionRegistroMensual(
Set<Factordosificacionregistromensu> factorDosificacionRegistroMensualBeans);
/**
* @param hojaRuta
* @return
*/
public abstract HojaRutaBean transformarHojaRuta(Hojaruta hojaRuta);
public abstract HojaRutaBean transformarHojaRutaParaConsultaOrdenProduccion(
Hojaruta hojaRuta);
/**
* @param listaHojaRuta
* @return
*/
public abstract List<HojaRutaBean> transformarListaHojaRuta(
List<Hojaruta> listaHojaRuta);
public abstract List<HojaRutaBean> transformarListaHojaRutaParaCombo(
List<Hojaruta> listaHojaRuta);
/**
* @param listaHojaruta
* @return
*/
public abstract List<HojaRutaBean> transformarListaHojaRutaConFactoresDosificacion(
List<Hojaruta> listaHojaruta);
/**
* @param hojaRutaComponente
* @return
*/
public abstract HojaRutaComponenteBean transformarHojaRutaComponente(
Hojarutacomponente hojaRutaComponente);
/**
* @param listaHojaRutaComponente
* @return
*/
public abstract List<HojaRutaComponenteBean> transformarListaHojaRutaComponente(
List<Hojarutacomponente> listaHojaRutaComponente);
/**
* @param listaHojaRutaComponente
* @return
*/
public abstract List<HojaRutaComponenteBean> transformarListaHojaRutaComponente(
Set<Hojarutacomponente> listaHojaRutaComponente);
/**
* @param lineaNegocio
* @return
*/
public abstract LineaNegocioBean transformarLineaNegocio(
Lineanegocio lineaNegocio);
/**
* @param listaLineaNegocio
* @return
*/
public abstract List<LineaNegocioBean> transformarListaLineaNegocio(
List<Lineanegocio> listaLineaNegocio);
/**
* @param lineaNegocio
* @return
*/
public abstract LineaNegocioBean transformarLineaNegocioBasico(
Lineanegocio lineaNegocio);
/**
* @param listaLineaNegocio
* @return
*/
public abstract List<LineaNegocioBean> transformarListaLineaNegocioBasico(
List<Lineanegocio> listaLineaNegocio);
/**
* @param operacion
* @return
*/
public abstract OperacionBean transformarOperacion(Operacion operacion);
public abstract OperacionBean transformarOperacionParaPlanAnual(
Operacion operacion);
/**
* @param listaOperacion
* @return
*/
public abstract List<OperacionBean> transformarListaOperacion(
List<Operacion> listaOperacion);
public abstract List<OperacionBean> transformarListaOperacionParaPlanAnual(
List<Operacion> listaOperacion);
public abstract OperacionComponenteBean transformarOperacionComponente(
Operacioncomponente operacionComponente);
/**
* @param listaOperacionComponente
* @return
*/
public abstract List<OperacionComponenteBean> transformarListaOperacionComponente(
Set<Operacioncomponente> listaOperacionComponente);
/**
* @param operacionRecurso
* @return
*/
public abstract OperacionRecursoBean transformarOperacionRecurso(
Operacionrecurso operacionRecurso);
/**
* @param listaOperacionComponente
* @return
*/
public abstract List<OperacionRecursoBean> transformarListaOperacionRecurso(
Set<Operacionrecurso> listaOperacionComponente);
/**
* @param proceso
* @return
*/
public abstract ProcesoBean transformarProceso(Proceso proceso);
/**
* @param procesos
* @return
*/
public abstract List<ProcesoBean> transformarListaProceso(
List<Proceso> procesos);
/**
* @param procesos
* @return
*/
public abstract List<ProcesoBean> transformarListaProcesoBasico(
List<Proceso> procesos);
/**
* @param produccion
* @return
*/
public abstract ProduccionBean transformarProduccion(Produccion produccion);
/**
* @param produccionsBeans
* @return
*/
public abstract List<ProduccionBean> transformarListaProduccion(
List<Produccion> produccionsBeans);
/**
* @param producto
* @return
*/
public abstract ProductoBean transformarProducto(Producto producto);
/**
* @param producto
* @return
*/
public abstract ProductoBean transformarProductoBasico(Producto producto);
/**
* @param productosBeans
* @return
*/
public abstract List<ProductoBean> transformarListaProductos(
List<Producto> productosBeans);
/**
* @param produccionesBeans
* @return
*/
public abstract Set<ProduccionBean> transformarListaProducciones(
Set<Produccion> produccionesBeans);
/**
* @param puestosTrabajo
* @return
*/
public abstract List<PuestoTrabajoBean> transformarListaPuestoTrabajo(
List<Puestotrabajo> puestosTrabajo);
/**
* @param puestoTrabajo
* @return
*/
public abstract PuestoTrabajoBean transformarPuestoTrabajo(
Puestotrabajo puestoTrabajo);
/**
* @param recurso
* @return
*/
public abstract RecursoBean transformarRecurso(Recurso recurso);
/**
* @param recursoLista
* @return
*/
public abstract List<RecursoBean> transformarListaRecurso(
List<Recurso> recursoLista);
/**
* @param listaRecursosRM
* @return
*/
public RecursoRegistroMensualBean[] transformarListaRecursosRM(
Set<Recursoregistromensual> listaRecursosRM);
/**
* @param sociedad
* @return
*/
public abstract SociedadBean transformarSociedad(Sociedad sociedad);
/**
* @param sociedadBeans
* @return
*/
public abstract List<SociedadBean> transformarListaSociedad(
List<Sociedad> sociedadBeans);
/**
* @param tipoComponente
* @return
*/
public abstract TipoComponenteBean transformarTipoComponente(
Tipocomponente tipoComponente);
/**
* @param listaTipoComponentes
* @return
*/
public abstract List<TipoComponenteBean> transformarListaTipoComponentes(
List<Tipocomponente> listaTipoComponentes);
/**
* @param tipoMedioAlmacenamiento
* @return
*/
public abstract TipoMedioAlmacenamientoBean transformarTipoMedioAlmacenamiento(
Tipomedioalmacenamiento tipoMedioAlmacenamiento);
public abstract List<TipoMedioAlmacenamientoBean> transformarListaTipoMedioAlmacenamiento(
List<Tipomedioalmacenamiento> tipoMedioAlmacenamientoBeans);
/**
* @param tipoMovimiento
* @return
*/
public abstract TipoMovimientoBean transformarTipoMovimiento(
Tipomovimiento tipoMovimiento);
/**
* @param listaTipoMovimientoBeans
* @return
*/
public abstract List<TipoMovimientoBean> transformarListaTipoMovimiento(
List<Tipomovimiento> listaTipoMovimientoBeans);
/**
* @param tipoProductoBeans
* @return
*/
public abstract List<TipoProductoBean> transformarListaTipoProducto(
List<Tipoproducto> tipoProductoBeans);
/**
* @param tipoProducto
* @return
*/
public abstract TipoProductoBean transformarTipoProducto(
Tipoproducto tipoProducto);
/**
* @param tipoPuestoTrabajo
* @return
*/
public abstract TipoPuestoTrabajoBean transformarTipoPuestoTrabajo(
Tipopuestotrabajo tipoPuestoTrabajo);
/**
* @param puestosTrabajo
* @return
*/
public abstract List<TipoPuestoTrabajoBean> transformarListaTipoPuestoTrabajo(
List<Tipopuestotrabajo> puestosTrabajo);
/**
* @param puestosTrabajo
* @return
*/
public abstract List<UbicacionBean> transformarListaUbicaciones(
List<Ubicacion> puestosTrabajo);
/**
* @param ubicacion
* @return
*/
public abstract UbicacionBean transformarUbicacion(Ubicacion ubicacion);
/**
* @param unidad
* @return
*/
public abstract UnidadBean transformarUnidad(Unidad unidad);
/**
* @param unidad
* @return
*/
public abstract UnidadBean transformarUnidadBasico(Unidad unidad);
/**
* @param unidadBeans
* @return
*/
public abstract List<UnidadBean> transformarListaUnidad(
List<Unidad> unidadBeans);
/**
* @param unidadBeans
* @return
*/
public abstract List<UnidadBean> transformarListaUnidadBasico(
List<Unidad> unidadBeans);
/**
* @param unidadMedidaBeans
* @return
*/
public abstract List<UnidadMedidaBean> transformarListaUnidadMedida(
List<Unidadmedida> unidadMedidaBeans);
/**
* @param unidadMedida
* @return
*/
public abstract UnidadMedidaBean transformarUnidadMedida(
Unidadmedida unidadMedida);
/**
* @param persona
* @return
*/
public abstract PersonaBean transformarPersona(Persona persona);
/**
* @param personas
* @return
*/
public abstract List<PersonaBean> transformarListaPersona(
List<Persona> personas);
/**
* @param usuarios
* @return
*/
public abstract List<UsuarioBean> transformarListaUsuario(
List<Usuario> usuarios);
/**
* @param usuario
* @return
*/
public abstract UsuarioBean transformarUsuario(Usuario usuario);
/**
* Toma los datos de un objeto de persistencia Ordenproduccion y crea el
* objeto bean de la orden de produccion
*
* @param ordenproduccion
* objeto de persistencia
* @return OrdenProduccionBeanImpl
*/
public abstract OrdenProduccionBean transformarOrdenProduccion(
Ordenproduccion ordenproduccion);
/**
* @param ordenproduccion
* @return
*/
public abstract OrdenProduccionBean transformarOrdenProduccionBasico(
Ordenproduccion ordenproduccion);
/**
* Toma los datos de un objeto bean de orden de produccion y crea el objeto
* de persistencia Ordenproduccion
*
* @param ordenproduccionBean
* OrdenProduccionBeanImpl
* @return Ordenproduccion objeto de persistencia
*/
public abstract Ordenproduccion transformarOrdenProduccionBean(
OrdenProduccionBean ordenProduccionBean);
/**
* Toma una lista de objetos de persistencia Ordenproduccion y retorna un
* ArrayList de objetos q implenentan la interfaz OrdenProduccionBean
*
* @param listOrdenProduccion
* @return
*/
public abstract List<OrdenProduccionBean> transformarListaOrdenProduccion(
List<Ordenproduccion> listOrdenProduccion);
/**
* @param listOrdenProduccion
* @return
*/
public abstract List<OrdenProduccionBean> transformarListaOrdenProduccionBasico(
List<Ordenproduccion> listOrdenProduccion);
/**
* Método para transformar el objeto Plananual en objeto de negocio
* PlanAnualBean
*
* @param plananual
* @return Data Object tranformado
*/
public abstract PlanAnualBean transformarPlanAnual(Plananual plananual);
/**
* Método para transformar el objeto Plananual en objeto de negocio
* PlanAnualBean, asi como las tablas asociadas al plan anual: - Plan de
* Comercializacion
*
* @param plananual
* @return Data Object tranformado
*/
public abstract List<PlanComercializacionBean> transformarListaPlanComercializacion(
Set<Plancomercializacion> plancomercializacions);
/**
* @param planAnualBeans
* @return
*/
public abstract List<PlanAnualBean> transformarListaPlanAnual(
List<Plananual> planAnualBeans);
/**
* @param estadoPlanList
* @return
*/
public abstract List<EstadoPlanBean> transformarListaEstadoPlanAnual(
List<Estadoplananual> estadoPlanList);
/**
* @param estadoplananual
* @return
*/
public abstract EstadoPlanBean transformarEstadoPlan(
Estadoplananual estadoplananual);
/**
* @param plananual
* @return
*/
public abstract PlanAnualBean transformarPlanAnualCompleto(
Plananual plananual);
/**
* @param concepto
* @return
*/
public abstract ConceptoBean transformarConcepto(Concepto concepto);
/**
* @param concepto
* @return
*/
public abstract List<ConceptoBean> transformarListaConcepto(
List<Concepto> concepto);
/**
* @param medioalmacenamiento
* @return
*/
public abstract MedioAlmacenamientoBean transformarMedioAlmacenamiento(
Medioalmacenamiento medioalmacenamiento);
/**
* @param mediosAlmacenamiento
* @return
*/
public abstract List<MedioAlmacenamientoBean> transformarListaMedioAlmacenamiento(
List<Medioalmacenamiento> mediosAlmacenamiento);
/**
* @param dosificacionRegistroMensual
* @return
*/
public abstract DosificacionRegistroMensualBean transformarDosificacionRegistroMensual(
Dosificacionregistromensual dosificacionRegistroMensual);
/**
* @param dosificacionRegistroMensuals
* @return
*/
public abstract DosificacionRegistroMensualBean[] transformarListaDosificacionRegistroMensual(
Collection<Dosificacionregistromensual> dosificacionRegistroMensuals);
/**
* @param listaTemporalPlan
* @return
*/
public abstract List<PlanNecesidadBean> transformarListaPlanNecesidad(
List<Plannecesidad> listaTemporalPlan);
/**
* @param plannecesidad
* @return
*/
public abstract PlanNecesidadBean transformarPlanNecesidad(
Plannecesidad plannecesidad);
/**
* @param listaConceptoRegistroMensual
* @return
*/
public abstract ConceptoRegistroMensualBean[] transformarListaConceptoRegistroMensual(
Collection<Conceptoregistromensual> listaConceptoRegistroMensual);
/**
* @param conceptoRegistroMensual
* @return
*/
public abstract ConceptoRegistroMensualBean transformarConceptoRegistroMensual(
Conceptoregistromensual conceptoRegistroMensual);
/**
* @param conceptoMensual
* @return
*/
public abstract ConceptoMensualBean transformarConceptoMensual(
Conceptomensual conceptoMensual);
/**
* @param tasarealproduccionregmen
* @return
*/
public abstract TasaRealProduccionRegistroMensualBean[] transformarTasaRealProduccionRegMen(
Set<Tasarealprodregistromensual> tasarealproduccionregmen);
/**
* @param tasarealprod
* @return
*/
public abstract TasaRealProduccionBean transformarTasaRealProduccion(
Tasarealproduccion tasarealprod);
/**
* @param tasarealprodregmen
* @return
*/
public abstract TasaRealProduccionRegistroMensualBean transformarTasaRealProduccionRegistroMensual(
Tasarealprodregistromensual tasarealprodregmen);
/**
* @param listaTasaRealProduccion
* @return
*/
public abstract List<TasaRealProduccionBean> transformarListaTasaRealProduccion(
List<Tasarealproduccion> listaTasaRealProduccion);
/**
* @param capacidadoperativaregistromensus
* @return
*/
public abstract CapacidadOperativaRegistroMensualBean[] transformarListaCapacidadOperativaRM(
Set<Capacidadoperativaregistromensu> capacidadoperativaregistromensus);
/**
* @param listaCapOperRegMen
* @return
*/
public abstract List<CapacidadOperativaRegistroMensualBean> transformarListaCapacidadOperativaRegistroMensual(
Set<Capacidadoperativaregistromensu> listaCapOperRegMen);
/**
* @param movimientos
* @return
*/
public abstract List<MovimientoBean> transformarListaMovimiento(
List<Movimiento> movimientos);
/**
* @param capacidadOperativa
* @return
*/
public abstract CapacidadOperativaBean transformarCapacidadOperativa(
Capacidadoperativa capacidadOperativa);
/**
* @param tipoCapacidadOperativa
* @return
*/
public abstract TipoCapacidadOperativaBean transformarTipoCapacidadOperativa(
Tipocapacidadoperativa tipoCapacidadOperativa);
/**
* @param movimiento
* @return
*/
public abstract MovimientoBean transformarMovimiento(Movimiento movimiento);
/**
* @param estadoMovimientos
* @return
*/
public abstract List<EstadoMovimientoBean> transformarListaEstadoMovimiento(
List<Estadomovimiento> estadoMovimientos);
/**
* @param estadomovimiento
* @return
*/
public abstract EstadoMovimientoBean transformarEstadoMovimiento(
Estadomovimiento estadomovimiento);
/**
* @param documentomateriales
* @return
*/
public abstract List<DocumentoMaterialBean> transformarListaDocumentoMaterial(
List<Documentomaterial> documentomateriales);
/**
* @param documentomaterial
* @return
*/
public abstract DocumentoMaterialBean transformarDocumentoMaterial(
Documentomaterial documentomaterial);
/**
* @param tipoDocuentomateriales
* @return
*/
public abstract List<TipoDocumentoMaterialBean> transformarListaTipoDocumentoMaterial(
List<Tipodocumentomaterial> tipoDocuentomateriales);
/**
* @param tipodocumentomaterial
* @return
*/
public abstract TipoDocumentoMaterialBean transformarTipoDocumentoMaterial(
Tipodocumentomaterial tipodocumentomaterial);
/**
* @param periodosContables
* @return
*/
public abstract List<PeriodoContableBean> transformarListaPeriodoContable(
List<Periodocontable> periodosContables);
/**
* @param periodoContable
* @return
*/
public abstract PeriodoContableBean transformarPeriodoContable(
Periodocontable periodoContable);
/**
* @param movimientoAjustes
* @return
*/
public abstract List<MovimientoAjusteBean> transformarListaMovimientoAjuste(
List<Movimientoajuste> movimientoAjustes);
/**
* @param movimientoajuste
* @return
*/
public abstract MovimientoAjusteBean transformarMovimientoAjuste(
Movimientoajuste movimientoajuste);
/**
* @param consumoComponentePuestoTrabajos
* @return
*/
public abstract List<ConsumoComponentePuestoTrabajoBean> transformarListaConsumoComponentePuestoTrabajo(
List<Consumocomponentepuestotrabajo> consumoComponentePuestoTrabajos);
/**
* @param consumoComponentePuestoTrabajo
* @return
*/
public abstract ConsumoComponentePuestoTrabajoBean transformarConsumoComponentePuestoTrabajo(
Consumocomponentepuestotrabajo consumoComponentePuestoTrabajo);
/**
* @param listaDataObjects
* @return
*/
public abstract List<ConsumoComponenteAjusteBean> transformarListaConsumoComponenteAjuste(
List<Consumocomponenteajuste> listaDataObjects);
/**
* @param dataObject
* @return
*/
public abstract ConsumoComponenteAjusteBean transformarConsumoComponenteAjuste(
Consumocomponenteajuste dataObject);
/**
* @param listaDataObjects
* @return
*/
public abstract List<PuestoTrabajoProduccionBean> transformarListaPuestoTrabajoProduccion(
List<Puestotrabajoproduccion> listaDataObjects);
/**
* @param dataObject
* @return
*/
public abstract PuestoTrabajoProduccionBean transformarPuestoTrabajoProduccion(
Puestotrabajoproduccion dataObject);
/**
* @param ajusteProductos
* @return
*/
public abstract List<AjusteProductoBean> transformarListaAjusteProducto(
List<Ajusteproducto> ajusteProductos);
/**
* @param ajusteProducto
* @return
*/
public abstract AjusteProductoBean transformarAjusteProducto(
Ajusteproducto ajusteProducto);
/**
* @param estadoAjusteProductos
* @return
*/
public abstract List<EstadoAjusteProductoBean> transformarListaEstadoAjusteProducto(
List<Estadoajusteproducto> estadoAjusteProductos);
/**
* @param estadoAjusteProducto
* @return
*/
public abstract EstadoAjusteProductoBean transformarEstadoAjusteProducto(
Estadoajusteproducto estadoAjusteProducto);
/**
* @param balanceProductos
* @return
*/
public abstract List<BalanceProductoBean> transformarListaBalanceProducto(
List<Balanceproducto> balanceProductos);
/**
* @param balanceProducto
* @return
*/
public abstract BalanceProductoBean transformarBalanceProducto(
Balanceproducto balanceProducto);
/**
* @param tipoBalances
* @return
*/
public abstract List<TipoBalanceBean> transformarListaTipoBalance(
List<Tipobalance> tipoBalances);
/**
* @param tipoBalance
* @return
*/
public abstract TipoBalanceBean transformarTipoBalance(
Tipobalance tipoBalance);
/**
* @param plantillaGrupoAjustes
* @return
*/
public abstract List<PlantillaGrupoAjusteBean> transformarListaPlantillaGrupoAjuste(
List<Plantillagrupoajuste> plantillaGrupoAjustes);
/**
* @param plantillaGrupoAjuste
* @return
*/
public abstract PlantillaGrupoAjusteBean transformarPlantillaGrupoAjuste(
Plantillagrupoajuste plantillaGrupoAjuste);
/**
* @param plantillaAjusteProductos
* @return
*/
public abstract List<PlantillaAjusteProductoBean> transformarListaPlantillaAjusteProducto(
List<Plantillaajusteproducto> plantillaAjusteProductos);
/**
* @param plantillaAjusteProducto
* @return
*/
public abstract PlantillaAjusteProductoBean transformarPlantillaAjusteProducto(
Plantillaajusteproducto plantillaAjusteProducto);
/**
* @param parteDiarios
* @return
*/
public abstract List<ParteDiarioBean> transformarListaParteDiario(
List<Partediario> parteDiarios);
/**
* @param parteDiario
* @return
*/
public abstract ParteDiarioBean transformarParteDiario(
Partediario parteDiario);
/**
* @param produccionPuestoTrabajos
* @return
*/
public abstract List<ProduccionPuestoTrabajoBean> transformarListaProduccionPuestoTrabajos(
ArrayList<Produccionpuestotrabajo> produccionPuestoTrabajos);
/**
* @param produccionPuestoTrabajo
* @return
*/
public abstract ProduccionPuestoTrabajoBean transformarProduccionPuestoTrabajo(
Produccionpuestotrabajo produccionPuestoTrabajo);
/**
* @param tablasOperaciones
* @return
*/
public abstract List<TablaOperacionBean> transformarListaTablaOperaciones(
ArrayList<Tablaoperacion> tablasOperaciones);
/**
* @param tablaOperacion
* @return
*/
public abstract TablaOperacionBean transformarTablaOperaciones(
Tablaoperacion tablaOperacion);
/**
* @param productosGenerados
* @return
*/
public abstract List<ProductoGeneradoBean> transformarListaProductosGenerados(
ArrayList<Productogenerado> productosGenerados);
/**
* @param productoGenerado
* @return
*/
public abstract ProductoGeneradoBean transformarProductoGenerado(
Productogenerado productoGenerado);
/**
* @param consumoPuestoTrabajos
* @return
*/
public abstract List<ConsumoPuestoTrabajoBean> transformarListaConsumoPuestoTrabajo(
ArrayList<Consumopuestotrabajo> consumoPuestoTrabajos);
/**
* @param consumoPuestoTrabajo
* @return
*/
public abstract ConsumoPuestoTrabajoBean transformarConsumoPuestoTrabajo(
Consumopuestotrabajo consumoPuestoTrabajo);
/**
* @param produccionesDiarias
* @return
*/
public abstract List<ProduccionDiariaBean> transformarListaProduccionDiaria(
ArrayList<Producciondiaria> produccionesDiarias);
/**
* @param produccionDiaria
* @return
*/
public abstract ProduccionDiariaBean transformarProduccionDiaria(
Producciondiaria produccionDiaria);
/**
* @param produccionDiaria
* @return
*/
public abstract ProduccionDiariaBean transformarProduccionDiariaBasico(
Producciondiaria produccionDiaria);
/**
* @param tablaKardexes
* @return
*/
public abstract List<TablaKardexBean> transformarListaTablaKardex(
List<Tablakardex> tablaKardexes);
/**
* @param tablaKardex
* @return
*/
public abstract TablaKardexBean transformarTablaKardex(
Tablakardex tablaKardex);
/**
* @param valoresPromVariablesCalidades
* @return
*/
public abstract List<ValorPromVariableCalidadBean> transformarListaValorPromedioVarCalidad(
ArrayList<Valorpromvariablecalidad> valoresPromVariablesCalidades);
/**
* @param valorPromVariableCalidad
* @return
*/
public abstract ValorPromVariableCalidadBean transformarValorPromedioVarCalidad(
Valorpromvariablecalidad valorPromVariableCalidad);
/**
* @param productosVariableCalidad
* @return
*/
public abstract List<ProductoVariableCalidadBean> transformarListaProductoVariableCalidad(
List<Productovariablecalidad> productosVariableCalidad);
/**
* @param productoVariableCalidad
* @return
*/
public abstract ProductoVariableCalidadBean transformarProductoVariableCalidad(
Productovariablecalidad productoVariableCalidad);
/**
* @param variablesCalidad
* @return
*/
public abstract List<VariableCalidadBean> transformarListaVariableCalidad(
List<Variablecalidad> variablesCalidad);
/**
* @param variableCalidad
* @return
*/
public abstract VariableCalidadBean transformarVariableCalidad(
Variablecalidad variableCalidad);
/**
* @param factorKardexes
* @return
*/
public abstract List<FactorKardexBean> transformarListaFactorKardex(
ArrayList<Factorvariacionpuestotrabajo> factorKardexes);
/**
* @param factorKardex
* @return
*/
public abstract FactorKardexBean transformarFactorKardex(
Factorvariacionpuestotrabajo factorKardex);
/**
* @param consumoComponentes
* @return
*/
public abstract List<ConsumoComponenteBean> transformarListaConsumoComponente(
List<Consumocomponente> consumoComponentes);
/**
* @param consumoComponente
* @return
*/
public abstract ConsumoComponenteBean transformarConsumoComponente(
Consumocomponente consumoComponente);
/**
* @param estadopartediario
* @return
*/
public abstract List<EstadoParteDiarioBean> transformarListaEstadoParteDiario(
List<Estadopartediario> estadopartediario);
/**
* @param estadoParteDiario
* @return
*/
public abstract EstadoParteDiarioBean transformarEstadoParteDiario(
Estadopartediario estadoParteDiario);
/**
* @param ajusteProducciones
* @return
*/
public abstract List<AjusteProduccionBean> transformarListaAjusteProduccion(
List<Ajusteproduccion> ajusteProducciones);
/**
* @param ajusteProduccion
* @return
*/
public abstract AjusteProduccionBean transformarAjusteProduccion(
Ajusteproduccion ajusteProduccion);
/**
* @param estadosAjusteProduccion
* @return
*/
public abstract List<EstadoAjusteProduccionBean> transformarListaEstadoAjusteProduccion(
List<Estadoajusteproduccion> estadosAjusteProduccion);
/**
* @param estadoAjusteProduccion
* @return
*/
public abstract EstadoAjusteProduccionBean transformarEstadoAjusteProduccion(
Estadoajusteproduccion estadoAjusteProduccion);
/**
* @param columnaReporte
* @return
*/
public abstract ColumnaReporteBean transformarColumnaPlantillaReporte(
Columnareporte columnaReporte);
/**
* @param columnasReporte
* @return
*/
public abstract List<ColumnaReporteBean> transformarListaColumnaPlantillaReporte(
Set<Columnareporte> columnasReporte);
/**
* @param estadoOrdenProduccion
* @return
*/
public abstract EstadoOrdenProduccionBean transformarEstadoOrdenProduccionBean(
Estadoordenproduccion estadoOrdenProduccion);
public abstract List<EstadoOrdenProduccionBean> transformarListaEstadoOrdenProduccionBean(
List<Estadoordenproduccion> listaEstadoordenProduccion);
/**
* @param plantillasProducto
* @return
*/
public abstract List<PlantillaProductoBean> transformarListaPlantillaProducto(
List<Plantillaproducto> plantillasProducto);
/**
* @param estado
* @return
*/
public abstract EstadoColumnaReporteBean transformarEstadoColumnaReporte(
Estadocolumnareporte estado);
/**
* @param estados
* @return
*/
public abstract List<EstadoColumnaReporteBean> transformarListaEstadoColumnaReporte(
List<Estadocolumnareporte> estados);
/**
* @param notificaciondiaria
* @return
*/
public abstract NotificacionDiariaBean transformarNotificacionDiaria(
Notificaciondiaria notificaciondiaria);
/**
* @param notificaciondiaria
* @return
*/
public abstract NotificacionDiariaBean transformarNotificacionDiariaSimple(
Notificaciondiaria notificaciondiaria);
/**
* @param notificacionesDiaria
* @return
*/
public abstract List<NotificacionDiariaBean> transformarListaNotificacionDiaria(
List<Notificaciondiaria> notificacionesDiaria);
/**
* @param notificacionesDiaria
* @return
*/
public abstract List<NotificacionDiariaBean> transformarListaNotificacionDiariaSimple(
List<Notificaciondiaria> notificacionesDiaria);
/**
* @param tablerocontrol
* @return
*/
public abstract TableroControlBean transformarTableroControl(
Tablerocontrol tablerocontrol);
/**
* @param notificacionoperacion
* @return
*/
public abstract NotificacionOperacionBean transformarNotificacionOperacion(
Notificacionoperacion notificacionoperacion);
/**
* @param notificacionesOperacion
* @return
*/
public abstract Set<NotificacionOperacionBean> transformarListaNotificacionOperacion(
Set<Notificacionoperacion> notificacionesOperacion);
public abstract RegistroReporteEcsBean TransformarRegistroReporteEcs(
Registroreporteecs registroreporteecs);
/**
* @param notificacionproduccion
* @return
*/
public abstract NotificacionProduccionBean transformarNotificacionProduccion(
Notificacionproduccion notificacionproduccion);
/**
* @param notificacionesProduccion
* @return
*/
public abstract Set<NotificacionProduccionBean> transformarListaNotificacionProduccion(
Set<Notificacionproduccion> notificacionesProduccion);
/**
* @param hora
* @return
*/
public abstract HoraBean transformarHora(Hora hora);
/**
* @param horaBeans
* @return
* @throws AplicacionException
*/
public abstract List<HoraBean> transformarListaHora(List<Hora> horaBeans)
throws AplicacionException;
/**
* @param tablerosControl
* @return
*/
public abstract List<TableroControlBean> transformarListaTableroControl(
List<Tablerocontrol> tablerosControl);
/**
* @param notificacionDiariaBean
* @return
*/
abstract Notificaciondiaria transformarNotificacionDiariaBean(
NotificacionDiariaBean notificacionDiariaBean);
/**
* @param usuarioBean
* @return
*/
public abstract Usuario transformarUsuarioBean(UsuarioBean usuarioBean);
/**
* @param personaBean
* @return
*/
public abstract Persona transformarPersonaBean(PersonaBean personaBean);
/**
* @param tableroControlBean
* @return
*/
public abstract Tablerocontrol transformarTableroControlBean(
TableroControlBean tableroControlBean);
/**
* @param lineaNegocioBean
* @return
*/
public abstract Lineanegocio transformarLineaNegocioBean(
LineaNegocioBean lineaNegocioBean);
/**
* @param unidadBean
* @return
*/
public abstract Unidad transformarUnidadBean(UnidadBean unidadBean);
/**
* @param componenteNotificacionHO
* @return
*/
public ComponenteNotificacionBean transformarComponenteNotificacion(
Componentenotificacion componenteNotificacionHO);
/**
* @param componentesNotificacionHO
* @return
*/
public List<ComponenteNotificacionBean> tranformarListaComponenteNotificacion(
List<Componentenotificacion> componentesNotificacionHO);
/**
* @param listaHojaruta
* @return
*/
public abstract List<HojaRutaBean> transformarListaHojaRutaParaConsulta(
List<Hojaruta> listaHojaruta);
/**
* @param lineaNegocios
* @return
*/
public abstract List<LineaNegocioBean> transformarListaLineaNegocioParaCombos(
List<Lineanegocio> lineaNegocios);
/**
* @param unidades
* @return
*/
public abstract List<UnidadBean> transformarListaUnidadParaCombos(
List<Unidad> unidades);
/**
* @param procesos
* @return
*/
public abstract List<ProcesoBean> transformarListaProcesoParaCombos(
List<Proceso> procesos);
/**
* @param productos
* @return
*/
public abstract List<ProductoBean> transformarListaProductoParaCombos(
List<Producto> productos);
/**
* @param tipoCategoriaProducto
* @return
*/
public abstract TipoCategoriaProductoBean transformarTipoCategoriaProducto(
Tipocategoriaproducto tipoCategoriaProducto);
/**
* @param listaTipoCategoriaProducto
* @return
*/
public abstract List<TipoCategoriaProductoBean> transformarListaTipoCategoriaProducto(
List<Tipocategoriaproducto> listaTipoCategoriaProducto);
public List<OperacionBean> transformarListaOperacionModificarHojaRuta(
List<Operacion> listaOperacion);
public OperacionBean transformarOperacionModificarHojaRuta(
Operacion operacion);
/**
* @param plananual
* @return PlanAnualBean
*/
public abstract PlanAnualBean transformarPlanAnualParaConsulta(
Plananual plananual);
/**
* @param estados
* @return
*/
public List<EstadoUsuarioBean> transformarListaEstados(
List<Estadousuario> estados);
/**
* @param grupos
* @return
*/
public List<GrupoUsuarioBean> transformarListaGruposUsuario(
List<Grupousuario> grupos);
/**
* @param cargos
* @return
*/
public List<CargoBean> transformarListaCargos(List<Cargo> cargos);
/**
* @param usuarioGrupoLista
* @return
*/
public List<UsuarioGrupoUsuarioBean> transformarListaUsuarioGruposUsuarios(
List<Usuariogrupousuario> usuarioGrupoLista);
/**
* @param estadoBean
* @return
*/
public Estadousuario transformarEstadoUsuarioDTO(
EstadoUsuarioBean estadoBean);
/**
* @param grupoBean
* @return
*/
public Grupousuario transformarGrupoUsuarioDTO(GrupoUsuarioBean grupoBean);
/**
* @param grupoBean
* @param usuario
* @return
*/
public Usuariogrupousuario transformarUsuarioGrupoUsuarioDTO(
UsuarioGrupoUsuarioBean grupoBean, Usuario usuario);
public abstract List<RendimientoTermicoBean> transformarListaRendimientoTermico(
List<RendimientoTermico> listRendimientoTermico)
throws LogicaException;
public abstract RendimientoTermicoBean transformarRendimientoTermico(
RendimientoTermico rendimientoTermico);
public abstract ParametroSistemaBean transformarParametroSistema(
ParametroSistema parametro);
public abstract OrdenReporteBean transformarOrdenReporte(
Ordenreporte ordenreporte);
public abstract List<OrdenReporteBean> transformarListaOrdenResumen(
List<Ordenreporte> listaOrdenesReporte);
public abstract List<ParametroSistemaBean> transformarParametrosSistema(
List<ParametroSistema> parametros);
public abstract List<TipoConsumoBean> transformarListaTipoConsumo(
List<Tipoconsumo> listaTipoConsumo);
public CapacidadBolsaProductoBean transformarCapacidadBolsaProduccion(
Capacidadbolsaproducto capacidadbolsaproducto);
/**
* @param cubicacionProductos
* @return
*/
public abstract List<CubicacionProductoBean> transformarListaCubicacionProducto(List<Cubicacionproducto> cubicacionProductos);
/**
* @param estadosCubicacion
* @return
*/
public abstract List<EstadoCubicacionBean> transformarListaEstadoCubicacion(List<Estadocubicacion> estadosCubicacion);
}
| [
"[email protected]"
] | |
db54a635c9e9846755c1dd48ba369de52e79a503 | 117db017c2e7c8e2c0803f85cb8e66625a07b4b4 | /src/com/example/watchwaterpollution/WaterManager.java | 4df88aae4549072d25069d69ed797690fb5fa78b | [] | no_license | sausame/water | 7a8d7e2527a5fdf4e6eabe386479cbb7e31001bc | 9bdff60924a55459ce961b8d4fa6e856948ce02b | refs/heads/master | 2016-09-06T09:29:39.257670 | 2013-10-21T09:01:01 | 2013-10-21T09:01:01 | 13,644,764 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,434 | java | package com.example.watchwaterpollution;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class WaterManager {
private static final String TAG = "WaterManager";
private JSONArray mJsonArray = null;
private int mCurrentIndex = 0;
private String mPathname;
public void setPathname(String path) {
mPathname = path;
}
public int getSize() {
return mJsonArray == null ? 0 : mJsonArray.length();
}
public void load() {
try {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(mPathname)));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
setWaterBuffer(sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public void save() {
if (null == mJsonArray || 0 == mJsonArray.length()) {
Log.e(TAG, "Nothing is needed to save.");
return;
}
try {
String jsonString = mJsonArray.toString();
OutputStreamWriter osw = new OutputStreamWriter(
new FileOutputStream(mPathname));
osw.write(jsonString, 0, jsonString.length());
osw.flush();
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void setWaterBuffer(String buffer) {
try {
mJsonArray = new JSONArray(buffer);
mCurrentIndex = 0;
if (0 == mJsonArray.length()) {
mJsonArray = null;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void reset() {
mCurrentIndex = 0;
}
public boolean add(Water water) {
reset();
if (mJsonArray == null) {
mJsonArray = new JSONArray();
}
mJsonArray.put(water.toJSONObject());
return true;
}
public boolean del(int id) {
reset();
JSONArray array = new JSONArray();
Water water = null;
for (; null != (water = getWater()); id--) {
if (0 == id) {
continue;
}
array.put(water.toJSONObject());
}
mJsonArray = array;
return true;
}
public boolean modify(int id, Water water) {
if (!del(id)) {
return false;
}
return add(water);
}
public Water getWater() {
if (null == mJsonArray || mCurrentIndex >= mJsonArray.length()) {
Log.d(TAG, (mJsonArray == null) ? "NO array" : "" + mCurrentIndex
+ " >= " + mJsonArray.length());
return null;
}
try {
JSONObject obj = mJsonArray.getJSONObject(mCurrentIndex++);
return Water.parseWater(obj);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public String toString() {
String str = "\n-------------------------------------------------------------------------------\n";
str += "Pathname: " + mPathname + "\n";
try {
str += mJsonArray.toString(2);
} catch (JSONException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
str += "\n-------------------------------------------------------------------------------\n";
return str;
}
public static void test() {
WaterManager manager = new WaterManager();
manager.setPathname("/sdcard/water.json");
manager.load();
Log.i(TAG, manager.toString());
manager.add(Water.createRandomWater());
manager.save();
Log.i(TAG, manager.toString());
}
}
| [
"[email protected]"
] | |
7df9a232a1cf1b4a4522717b3575eb650ec9182c | 419e0607d4bb1ff298faca921447ee4b35e5b894 | /plugins/es-analysis-common/src/main/java/org/elasticsearch/analysis/common/RussianStemTokenFilterFactory.java | 24bb509530c1b22d70a09c22995954893a75b970 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | crate/crate | 7af793e2f709b77a5addc617d6e9dbba452d4e68 | 8acb044a7cdbab048b045854d0466fccc2492550 | refs/heads/master | 2023-08-31T07:17:42.891453 | 2023-08-30T15:09:09 | 2023-08-30T17:13:14 | 9,342,529 | 3,540 | 639 | Apache-2.0 | 2023-09-14T21:00:43 | 2013-04-10T09:17:16 | Java | UTF-8 | Java | false | false | 1,548 | java | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.analysis.common;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.snowball.SnowballFilter;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.AbstractTokenFilterFactory;
public class RussianStemTokenFilterFactory extends AbstractTokenFilterFactory {
public RussianStemTokenFilterFactory(IndexSettings indexSettings, Environment environment, String name, Settings settings) {
super(indexSettings, name, settings);
}
@Override
public TokenStream create(TokenStream tokenStream) {
return new SnowballFilter(tokenStream, "Russian");
}
} | [
"[email protected]"
] | |
0d8fb354b1ff4caffa2c4e06d42669fb2759cb5b | 651e5536597803f0d8b292fb62fca4957a419d43 | /src/library/catalog/SearchResult.java | 266b7f4042bcf5f3f068a6c911641aa3e8a7a0cb | [] | no_license | Nihat17/Library-Catalog-SWING-JAVA-app | 6638c7e31530d8cafc3183c898b6f11a62c2d5c8 | 46e4bda1a2e76f87bb4e121a350497fbe95ac00e | refs/heads/master | 2020-03-31T23:25:53.516184 | 2018-10-11T21:23:25 | 2018-10-11T21:23:25 | 152,655,667 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,518 | java | /*
* 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 library.catalog;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author marshall
*/
public class SearchResult extends javax.swing.JDialog {
/**
* Creates new form SearchResult
*/
Return retObj = new Return();
int userID = 0;
int selectedRow = -1;
boolean putDetsToTable = true;
public SearchResult(java.awt.Frame parent, boolean modal, String title,
String author, int userID) {
super(parent, modal);
setLocationRelativeTo(parent);
initComponents();
this.userID = userID;
searchBook(title, author);
}
private void searchBook(String title, String author) {
List<ArrayList> listOfResults = new ArrayList<>();
listOfResults = retObj.searchBook(title, author);
retObj.setBookTable(bookDetTable, listOfResults);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
bookDetTable = new javax.swing.JTable();
getButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
setDateLabel = new javax.swing.JLabel();
setDateField = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
bookDetTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ISBN", "Title", "Author", "Genre", "Edition", "Publication Date", "DueDate"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane2.setViewportView(bookDetTable);
getButton.setText("Get the book!");
getButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
getButtonActionPerformed(evt);
}
});
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
setDateLabel.setText("Set due date:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(55, 55, 55)
.addComponent(getButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(127, 127, 127))
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(setDateLabel)
.addGap(18, 18, 18)
.addComponent(setDateField, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(375, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane2)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(setDateLabel)
.addComponent(setDateField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(getButton)
.addComponent(cancelButton)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
putDetsToTable = false;
this.dispose();
}//GEN-LAST:event_cancelButtonActionPerformed
private void getButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getButtonActionPerformed
String date = getCurrentDate();
Book book = new Book();
Return retObj = new Return();
if(checkIfGivenDateIsValid()){
int ISBN = getDetailsOnSelectedRow();
if(ISBN > 0){
book.setDueDate(setDateField.getText());
book.setStatus(StatusType.notAvailable);
try {
if(retObj.modifyBookTableAfterTaken(book, userID, ISBN)){
JOptionPane.showMessageDialog(this, "You took the book successfully. \n"
+ "Please remember to bring it back on " + setDateField.getText(),
"Information", JOptionPane.INFORMATION_MESSAGE);
this.dispose();
}
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(SearchResult.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(ISBN < 0){
JOptionPane.showMessageDialog(this, "Please select one of these list on table.",
"Warning",JOptionPane.ERROR_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(this, "Please use a date in dd/mm/yyyy format");
}
}//GEN-LAST:event_getButtonActionPerformed
private int getDetailsOnSelectedRow() {
selectedRow = bookDetTable.getSelectedRow();
String ISBN = "";
if(selectedRow > -1){
ISBN = (String) bookDetTable.getValueAt(selectedRow, 0);
}
return Integer.parseInt(ISBN);
}
private boolean checkIfGivenDateIsValid(){
boolean output = true;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
try{
LocalDate date = formatter.parse(setDateField.getText(), LocalDate::from);
}
catch(DateTimeParseException ex){
output = false;
}
return output;
}
public List getListForTable() {
List bookDetails = new ArrayList();
List listOfLists = new ArrayList();
if(putDetsToTable){
for(int i = 0; i < 6; i++){
bookDetails.add(bookDetTable.getValueAt(selectedRow, i));
}
bookDetails.add(setDateField.getText());
listOfLists.add(bookDetails);
}
return listOfLists;
}
private void checkIfDateIsPassed(String date) {
int inputYear, inputMonth, inputDay;
int currYear, currMonth, currDay;
String inputDate = setDateField.getText();
String inputYearStr = "", inputMonthStr = "", inputDayStr= "";
String currYearStr = "", currMonthStr = "", currDayStr = "";
String str = "";
boolean checkYear, checkMonth, checkDay;
for(int c = 0; c < 2; c++){
checkYear = true;
checkMonth = false;
checkDay = false;
for(int i = 0; i < setDateField.getText().length(); i++){
if(c == 0){
if(!"/".equals(inputDate.substring(i, ++i)) && checkYear){
inputYearStr += inputDate.substring(i - 1, i);
}
if(inputDate.substring(i, ++i).equals("/")){
checkYear = false;
checkMonth = true;
continue;
}
if(!inputDate.substring(i, ++i).equals("/") && checkMonth){
inputMonthStr += inputDate.substring(i - 1, i);
}
if(inputDate.substring(i, ++i).equals("/")){
checkMonth = false;
checkDay = true;
continue;
}
if(!inputDate.substring(i, ++i).equals("/") && checkDay){
inputDayStr += inputDate.substring(i - 1, i);
}
if(inputDate.substring(i, ++i).equals("/")){
checkDay = false;
continue;
}
}
else{
if(!"/".equals(date.substring(i, ++i)) && checkYear){
currYearStr += date.substring(i - 1, i);
}
if(date.substring(i, ++i).equals("/")){
checkYear = false;
checkMonth = true;
continue;
}
if(!date.substring(i, ++i).equals("/") && checkMonth){
currMonthStr += date.substring(i - 1, i);
}
if(date.substring(i, ++i).equals("/")){
checkMonth = false;
checkDay = true;
continue;
}
if(!date.substring(i, ++i).equals("/") && checkDay){
currDayStr += date.substring(i - 1, i);
}
if(date.substring(i, ++i).equals("/")){
checkDay = false;
continue;
}
}
}
}
int m = 0;
}
private String getCurrentDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Calendar cal = Calendar.getInstance();
String date = dateFormat.format(cal.getTime());
return date;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTable bookDetTable;
private javax.swing.JButton cancelButton;
private javax.swing.JButton getButton;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextField setDateField;
private javax.swing.JLabel setDateLabel;
// End of variables declaration//GEN-END:variables
}
| [
"[email protected]"
] | |
f10a7747505ec9230746f8e806e4141019fc03f3 | b3942abc20b7b6a46c249de1c6bc7320c592b65f | /java/eclipse-workspace/hellowMaven/src/test/java/com/AndyYUE/maven/HellowMavenTest.java | c51b510366017300883d5af81b90e6fcaf537d42 | [] | no_license | dbyqs21/My_Code | b093da2a953d8f3d200a61cf1101994bfb698c3c | c14bc4e6b01855cbf1376d417918df84f1c1bdd3 | refs/heads/master | 2021-07-17T10:07:52.856835 | 2017-10-08T13:17:57 | 2017-10-08T13:17:57 | 100,031,123 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 293 | java | package com.AndyYUE.maven;
import org.junit.Test;
import static junit.framework.Assert.*;
public class HellowMavenTest
{
@Test
public void sayHellowTest()
{
HellowMaven hm = new HellowMaven();
String result = hm.sayHellow("zhangsan");
assertEquals("hellow zhangsan",result);
}
} | [
"[email protected]"
] | |
5708c1dc32876251e9b81c5d3d21e4f6fe2f7177 | 02cf6b8c574bdcf7955f844fa236a4a37c6a6c47 | /app/src/main/java/org/team2767/deadeye/DeadeyeView.java | ef5b6355d33e0b5055d2274a07f7473fb290f30d | [
"MIT"
] | permissive | strykeforce/deadeye-android | e927e116abba3ff6f1b7ebeec283558d9778f6af | e070d83c9732de731f3336e697544838175dead2 | refs/heads/master | 2021-07-18T04:51:53.642320 | 2021-04-29T09:32:06 | 2021-04-29T09:32:06 | 113,485,090 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,320 | java | package org.team2767.deadeye;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.team2767.deadeye.di.Injector;
import timber.log.Timber;
/** Deadeye main view. */
public class DeadeyeView extends GLSurfaceView {
private final DeadeyeRenderer renderer;
public DeadeyeView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
setEGLContextClientVersion(2);
renderer = Injector.get().deadeyeRendererFactory().create(this);
setRenderer(renderer);
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
Timber.tag("LifeCycles");
Timber.d("DeadeyeView constructed");
}
public DeadeyeView(Context context) {
this(context, null);
}
public void setHueRange(int low, int high) {
renderer.setHueRange(low, high);
}
public void setSaturationRange(int low, int high) {
renderer.setSaturationRange(low, high);
}
public void setValueRange(int low, int high) {
renderer.setValueRange(low, high);
}
public void setMonitor(FrameProcessor.Monitor monitor) {
renderer.setMonitor(monitor);
}
public void setContour(FrameProcessor.Contours contour) {
renderer.setContours(contour);
}
}
| [
"[email protected]"
] | |
77d7da4812b277d88af08fbf1b307ee773a9abfd | 28741ef7a80f0fa7c3f9ef14252f0958945580f3 | /Java/Java11-14-master/Java11-14-master/Lab 13/Lab12/src/LoginAndPassword.java | 290daf569a12cb2cd3995c68542aff286d9a56cf | [] | no_license | alyona0stepashka/Java-2018-2019 | f0c50fd5e2d0a6a54ed0c36fcb9397441f0f2c20 | 588241bba4540f996a594598cad520dbf80efe29 | refs/heads/master | 2020-04-25T17:49:50.056644 | 2019-02-28T17:39:37 | 2019-02-28T17:39:37 | 172,962,826 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,479 | java | import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;
import java.time.LocalDateTime;
@WebServlet(name = "LoginAndPassword", urlPatterns = {"/LoginAndPassword"})
public class LoginAndPassword extends HttpServlet
{
// JDBC driver name and database URL
//static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/users";
static final String USER = "root";
static final String PASS = "root";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
static String Role = "";
private String IsCorrectLoginAndPassword(String login, String password, HttpServletResponse response) throws IOException
{
Connection conn = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
//response.getWriter().println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
String query;
query = "SELECT " + " Role, " + " Name " + "FROM userstable WHERE Login='" + login + "' AND Password='" + password + "'";
PreparedStatement stm = conn.prepareStatement(query);
ResultSet rs = stm.executeQuery();
if(rs.next())
{
Role = rs.getString("Role");
return rs.getString("Name");
}
} catch(Exception e)
{
System.out.println(e.getMessage());
} finally
{
if(conn != null)
try
{
conn.close();
} catch(SQLException e)
{
e.printStackTrace();
}
}
return "";
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String Login = request.getParameter("Login");
System.out.println(Login);
String Password = request.getParameter("Password");
System.out.println(Password);
String name = "";
if((name = IsCorrectLoginAndPassword(Login, Password, response)) != "")
{
//response.getWriter().println("Name = " + name);
//response.getWriter().println("Role = " + Role);
//response.getWriter().println("Time now = " + LocalDateTime.now());
request.getServletContext().log("Auth " + name + " is succesful");
HttpSession session = request.getSession(true);
session.setAttribute("Role", Role);
session.setAttribute("TimeStart", LocalDateTime.now());
session.setAttribute("Name", name);
Cookie[] last = request.getCookies();
boolean flag = false;
for(int i = 0; i < last.length; i++)
{
Cookie buffer = last[i];
if(buffer.getName() == "KolVisits")
{
int gg = Integer.parseInt(buffer.getValue() + 1);
buffer.setValue(Integer.toString(gg));
flag = true;
}
}
if(!flag)
{
Cookie cc = new Cookie("KolVisits", "1");
response.addCookie(cc);
}
Cookie cookie = new Cookie("LastSession", LocalDateTime.now().toString());
response.addCookie(cookie);
response.addCookie(new Cookie("Role", Role));
request.setAttribute("Role", Role);
response.setHeader("Role", Role);
request.getRequestDispatcher("/GoodLogin.jsp").forward(request, response);
} else
{
//response.getWriter().println("Error with your roots");
//response.getWriter().println("May be you want to register?");
response.getWriter().println("<html><head><title>May be register?</title></head><body><p>May be you want to register?)</p><a href=\"Registration.jsp\">Go to registration</a></body></html>");
}
}
}
| [
"[email protected]"
] | |
8c67118eced94ba31453e841c5756a4e33e8ec92 | 76daa024dc7e129ea719502853dc523e9fcea7e8 | /starter/app/build/tmp/kapt3/stubs/debug/com/raywenderlich/android/redditclone/models/Post.java | 4175986c99ded91fb9f7dd92a729224d9ac7a227 | [] | no_license | begarss/AdvancedAndroidLabs | 99987e03bb6fcb84af1b075b363491966d590de2 | 553b99290e82281e07a61558a68767551c9c118f | refs/heads/master | 2023-01-19T19:03:45.888970 | 2020-11-29T21:05:22 | 2020-11-29T21:05:22 | 297,145,156 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,685 | java | package com.raywenderlich.android.redditclone.models;
import java.lang.System;
@kotlin.Metadata(mv = {1, 4, 0}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000,\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u000e\n\u0002\b\u0002\n\u0002\u0010\b\n\u0000\n\u0002\u0010\u000b\n\u0002\b\u001a\b\u0086\b\u0018\u00002\u00020\u0001B=\u0012\u0006\u0010\u0002\u001a\u00020\u0003\u0012\u0006\u0010\u0004\u001a\u00020\u0005\u0012\u0006\u0010\u0006\u001a\u00020\u0007\u0012\u0006\u0010\b\u001a\u00020\u0007\u0012\u0006\u0010\t\u001a\u00020\n\u0012\u0006\u0010\u000b\u001a\u00020\f\u0012\u0006\u0010\r\u001a\u00020\u0007\u00a2\u0006\u0002\u0010\u000eJ\t\u0010\u001a\u001a\u00020\u0003H\u00c6\u0003J\t\u0010\u001b\u001a\u00020\u0005H\u00c6\u0003J\t\u0010\u001c\u001a\u00020\u0007H\u00c6\u0003J\t\u0010\u001d\u001a\u00020\u0007H\u00c6\u0003J\t\u0010\u001e\u001a\u00020\nH\u00c6\u0003J\t\u0010\u001f\u001a\u00020\fH\u00c6\u0003J\t\u0010 \u001a\u00020\u0007H\u00c6\u0003JO\u0010!\u001a\u00020\u00002\b\b\u0002\u0010\u0002\u001a\u00020\u00032\b\b\u0002\u0010\u0004\u001a\u00020\u00052\b\b\u0002\u0010\u0006\u001a\u00020\u00072\b\b\u0002\u0010\b\u001a\u00020\u00072\b\b\u0002\u0010\t\u001a\u00020\n2\b\b\u0002\u0010\u000b\u001a\u00020\f2\b\b\u0002\u0010\r\u001a\u00020\u0007H\u00c6\u0001J\u0013\u0010\"\u001a\u00020\f2\b\u0010#\u001a\u0004\u0018\u00010\u0001H\u00d6\u0003J\t\u0010$\u001a\u00020\nH\u00d6\u0001J\t\u0010%\u001a\u00020\u0007H\u00d6\u0001R\u0011\u0010\u0002\u001a\u00020\u0003\u00a2\u0006\b\n\u0000\u001a\u0004\b\u000f\u0010\u0010R\u0011\u0010\u0004\u001a\u00020\u0005\u00a2\u0006\b\n\u0000\u001a\u0004\b\u0011\u0010\u0012R\u0011\u0010\u0006\u001a\u00020\u0007\u00a2\u0006\b\n\u0000\u001a\u0004\b\u0013\u0010\u0014R\u0011\u0010\b\u001a\u00020\u0007\u00a2\u0006\b\n\u0000\u001a\u0004\b\u0015\u0010\u0014R\u0011\u0010\t\u001a\u00020\n\u00a2\u0006\b\n\u0000\u001a\u0004\b\u0016\u0010\u0017R\u0011\u0010\u000b\u001a\u00020\f\u00a2\u0006\b\n\u0000\u001a\u0004\b\u000b\u0010\u0018R\u0011\u0010\r\u001a\u00020\u0007\u00a2\u0006\b\n\u0000\u001a\u0004\b\u0019\u0010\u0014\u00a8\u0006&"}, d2 = {"Lcom/raywenderlich/android/redditclone/models/Post;", "", "author", "Lcom/raywenderlich/android/redditclone/models/Author;", "category", "Lcom/raywenderlich/android/redditclone/models/Category;", "date", "", "description", "id", "", "is_published", "", "title", "(Lcom/raywenderlich/android/redditclone/models/Author;Lcom/raywenderlich/android/redditclone/models/Category;Ljava/lang/String;Ljava/lang/String;IZLjava/lang/String;)V", "getAuthor", "()Lcom/raywenderlich/android/redditclone/models/Author;", "getCategory", "()Lcom/raywenderlich/android/redditclone/models/Category;", "getDate", "()Ljava/lang/String;", "getDescription", "getId", "()I", "()Z", "getTitle", "component1", "component2", "component3", "component4", "component5", "component6", "component7", "copy", "equals", "other", "hashCode", "toString", "app_debug"})
public final class Post {
@org.jetbrains.annotations.NotNull()
private final com.raywenderlich.android.redditclone.models.Author author = null;
@org.jetbrains.annotations.NotNull()
private final com.raywenderlich.android.redditclone.models.Category category = null;
@org.jetbrains.annotations.NotNull()
private final java.lang.String date = null;
@org.jetbrains.annotations.NotNull()
private final java.lang.String description = null;
private final int id = 0;
private final boolean is_published = false;
@org.jetbrains.annotations.NotNull()
private final java.lang.String title = null;
@org.jetbrains.annotations.NotNull()
public final com.raywenderlich.android.redditclone.models.Author getAuthor() {
return null;
}
@org.jetbrains.annotations.NotNull()
public final com.raywenderlich.android.redditclone.models.Category getCategory() {
return null;
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String getDate() {
return null;
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String getDescription() {
return null;
}
public final int getId() {
return 0;
}
public final boolean is_published() {
return false;
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String getTitle() {
return null;
}
public Post(@org.jetbrains.annotations.NotNull()
com.raywenderlich.android.redditclone.models.Author author, @org.jetbrains.annotations.NotNull()
com.raywenderlich.android.redditclone.models.Category category, @org.jetbrains.annotations.NotNull()
java.lang.String date, @org.jetbrains.annotations.NotNull()
java.lang.String description, int id, boolean is_published, @org.jetbrains.annotations.NotNull()
java.lang.String title) {
super();
}
@org.jetbrains.annotations.NotNull()
public final com.raywenderlich.android.redditclone.models.Author component1() {
return null;
}
@org.jetbrains.annotations.NotNull()
public final com.raywenderlich.android.redditclone.models.Category component2() {
return null;
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String component3() {
return null;
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String component4() {
return null;
}
public final int component5() {
return 0;
}
public final boolean component6() {
return false;
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String component7() {
return null;
}
@org.jetbrains.annotations.NotNull()
public final com.raywenderlich.android.redditclone.models.Post copy(@org.jetbrains.annotations.NotNull()
com.raywenderlich.android.redditclone.models.Author author, @org.jetbrains.annotations.NotNull()
com.raywenderlich.android.redditclone.models.Category category, @org.jetbrains.annotations.NotNull()
java.lang.String date, @org.jetbrains.annotations.NotNull()
java.lang.String description, int id, boolean is_published, @org.jetbrains.annotations.NotNull()
java.lang.String title) {
return null;
}
@org.jetbrains.annotations.NotNull()
@java.lang.Override()
public java.lang.String toString() {
return null;
}
@java.lang.Override()
public int hashCode() {
return 0;
}
@java.lang.Override()
public boolean equals(@org.jetbrains.annotations.Nullable()
java.lang.Object p0) {
return false;
}
} | [
"[email protected]"
] | |
4d1f04ec41d1fc4d8f2fe2e51850bfa06515286d | c4448babb35c52c97c28e7666b2dcd0751315658 | /app/src/main/java/com/anlida/smartlock/utils/RxTimerUtil.java | 4e1129c787d519167a159cf75975458414112ffd | [] | no_license | 425296516/smartlock | 1d4ec3bd8c00cbfede364240b28448e7cbb3a40c | 3b25f9fe501e35d7d0ae6bbfc3292f65e97d78cf | refs/heads/master | 2020-06-05T03:05:37.139149 | 2019-10-23T09:19:03 | 2019-10-23T09:19:03 | 192,291,992 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,883 | java | package com.anlida.smartlock.utils;
/**
* Created by zhangcirui on 2018/9/7.
*/
import android.support.annotation.NonNull;
import com.orhanobut.logger.Logger;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
/**
* Rxjava2.x实现轮询定时器.
*
*/
public class RxTimerUtil {
private static Disposable mDisposable;
/**
* milliseconds毫秒后执行next操作
*/
public static void timer(long milliseconds, final IRxNext next) {
Observable.timer(milliseconds, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Long>() {
@Override
public void onSubscribe(@NonNull Disposable disposable) {
mDisposable = disposable;
}
@Override
public void onNext(@NonNull Long number) {
if (next != null) {
next.doNext(number);
}
}
@Override
public void onError(@NonNull Throwable e) {
//取消订阅
cancel();
}
@Override
public void onComplete() {
//取消订阅
cancel();
}
});
}
/**
* 每隔milliseconds毫秒后执行next操作
*/
public static void interval(long milliseconds, final IRxNext next) {
Observable.interval(milliseconds, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Long>() {
@Override
public void onSubscribe(@NonNull Disposable disposable) {
mDisposable = disposable;
}
@Override
public void onNext(@NonNull Long number) {
if (next != null) {
next.doNext(number);
}
}
@Override
public void onError(@NonNull Throwable e) {
}
@Override
public void onComplete() {
}
});
}
/**
* 取消订阅
*/
public static void cancel() {
if (mDisposable != null && !mDisposable.isDisposed()) {
mDisposable.dispose();
Logger.d("====Rx定时器取消======");
}
}
public interface IRxNext {
void doNext(long number);
}
}
| [
"[email protected]"
] | |
be5b0edfb33ce72b80606c651e9326f36efe32aa | 8fddc4db622a5a9e6e5075bcf76decfe35220afe | /src/gui/Transaction.java | 31cf5dfeb35f7aa28d087156ae57fd4f9288e00b | [] | no_license | richlim16/oop-ordering-system | 523c31cb56f008a4508ba85fbc08c8907ac4ca68 | e9810a81b18b18bbd541e1d736ca3b5c91a11f69 | refs/heads/main | 2023-02-08T00:03:54.162614 | 2020-12-30T14:34:11 | 2020-12-30T14:34:11 | 316,720,003 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 303 | java | /*
* 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 gui;
/**
*
* @author Rich Tristan Lim
*/
interface Transaction {
public void send(String msg);
}
| [
"[email protected]"
] | |
8149cce9d075bf56ccac08293243a02bdb04b492 | 5d219e8197528b86a1dfc7b9845b3c476e580ce5 | /app/src/main/java/sventrapopizz/amoledblackthemeshowcase/JamXFragment.java | 6749cb3270de99dcec427789b1326080c8320cc1 | [] | no_license | Sventra/AmoledBlackThemeShowcase | b3f37d8cb08fd8e4602b3d72d6a7fd3db43c495f | 78c61bc60513c8feb3f7437395963c94101eab40 | refs/heads/master | 2022-06-12T21:55:25.543902 | 2022-06-01T19:39:22 | 2022-06-01T19:39:22 | 150,482,584 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 571 | java | package sventrapopizz.amoledblackthemeshowcase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class JamXFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_jamx, container, false);
}
}
| [
"[email protected]"
] | |
cef724c9c543d96fb8ea0da2b6f9b352eb0fcead | 28552d7aeffe70c38960738da05ebea4a0ddff0c | /google-ads/src/main/java/com/google/ads/googleads/v5/resources/CampaignLabelOrBuilder.java | fc0d051320d7bb335991b4e22ce644898ad0813f | [
"Apache-2.0"
] | permissive | PierrickVoulet/google-ads-java | 6f84a3c542133b892832be8e3520fb26bfdde364 | f0a9017f184cad6a979c3048397a944849228277 | refs/heads/master | 2021-08-22T08:13:52.146440 | 2020-12-09T17:10:48 | 2020-12-09T17:10:48 | 250,642,529 | 0 | 0 | Apache-2.0 | 2020-03-27T20:41:26 | 2020-03-27T20:41:25 | null | UTF-8 | Java | false | true | 3,062 | java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v5/resources/campaign_label.proto
package com.google.ads.googleads.v5.resources;
public interface CampaignLabelOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v5.resources.CampaignLabel)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Immutable. Name of the resource.
* Campaign label resource names have the form:
* `customers/{customer_id}/campaignLabels/{campaign_id}~{label_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The resourceName.
*/
java.lang.String getResourceName();
/**
* <pre>
* Immutable. Name of the resource.
* Campaign label resource names have the form:
* `customers/{customer_id}/campaignLabels/{campaign_id}~{label_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for resourceName.
*/
com.google.protobuf.ByteString
getResourceNameBytes();
/**
* <pre>
* Immutable. The campaign to which the label is attached.
* </pre>
*
* <code>.google.protobuf.StringValue campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return Whether the campaign field is set.
*/
boolean hasCampaign();
/**
* <pre>
* Immutable. The campaign to which the label is attached.
* </pre>
*
* <code>.google.protobuf.StringValue campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The campaign.
*/
com.google.protobuf.StringValue getCampaign();
/**
* <pre>
* Immutable. The campaign to which the label is attached.
* </pre>
*
* <code>.google.protobuf.StringValue campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
*/
com.google.protobuf.StringValueOrBuilder getCampaignOrBuilder();
/**
* <pre>
* Immutable. The label assigned to the campaign.
* </pre>
*
* <code>.google.protobuf.StringValue label = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return Whether the label field is set.
*/
boolean hasLabel();
/**
* <pre>
* Immutable. The label assigned to the campaign.
* </pre>
*
* <code>.google.protobuf.StringValue label = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The label.
*/
com.google.protobuf.StringValue getLabel();
/**
* <pre>
* Immutable. The label assigned to the campaign.
* </pre>
*
* <code>.google.protobuf.StringValue label = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
*/
com.google.protobuf.StringValueOrBuilder getLabelOrBuilder();
}
| [
"[email protected]"
] | |
3863c9e220e554ea2ff376b192d0d28162813e83 | 94e3ade0a9cccd9bc2d7e9dd544bba20c7834c03 | /webservice/src/main/java/md/utm/fcim/webservice/controller/UserController.java | dc81f5de4e612d39e92043b6d34543944808754f | [] | no_license | vadimeladii/data-warehouse | efc7a29bc4d94a438f99dd22431d0e3c21b1166f | 198c6988875d87efda4a1e2db14b7dee373c17da | refs/heads/master | 2021-08-30T11:21:10.172639 | 2017-11-22T18:19:39 | 2017-11-22T18:19:39 | 111,717,274 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 343 | java | package md.utm.fcim.webservice.controller;
import md.utm.fcim.webservice.view.UserView;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/user")
public interface UserController {
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
UserView test();
}
| [
"[email protected]"
] | |
6349fea96a60aeda5fe2d23b0a123aa3c8c001fc | 255af43d73078259c53b12117b4f36a99550c67d | /src/org/hopen/jjbus/action/CashOperationController.java | b79ad8f4b09c28b11519f65a6119db8609aa7cdf | [] | no_license | npmcdn-to-unpkg-bot/99bus | d5d63299f2f2232abbe610f80e814f776fa75ed5 | 0384af164f8837a18f8f2ea01ed94f29dd182819 | refs/heads/master | 2021-01-21T15:32:05.454033 | 2016-08-10T18:18:31 | 2016-08-10T18:37:27 | 67,423,641 | 0 | 0 | null | 2016-09-05T13:32:35 | 2016-09-05T13:32:34 | null | UTF-8 | Java | false | false | 6,604 | java | /**
* @author jerry
* @mail : [email protected]
*/
package org.hopen.jjbus.action;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.hopen.bean.SessionInfo;
import org.hopen.jjbus.security.Encrypt;
import org.hopen.jjbus.service.ICashOperationService;
import org.hopen.utils.ConfigUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* @author jerry
*
*/
@Controller
@RequestMapping("/cshoprtn")
public class CashOperationController extends BaseController {
@Autowired
ICashOperationService cashOperationSevice;
@RequestMapping("/toDrawInFyPage")
public String toDrawInFyPage(HttpServletRequest request, String amount) {
request.setAttribute("page", SessionInfo.getUserInfo(request).getTransText());
SessionInfo.getUserInfo(request).setTransText(null);
return "/acct/fyWithPayInPage";
}
@RequestMapping("/toDrwIn")
public String toDrawInNew(HttpServletRequest request, String amount) {
if (amount == null || amount == "" || Float.parseFloat(amount) <= 0) {
request.setAttribute("msg", "充值金额必须大于0");
return "forward:/usrbs/toCptl";
}
Map<String, String> jobj = new HashMap<String, String>();
jobj.put("userId", SessionInfo.getUserInfo(request).getUserId());
jobj.put("amount", amount);
JSONObject job = cashOperationSevice.queryPayInPage(jobj);
String htmlPar = job.getString("htmlParam");
Document document = Jsoup.parse(htmlPar);
Element e = document.getElementById("frm1");
e.attr("target","fyFrame");
job.put("htmlParam", document.html());
SessionInfo.getUserInfo(request).setTransText(document.html());
String error = job.getString("error");
if(!error.equals("-1")){
request.setAttribute("msg", job.getString("msg"));
return "forward:/usrbs/toCptl";
}
request.setAttribute("response", job);
return "/acct/in_money";
}
@RequestMapping("/toDrwOt")
public String toDrawOut(HttpServletRequest request) {
String userId = SessionInfo.getUserInfo(request).getUserId();
JSONObject jobj = cashOperationSevice.queryCashInit(userId);
String error = jobj.getString("error");
if(!error.equals("-1")){
request.setAttribute("msg", jobj.getString("msg"));
return "forward:/usr/toCptl";
}
request.setAttribute("response", jobj);
return "/acct/draw_money";
}
@RequestMapping("/toDrawOutPage")
public String toDrawOutPage(HttpServletRequest request){
request.setAttribute("page", SessionInfo.getUserInfo(request).getTransText());
SessionInfo.getUserInfo(request).setTransText(null);
return "/acct/fyWithDrawPage";
}
@RequestMapping("/drawRqst")
public String drawRqst(HttpServletRequest request,String bankId,String amount,String payPassword) {
String userId = SessionInfo.getUserInfo(request).getUserId();
Map<String, String> inMap = new HashMap<String, String>();
inMap.put("user_id", userId);
inMap.put("amount", amount);
inMap.put("payPassword",Encrypt.encrypt3DES(payPassword, ConfigUtil.getSecretKey()));
inMap.put("bankId", bankId);
JSONObject jobj = cashOperationSevice.storeDrawRqst(inMap);
String error = jobj.getString("error");
if(!error.equals("-1")){
request.setAttribute("msg", jobj.getString("msg"));
request.setAttribute("amount", amount);
return "forward:/cshoprtn/toDrwOt";
}
String htmlParam = jobj.getString("htmlParam");
Document document = Jsoup.parse(htmlParam);
Elements e = document.getElementsByAttributeValue("id", "frm1");
e.attr("target","fyFrame");
SessionInfo.getUserInfo(request).setTransText(document.html());
request.setAttribute("response", jobj);
return "/acct/draw_brige";
}
@RequestMapping("/checkTrad")
@ResponseBody
public JSONObject checkTrad(HttpServletRequest request) {
String userId = SessionInfo.getUserInfo(request).getUserId();
if(userId != null && !userId.equals("")){
JSONObject jobj = cashOperationSevice.queryCashInit(userId);
String error = jobj.getString("error");
boolean setTradPwd = jobj.getBoolean("payPasswordStatus");
if(error.equals("-1")&&setTradPwd){
return JSONObject.parseObject("{error:-1,msg:'检查通过'}");
} else {
return JSONObject.parseObject("{error:-8,msg:'未设置交易密码'}");
}
} else {
return JSONObject.parseObject("{error:-9,msg:'未登录'}");
}
}
@RequestMapping("/checkBank")
@ResponseBody
public JSONObject checkBank(HttpServletRequest request) {
String userId = SessionInfo.getUserInfo(request).getUserId();
JSONObject jobj = cashOperationSevice.queryCashInit(userId);
String error = jobj.getString("error");
JSONArray bankList = jobj.getJSONArray("bankList");
if(error.equals("-1")&&bankList != null &&bankList.size()>0){
return JSONObject.parseObject("{error:-1,msg:'检查通过'}");
} else {
return JSONObject.parseObject("{error:9999,msg:'检查失败'}");
}
}
@RequestMapping("/inverstBid")
public String inverstBid(HttpServletRequest request, String borrowId,
String amount, String dealPwd) {
String userid = SessionInfo.getUserInfo(request).getUserId();
Map<String, String> map = new HashMap<String, String>();
map.put("borrowId", borrowId);
map.put("userId", userid);
map.put("amount", amount);
map.put("dealPwd", Encrypt.encrypt3DES(dealPwd, ConfigUtil.getSecretKey()));
JSONObject rjob = cashOperationSevice.stroeInverstBid(map);
String error = rjob.getString("error");
if (!error.equals("-1")) {
return "forward:/prdct/toBdDtl?bid=" +borrowId +"&msg=" + rjob.get("msg");
}
request.setAttribute("msg",rjob.getString("msg"));
return "forward:/usrbs/toCptl";
}
@RequestMapping("/toQueryTradList")
public String toQueryTradList(HttpServletRequest request, String borrowId,
String amount, String dealPwd) {
String userid = SessionInfo.getUserInfo(request).getUserId();
Map<String, String> map = new HashMap<String, String>();
map.put("id", userid);
map.put("purpose", "0");
JSONObject rjob = cashOperationSevice.queryTradRecord(map);
request.setAttribute("response", rjob);
return "/user/tradlist";
}
}
| [
"[email protected]"
] | |
6749084dd70d3b387d5f4c41d336e45e1dcce6a0 | 15bb61e7e026a403114ac570be024d19b29ea0c3 | /DesignPattern/Structural/it/lmpetrella/tutorials/designpattern/bridge/AbstractionIF.java | 55a77e898a93ab3f041e26fe54d93e1ec3fd7035 | [] | no_license | luigimartin/java-tutorials-lmpetrella | ca8e29f7650c163da576c720a14ddb6d48c1b5f6 | b45f9766c74ffa63151711d1c1f8cf5718471012 | refs/heads/master | 2021-01-10T07:41:12.425424 | 2015-01-28T13:51:08 | 2015-01-28T13:51:08 | 43,546,141 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 119 | java | package it.lmpetrella.tutorials.designpattern.bridge;
public interface AbstractionIF {
public void action();
} | [
"[email protected]"
] | |
eebbacb19511f7350e810a6101d0b946941bb889 | f0a9a2675c84b05f56f627b718932e96b894c09a | /src/main/java/com/yang/bms/service/UserService.java | 899388a46b5f239fb64c9ad23d80f0ab3beec064 | [
"Apache-2.0"
] | permissive | zhichuwy/BMS | a2713f9b4ebdc877c6063cece0ff04b6567c14c3 | 85b15d42623ba4ffccba941ddfe52cf83485ebcd | refs/heads/master | 2022-07-08T15:11:47.703113 | 2019-12-14T15:58:39 | 2019-12-14T15:58:39 | 228,047,617 | 0 | 0 | Apache-2.0 | 2022-06-21T02:26:59 | 2019-12-14T15:46:32 | Java | UTF-8 | Java | false | false | 111 | java | package com.yang.bms.service;
public interface UserService {
void haveUser(String userId,String pwd);
}
| [
"[email protected]"
] | |
f742e724e87776d18a2ace55afd5b388f15b6f64 | 318dbf15015fddfb0d93d77d6311a77eed3a9b4b | /ParseURLFunction.java | d0995320be864cecb6d8d33cb47c40972b6b845e | [] | no_license | ketanp28/testCG | fd5db53debebc68ac7fadbe1984a108a16770bc3 | 7343ee2a1b1a66fc230527d095b01ad9ea0cb7db | refs/heads/master | 2021-01-19T21:45:07.548106 | 2017-04-19T05:00:14 | 2017-04-19T05:00:14 | 88,701,229 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 656 | java |
package blackberry.utils;
import blackberry.core.FunctionSignature;
import blackberry.core.ScriptableFunctionBase;
import blackberry.utils.URL.URLObject;
public final class ParseURLFunction extends ScriptableFunctionBase {
public static final String NAME = "parseURL";
public Object execute( Object thiz, Object[] args ) throws Exception {
return new URLObject( args[ 0 ].toString() );
}
protected FunctionSignature[] getFunctionSignatures() {
FunctionSignature fs = new FunctionSignature( 1 );
fs.addParam( String.class, true );
return new FunctionSignature[] { fs };
}
}
| [
"[email protected]"
] | |
260cb2ab3140093a003e11f1ac5f9328486312d8 | 576886b5d295fe04ef5eb62a7ae7c7d6ff9d4ff4 | /CreateFolder/src/sep/util/net/ipseeker/Helper.java | 8d92d67181be9378fce285504b927992930e5228 | [] | no_license | yc-zhaoming/my | 5d95fb74486c1cad18e8bd6351aa2d85e9fe5837 | 4403fc9ad6d50b8976eb52330c529ff79917f06a | refs/heads/master | 2020-03-11T00:35:03.135184 | 2018-04-17T02:07:35 | 2018-04-17T02:07:35 | 129,667,414 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,095 | java | package sep.util.net.ipseeker;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import sep.util.net.IP4Util;
class Helper {
static final int RecordLength = 7;
static final byte RedirectMode1 = 0x01;
static final byte RedirectMode2 = 0x02;
/** 计算中间位置的偏移 */
static int calcMiddleOffset(final int begin, final int end) {
final int records = ((end - begin) / RecordLength) >> 1;
return begin + ((records == 0) ? 1 : records) * RecordLength;
}
static int compare(byte[] ip, byte[] begin) {
for (int i = 0, x, y; i < 4; i++) {
x = ip[i]; y = begin[i];
if ((x & 0xFF) > (y & 0xFF)) {
return 1;
} else if ((x ^ y) == 0) {
continue;
} else {
return -1;
}
}
return 0;
}
private final ByteBuffer buffer;
private final IPSeeker seeker;
Helper(IPSeeker seeker) {
this.buffer = seeker.buffer;
this.seeker = seeker;
}
IPLocation getLocation(int offset) {
if (offset == -1) {
return IPLocation.Unknown;
}
buffer.position(offset + 4);
switch (buffer.get()) {
case RedirectMode1:
// Read CountryOffset & Set Position
buffer.position(offset = readInt3());
final String country;
switch (buffer.get()) {
case RedirectMode2:
country = readString(readInt3());
buffer.position(offset + 4);
break;
default:
country = readString(offset);
break;
}
return IPLocation.of(country, readArea(buffer.position()));
case RedirectMode2:
return IPLocation.of(readString(readInt3()), readArea(offset + 8));
default:
return IPLocation.of(readString(buffer.position() - 1), readArea(buffer.position()));
}
}
/** 定位IP的绝对偏移 */
int locateOffset(final byte[] address) {
switch (compare(address, readIP(seeker.offsetBegin))) {
case -1:
return -1;
case 0:
return seeker.offsetBegin;
}
int middleOffset = 0;
for (int begin = seeker.offsetBegin, end = seeker.offsetEnd; begin < end;) {
switch (compare(address, readIP(middleOffset = calcMiddleOffset(begin, end)))) {
case 1:
begin = middleOffset;
break;
case -1:
if (middleOffset == end) {
middleOffset = (end -= RecordLength);
} else {
end = middleOffset;
}
break;
case 0:
return readInt3(middleOffset + 4);
}
}
middleOffset = readInt3(middleOffset + 4);
switch (compare(address, readIP(middleOffset))) {
case -1:
case 0:
return middleOffset;
default:
return -1;
}
}
private String readArea(int offset) {
buffer.position(offset);
switch (buffer.get()) {
case RedirectMode1:
case RedirectMode2:
offset = readInt3(offset + 1);
return (offset != 0) ? readString(offset) : IPLocation.Unknown.getArea();
default:
return readString(offset);
}
}
private int readInt3() {
return buffer.getInt() & 0x00FFFFFF;
}
int readInt3(int offset) {
buffer.position(offset);
return buffer.getInt() & 0x00FFFFFF;
}
byte[] readIP(int offset) {
buffer.position(offset);
return IP4Util.toBytes(buffer.getInt());
}
private String readString(int offset) {
buffer.position(offset);
final byte[] buf = new byte[0xFF];
offset = -1;
while ((buf[++offset] = buffer.get()) != 0);
return (offset != 0) ? new String(buf, 0, offset, Charset.forName("GBK")) : null;
}
} | [
"[email protected]"
] | |
6df60a304ddf403ff4d9605e788798fbc952b9e9 | 1777c53ef3947a33d2954b71f566ef6f6e705414 | /src/main/java/filter/CodingFilter.java | 9353d71beefbc581d38c7687634ed4edba893ca0 | [] | no_license | tianhan1998/ojtools | 5b94172554277fb0d8ecf79a24fd5820243f7ed3 | b6e9fb305004e587b079319830d2b89c1f61ca80 | refs/heads/master | 2022-07-02T04:16:59.430943 | 2019-08-29T12:12:34 | 2019-08-29T12:12:34 | 195,880,548 | 2 | 0 | null | 2022-06-21T01:26:58 | 2019-07-08T20:19:03 | Java | UTF-8 | Java | false | false | 1,590 | java | package filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet Filter implementation class CodingFilter
*/
public class CodingFilter implements Filter {
/**
* Default constructor.
*/
public CodingFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest re = (HttpServletRequest) request;
HttpServletResponse rs = (HttpServletResponse) response;
String spath = re.getServletPath();
String[] urls = { "/login", "/json", ".js", ".css", ".ico", ".jpg", ".png" };
boolean flag = true;
for (String str : urls) {
if (spath.indexOf(str) != -1) {
flag = false;
break;
}
}
if (flag) {
re.setCharacterEncoding("UTF-8");
rs.setContentType("text/html;charset=utf-8");
}
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
| [
"[email protected]"
] | |
d0dc41b5ff83de95db832d815ee96820ffc42a98 | 04bd74d3404a807c424694c7afc906fe5f4b5fc2 | /DemoMaven1/src/test/java/subha/OR3.java | b1753c452c85a2cf932bd8ee4f9dbb220e2bcf20 | [] | no_license | sudharanith/demomaven1 | eb81f14fe07a366cf611d8dd95689b8b9ce3c817 | fb05c4a250989cdcf5aef39666c64baa351a9de2 | refs/heads/master | 2023-08-10T01:04:09.186676 | 2019-07-31T10:07:19 | 2019-07-31T10:07:19 | 199,830,248 | 0 | 0 | null | 2023-07-22T12:19:29 | 2019-07-31T10:03:32 | Java | UTF-8 | Java | false | false | 464 | java | package subha;
import org.openqa.selenium.WebDriver;
public class OR3 {
public static String email= " //input[@type='email' and @name='email'] ";
public static String password=" //input[@type='password' and @name='pass'] ";
public static String login=" //input[@type='submit'and @id='u_0_2'] ";
public static String invoke =" //div[text()='Account Settings'] ";
public static String logout =" //text()[.='Log Out']/ancestor::span[1] ";
}
| [
"Administroator@Atyam"
] | Administroator@Atyam |
b0a9f4906db6dd990bdc2e8ce03f3ff49bec6f2b | 2bf767c50c07906e17df0d3678107a077985f229 | /src/main/java/io/pivotal/pal/tracker/PalTrackerApplication.java | b6f3e655399bbbc272a380e1a9535085826f7abf | [] | no_license | uberscott/pal-tracker | 805734fc5d62a2a695ee5c0e7f52bac10ddea95f | aff8d1f61cef0fa9845ef88da55041cd7a9758fa | refs/heads/master | 2020-03-19T06:45:00.980312 | 2018-06-06T18:00:07 | 2018-06-06T18:00:07 | 136,051,520 | 0 | 0 | null | 2018-06-04T16:15:21 | 2018-06-04T16:15:20 | null | UTF-8 | Java | false | false | 1,300 | java | package io.pivotal.pal.tracker;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.mysql.cj.jdbc.MysqlDataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import javax.sql.DataSource;
@SpringBootApplication
public class PalTrackerApplication {
@Bean
public TimeEntryRepository timeEntryRepository(DataSource dataSource)
{
return new JdbcTimeEntryRepository(dataSource);
}
@Bean
public ObjectMapper jsonObjectMapper ()
{
return Jackson2ObjectMapperBuilder.json()
.serializationInclusion(JsonInclude.Include.NON_NULL) // Don’t include null values
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) //ISODate
.modules(new JavaTimeModule())
.build();
}
public static void main(String[] args){
SpringApplication.run(PalTrackerApplication.class, args);
}
}
| [
"[email protected]"
] | |
0d629a22baf6b4b5c85ee0459a144f9799c315be | 2133ffc4e97323ea4e62059e1b793776880f419d | /src/java/it/unibo/cs/rgb/test/TeiTestInputStreamConcordanze.java | 0e4804c46ae0ab7979ad8202210233fd8c0f7438 | [] | no_license | fedo/RgB | 1f92a3b51bd700c1622d60264fa37d4d5849b3b7 | 8c3dcb1d6418d7fe7678b68cf2c0a87e631e6e3b | refs/heads/master | 2020-05-31T04:46:07.138064 | 2010-07-02T13:36:03 | 2010-07-02T13:36:03 | 629,360 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,304 | java | package it.unibo.cs.rgb.test;
import it.unibo.cs.rgb.tei.TeiConcordanze;
import it.unibo.cs.rgb.tei.TeiDocument;
import it.unibo.cs.rgb.tei.TeiSvg;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import sun.net.www.content.text.PlainTextInputStream;
/**
*
* @author fedo
*/
public class TeiTestInputStreamConcordanze {
public static void main(String[] args) throws FileNotFoundException, IOException {
String xmlString = "/home/gine/NetBeansProjects/RgB/web/collection6/prophecy_of_merlin.xml";
String xslString = "/home/gine/NetBeansProjects/RgB/web/stylesheets/witList.xsl";
String xslString2 = "/home/gine/NetBeansProjects/RgB/web/stylesheets/content_text.xsl";
File xmlFile = new File(xmlString);
File xslFile = new File(xslString);
File xslFile2 = new File(xslString2);
if (xmlFile.exists() && xslFile.exists()) {
//System.out.println("i files esistono");
}
HashMap xslHashMap = new HashMap();
xslHashMap.put("/stylesheets/witList.xsl", FileUtils.readFileToString(xslFile));
xslHashMap.put("/stylesheets/content_text.xsl", FileUtils.readFileToString(xslFile2));
TeiDocument tei = new TeiDocument("zuppaditei", FileUtils.readFileToString(xmlFile), xslHashMap);
String[] witnesses = tei.getWitnessesList();
String out="";
for (int i=0; i<witnesses.length; i++) {
String plainText = tei.getEstrazioneDiConcordanzeContentDataString(witnesses[i]);
//String a[] = plainText.split("\\|");
TeiConcordanze con = new TeiConcordanze("and", 3, plainText, witnesses[i], "pirla");
out += con.getConcordanze();
}
System.out.println(out);
//System.out.println(getContentType(new FileInputStream(xmlFile)));
//System.out.println("nome " + tei.getTeiName());
//System.out.println("path " + tei.getAbsolutePath());
//System.out.println(tei.getHover());
//System.out.println("view " + tei.getView("fasdfdfs"));
//System.out.println(RgB.getXmlStreamEncoding(new FileInputStream(xmlFile)));
//System.out.println("\n\n\nCCCCC\n\n\n");
//System.out.println(RgB.convertXmlStreamToString(new FileInputStream(xmlFile)));
//System.out.println("\n\n\nCCCCC\n\n\n");
//System.out.println(FileUtils.readFileToString(xmlFile));
//System.out.println(RgB.convertStreamToString(new FileInputStream(xmlFile), "UTF-8"));
// parsing dei dati ricevuti
//ArrayList<HashMap> data = new ArrayList<HashMap>();
//String svgDataString = tei.getSvgDataString();
//String svgDataString = "der1 1 sigil1 id1" + "----" + "der2 0 sigil2 id2"; //tring "der", boolean "missing", String "sigil", String "id"
//String svgDataString = "null 0 a a" + "----" + "a 0 b b";
/*str = str.substring(0, str.indexOf("|"));
System.out.println(str);
String[] lines = str.split("-");
for (int i = 0; i < lines.length; i++) {
System.out.println(lines[i]);
HashMap witnessMap = new HashMap();
StringTokenizer tokens = new StringTokenizer(lines[i]);
String der = tokens.nextToken();
if (!der.equalsIgnoreCase("null")) {
witnessMap.put("der", der);
}
witnessMap.put("missing", Boolean.parseBoolean(tokens.nextToken()));
witnessMap.put("sigil", tokens.nextToken());
witnessMap.put("id", tokens.nextToken());
data.add(witnessMap);
}*/
//TeiSvg svg = new TeiSvg(data);
//System.out.println("svg "+svg.getSvg());
//System.out.println("γδεζηθικλμνξο");
}
public static String convertStreamToString(InputStream is) throws IOException {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
String encoding = "UTF-8"; //default
// cerca se il documento specifica un altro encoding
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));//"UTF-8"));
while ((line = reader.readLine()) != null) { //CRASHA
sb.append(line).append("\n");
if ((sb.toString().contains("<?") && sb.toString().contains("?>")) && sb.toString().contains("encoding=")) {
Pattern p = Pattern.compile(".*<\\?.*encoding=.(.*).\\?>.*", Pattern.DOTALL);
Matcher matcher = p.matcher(sb.toString());
if (matcher.matches()) {
encoding = matcher.group(1);
}
break;
}
}
}
// converte
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, encoding));//"UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
System.out.println(line);
}
} finally {
is.close();
}
return sb.toString();
} else {
return "error";
}
}
public static String getContentType(InputStream is) throws IOException {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
String encoding = "UTF-8"; //default
// cerca se il documento specifica un altro encoding
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));//"UTF-8"));
while ((line = reader.readLine()) != null) { //CRASHA
sb.append(line).append("\n");
if ((sb.toString().contains("<?") && sb.toString().contains("?>")) && sb.toString().contains("encoding=")) {
Pattern p = Pattern.compile(".*<\\?.*encoding=.(.*).\\?>.*", Pattern.DOTALL);
Matcher matcher = p.matcher(sb.toString());
if (matcher.matches()) {
encoding = matcher.group(1);
}
break;
}
}
}
return encoding;
}
}
| [
"[email protected]"
] | |
406289798bb4b64d687992cc4a9f41a288569b5f | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/6/6_24a45a22114df592a6af77813caea242f274c7eb/ServiceInfo/6_24a45a22114df592a6af77813caea242f274c7eb_ServiceInfo_s.java | 69c2640f71457316554165e681c746324e93e1cc | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 281,640 | java | /*
* This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH
* written by Rasto Levrinc.
*
* Copyright (C) 2009-2010, LINBIT HA-Solutions GmbH.
* Copyright (C) 2009-2010, Rasto Levrinc
*
* DRBD Management Console 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, or (at your option)
* any later version.
*
* DRBD Management Console 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 drbd; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package lcmc.gui.resources;
import lcmc.gui.Browser;
import lcmc.gui.ClusterBrowser;
import lcmc.data.Host;
import lcmc.data.HostLocation;
import lcmc.data.ResourceAgent;
import lcmc.gui.widget.Widget;
import lcmc.gui.widget.WidgetFactory;
import lcmc.gui.widget.TextfieldWithUnit;
import java.awt.geom.Point2D;
import lcmc.data.resources.Service;
import lcmc.data.Subtext;
import lcmc.data.CRMXML;
import lcmc.data.ClusterStatus;
import lcmc.data.ConfigData;
import lcmc.data.PtestData;
import lcmc.data.AccessMode;
import lcmc.utilities.MyMenu;
import lcmc.utilities.UpdatableItem;
import lcmc.utilities.Unit;
import lcmc.utilities.Tools;
import lcmc.utilities.CRM;
import lcmc.utilities.ButtonCallback;
import lcmc.utilities.MyMenuItem;
import lcmc.utilities.MyList;
import lcmc.utilities.MyListModel;
import lcmc.utilities.WidgetListener;
import lcmc.gui.SpringUtilities;
import lcmc.gui.dialog.pacemaker.ServiceLogs;
import lcmc.gui.dialog.EditConfig;
import java.awt.Color;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.util.List;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Map;
import java.util.HashMap;
import java.util.TreeSet;
import java.util.LinkedHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JComponent;
import javax.swing.ImageIcon;
import javax.swing.BoxLayout;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JMenuBar;
import javax.swing.JScrollPane;
import javax.swing.JRadioButton;
import javax.swing.JCheckBox;
import javax.swing.SpringLayout;
import javax.swing.AbstractButton;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.collections15.map.MultiKeyMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.Lock;
/**
* This class holds info data for one hearteat service and allows to enter
* its arguments and execute operations on it.
*/
public class ServiceInfo extends EditableInfo {
/** A map from host to the combobox with scores. */
private final Map<HostInfo, Widget> scoreComboBoxHash =
new HashMap<HostInfo, Widget>();
/** A map from host to stored score. */
private final Map<HostInfo, HostLocation> savedHostLocations =
new HashMap<HostInfo, HostLocation>();
/** A combobox with pingd constraint. */
private Widget pingComboBox = null;
/** Saved ping constraint. */
private String savedPingOperation = null;
/** Saved meta attrs id. */
private String savedMetaAttrsId = null;
/** Saved operations id. */
private String savedOperationsId = null;
/** A map from operation to the stored value. First key is
* operation name like "start" and second key is parameter like
* "timeout". */
private final MultiKeyMap<String, String> savedOperation =
new MultiKeyMap<String, String>();
/** Whether id-ref for meta-attributes is used. */
private ServiceInfo savedMetaAttrInfoRef = null;
/** Combo box with same as operations option. */
private Widget sameAsMetaAttrsWi = null;
/** Whether id-ref for operations is used. */
private ServiceInfo savedOperationIdRef = null;
/** Combo box with same as operations option. */
private Widget sameAsOperationsWi = null;
/** Saved operations lock. */
private final Lock mSavedOperationsLock = new ReentrantLock();
/** Operations combo box hash lock. */
private final ReadWriteLock mOperationsComboBoxHashLock =
new ReentrantReadWriteLock();
/** Operations combo box hash read lock. */
private final Lock mOperationsComboBoxHashReadLock =
mOperationsComboBoxHashLock.readLock();
/** Operations combo box hash write lock. */
private final Lock mOperationsComboBoxHashWriteLock =
mOperationsComboBoxHashLock.writeLock();
/** A map from operation to its combo box. */
private final MultiKeyMap<String, Widget> operationsComboBoxHash =
new MultiKeyMap<String, Widget>();
/** Cache for the info panel. */
private JComponent infoPanel = null;
/** Group info object of the group this service is in or null, if it is
* not in any group. */
private GroupInfo groupInfo = null;
/** Master/Slave info object, if is null, it is not master/slave
* resource. */
private volatile CloneInfo cloneInfo = null;
/** ResourceAgent object of the service, with name, ocf informations
* etc. */
private final ResourceAgent resourceAgent;
/** Radio buttons for clone/master/slave primitive resources. */
private Widget typeRadioGroup;
/** Default values item in the "same as" scrolling list in meta
attributes.*/
private static final String META_ATTRS_DEFAULT_VALUES_TEXT =
"default values";
/** Default values internal name. */
private static final String META_ATTRS_DEFAULT_VALUES = "default";
/** Default values item in the "same as" scrolling list in operations. */
private static final String OPERATIONS_DEFAULT_VALUES_TEXT =
"advisory minimum";
/** Default values internal name. */
private static final String OPERATIONS_DEFAULT_VALUES = "default";
/** Check the cached fields. */
protected static final String CACHED_FIELD = "cached";
/** Master / Slave type string. */
static final String MASTER_SLAVE_TYPE_STRING = "Master/Slave";
/** Manage by CRM icon. */
static final ImageIcon MANAGE_BY_CRM_ICON = Tools.createImageIcon(
Tools.getDefault("ServiceInfo.ManageByCRMIcon"));
/** Don't Manage by CRM icon. */
static final ImageIcon UNMANAGE_BY_CRM_ICON = Tools.createImageIcon(
Tools.getDefault("ServiceInfo.UnmanageByCRMIcon"));
/** Icon that indicates a running service. */
public static final ImageIcon SERVICE_RUNNING_ICON_SMALL =
Tools.createImageIcon(Tools.getDefault(
"ServiceInfo.ServiceRunningIconSmall"));
/** Icon that indicates a running that failed. */
private static final ImageIcon SERVICE_RUNNING_FAILED_ICON_SMALL =
Tools.createImageIcon(Tools.getDefault(
"ServiceInfo.ServiceRunningFailedIconSmall"));
/** Icon that indicates a started service (but not running). */
private static final ImageIcon SERVICE_STARTED_ICON_SMALL =
Tools.createImageIcon(Tools.getDefault(
"ServiceInfo.ServiceStartedIconSmall"));
/** Icon that indicates a stopping service (but not stopped). */
private static final ImageIcon SERVICE_STOPPING_ICON_SMALL =
Tools.createImageIcon(Tools.getDefault(
"ServiceInfo.ServiceStoppingIconSmall"));
/** Icon that indicates a not running service. */
public static final ImageIcon SERVICE_STOPPED_ICON_SMALL =
Tools.createImageIcon(Tools.getDefault(
"ServiceInfo.ServiceStoppedIconSmall"));
/** Icon that indicates a not running service that failed. */
private static final ImageIcon SERVICE_STOPPED_FAILED_ICON_SMALL =
Tools.createImageIcon(Tools.getDefault(
"ServiceInfo.ServiceStoppedFailedIconSmall"));
/** Running service icon. */
static final ImageIcon SERVICE_RUNNING_ICON =
Tools.createImageIcon(
Tools.getDefault("CRMGraph.ServiceRunningIcon"));
/** Not running service icon. */
private static final ImageIcon SERVICE_STOPPED_ICON =
Tools.createImageIcon(
Tools.getDefault("CRMGraph.ServiceStoppedIcon"));
/** Start service icon. */
static final ImageIcon START_ICON = SERVICE_RUNNING_ICON;
/** Stop service icon. */
static final ImageIcon STOP_ICON = SERVICE_STOPPED_ICON;
/** Migrate icon. */
protected static final ImageIcon MIGRATE_ICON = Tools.createImageIcon(
Tools.getDefault("CRMGraph.MigrateIcon"));
/** Unmigrate icon. */
static final ImageIcon UNMIGRATE_ICON = Tools.createImageIcon(
Tools.getDefault("CRMGraph.UnmigrateIcon"));
/** Group up icon. */
static final ImageIcon GROUP_UP_ICON = Tools.createImageIcon(
Tools.getDefault("CRMGraph.GroupUp"));
/** Group down icon. */
static final ImageIcon GROUP_DOWN_ICON = Tools.createImageIcon(
Tools.getDefault("CRMGraph.GroupDown"));
/** Orphaned subtext. */
private static final Subtext ORPHANED_SUBTEXT = new Subtext("(LRM)",
null,
Color.BLACK);
/** Orphaned with fail-count subtext. */
private static final Subtext ORPHANED_FAILED_SUBTEXT =
new Subtext("(ORPHANED)", null, Color.RED);
/** Unmanaged subtext. */
private static final Subtext UNMANAGED_SUBTEXT =
new Subtext("(unmanaged)", null, Color.RED);
/** Migrated subtext. */
private static final Subtext MIGRATED_SUBTEXT =
new Subtext("(migrated)", null, Color.RED);
/** Clone type string. */
protected static final String CLONE_TYPE_STRING = "Clone";
/** Primitive type string. */
private static final String PRIMITIVE_TYPE_STRING = "Primitive";
/** Gui ID parameter. */
public static final String GUI_ID = "__drbdmcid";
/** PCMK ID parameter. */
public static final String PCMK_ID = "__pckmkid";
/** String that appears as a tooltip in menu items if item is being
* removed. */
static final String IS_BEING_REMOVED_STRING = "it is being removed";
/** String that appears as a tooltip in menu items if item is orphan. */
static final String IS_ORPHANED_STRING = "cannot do that to an ophan";
/** String that appears as a tooltip in menu items if item is new. */
static final String IS_NEW_STRING = "it is not applied yet";
/** Ping attributes. */
private static final Map<String, String> PING_ATTRIBUTES =
new HashMap<String, String>();
static {
PING_ATTRIBUTES.put("eq0", "no ping: stop"); /* eq 0 */
PING_ATTRIBUTES.put("defined", "most connections");
}
/**
* Prepares a new <code>ServiceInfo</code> object and creates
* new service object.
*/
ServiceInfo(final String name,
final ResourceAgent resourceAgent,
final Browser browser) {
super(name, browser);
this.resourceAgent = resourceAgent;
if (resourceAgent != null && resourceAgent.isStonith()) {
setResource(new Service(name.replaceAll("/", "_")));
getService().setStonith(true);
} else {
setResource(new Service(name));
}
getService().setNew(true);
}
/**
* Prepares a new <code>ServiceInfo</code> object and creates
* new service object. It also initializes parameters along with
* heartbeat id with values from xml stored in resourceNode.
*/
ServiceInfo(final String name,
final ResourceAgent ra,
final String heartbeatId,
final Map<String, String> resourceNode,
final Browser browser) {
this(name, ra, browser);
getService().setHeartbeatId(heartbeatId);
/* TODO: cannot call setParameters here, only after it is
* constructed. */
setParameters(resourceNode);
}
/**
* Returns id of the service, which is heartbeatId.
* TODO: this id is used for stored position info, should be named
* differently.
*/
@Override
public String getId() {
return getService().getHeartbeatId();
}
/** Returns browser object of this info. */
@Override
protected ClusterBrowser getBrowser() {
return (ClusterBrowser) super.getBrowser();
}
/** Sets info panel of the service. */
public void setInfoPanel(final JPanel infoPanel) {
this.infoPanel = infoPanel;
}
/** Returns true if the node is active. */
boolean isOfflineNode(final String node) {
return "no".equals(getBrowser().getClusterStatus().isOnlineNode(node));
}
/**
* Returns whether all the parameters are correct. If param is null,
* all paremeters will be checked, otherwise only the param, but other
* parameters will be checked only in the cache. This is good if only
* one value is changed and we don't want to check everything.
*/
@Override
boolean checkResourceFieldsCorrect(final String param,
final String[] params) {
return checkResourceFieldsCorrect(param, params, false, false, false);
}
/**
* Returns whether all the parameters are correct. If param is null,
* all paremeters will be checked, otherwise only the param, but other
* parameters will be checked only in the cache. This is good if only
* one value is changed and we don't want to check everything.
*/
boolean checkResourceFieldsCorrect(final String param,
final String[] params,
final boolean fromServicesInfo,
final boolean fromCloneInfo,
final boolean fromGroupInfo) {
if (getComboBoxValue(GUI_ID) == null) {
return true;
}
final CloneInfo ci = getCloneInfo();
if (!fromCloneInfo && ci != null) {
return ci.checkResourceFieldsCorrect(param,
ci.getParametersFromXML(),
fromServicesInfo);
}
final GroupInfo gi = getGroupInfo();
if (!fromGroupInfo && gi != null) {
if (!gi.checkResourceFieldsCorrect(param,
gi.getParametersFromXML(),
fromServicesInfo,
fromCloneInfo)) {
return false;
}
}
if (!fromGroupInfo && gi != null) {
if (!fromServicesInfo) {
gi.setApplyButtons(null, gi.getParametersFromXML());
}
}
if (getService().isOrphaned()) {
return false;
}
/* Allow it only for resources that are in LRM. */
final String id = getComboBoxValue(GUI_ID);
final ServiceInfo si =
getBrowser().getServiceInfoFromId(getService().getName(), id);
if (si != null && si != this && !si.getService().isOrphaned()) {
return false;
}
if (!super.checkResourceFieldsCorrect(param, params)) {
return false;
}
if (ci == null) {
boolean on = false;
for (Host host : getBrowser().getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
/* at least one "eq" */
final Widget wi = scoreComboBoxHash.get(hi);
if (wi != null) {
final JLabel label = wi.getLabel();
if (label != null) {
final String op = getOpFromLabel(hi.getName(),
label.getText());
if (wi.getValue() == null || "eq".equals(op)) {
on = true;
break;
}
}
}
}
if (!on) {
return false;
}
}
return true;
}
/**
* Returns whether the specified parameter or any of the parameters
* have changed. If param is null, only param will be checked,
* otherwise all parameters will be checked.
*/
@Override
public boolean checkResourceFieldsChanged(final String param,
final String[] params) {
return checkResourceFieldsChanged(param, params, false, false, false);
}
/**
* Returns whether the specified parameter or any of the parameters
* have changed. If param is null, only param will be checked,
* otherwise all parameters will be checked.
*/
public boolean checkResourceFieldsChanged(final String param,
final String[] params,
final boolean fromServicesInfo,
final boolean fromCloneInfo,
final boolean fromGroupInfo) {
final String id = getComboBoxValue(GUI_ID);
final CloneInfo ci = getCloneInfo();
if (!fromCloneInfo && ci != null) {
return ci.checkResourceFieldsChanged(param,
ci.getParametersFromXML(),
fromServicesInfo);
}
final GroupInfo gi = getGroupInfo();
if (!fromGroupInfo && gi != null) {
if (!fromServicesInfo) {
gi.setApplyButtons(null, gi.getParametersFromXML());
}
}
if (id == null) {
return false;
}
boolean changed = false;
if (super.checkResourceFieldsChanged(param, params)) {
changed = true;
}
boolean allMetaAttrsAreDefaultValues = true;
if (params != null) {
for (String otherParam : params) {
if (isMetaAttr(otherParam)) {
final Widget wi = getWidget(otherParam, null);
if (wi == null) {
continue;
}
final Object newValue = wi.getValue();
final Object defaultValue = getParamDefault(otherParam);
if (!Tools.areEqual(newValue, defaultValue)) {
allMetaAttrsAreDefaultValues = false;
}
}
}
}
final String heartbeatId = getService().getHeartbeatId();
if (ConfigData.PM_GROUP_NAME.equals(getName())) {
if (heartbeatId == null) {
changed = true;
} else if (heartbeatId.equals(Service.GRP_ID_PREFIX + id)
|| heartbeatId.equals(id)) {
if (checkHostLocationsFieldsChanged()
|| checkOperationFieldsChanged()) {
changed = true;
}
} else {
changed = true;
}
} else if (ConfigData.PM_CLONE_SET_NAME.equals(getName())
|| ConfigData.PM_MASTER_SLAVE_SET_NAME.equals(getName())) {
String prefix;
if (getService().isMaster()) {
prefix = Service.MS_ID_PREFIX;
} else {
prefix = Service.CL_ID_PREFIX;
}
if (heartbeatId.equals(prefix + id)
|| heartbeatId.equals(id)) {
if (checkHostLocationsFieldsChanged()) {
changed = true;
}
} else {
changed = true;
}
} else {
if (heartbeatId == null) {
} else if (heartbeatId.equals(Service.RES_ID_PREFIX
+ getService().getName()
+ "_" + id)
|| heartbeatId.equals(Service.STONITH_ID_PREFIX
+ getService().getName()
+ "_" + id)
|| heartbeatId.equals(id)) {
if (checkHostLocationsFieldsChanged()
|| checkOperationFieldsChanged()) {
changed = true;
}
} else {
changed = true;
}
}
final String cl = getService().getResourceClass();
if (cl != null && (cl.equals(ResourceAgent.HEARTBEAT_CLASS)
|| ResourceAgent.SERVICE_CLASSES.contains(cl))) {
/* in old style resources don't show all the textfields */
boolean visible = false;
Widget wi = null;
for (int i = params.length - 1; i >= 0; i--) {
final Widget prevWi = getWidget(params[i], null);
if (prevWi == null) {
continue;
}
if (!visible && !prevWi.getStringValue().equals("")) {
visible = true;
}
if (wi != null && wi.isVisible() != visible) {
final boolean v = visible;
final Widget c = wi;
c.setVisible(v);
}
wi = prevWi;
}
}
/* id-refs */
if (sameAsMetaAttrsWi != null) {
final Info info = sameAsMetaAttrsWiValue();
final boolean defaultValues =
info != null
&& META_ATTRS_DEFAULT_VALUES_TEXT.equals(info.toString());
final boolean nothingSelected =
info == null
|| Widget.NOTHING_SELECTED_DISPLAY.equals(
info.toString());
if (!nothingSelected
&& !defaultValues
&& info != savedMetaAttrInfoRef) {
changed = true;
} else {
if ((nothingSelected || defaultValues)
&& savedMetaAttrInfoRef != null) {
changed = true;
}
if (savedMetaAttrInfoRef == null
&& defaultValues != allMetaAttrsAreDefaultValues) {
if (allMetaAttrsAreDefaultValues) {
sameAsMetaAttrsWi.setValueNoListeners(
META_ATTRS_DEFAULT_VALUES_TEXT);
} else {
sameAsMetaAttrsWi.setValueNoListeners(
Widget.NOTHING_SELECTED_INTERNAL);
}
}
}
sameAsMetaAttrsWi.processAccessMode();
}
if (!fromServicesInfo) {
final ServicesInfo sis = getBrowser().getServicesInfo();
sis.setApplyButtons(null, sis.getParametersFromXML());
}
return changed;
}
/** Returns operation default for parameter. */
private String getOpDefaultsDefault(final String param) {
assert param != null;
/* if op_defaults is set... It cannot be set in the GUI */
final ClusterStatus cs = getBrowser().getClusterStatus();
if (cs != null) {
return cs.getOpDefaultsValuePairs().get(param);
}
return null;
}
/** Sets service parameters with values from resourceNode hash. */
void setParameters(final Map<String, String> resourceNode) {
if (resourceNode == null) {
return;
}
final boolean infoPanelOk = isInfoPanelOk();
final CRMXML crmXML = getBrowser().getCRMXML();
if (crmXML == null) {
Tools.appError("crmXML is null");
return;
}
/* Attributes */
final String[] params = getEnabledSectionParams(
crmXML.getParameters(resourceAgent,
getService().isMaster()));
final ClusterStatus cs = getBrowser().getClusterStatus();
if (params != null) {
boolean allMetaAttrsAreDefaultValues = true;
boolean allSavedMetaAttrsAreDefaultValues = true;
final String newMetaAttrsId = cs.getMetaAttrsId(
getService().getHeartbeatId());
if ((savedMetaAttrsId == null && newMetaAttrsId != null)
|| (savedMetaAttrsId != null
&& !savedMetaAttrsId.equals(newMetaAttrsId))) {
/* newly generated operations id, reload all other combo
boxes. */
getBrowser().reloadAllComboBoxes(this);
}
savedMetaAttrsId = newMetaAttrsId;
String refCRMId = cs.getMetaAttrsRef(getService().getHeartbeatId());
final ServiceInfo metaAttrInfoRef =
getBrowser().getServiceInfoFromCRMId(refCRMId);
if (refCRMId == null) {
refCRMId = getService().getHeartbeatId();
}
resourceNode.put(PCMK_ID, getService().getHeartbeatId());
resourceNode.put(GUI_ID, getService().getId());
for (String param : params) {
String value;
if (isMetaAttr(param) && refCRMId != null) {
value = cs.getParameter(refCRMId, param, false);
} else {
value = resourceNode.get(param);
}
final String defaultValue = getParamDefault(param);
if (value == null) {
value = defaultValue;
}
if (value == null) {
value = "";
}
final String oldValue = getResource().getValue(param);
if (isMetaAttr(param)) {
if (!Tools.areEqual(defaultValue, value)) {
allMetaAttrsAreDefaultValues = false;
}
if (!Tools.areEqual(defaultValue, oldValue)) {
allSavedMetaAttrsAreDefaultValues = false;
}
}
if (infoPanelOk) {
final Widget wi = getWidget(param, null);
final boolean haveChanged =
!Tools.areEqual(value, oldValue)
|| !Tools.areEqual(defaultValue,
getResource().getDefaultValue(param));
if (haveChanged
|| (metaAttrInfoRef != null && isMetaAttr(param))) {
getResource().setValue(param, value);
/* set default value, because it can change in
* rsc_defaults. */
getResource().setDefaultValue(param, defaultValue);
if (wi != null && metaAttrInfoRef == null) {
wi.setValue(value);
}
}
}
}
if (!Tools.areEqual(metaAttrInfoRef, savedMetaAttrInfoRef)) {
savedMetaAttrInfoRef = metaAttrInfoRef;
if (sameAsMetaAttrsWi != null) {
if (metaAttrInfoRef == null) {
if (allMetaAttrsAreDefaultValues) {
if (!allSavedMetaAttrsAreDefaultValues) {
sameAsMetaAttrsWi.setValue(
META_ATTRS_DEFAULT_VALUES_TEXT);
}
} else {
if (metaAttrInfoRef != null) {
sameAsMetaAttrsWi.setValue(
Widget.NOTHING_SELECTED_INTERNAL);
}
}
} else {
sameAsMetaAttrsWi.setValue(metaAttrInfoRef);
}
}
}
}
/* set scores */
for (Host host : getBrowser().getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
final HostLocation hostLocation = cs.getScore(
getService().getHeartbeatId(),
hi.getName(),
false);
final HostLocation savedLocation = savedHostLocations.get(hi);
if (!Tools.areEqual(hostLocation, savedLocation)) {
if (hostLocation == null) {
savedHostLocations.remove(hi);
} else {
savedHostLocations.put(hi, hostLocation);
}
if (infoPanelOk) {
final Widget wi = scoreComboBoxHash.get(hi);
if (wi != null) {
String score = null;
String op = null;
if (hostLocation != null) {
score = hostLocation.getScore();
op = hostLocation.getOperation();
}
wi.setValue(score);
final JLabel label = wi.getLabel();
final String text =
getHostLocationLabel(hi.getName(), op);
label.setText(text);
}
}
}
}
/* set ping constraint */
final HostLocation hostLocation = cs.getPingScore(
getService().getHeartbeatId(),
false);
String pingOperation = null;
if (hostLocation != null) {
final String op = hostLocation.getOperation();
final String value = hostLocation.getValue();
if ("eq".equals(op) && "0".equals(value)) {
pingOperation = "eq0";
} else {
pingOperation = hostLocation.getOperation();
}
}
if (!Tools.areEqual(pingOperation, savedPingOperation)) {
savedPingOperation = pingOperation;
}
if (infoPanelOk) {
final Widget wi = pingComboBox;
if (wi != null) {
if (pingOperation == null) {
wi.setValue(Widget.NOTHING_SELECTED_INTERNAL);
} else {
wi.setValue(PING_ATTRIBUTES.get(pingOperation));
}
}
}
boolean allAreDefaultValues = true;
boolean allSavedAreDefaultValues = true;
/* Operations */
final String newOperationsId = cs.getOperationsId(
getService().getHeartbeatId());
if ((savedOperationsId == null && newOperationsId != null)
|| (savedOperationsId != null
&& !savedOperationsId.equals(newOperationsId))) {
/* newly generated operations id, reload all other combo
boxes. */
getBrowser().reloadAllComboBoxes(this);
}
savedOperationsId = newOperationsId;
String refCRMId = cs.getOperationsRef(getService().getHeartbeatId());
final ServiceInfo operationIdRef =
getBrowser().getServiceInfoFromCRMId(refCRMId);
if (refCRMId == null) {
refCRMId = getService().getHeartbeatId();
}
mSavedOperationsLock.lock();
for (final String op : getResourceAgent().getOperationNames()) {
for (final String param
: getBrowser().getCRMOperationParams(op)) {
String defaultValue =
resourceAgent.getOperationDefault(op, param);
if (defaultValue == null) {
continue;
}
if (ClusterBrowser.HB_OP_IGNORE_DEFAULT.contains(op)) {
defaultValue = "";
}
String value = cs.getOperation(refCRMId, op, param);
if (value == null || "".equals(value)) {
value = getOpDefaultsDefault(param);
}
if (value == null) {
value = "";
}
if (!defaultValue.equals(value)) {
allAreDefaultValues = false;
}
if (!defaultValue.equals(savedOperation.get(op, param))) {
allSavedAreDefaultValues = false;
}
}
}
boolean sameAs = false;
if (!Tools.areEqual(operationIdRef, savedOperationIdRef)) {
savedOperationIdRef = operationIdRef;
if (sameAsOperationsWi != null) {
if (operationIdRef == null) {
if (allAreDefaultValues) { // TODO: don't have it yet.
if (!allSavedAreDefaultValues) {
sameAsOperationsWi.setValue(
OPERATIONS_DEFAULT_VALUES_TEXT);
}
} else {
if (savedOperationIdRef != null) {
sameAsOperationsWi.setValue(
Widget.NOTHING_SELECTED_INTERNAL);
}
}
} else {
sameAs = false;
sameAsOperationsWi.setValue(operationIdRef);
}
}
}
if (!sameAs) {
for (final String op : getResourceAgent().getOperationNames()) {
for (final String param
: getBrowser().getCRMOperationParams(op)) {
String defaultValue =
resourceAgent.getOperationDefault(op, param);
if (defaultValue == null) {
continue;
}
if (ClusterBrowser.HB_OP_IGNORE_DEFAULT.contains(op)) {
defaultValue = "";
}
String value = cs.getOperation(refCRMId, op, param);
if (value == null || "".equals(value)) {
value = getOpDefaultsDefault(param);
}
if (value == null) {
value = "";
}
if (!value.equals(savedOperation.get(op, param))) {
savedOperation.put(op, param, value);
if (infoPanelOk) {
mOperationsComboBoxHashReadLock.lock();
final Widget wi = operationsComboBoxHash.get(op,
param);
mOperationsComboBoxHashReadLock.unlock();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
wi.setEnabled(operationIdRef == null);
}
});
if (value != null) {
wi.setValue(value);
}
}
}
}
}
}
mSavedOperationsLock.unlock();
getService().setAvailable();
if (cs.isOrphaned(getHeartbeatId(false))) {
getService().setOrphaned(true);
getService().setNew(false);
final CloneInfo ci = getCloneInfo();
if (ci != null) {
ci.getService().setNew(false);
}
} else {
getService().setOrphaned(false);
}
}
/** Returns name of this resource, that is used in logs. */
String getNameForLog() {
return getName();
}
/**
* Returns a name of the service with id in the parentheses.
* It adds prefix 'new' if id is null.
*/
@Override
public String toString() {
final StringBuilder s = new StringBuilder(30);
final String provider = resourceAgent.getProvider();
if (!ResourceAgent.HEARTBEAT_PROVIDER.equals(provider)
&& !"".equals(provider)) {
s.append(provider);
s.append(':');
}
s.append(getName());
final String string = getService().getId();
/* 'string' contains the last string if there are more dependent
* resources, although there is usually only one. */
if (string == null) {
s.insert(0, "new ");
} else {
if (!"".equals(string)) {
s.append(" (");
s.append(string);
s.append(')');
}
}
return s.toString();
}
/** Returns node name of the host where this service is running. */
List<String> getMasterOnNodes(final boolean testOnly) {
return getBrowser().getClusterStatus().getMasterOnNodes(
getHeartbeatId(testOnly),
testOnly);
}
/** Returns node name of the host where this service is running. */
List<String> getRunningOnNodes(final boolean testOnly) {
return getBrowser().getClusterStatus().getRunningOnNodes(
getHeartbeatId(testOnly),
testOnly);
}
/** Returns whether service is started. */
boolean isStarted(final boolean testOnly) {
final Host dcHost = getBrowser().getDCHost();
final String hbV = dcHost.getHeartbeatVersion();
final String pmV = dcHost.getPacemakerVersion();
String targetRoleString = "target-role";
if (Tools.versionBeforePacemaker(dcHost)) {
targetRoleString = "target_role";
}
String crmId = getHeartbeatId(testOnly);
final ClusterStatus cs = getBrowser().getClusterStatus();
final String refCRMId = cs.getMetaAttrsRef(crmId);
if (refCRMId != null) {
crmId = refCRMId;
}
String targetRole = cs.getParameter(crmId, targetRoleString, testOnly);
if (targetRole == null) {
targetRole = getParamDefault(targetRoleString);
}
if (!CRMXML.TARGET_ROLE_STOPPED.equals(targetRole)) {
return true;
}
return false;
}
/** Returns whether the service was set to be in slave role. */
public boolean isEnslaved(final boolean testOnly) {
final Host dcHost = getBrowser().getDCHost();
String targetRoleString = "target-role";
if (Tools.versionBeforePacemaker(dcHost)) {
targetRoleString = "target_role";
}
String crmId = getHeartbeatId(testOnly);
final ClusterStatus cs = getBrowser().getClusterStatus();
final String refCRMId = cs.getMetaAttrsRef(crmId);
if (refCRMId != null) {
crmId = refCRMId;
}
String targetRole = cs.getParameter(crmId, targetRoleString, testOnly);
if (targetRole == null) {
targetRole = getParamDefault(targetRoleString);
}
if (CRMXML.TARGET_ROLE_SLAVE.equals(targetRole)) {
return true;
}
return false;
}
/** Returns whether service is stopped. */
public boolean isStopped(final boolean testOnly) {
final Host dcHost = getBrowser().getDCHost();
String targetRoleString = "target-role";
if (Tools.versionBeforePacemaker(dcHost)) {
targetRoleString = "target_role";
}
String crmId = getHeartbeatId(testOnly);
final ClusterStatus cs = getBrowser().getClusterStatus();
final String refCRMId = cs.getMetaAttrsRef(crmId);
if (refCRMId != null) {
crmId = refCRMId;
}
String targetRole = cs.getParameter(crmId, targetRoleString, testOnly);
if (targetRole == null) {
targetRole = getParamDefault(targetRoleString);
}
if (CRMXML.TARGET_ROLE_STOPPED.equals(targetRole)) {
return true;
}
return false;
}
/** Returns whether the group is stopped. */
boolean isGroupStopped(final boolean testOnly) {
return false;
}
/**
* Returns whether service is managed.
* TODO: "default" value
*/
public boolean isManaged(final boolean testOnly) {
return getBrowser().getClusterStatus().isManaged(
getHeartbeatId(testOnly),
testOnly);
}
/** Returns whether the service where was migrated or null. */
public List<Host> getMigratedTo(final boolean testOnly) {
final ClusterStatus cs = getBrowser().getClusterStatus();
for (Host host : getBrowser().getClusterHosts()) {
final String locationId = cs.getLocationId(getHeartbeatId(testOnly),
host.getName(),
testOnly);
if (locationId == null
|| (!locationId.startsWith("cli-prefer-")
&& !locationId.startsWith("cli-standby-"))) {
continue;
}
final HostInfo hi = host.getBrowser().getHostInfo();
final HostLocation hostLocation = cs.getScore(
getHeartbeatId(testOnly),
hi.getName(),
testOnly);
String score = null;
String op = null;
if (hostLocation != null) {
score = hostLocation.getScore();
op = hostLocation.getOperation();
}
if ((CRMXML.INFINITY_STRING.equals(score)
|| CRMXML.PLUS_INFINITY_STRING.equals(score))
&& "eq".equals(op)) {
final List<Host> hosts = new ArrayList<Host>();
hosts.add(host);
return hosts;
}
}
return null;
}
/** Returns whether the service where was migrated or null. */
public List<Host> getMigratedFrom(final boolean testOnly) {
final ClusterStatus cs = getBrowser().getClusterStatus();
for (Host host : getBrowser().getClusterHosts()) {
final String locationId = cs.getLocationId(getHeartbeatId(testOnly),
host.getName(),
testOnly);
if (locationId == null
|| (!locationId.startsWith("cli-prefer-")
&& !locationId.startsWith("cli-standby-"))) {
continue;
}
final HostInfo hi = host.getBrowser().getHostInfo();
final HostLocation hostLocation = cs.getScore(
getHeartbeatId(testOnly),
hi.getName(),
testOnly);
String score = null;
String op = null;
if (hostLocation != null) {
score = hostLocation.getScore();
op = hostLocation.getOperation();
}
if (CRMXML.MINUS_INFINITY_STRING.equals(score)
&& "eq".equals(op)) {
final List<Host> hosts = new ArrayList<Host>();
hosts.add(host);
return hosts;
}
}
return null;
}
/** Returns whether the service is running. */
public boolean isRunning(final boolean testOnly) {
final List<String> runningOnNodes = getRunningOnNodes(testOnly);
return runningOnNodes != null && !runningOnNodes.isEmpty();
}
/** Returns fail count string that appears in the graph. */
private String getFailCountString(final String hostName,
final boolean testOnly) {
String fcString = "";
final String failCount = getFailCount(hostName, testOnly);
if (failCount != null) {
if (CRMXML.INFINITY_STRING.equals(failCount)) {
fcString = " failed";
} else {
fcString = " failed: " + failCount;
}
}
return fcString;
}
/** Returns fail count. */
protected String getFailCount(final String hostName,
final boolean testOnly) {
final ClusterStatus cs = getBrowser().getClusterStatus();
return cs.getFailCount(hostName, getHeartbeatId(testOnly), testOnly);
}
/** Returns ping count. */
protected String getPingCount(final String hostName,
final boolean testOnly) {
final ClusterStatus cs = getBrowser().getClusterStatus();
return cs.getPingCount(hostName, testOnly);
}
/** Returns fail ping string that appears in the graph. */
protected String getPingCountString(final String hostName,
final boolean testOnly) {
if (!resourceAgent.isPingService()) {
return "";
}
final String pingCount = getPingCount(hostName, testOnly);
if (pingCount == null || "0".equals(pingCount)) {
return " / no ping";
} else {
return " / ping: " + pingCount;
}
}
/** Returns whether the resource is orphaned on the specified host. */
protected final boolean isInLRMOnHost(final String hostName,
final boolean testOnly) {
final ClusterStatus cs = getBrowser().getClusterStatus();
return cs.isInLRMOnHost(hostName, getHeartbeatId(testOnly), testOnly);
}
/** Returns whether the resource failed on the specified host. */
protected final boolean failedOnHost(final String hostName,
final boolean testOnly) {
final String failCount = getFailCount(hostName,
testOnly);
return failCount != null
&& CRMXML.INFINITY_STRING.equals(failCount);
}
/** Returns whether the resource has failed to start. */
public boolean isFailed(final boolean testOnly) {
if (isRunning(testOnly)) {
return false;
}
for (final Host host : getBrowser().getClusterHosts()) {
if (host.isClStatus() && failedOnHost(host.getName(),
testOnly)) {
return true;
}
}
return false;
}
/** Returns whether the resource has failed on one of the nodes. */
boolean isOneFailed(final boolean testOnly) {
for (final Host host : getBrowser().getClusterHosts()) {
if (failedOnHost(host.getName(), testOnly)) {
return true;
}
}
return false;
}
/** Returns whether the resource has fail-count on one of the nodes. */
boolean isOneFailedCount(final boolean testOnly) {
for (final Host host : getBrowser().getClusterHosts()) {
if (getFailCount(host.getName(), testOnly) != null) {
return true;
}
}
return false;
}
/** Sets whether the service is managed. */
void setManaged(final boolean isManaged,
final Host dcHost,
final boolean testOnly) {
if (!testOnly) {
setUpdated(true);
}
CRM.setManaged(dcHost, getHeartbeatId(testOnly), isManaged, testOnly);
}
/** Returns color for the host vertex. */
public List<Color> getHostColors(final boolean testOnly) {
return getBrowser().getCluster().getHostColors(
getRunningOnNodes(testOnly));
}
/**
* Returns service icon in the menu. It can be started or stopped.
* TODO: broken icon, not managed icon.
*/
@Override
public ImageIcon getMenuIcon(final boolean testOnly) {
if (isFailed(testOnly)) {
if (isRunning(testOnly)) {
return SERVICE_RUNNING_FAILED_ICON_SMALL;
} else {
return SERVICE_STOPPED_FAILED_ICON_SMALL;
}
} else if (isStopped(testOnly) || getBrowser().allHostsDown()) {
if (isRunning(testOnly)) {
return SERVICE_STOPPING_ICON_SMALL;
} else {
return SERVICE_STOPPED_ICON_SMALL;
}
} else {
if (isRunning(testOnly)) {
return SERVICE_RUNNING_ICON_SMALL;
} else {
return SERVICE_STARTED_ICON_SMALL;
}
}
}
/** Gets saved host scores. */
Map<HostInfo, HostLocation> getSavedHostLocations() {
return savedHostLocations;
}
/** Returns list of all host names in this cluster. */
List<String> getHostNames() {
final List<String> hostNames = new ArrayList<String>();
@SuppressWarnings("unchecked")
final Enumeration<DefaultMutableTreeNode> e =
getBrowser().getClusterHostsNode().children();
while (e.hasMoreElements()) {
final DefaultMutableTreeNode n = e.nextElement();
final String hostName = ((HostInfo) n.getUserObject()).getName();
hostNames.add(hostName);
}
return hostNames;
}
/**
* TODO: wrong doku
* Converts enumeration to the info array, get objects from
* hash if they exist.
*/
protected Info[] enumToInfoArray(
final Info defaultValue,
final String serviceName,
final Enumeration<DefaultMutableTreeNode> e) {
final List<Info> list = new ArrayList<Info>();
if (defaultValue != null) {
list.add(defaultValue);
}
while (e.hasMoreElements()) {
final DefaultMutableTreeNode n = e.nextElement();
final Info i = (Info) n.getUserObject();
final String name = i.getName();
final ServiceInfo si = getBrowser().getServiceInfoFromId(
serviceName,
i.getName());
if (si == null && !name.equals(defaultValue)) {
list.add(i);
}
}
return list.toArray(new Info[list.size()]);
}
/**
* Stores scores for host.
*/
private void storeHostLocations() {
savedHostLocations.clear();
for (final Host host : getBrowser().getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
final Widget wi = scoreComboBoxHash.get(hi);
final String score = wi.getStringValue();
final String op = getOpFromLabel(hi.getName(),
wi.getLabel().getText());
if (score == null || "".equals(score)) {
savedHostLocations.remove(hi);
} else {
savedHostLocations.put(hi,
new HostLocation(score, op, null, null));
}
}
/* ping */
final Object o = pingComboBox.getValue();
String value = null;
if (o != null) {
value = ((StringInfo) o).getInternalValue();
}
savedPingOperation = value;
}
/**
* Returns thrue if an operation field changed.
*/
private boolean checkOperationFieldsChanged() {
boolean changed = false;
boolean allAreDefaultValues = true;
mSavedOperationsLock.lock();
for (final String op : getResourceAgent().getOperationNames()) {
for (final String param : getBrowser().getCRMOperationParams(op)) {
String defaultValue =
resourceAgent.getOperationDefault(op, param);
if (defaultValue == null) {
continue;
}
if (ClusterBrowser.HB_OP_IGNORE_DEFAULT.contains(op)) {
defaultValue = "";
}
mOperationsComboBoxHashReadLock.lock();
final Widget wi = operationsComboBoxHash.get(op, param);
mOperationsComboBoxHashReadLock.unlock();
if (wi == null) {
continue;
}
if (CRMXML.PAR_CHECK_LEVEL.equals(param)) {
final Object value = wi.getValue();
if (!Tools.areEqual(value, defaultValue)) {
allAreDefaultValues = false;
}
final String savedOp = savedOperation.get(op, param);
if (savedOp == null) {
if (!Tools.areEqual(value, defaultValue)) {
changed = true;
}
} else if (!Tools.areEqual(value, savedOp)) {
changed = true;
}
wi.setBackground(defaultValue, savedOp, false);
} else {
final Object[] defaultValueE =
Tools.extractUnit(defaultValue);
Object value = wi.getValue();
if (Tools.areEqual(value, new Object[]{"", ""})) {
value = new Object[]{getOpDefaultsDefault(param), null};
}
if (!Tools.areEqual(value, defaultValueE)) {
allAreDefaultValues = false;
}
final String savedOp = savedOperation.get(op, param);
final Object[] savedOpE = Tools.extractUnit(savedOp);
if (savedOp == null) {
if (!Tools.areEqual(value, defaultValueE)) {
changed = true;
}
} else if (!Tools.areEqual(value, savedOpE)) {
changed = true;
}
wi.setBackground(defaultValueE, savedOpE, false);
}
}
}
if (sameAsOperationsWi != null) {
final Info info = sameAsOperationsWiValue();
final boolean defaultValues =
info != null
&& OPERATIONS_DEFAULT_VALUES_TEXT.equals(info.toString());
final boolean nothingSelected =
info == null
|| Widget.NOTHING_SELECTED_DISPLAY.equals(
info.toString());
if (!nothingSelected
&& !defaultValues
&& info != savedOperationIdRef) {
changed = true;
} else {
if ((nothingSelected || defaultValues)
&& savedOperationIdRef != null) {
changed = true;
}
if (savedOperationIdRef == null
&& defaultValues != allAreDefaultValues) {
if (allAreDefaultValues) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
sameAsOperationsWi.setValueNoListeners(
OPERATIONS_DEFAULT_VALUES_TEXT);
}
});
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
sameAsOperationsWi.setValueNoListeners(
Widget.NOTHING_SELECTED_INTERNAL);
}
});
}
}
}
sameAsOperationsWi.processAccessMode();
}
mSavedOperationsLock.unlock();
return changed;
}
/**
* Returns true if some of the scores have changed.
*/
private boolean checkHostLocationsFieldsChanged() {
boolean changed = false;
for (Host host : getBrowser().getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
final Widget wi = scoreComboBoxHash.get(hi);
final HostLocation hlSaved = savedHostLocations.get(hi);
String hsSaved = null;
String opSaved = null;
if (hlSaved != null) {
hsSaved = hlSaved.getScore();
opSaved = hlSaved.getOperation();
}
final String opSavedLabel = getHostLocationLabel(host.getName(),
opSaved);
if (wi == null) {
continue;
}
String labelText = null;
if (wi.getLabel() != null) {
labelText = wi.getLabel().getText();
}
if (!Tools.areEqual(hsSaved, wi.getStringValue())
|| (!Tools.areEqual(opSavedLabel, labelText)
&& (hsSaved != null && !"".equals(hsSaved)))) {
changed = true;
}
wi.setBackground(getHostLocationLabel(host.getName(), "eq"),
null,
opSavedLabel,
hsSaved,
false);
}
/* ping */
final Widget pwi = pingComboBox;
if (pwi != null) {
if (!Tools.areEqual(savedPingOperation,
pwi.getValue())) {
changed = true;
}
pwi.setBackground(null,
savedPingOperation,
false);
}
return changed;
}
/**
* Returns the list of all services, that can be used in the 'add
* service' action.
*/
List<ResourceAgent> getAddServiceList(final String cl) {
return getBrowser().globalGetAddServiceList(cl);
}
/**
* Returns info object of all block devices on all hosts that have the
* same names and other attributes.
*/
Info[] getCommonBlockDevInfos(final Info defaultValue,
final String serviceName) {
final List<Info> list = new ArrayList<Info>();
/* drbd resources */
@SuppressWarnings("unchecked")
final Enumeration<DefaultMutableTreeNode> drbdResources =
getBrowser().getDrbdNode().children();
if (defaultValue != null) {
list.add(defaultValue);
}
while (drbdResources.hasMoreElements()) {
final DefaultMutableTreeNode n = drbdResources.nextElement();
final DrbdResourceInfo drbdRes =
(DrbdResourceInfo) n.getUserObject();
final DefaultMutableTreeNode drbdResNode = drbdRes.getNode();
if (drbdResNode != null) {
@SuppressWarnings("unchecked")
final Enumeration<DefaultMutableTreeNode> drbdVolumes =
drbdResNode.children();
while (drbdVolumes.hasMoreElements()) {
final DefaultMutableTreeNode vn = drbdVolumes.nextElement();
final CommonDeviceInterface drbdVol =
(CommonDeviceInterface) vn.getUserObject();
list.add((Info) drbdVol);
}
}
}
/* block devices that are the same on all hosts */
@SuppressWarnings("unchecked")
final Enumeration<DefaultMutableTreeNode> wids =
getBrowser().getCommonBlockDevicesNode().children();
while (wids.hasMoreElements()) {
final DefaultMutableTreeNode n = wids.nextElement();
final CommonDeviceInterface wid =
(CommonDeviceInterface) n.getUserObject();
list.add((Info) wid);
}
return list.toArray(new Info[list.size()]);
}
/**
* Adds clone fields to the option pane.
*/
protected void addCloneFields(final JPanel optionsPanel,
final int leftWidth,
final int rightWidth) {
final CloneInfo ci = getCloneInfo();
final String[] params = ci.getParametersFromXML();
final Info savedMAIdRef = ci.getSavedMetaAttrInfoRef();
ci.getResource().setValue(GUI_ID, ci.getService().getId());
ci.addParams(optionsPanel,
params,
ClusterBrowser.SERVICE_LABEL_WIDTH,
ClusterBrowser.SERVICE_FIELD_WIDTH,
ci.getSameAsFields(savedMAIdRef));
if (!ci.getService().isNew()) {
ci.getWidget(GUI_ID, null).setEnabled(false);
}
for (final String param : params) {
if (ci.isMetaAttr(param)) {
final Widget wi = ci.getWidget(param, null);
wi.setEnabled(savedMAIdRef == null);
}
}
ci.addHostLocations(optionsPanel,
ClusterBrowser.SERVICE_LABEL_WIDTH,
ClusterBrowser.SERVICE_FIELD_WIDTH);
}
/**
* Returns label for host locations, which consist of host name and
* operation.
*/
private String getHostLocationLabel(final String hostName,
final String op) {
final StringBuilder sb = new StringBuilder(20);
if (op == null || "eq".equals(op)) {
sb.append("on ");
} else if ("ne".equals(op)) {
sb.append("NOT on ");
} else {
sb.append(op);
sb.append(' ');
}
sb.append(hostName);
return sb.toString();
}
/**
* Creates host score combo boxes with labels, one per host.
*/
protected void addHostLocations(final JPanel optionsPanel,
final int leftWidth,
final int rightWidth) {
int rows = 0;
final JPanel panel =
getParamPanel(Tools.getString("ClusterBrowser.HostLocations"));
panel.setLayout(new SpringLayout());
for (final Host host : getBrowser().getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
final Map<String, String> abbreviations =
new HashMap<String, String>();
abbreviations.put("i", CRMXML.INFINITY_STRING);
abbreviations.put("+", CRMXML.PLUS_INFINITY_STRING);
abbreviations.put("I", CRMXML.INFINITY_STRING);
abbreviations.put("a", "ALWAYS");
abbreviations.put("n", "NEVER");
final Widget wi = WidgetFactory.createInstance(
Widget.Type.COMBOBOX,
null,
new String[]{null,
"0",
"2",
"ALWAYS",
"NEVER",
CRMXML.INFINITY_STRING,
CRMXML.MINUS_INFINITY_STRING,
CRMXML.INFINITY_STRING},
"^((-?\\d*|(-|\\+)?" + CRMXML.INFINITY_STRING
+ "))|ALWAYS|NEVER|@NOTHING_SELECTED@$",
rightWidth,
abbreviations,
new AccessMode(ConfigData.AccessType.ADMIN,
false),
Widget.NO_BUTTON);
wi.setEditable(true);
final Widget prevWi = scoreComboBoxHash.get(hi);
scoreComboBoxHash.put(hi, wi);
/* set selected host scores in the combo box from
* savedHostLocations */
if (prevWi == null) {
final HostLocation hl = savedHostLocations.get(hi);
String hsSaved = null;
if (hl != null) {
hsSaved = hl.getScore();
}
wi.setValue(hsSaved);
} else {
wi.setValue(prevWi.getValue());
}
}
/* host score combo boxes */
for (Host host : getBrowser().getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
final Widget wi = scoreComboBoxHash.get(hi);
String op = null;
final HostLocation hl = savedHostLocations.get(hi);
if (hl != null) {
op = hl.getOperation();
}
final String text = getHostLocationLabel(hi.getName(), op);
final JLabel label = new JLabel(text);
final String onText = getHostLocationLabel(hi.getName(), "eq");
final String notOnText = getHostLocationLabel(hi.getName(), "ne");
label.addMouseListener(new MouseListener() {
@Override
public final void mouseClicked(final MouseEvent e) {
/* do nothing */
}
@Override
public final void mouseEntered(final MouseEvent e) {
/* do nothing */
}
@Override
public final void mouseExited(final MouseEvent e) {
/* do nothing */
}
@Override
public final void mousePressed(final MouseEvent e) {
final String currentText = label.getText();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (currentText.equals(onText)) {
label.setText(notOnText);
} else if (currentText.equals(notOnText)) {
label.setText(onText);
} else {
/* wierd things */
label.setText(onText);
}
final String[] params = getParametersFromXML();
setApplyButtons(CACHED_FIELD, params);
}
});
}
@Override
public final void mouseReleased(final MouseEvent e) {
/* do nothing */
}
});
wi.setLabel(label, text);
addField(panel,
label,
wi,
leftWidth,
rightWidth,
0);
rows++;
}
rows += addPingField(panel, leftWidth, rightWidth);
SpringUtilities.makeCompactGrid(panel, rows, 2, /* rows, cols */
1, 1, /* initX, initY */
1, 1); /* xPad, yPad */
optionsPanel.add(panel);
}
/** Adds field with ping constraint. */
private int addPingField(final JPanel panel,
final int leftWidth,
final int rightWidth) {
int rows = 0;
final JLabel pingLabel = new JLabel("pingd");
String savedPO = null;
final Widget prevWi = pingComboBox;
if (prevWi == null) {
savedPO = savedPingOperation;
} else {
savedPO = prevWi.getStringValue();
}
final Widget pingWi = WidgetFactory.createInstance(
Widget.Type.COMBOBOX,
savedPO,
new StringInfo[]{new StringInfo(
Widget.NOTHING_SELECTED_DISPLAY,
Widget.NOTHING_SELECTED_INTERNAL,
getBrowser()),
new StringInfo(
PING_ATTRIBUTES.get("defined"),
"defined",
getBrowser()),
new StringInfo(
PING_ATTRIBUTES.get("eq0"),
"eq0",
getBrowser())},
Widget.NO_REGEXP,
rightWidth,
Widget.NO_ABBRV,
new AccessMode(ConfigData.AccessType.ADMIN,
false),
Widget.NO_BUTTON);
addField(panel, pingLabel, pingWi, leftWidth, rightWidth, 0);
pingWi.setLabel(pingLabel,
Tools.getString("ServiceInfo.PingdToolTip"));
if (resourceAgent.isPingService() && savedPingOperation == null) {
pingWi.setEnabled(false);
}
pingComboBox = pingWi;
rows++;
return rows;
}
/**
* Returns whetrher this service's meta attributes are referenced by
* some other service.
*/
private boolean isMetaAttrReferenced() {
final ClusterStatus cs = getBrowser().getClusterStatus();
getBrowser().mHeartbeatIdToServiceLock();
final Map<String, ServiceInfo> services =
getBrowser().getHeartbeatIdToServiceInfo();
for (final ServiceInfo si : services.values()) {
final String refCRMId = cs.getMetaAttrsRef(
si.getService().getHeartbeatId());
if (refCRMId != null
&& refCRMId.equals(getService().getHeartbeatId())) {
getBrowser().mHeartbeatIdToServiceUnlock();
return true;
}
}
getBrowser().mHeartbeatIdToServiceUnlock();
return false;
}
/**
* Sets meta attrs with same values as other service info, or default
* values.
*/
private void setMetaAttrsSameAs(final Info info) {
if (sameAsMetaAttrsWi == null || info == null) {
return;
}
boolean nothingSelected = false;
if (Widget.NOTHING_SELECTED_DISPLAY.equals(info.toString())) {
nothingSelected = true;
}
boolean sameAs = true;
if (META_ATTRS_DEFAULT_VALUES_TEXT.equals(info.toString())) {
sameAs = false;
}
final String[] params = getParametersFromXML();
if (params != null) {
for (final String param : params) {
if (!isMetaAttr(param)) {
continue;
}
String defaultValue = getParamPreferred(param);
if (defaultValue == null) {
defaultValue = getParamDefault(param);
}
final Widget wi = getWidget(param, null);
if (wi == null) {
continue;
}
Object oldValue = wi.getValue();
if (oldValue == null) {
oldValue = defaultValue;
}
wi.setEnabled(!sameAs || nothingSelected);
if (!nothingSelected) {
if (sameAs) {
/* same as some other service */
defaultValue =
((ServiceInfo) info).getParamSaved(param);
}
final String newValue = defaultValue;
if (!Tools.areEqual(oldValue, newValue)) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (wi != null) {
wi.setValue(newValue);
}
}
});
}
}
}
}
}
/**
* Returns whetrher this service's operations are referenced by some
* other service.
*/
private boolean isOperationReferenced() {
final ClusterStatus cs = getBrowser().getClusterStatus();
getBrowser().mHeartbeatIdToServiceLock();
final Map<String, ServiceInfo> services =
getBrowser().getHeartbeatIdToServiceInfo();
for (final ServiceInfo si : services.values()) {
final String refCRMId = cs.getOperationsRef(
si.getService().getHeartbeatId());
if (refCRMId != null
&& refCRMId.equals(getService().getHeartbeatId())) {
getBrowser().mHeartbeatIdToServiceUnlock();
return true;
}
}
getBrowser().mHeartbeatIdToServiceUnlock();
return false;
}
/** Returns selected operations id reference. */
private Info getSameServiceOpIdRef() {
mSavedOperationsLock.lock();
final ServiceInfo savedOpIdRef = savedOperationIdRef;
mSavedOperationsLock.unlock();
return savedOpIdRef;
}
/**
* Returns all services except this one, that are of the same type
* for meta attributes.
*/
private Info[] getSameServicesMetaAttrs() {
final List<Info> sl = new ArrayList<Info>();
sl.add(new StringInfo(Widget.NOTHING_SELECTED_DISPLAY,
Widget.NOTHING_SELECTED_INTERNAL,
getBrowser()));
sl.add(new StringInfo(META_ATTRS_DEFAULT_VALUES_TEXT,
META_ATTRS_DEFAULT_VALUES,
getBrowser()));
final Host dcHost = getBrowser().getDCHost();
if (isMetaAttrReferenced() || Tools.versionBeforePacemaker(dcHost)) {
return sl.toArray(new Info[sl.size()]);
}
getBrowser().lockNameToServiceInfo();
final Map<String, ServiceInfo> idToInfoHash =
getBrowser().getNameToServiceInfoHash().get(getName());
final ClusterStatus cs = getBrowser().getClusterStatus();
if (idToInfoHash != null) {
for (final ServiceInfo si : new TreeSet<ServiceInfo>(
idToInfoHash.values())) {
if (si != this
&& cs.getMetaAttrsId(
si.getService().getHeartbeatId()) != null
&& cs.getMetaAttrsRef(
si.getService().getHeartbeatId()) == null) {
sl.add(si);
}
}
}
final boolean clone = getResourceAgent().isClone();
for (final String name
: getBrowser().getNameToServiceInfoHash().keySet()) {
final Map<String, ServiceInfo> idToInfo =
getBrowser().getNameToServiceInfoHash().get(name);
for (final ServiceInfo si : new TreeSet<ServiceInfo>(
idToInfo.values())) {
if (si != this
&& !si.getName().equals(getName())
&& si.getResourceAgent() != null
&& si.getResourceAgent().isClone() == clone
&& cs.getMetaAttrsId(
si.getService().getHeartbeatId()) != null
&& cs.getMetaAttrsRef(
si.getService().getHeartbeatId()) == null) {
sl.add(si);
}
}
}
getBrowser().unlockNameToServiceInfo();
return sl.toArray(new Info[sl.size()]);
}
/**
* Returns all services except this one, that are of the same type
* for operations.
*/
private Info[] getSameServicesOperations() {
final List<Info> sl = new ArrayList<Info>();
sl.add(new StringInfo(Widget.NOTHING_SELECTED_DISPLAY,
Widget.NOTHING_SELECTED_INTERNAL,
getBrowser()));
sl.add(new StringInfo(OPERATIONS_DEFAULT_VALUES_TEXT,
OPERATIONS_DEFAULT_VALUES,
getBrowser()));
final Host dcHost = getBrowser().getDCHost();
final String pmV = dcHost.getPacemakerVersion();
final String hbV = dcHost.getHeartbeatVersion();
if (isOperationReferenced() || Tools.versionBeforePacemaker(dcHost)) {
return sl.toArray(new Info[sl.size()]);
}
getBrowser().lockNameToServiceInfo();
final Map<String, ServiceInfo> idToInfoHash =
getBrowser().getNameToServiceInfoHash().get(getName());
final ClusterStatus cs = getBrowser().getClusterStatus();
if (idToInfoHash != null) {
for (final ServiceInfo si : new TreeSet<ServiceInfo>(
idToInfoHash.values())) {
if (si != this
&& cs.getOperationsId(
si.getService().getHeartbeatId()) != null
&& cs.getOperationsRef(
si.getService().getHeartbeatId()) == null) {
sl.add(si);
}
}
}
final boolean clone = getResourceAgent().isClone();
for (final String name
: getBrowser().getNameToServiceInfoHash().keySet()) {
final Map<String, ServiceInfo> idToInfo =
getBrowser().getNameToServiceInfoHash().get(name);
for (final ServiceInfo si : new TreeSet<ServiceInfo>(
idToInfo.values())) {
if (si != this
&& si.getResourceAgent() != null
&& si.getResourceAgent().isClone() == clone
&& !si.getName().equals(getName())
&& cs.getOperationsId(
si.getService().getHeartbeatId()) != null
&& cs.getOperationsRef(
si.getService().getHeartbeatId()) == null) {
sl.add(si);
}
}
}
getBrowser().unlockNameToServiceInfo();
return sl.toArray(new Info[sl.size()]);
}
/**
* Sets operations with same values as other service info, or default
* values.
*/
private void setOperationsSameAs(final Info info) {
if (sameAsOperationsWi == null) {
return;
}
boolean nothingSelected = false;
if (info == null
|| Widget.NOTHING_SELECTED_DISPLAY.equals(info.toString())) {
nothingSelected = true;
}
boolean sameAs = true;
if (info == null
|| OPERATIONS_DEFAULT_VALUES_TEXT.equals(info.toString())) {
sameAs = false;
}
mSavedOperationsLock.lock();
for (final String op : getResourceAgent().getOperationNames()) {
for (final String param : getBrowser().getCRMOperationParams(op)) {
String defaultValue =
resourceAgent.getOperationDefault(op, param);
if (defaultValue == null) {
continue;
}
if (ClusterBrowser.HB_OP_IGNORE_DEFAULT.contains(op)) {
defaultValue = "";
}
mOperationsComboBoxHashReadLock.lock();
final Widget wi = operationsComboBoxHash.get(op, param);
mOperationsComboBoxHashReadLock.unlock();
final Object oldValue = wi.getValue();
wi.setEnabled(!sameAs || nothingSelected);
if (!nothingSelected) {
if (sameAs) {
/* same as some other service */
defaultValue =
((ServiceInfo) info).getSavedOperation().get(op,
param);
}
final String newValue = defaultValue;
if (!Tools.areEqual(oldValue,
Tools.extractUnit(newValue))) {
if (wi != null) {
wi.setValueNoListeners(newValue);
}
}
}
}
}
mSavedOperationsLock.unlock();
}
/** Creates operations combo boxes with labels. */
protected void addOperations(final JPanel optionsPanel,
final int leftWidth,
final int rightWidth) {
int rows = 0;
final JPanel sectionPanel = getParamPanel(
Tools.getString("ClusterBrowser.Operations"));
String defaultOpIdRef = null;
final Info savedOpIdRef = getSameServiceOpIdRef();
if (savedOpIdRef != null) {
defaultOpIdRef = savedOpIdRef.toString();
}
sameAsOperationsWi = WidgetFactory.createInstance(
Widget.Type.COMBOBOX,
defaultOpIdRef,
getSameServicesOperations(),
Widget.NO_REGEXP,
rightWidth,
Widget.NO_ABBRV,
new AccessMode(
ConfigData.AccessType.ADMIN,
false),
Widget.NO_BUTTON);
sameAsOperationsWi.setToolTipText(defaultOpIdRef);
final JLabel label = new JLabel(Tools.getString(
"ClusterBrowser.OperationsSameAs"));
sameAsOperationsWi.setLabel(label, "");
final JPanel saPanel = new JPanel(new SpringLayout());
saPanel.setBackground(ClusterBrowser.BUTTON_PANEL_BACKGROUND);
addField(saPanel,
label,
sameAsOperationsWi,
leftWidth,
rightWidth,
0);
SpringUtilities.makeCompactGrid(saPanel, 1, 2,
1, 1, // initX, initY
1, 1); // xPad, yPad
sectionPanel.add(saPanel);
boolean allAreDefaultValues = true;
mSavedOperationsLock.lock();
final JPanel normalOpPanel = new JPanel(new SpringLayout());
normalOpPanel.setBackground(ClusterBrowser.PANEL_BACKGROUND);
int normalRows = 0;
final JPanel advancedOpPanel = new JPanel(new SpringLayout());
advancedOpPanel.setBackground(ClusterBrowser.PANEL_BACKGROUND);
addToAdvancedList(advancedOpPanel);
advancedOpPanel.setVisible(Tools.getConfigData().isAdvancedMode());
int advancedRows = 0;
for (final String op : getResourceAgent().getOperationNames()) {
for (final String param : getBrowser().getCRMOperationParams(op)) {
String defaultValue =
resourceAgent.getOperationDefault(op, param);
if (defaultValue == null) {
continue;
}
if (ClusterBrowser.HB_OP_IGNORE_DEFAULT.contains(op)) {
defaultValue = "";
}
final String regexp = "^-?\\d*$";
// TODO: old style resources
if (defaultValue == null) {
defaultValue = "0";
}
String savedValue = null;
mOperationsComboBoxHashWriteLock.lock();
try {
final Widget prevWi = operationsComboBoxHash.get(op, param);
if (prevWi != null) {
savedValue = prevWi.getStringValue();
}
} finally {
mOperationsComboBoxHashWriteLock.unlock();
}
if (savedValue == null) {
savedValue = savedOperation.get(op, param);
}
if (!getService().isNew()
&& (savedValue == null || "".equals(savedValue))) {
savedValue = getOpDefaultsDefault(param);
if (savedValue == null) {
savedValue = "";
}
}
if (!defaultValue.equals(savedValue)) {
allAreDefaultValues = false;
}
if (savedValue != null) {
defaultValue = savedValue;
}
Widget wi;
if (CRMXML.PAR_CHECK_LEVEL.equals(param)) {
wi = WidgetFactory.createInstance(
Widget.Type.COMBOBOX,
defaultValue,
new String[]{"",
"10",
"20"},
"^\\d*$",
rightWidth,
Widget.NO_ABBRV,
new AccessMode(ConfigData.AccessType.ADMIN,
false),
Widget.NO_BUTTON);
wi.setAlwaysEditable(true);
} else {
wi = new TextfieldWithUnit(defaultValue,
getUnits(),
regexp,
rightWidth,
Widget.NO_ABBRV,
new AccessMode(
ConfigData.AccessType.ADMIN,
!AccessMode.ADVANCED),
Widget.NO_BUTTON);
}
wi.setEnabled(savedOpIdRef == null);
mOperationsComboBoxHashWriteLock.lock();
try {
operationsComboBoxHash.put(op, param, wi);
} finally {
mOperationsComboBoxHashWriteLock.unlock();
}
rows++;
final String labelText = Tools.ucfirst(op)
+ " / "
+ Tools.ucfirst(param);
final JLabel wiLabel = new JLabel(labelText);
wi.setLabel(wiLabel, labelText);
JPanel panel;
if (getBrowser().isCRMOperationAdvanced(op, param)) {
panel = advancedOpPanel;
advancedRows++;
} else {
panel = normalOpPanel;
normalRows++;
}
addField(panel,
wiLabel,
wi,
leftWidth,
rightWidth,
0);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
wiLabel.setToolTipText(labelText);
}
});
}
}
SpringUtilities.makeCompactGrid(normalOpPanel, normalRows, 2,
1, 1, // initX, initY
1, 1); // xPad, yPad
SpringUtilities.makeCompactGrid(advancedOpPanel, advancedRows, 2,
1, 1, // initX, initY
1, 1); // xPad, yPad
sectionPanel.add(normalOpPanel);
sectionPanel.add(getMoreOptionsPanel(leftWidth + rightWidth + 4));
sectionPanel.add(advancedOpPanel);
mSavedOperationsLock.unlock();
if (allAreDefaultValues && savedOpIdRef == null) {
sameAsOperationsWi.setValue(OPERATIONS_DEFAULT_VALUES_TEXT);
}
sameAsOperationsWi.addListeners(
new WidgetListener() {
@Override
public void check(final Object value) {
final Info info = sameAsOperationsWiValue();
setOperationsSameAs(info);
final String[] params = getParametersFromXML();
setApplyButtons(CACHED_FIELD, params);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (info != null) {
sameAsOperationsWi.setToolTipText(
info.toString());
}
}
});
}
});
optionsPanel.add(sectionPanel);
}
/** Returns parameters. */
@Override
public String[] getParametersFromXML() {
final CRMXML crmXML = getBrowser().getCRMXML();
return getEnabledSectionParams(
crmXML.getParameters(resourceAgent, getService().isMaster()));
}
/** Returns the regexp of the parameter. */
@Override
protected String getParamRegexp(final String param) {
if (isInteger(param)) {
return "^((-?\\d*|(-|\\+)?" + CRMXML.INFINITY_STRING
+ "|" + CRMXML.DISABLED_STRING
+ "))|@NOTHING_SELECTED@$";
}
return null;
}
/** Returns true if the value of the parameter is ok. */
@Override
protected boolean checkParam(final String param, final String newValue) {
if (param.equals("ip")
&& newValue != null
&& !Tools.isIp(newValue)) {
return false;
}
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.checkParam(resourceAgent, param, newValue);
}
/** Returns default value for specified parameter. */
@Override
public String getParamDefault(final String param) {
if (isMetaAttr(param)) {
final String paramDefault = getBrowser().getRscDefaultsInfo()
.getResource().getValue(param);
if (paramDefault != null) {
return paramDefault;
}
}
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.getParamDefault(resourceAgent, param);
}
/** Returns saved value for specified parameter. */
@Override
protected String getParamSaved(final String param) {
final ClusterStatus clStatus = getBrowser().getClusterStatus();
if (isMetaAttr(param)) {
final String crmId = getService().getHeartbeatId();
final String refCRMId = clStatus.getMetaAttrsRef(crmId);
if (refCRMId != null) {
String value = clStatus.getParameter(refCRMId, param, false);
if (value == null) {
value = getParamPreferred(param);
if (value == null) {
return getParamDefault(param);
}
}
return value;
}
}
String value = super.getParamSaved(param);
if (value == null) {
value = clStatus.getParameter(getService().getHeartbeatId(),
param,
false);
if (value == null) {
if (getService().isNew()) {
value = getParamPreferred(param);
}
if (value == null) {
return getParamDefault(param);
}
}
}
return value;
}
/**
* Returns preferred value for specified parameter.
*/
@Override
protected String getParamPreferred(final String param) {
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.getParamPreferred(resourceAgent, param);
}
/**
* Returns possible choices for drop down lists.
*/
@Override
protected Object[] getParamPossibleChoices(final String param) {
final CRMXML crmXML = getBrowser().getCRMXML();
if (isCheckBox(param)) {
return crmXML.getCheckBoxChoices(resourceAgent, param);
} else {
final CloneInfo ci = getCloneInfo();
final boolean ms = ci != null
&& ci.getService().isMaster();
return crmXML.getParamPossibleChoices(resourceAgent, param, ms);
}
}
/**
* Returns short description of the specified parameter.
*/
@Override
protected String getParamShortDesc(final String param) {
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.getParamShortDesc(resourceAgent, param);
}
/**
* Returns long description of the specified parameter.
*/
@Override
protected String getParamLongDesc(final String param) {
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.getParamLongDesc(resourceAgent, param);
}
/**
* Returns section to which the specified parameter belongs.
*/
@Override
protected String getSection(final String param) {
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.getSection(resourceAgent, param);
}
/** Returns true if the specified parameter is required. */
@Override
protected boolean isRequired(final String param) {
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.isRequired(resourceAgent, param);
}
/** Returns whether this parameter is advanced. */
@Override
protected boolean isAdvanced(final String param) {
if (!Tools.areEqual(getParamDefault(param),
getParamSaved(param))) {
/* it changed, show it */
return false;
}
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.isAdvanced(resourceAgent, param);
}
/** Whether the parameter should be enabled. */
@Override
protected final String isEnabled(final String param) {
if (GUI_ID.equals(param) && !getResource().isNew()) {
return "";
}
if (isMetaAttr(param)) {
final Info info = sameAsMetaAttrsWiValue();
if (info == null) {
return null;
}
boolean nothingSelected = false;
if (Widget.NOTHING_SELECTED_DISPLAY.equals(info.toString())) {
nothingSelected = true;
}
boolean sameAs = true;
if (META_ATTRS_DEFAULT_VALUES_TEXT.equals(info.toString())) {
sameAs = false;
}
if (!sameAs || nothingSelected) {
return null;
} else {
return "";
}
}
return null;
}
/** Whether the parameter should be enabled only in advanced mode. */
@Override
protected final boolean isEnabledOnlyInAdvancedMode(final String param) {
return false;
}
/** Returns access type of this parameter. */
@Override
protected ConfigData.AccessType getAccessType(final String param) {
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.getAccessType(resourceAgent, param);
}
/**
* Returns true if the specified parameter is meta attribute.
*/
protected boolean isMetaAttr(final String param) {
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.isMetaAttr(resourceAgent, param);
}
/** Returns true if the specified parameter is integer. */
@Override
protected boolean isInteger(final String param) {
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.isInteger(resourceAgent, param);
}
/** Returns true if the specified parameter is label. */
@Override
protected boolean isLabel(final String param) {
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.isLabel(resourceAgent, param);
}
/** Returns true if the specified parameter is of time type. */
@Override
protected boolean isTimeType(final String param) {
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.isTimeType(resourceAgent, param);
}
/** Returns whether parameter is checkbox. */
@Override
protected boolean isCheckBox(final String param) {
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.isBoolean(resourceAgent, param);
}
/** Returns the type of the parameter according to the OCF. */
@Override
protected String getParamType(final String param) {
final CRMXML crmXML = getBrowser().getCRMXML();
return crmXML.getParamType(resourceAgent, param);
}
/** Returns the type of the parameter. */
@Override
protected Widget.Type getFieldType(final String param) {
return resourceAgent.getFieldType(param);
}
/**
* Is called before the service is added. This is for example used by
* FilesystemInfo so that it can add LinbitDrbdInfo or DrbddiskInfo
* before it adds itself.
*/
void addResourceBefore(final Host dcHost, final boolean testOnly) {
/* Override to add resource before this one. */
}
/** Change type to Master, Clone or Primitive. */
protected final void changeType(final String value) {
boolean masterSlave = false;
boolean clone = false;
if (MASTER_SLAVE_TYPE_STRING.equals(value)) {
masterSlave = true;
clone = true;
} else if (CLONE_TYPE_STRING.equals(value)) {
clone = true;
}
final ServiceInfo thisClass = this;
if (clone) {
final CRMXML crmXML = getBrowser().getCRMXML();
final CloneInfo oldCI = getCloneInfo();
String title = ConfigData.PM_CLONE_SET_NAME;
if (masterSlave) {
title = ConfigData.PM_MASTER_SLAVE_SET_NAME;
}
final CloneInfo ci = new CloneInfo(crmXML.getHbClone(),
title,
masterSlave,
getBrowser());
setCloneInfo(ci);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (oldCI == null) {
getBrowser().getCRMGraph()
.exchangeObjectInTheVertex(ci, thisClass);
ci.setPingComboBox(pingComboBox);
for (final HostInfo hi : scoreComboBoxHash.keySet()) {
ci.getScoreComboBoxHash().put(
hi,
scoreComboBoxHash.get(hi));
}
final Widget prevWi = getWidget(GUI_ID, null);
if (prevWi != null) {
ci.getService().setId(
getName() + "_" + prevWi.getStringValue());
}
} else {
oldCI.removeNodeAndWait();
getBrowser().getCRMGraph()
.exchangeObjectInTheVertex(ci, oldCI);
cleanup();
oldCI.cleanup();
ci.setPingComboBox(oldCI.getPingComboBox());
for (final HostInfo hi
: oldCI.getScoreComboBoxHash().keySet()) {
ci.getScoreComboBoxHash().put(
hi, oldCI.getScoreComboBoxHash().get(hi));
}
getBrowser().removeFromServiceInfoHash(oldCI);
getBrowser().mHeartbeatIdToServiceLock();
getBrowser().getHeartbeatIdToServiceInfo().remove(
oldCI.getService().getHeartbeatId());
getBrowser().mHeartbeatIdToServiceUnlock();
final DefaultMutableTreeNode oldCINode =
oldCI.getNode();
if (oldCINode != null) {
oldCINode.setUserObject(null); /* would leak
without it*/
}
ci.getService().setId(oldCI.getWidget(
GUI_ID, null).getStringValue());
}
ci.setCloneServicePanel(thisClass);
infoPanel = null;
}
});
} else if (PRIMITIVE_TYPE_STRING.equals(value)) {
final CloneInfo ci = getCloneInfo();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setPingComboBox(ci.getPingComboBox());
for (final HostInfo hi
: ci.getScoreComboBoxHash().keySet()) {
scoreComboBoxHash.put(
hi, ci.getScoreComboBoxHash().get(hi));
}
final DefaultMutableTreeNode node = getNode();
final DefaultMutableTreeNode ciNode = ci.getNode();
removeNodeAndWait();
ci.removeNodeAndWait();
cleanup();
ci.cleanup();
setNode(node);
getBrowser().getServicesNode().add(node);
getBrowser().getCRMGraph().exchangeObjectInTheVertex(
thisClass,
ci);
getBrowser().mHeartbeatIdToServiceLock();
getBrowser().getHeartbeatIdToServiceInfo().remove(
ci.getService().getHeartbeatId());
getBrowser().mHeartbeatIdToServiceUnlock();
getBrowser().removeFromServiceInfoHash(ci);
infoPanel = null;
setCloneInfo(null);
selectMyself();
ciNode.setUserObject(null); /* would leak without it */
}
});
}
}
/** Adds host score listeners. */
protected void addHostLocationsListeners() {
final String[] params = getParametersFromXML();
for (Host host : getBrowser().getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
final Widget wi = scoreComboBoxHash.get(hi);
wi.addListeners(new WidgetListener() {
@Override
public void check(final Object value) {
setApplyButtons(CACHED_FIELD, params);
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
wi.setEditable();
}
});
}
});
}
pingComboBox.addListeners(new WidgetListener() {
@Override
public void check(final Object value) {
setApplyButtons(CACHED_FIELD, params);
}
});
}
/** Adds listeners for operation and parameter. */
private void addOperationListeners(final String op, final String param) {
final String dv = resourceAgent.getOperationDefault(op, param);
if (dv == null) {
return;
}
mOperationsComboBoxHashReadLock.lock();
final Widget wi = operationsComboBoxHash.get(op, param);
mOperationsComboBoxHashReadLock.unlock();
final String[] params = getParametersFromXML();
wi.addListeners(new WidgetListener() {
@Override
public void check(final Object value) {
setApplyButtons(CACHED_FIELD, params);
}
});
}
/**
* Returns "same as" fields for some sections. Currently only "meta
* attributes".
*/
protected final Map<String, Widget> getSameAsFields(
final Info savedMAIdRef) {
String defaultMAIdRef = null;
if (savedMAIdRef != null) {
defaultMAIdRef = savedMAIdRef.toString();
}
sameAsMetaAttrsWi = WidgetFactory.createInstance(
Widget.Type.COMBOBOX,
defaultMAIdRef,
getSameServicesMetaAttrs(),
Widget.NO_REGEXP,
ClusterBrowser.SERVICE_FIELD_WIDTH,
Widget.NO_ABBRV,
new AccessMode(
ConfigData.AccessType.ADMIN,
false),
Widget.NO_BUTTON);
sameAsMetaAttrsWi.setToolTipText(defaultMAIdRef);
final Map<String, Widget> sameAsFields = new HashMap<String, Widget>();
sameAsFields.put("Meta Attributes", sameAsMetaAttrsWi);
sameAsMetaAttrsWi.addListeners(new WidgetListener() {
@Override
public void check(final Object value) {
Info i = null;
final Object o = sameAsMetaAttrsWiValue();
if (o instanceof Info) {
i = (Info) o;
}
final Info info = i;
setMetaAttrsSameAs(info);
final String[] params =
getParametersFromXML();
setApplyButtons(CACHED_FIELD, params);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (info != null) {
sameAsMetaAttrsWi.setToolTipText(
info.toString());
}
}
});
}
});
return sameAsFields;
}
/** Returns saved meta attributes reference to another service. */
protected final Info getSavedMetaAttrInfoRef() {
return savedMetaAttrInfoRef;
}
/** Returns info panel with comboboxes for service parameters. */
@Override
public JComponent getInfoPanel() {
if (!getResourceAgent().isMetaDataLoaded()) {
final JPanel p = new JPanel();
p.add(new JLabel(Tools.getString("ServiceInfo.LoadingMetaData")));
return p;
}
final CloneInfo ci = getCloneInfo();
if (ci == null) {
getBrowser().getCRMGraph().pickInfo(this);
} else {
getBrowser().getCRMGraph().pickInfo(ci);
}
if (infoPanel != null) {
return infoPanel;
}
/* init save button */
final boolean abExisted = getApplyButton() != null;
final ServiceInfo thisClass = this;
final ButtonCallback buttonCallback = new ButtonCallback() {
private volatile boolean mouseStillOver = false;
/**
* Whether the whole thing should be enabled.
*/
@Override
public final boolean isEnabled() {
final Host dcHost = getBrowser().getDCHost();
if (dcHost == null) {
return false;
}
if (Tools.versionBeforePacemaker(dcHost)) {
return false;
}
return true;
}
@Override
public final void mouseOut() {
if (!isEnabled()) {
return;
}
mouseStillOver = false;
getBrowser().getCRMGraph().stopTestAnimation(
getApplyButton());
getApplyButton().setToolTipText("");
}
@Override
public final void mouseOver() {
if (!isEnabled()) {
return;
}
mouseStillOver = true;
getApplyButton().setToolTipText(
ClusterBrowser.STARTING_PTEST_TOOLTIP);
getApplyButton().setToolTipBackground(Tools.getDefaultColor(
"ClusterBrowser.Test.Tooltip.Background"));
Tools.sleep(250);
if (!mouseStillOver) {
return;
}
mouseStillOver = false;
final CountDownLatch startTestLatch = new CountDownLatch(1);
getBrowser().getCRMGraph().startTestAnimation(
getApplyButton(),
startTestLatch);
final Host dcHost = getBrowser().getDCHost();
getBrowser().ptestLockAcquire();
final ClusterStatus cs = getBrowser().getClusterStatus();
cs.setPtestData(null);
apply(dcHost, true);
final PtestData ptestData = new PtestData(CRM.getPtest(dcHost));
getApplyButton().setToolTipText(ptestData.getToolTip());
cs.setPtestData(ptestData);
getBrowser().ptestLockRelease();
startTestLatch.countDown();
}
};
if (getResourceAgent().isGroup()) {
initApplyButton(buttonCallback,
Tools.getString("Browser.ApplyGroup"));
} else {
initApplyButton(buttonCallback);
}
if (ci != null) {
ci.setApplyButton(getApplyButton());
ci.setRevertButton(getRevertButton());
}
/* add item listeners to the apply button. */
if (!abExisted) {
getApplyButton().addActionListener(
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
getBrowser().clStatusLock();
apply(getBrowser().getDCHost(), false);
getBrowser().clStatusUnlock();
}
});
thread.start();
}
}
);
getRevertButton().addActionListener(
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
getBrowser().clStatusLock();
revert();
getBrowser().clStatusUnlock();
}
});
thread.start();
}
}
);
}
/* main, button and options panels */
final JPanel mainPanel = new JPanel();
mainPanel.setBackground(ClusterBrowser.PANEL_BACKGROUND);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
final JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBackground(ClusterBrowser.BUTTON_PANEL_BACKGROUND);
buttonPanel.setMinimumSize(new Dimension(0, 50));
buttonPanel.setPreferredSize(new Dimension(0, 50));
buttonPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 50));
final JPanel optionsPanel = new JPanel();
optionsPanel.setBackground(ClusterBrowser.PANEL_BACKGROUND);
optionsPanel.setLayout(new BoxLayout(optionsPanel, BoxLayout.Y_AXIS));
optionsPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
/* Actions */
final JMenuBar mb = new JMenuBar();
mb.setBackground(ClusterBrowser.PANEL_BACKGROUND);
AbstractButton serviceMenu;
if (ci == null) {
serviceMenu = getActionsButton();
} else {
serviceMenu = ci.getActionsButton();
}
buttonPanel.add(serviceMenu, BorderLayout.EAST);
String defaultValue = PRIMITIVE_TYPE_STRING;
if (ci != null) {
if (ci.getService().isMaster()) {
defaultValue = MASTER_SLAVE_TYPE_STRING;
} else {
defaultValue = CLONE_TYPE_STRING;
}
}
if (!getResourceAgent().isClone() && getGroupInfo() == null) {
typeRadioGroup = WidgetFactory.createInstance(
Widget.Type.RADIOGROUP,
defaultValue,
new String[]{PRIMITIVE_TYPE_STRING,
CLONE_TYPE_STRING,
MASTER_SLAVE_TYPE_STRING},
Widget.NO_REGEXP,
ClusterBrowser.SERVICE_LABEL_WIDTH
+ ClusterBrowser.SERVICE_FIELD_WIDTH,
Widget.NO_ABBRV,
new AccessMode(ConfigData.AccessType.ADMIN,
false),
Widget.NO_BUTTON);
if (!getService().isNew()) {
typeRadioGroup.setEnabled(false);
}
typeRadioGroup.addListeners(new WidgetListener() {
@Override
public void check(final Object value) {
changeType(((JRadioButton) value).getText());
}
});
final JPanel tp = new JPanel();
tp.setBackground(ClusterBrowser.PANEL_BACKGROUND);
tp.setLayout(new BoxLayout(tp, BoxLayout.Y_AXIS));
tp.add(typeRadioGroup);
typeRadioGroup.setBackgroundColor(ClusterBrowser.PANEL_BACKGROUND);
optionsPanel.add(tp);
}
if (ci != null) {
/* add clone fields */
addCloneFields(optionsPanel,
ClusterBrowser.SERVICE_LABEL_WIDTH,
ClusterBrowser.SERVICE_FIELD_WIDTH);
}
getResource().setValue(GUI_ID, getService().getId());
/* get dependent resources and create combo boxes for ones, that
* need parameters */
final String[] params = getParametersFromXML();
final Info savedMAIdRef = savedMetaAttrInfoRef;
addParams(optionsPanel,
params,
ClusterBrowser.SERVICE_LABEL_WIDTH,
ClusterBrowser.SERVICE_FIELD_WIDTH,
getSameAsFields(savedMAIdRef));
if (ci == null) {
/* score combo boxes */
addHostLocations(optionsPanel,
ClusterBrowser.SERVICE_LABEL_WIDTH,
ClusterBrowser.SERVICE_FIELD_WIDTH);
}
for (final String param : params) {
if (isMetaAttr(param)) {
final Widget wi = getWidget(param, null);
wi.setEnabled(savedMAIdRef == null);
}
}
if (!getService().isNew()) {
getWidget(GUI_ID, null).setEnabled(false);
}
if (!getResourceAgent().isGroup()
&& !getResourceAgent().isClone()) {
/* Operations */
addOperations(optionsPanel,
ClusterBrowser.SERVICE_LABEL_WIDTH,
ClusterBrowser.SERVICE_FIELD_WIDTH);
/* add item listeners to the operations combos */
for (final String op : getResourceAgent().getOperationNames()) {
for (final String param
: getBrowser().getCRMOperationParams(op)) {
addOperationListeners(op, param);
}
}
}
/* add item listeners to the host scores combos */
if (ci == null) {
addHostLocationsListeners();
} else {
ci.addHostLocationsListeners();
}
/* apply button */
addApplyButton(buttonPanel);
addRevertButton(buttonPanel);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
/* invoke later on purpose */
setApplyButtons(null, params);
}
});
mainPanel.add(optionsPanel);
final JPanel newPanel = new JPanel();
newPanel.setBackground(ClusterBrowser.PANEL_BACKGROUND);
newPanel.setLayout(new BoxLayout(newPanel, BoxLayout.Y_AXIS));
newPanel.add(buttonPanel);
newPanel.add(getMoreOptionsPanel(
ClusterBrowser.SERVICE_LABEL_WIDTH
+ ClusterBrowser.SERVICE_FIELD_WIDTH + 4));
newPanel.add(new JScrollPane(mainPanel));
/* if id textfield was changed and this id is not used,
* enable apply button */
infoPanel = newPanel;
infoPanelDone();
return infoPanel;
}
/** Clears the info panel cache, forcing it to reload. */
@Override
boolean selectAutomaticallyInTreeMenu() {
return infoPanel == null;
}
/** Returns operation from host location label. "eq", "ne" etc. */
private String getOpFromLabel(final String onHost,
final String labelText) {
final int l = labelText.length();
final int k = onHost.length();
String op = null;
if (l > k) {
final String labelPart = labelText.substring(0, l - k - 1);
if ("on".equals(labelPart)) {
op = "eq";
} else if ("NOT on".equals(labelPart)) {
op = "ne";
} else {
op = labelPart;
}
}
return op;
}
/** Goes through the scores and sets preferred locations. */
protected void setLocations(final String heartbeatId,
final Host dcHost,
final boolean testOnly) {
final ClusterStatus cs = getBrowser().getClusterStatus();
for (Host host : getBrowser().getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
final Widget wi = scoreComboBoxHash.get(hi);
String hs = wi.getStringValue();
if ("ALWAYS".equals(hs)) {
hs = CRMXML.INFINITY_STRING;
} else if ("NEVER".equals(hs)) {
hs = CRMXML.MINUS_INFINITY_STRING;
}
final HostLocation hlSaved = savedHostLocations.get(hi);
String hsSaved = null;
String opSaved = null;
if (hlSaved != null) {
hsSaved = hlSaved.getScore();
opSaved = hlSaved.getOperation();
}
final String onHost = hi.getName();
final String op = getOpFromLabel(onHost, wi.getLabel().getText());
final HostLocation hostLoc = new HostLocation(hs, op, null, null);
if (!hostLoc.equals(hlSaved)) {
String locationId = cs.getLocationId(getHeartbeatId(testOnly),
onHost,
testOnly);
if (((hs == null || "".equals(hs))
|| !Tools.areEqual(op, opSaved))
&& locationId != null) {
CRM.removeLocation(dcHost,
locationId,
getHeartbeatId(testOnly),
testOnly);
locationId = null;
}
if (hs != null && !"".equals(hs)) {
CRM.setLocation(dcHost,
getHeartbeatId(testOnly),
onHost,
hostLoc,
locationId,
testOnly);
}
}
}
/* ping */
final Widget pwi = pingComboBox;
if (pwi != null) {
String value = null;
final Object o = pwi.getValue();
if (o != null) {
value = ((StringInfo) o).getInternalValue();
}
final String locationId = null;
if (!Tools.areEqual(savedPingOperation,
value)) {
final String pingLocationId = cs.getPingLocationId(
getHeartbeatId(testOnly),
testOnly);
if (pingLocationId != null) {
CRM.removeLocation(dcHost,
pingLocationId,
getHeartbeatId(testOnly),
testOnly);
}
if (value != null) {
CRM.setPingLocation(dcHost,
getHeartbeatId(testOnly),
value,
null, /* location id */
testOnly);
}
}
}
if (!testOnly) {
storeHostLocations();
}
}
/**
* Returns hash with changed operation ids and all name, value pairs.
* This works for new heartbeats >= 2.99.0
*/
protected Map<String, Map<String, String>> getOperations(
final String heartbeatId) {
final Map<String, Map<String, String>> operations =
new LinkedHashMap<String, Map<String, String>>();
final ClusterStatus cs = getBrowser().getClusterStatus();
final CloneInfo ci = getCloneInfo();
for (final String op : getResourceAgent().getOperationNames()) {
final Map<String, String> opHash =
new LinkedHashMap<String, String>();
String opId = cs.getOpId(heartbeatId, op);
if (opId == null) {
/* generate one */
opId = "op-" + heartbeatId + "-" + op;
}
/* operations have different kind of default, that is
* recommended, but not used by default. */
boolean firstTime = true;
for (final String param : ClusterBrowser.HB_OPERATION_PARAM_LIST) {
if (getBrowser().getCRMOperationParams(op).contains(param)) {
if (ci == null
&& (ClusterBrowser.HB_OP_DEMOTE.equals(op)
|| ClusterBrowser.HB_OP_PROMOTE.equals(op))) {
continue;
}
mOperationsComboBoxHashReadLock.lock();
final Widget wi = operationsComboBoxHash.get(op, param);
mOperationsComboBoxHashReadLock.unlock();
String value;
if (wi == null) {
value = "0";
} else {
value = wi.getStringValue();
}
if (value != null && !"".equals(value)) {
if (wi != null && firstTime) {
opHash.put("id", opId);
opHash.put("name", op);
firstTime = false;
operations.put(op, opHash);
}
opHash.put(param, value);
}
}
}
}
return operations;
}
/**
* Returns id of the meta attrs to which meta attrs of this service are
* referring to.
*/
protected String getMetaAttrsRefId() {
String metaAttrsRefId = null;
if (sameAsMetaAttrsWi != null) {
final Info i = sameAsMetaAttrsWiValue();
if (!Widget.NOTHING_SELECTED_DISPLAY.equals(i.toString())
&& !META_ATTRS_DEFAULT_VALUES_TEXT.equals(i.toString())) {
final ServiceInfo si = (ServiceInfo) i;
final ClusterStatus cs = getBrowser().getClusterStatus();
metaAttrsRefId = cs.getMetaAttrsId(
si.getService().getHeartbeatId());
}
}
return metaAttrsRefId;
}
/**
* Returns id of the operations to which operations of this service are
* referring to.
*/
protected String getOperationsRefId() {
String operationsRefId = null;
if (sameAsOperationsWi != null) {
final Info i = sameAsOperationsWiValue();
if (!Widget.NOTHING_SELECTED_DISPLAY.equals(i.toString())
&& !OPERATIONS_DEFAULT_VALUES_TEXT.equals(i.toString())) {
final ServiceInfo si = (ServiceInfo) i;
final ClusterStatus cs = getBrowser().getClusterStatus();
operationsRefId = cs.getOperationsId(
si.getService().getHeartbeatId());
}
}
return operationsRefId;
}
/** Returns attributes of this resource. */
protected Map<String, String> getPacemakerResAttrs(final boolean testOnly) {
final Map<String, String> pacemakerResAttrs =
new LinkedHashMap<String, String>();
final String raClass = getService().getResourceClass();
final String type = getName();
final String provider = resourceAgent.getProvider();
final String heartbeatId = getHeartbeatId(testOnly);
pacemakerResAttrs.put("id", heartbeatId);
pacemakerResAttrs.put("class", raClass);
if (!ResourceAgent.HEARTBEAT_CLASS.equals(raClass)
&& !ResourceAgent.SERVICE_CLASSES.contains(raClass)
&& !raClass.equals(ResourceAgent.STONITH_CLASS)) {
pacemakerResAttrs.put("provider", provider);
}
pacemakerResAttrs.put("type", type);
return pacemakerResAttrs;
}
/** Returns arguments of this resource. */
protected Map<String, String> getPacemakerResArgs() {
final Map<String, String> pacemakerResArgs =
new LinkedHashMap<String, String>();
final String[] params = getParametersFromXML();
for (final String param : params) {
if (isMetaAttr(param)) {
continue;
}
if (GUI_ID.equals(param)
|| PCMK_ID.equals(param)) {
continue;
}
String value = getComboBoxValue(param);
if (value == null) {
value = "";
}
if (!resourceAgent.isIgnoreDefaults()
&& value.equals(getParamDefault(param))) {
continue;
}
if (!"".equals(value)) {
/* for pacemaker */
pacemakerResArgs.put(param, value);
}
}
return pacemakerResArgs;
}
/** Returns meta arguments of this resource. */
protected Map<String, String> getPacemakerMetaArgs() {
final Map<String, String> pacemakerMetaArgs =
new LinkedHashMap<String, String>();
final String[] params = getParametersFromXML();
for (final String param : params) {
if (!isMetaAttr(param)) {
continue;
}
if (GUI_ID.equals(param)
|| PCMK_ID.equals(param)) {
continue;
}
String value = getComboBoxValue(param);
if (value == null) {
value = "";
}
if (value.equals(getParamDefault(param))) {
continue;
}
if (!"".equals(value)) {
/* for pacemaker */
pacemakerMetaArgs.put(param, value);
}
}
return pacemakerMetaArgs;
}
/** Revert all values. */
@Override
public void revert() {
final CRMXML crmXML = getBrowser().getCRMXML();
final String[] params = getParametersFromXML();
boolean allSavedMetaAttrsAreDefaultValues = true;
boolean sameAs = false;
if (sameAsMetaAttrsWi != null) {
for (String param : params) {
if (isMetaAttr(param)) {
final String defaultValue = getParamDefault(param);
final String oldValue = getResource().getValue(param);
if (!Tools.areEqual(defaultValue, oldValue)) {
allSavedMetaAttrsAreDefaultValues = false;
}
}
}
if (savedMetaAttrInfoRef == null) {
if (allSavedMetaAttrsAreDefaultValues) {
sameAsMetaAttrsWi.setValue(
META_ATTRS_DEFAULT_VALUES_TEXT);
} else {
sameAsMetaAttrsWi.setValue(
Widget.NOTHING_SELECTED_INTERNAL);
}
} else {
sameAs = true;
sameAsMetaAttrsWi.setValue(savedMetaAttrInfoRef);
}
}
for (String param : params) {
if (!sameAs || !isMetaAttr(param)) {
final String v = getParamSaved(param);
final Widget wi = getWidget(param, null);
if (wi != null
&& !Tools.areEqual(wi.getStringValue(), v)) {
if ("".equals(v)) {
wi.setValue(null);
} else {
wi.setValue(v);
}
}
}
}
final GroupInfo gInfo = groupInfo;
CloneInfo ci;
if (gInfo == null) {
ci = getCloneInfo();
} else {
ci = gInfo.getCloneInfo();
}
final CloneInfo clInfo = ci;
if (clInfo != null) {
clInfo.revert();
}
revertOperations();
revertLocations();
}
/** Revert locations to saved values. */
protected final void revertLocations() {
for (Host host : getBrowser().getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
final HostLocation savedLocation = savedHostLocations.get(hi);
final Widget wi = scoreComboBoxHash.get(hi);
if (wi == null) {
continue;
}
String score = null;
String op = null;
if (savedLocation != null) {
score = savedLocation.getScore();
op = savedLocation.getOperation();
}
wi.setValue(score);
final JLabel label = wi.getLabel();
final String text = getHostLocationLabel(hi.getName(), op);
label.setText(text);
}
/* pingd */
final Widget pwi = pingComboBox;
if (pwi != null) {
final String spo = savedPingOperation;
if (spo == null) {
pwi.setValue(Widget.NOTHING_SELECTED_INTERNAL);
} else {
pwi.setValue(PING_ATTRIBUTES.get(spo));
}
}
}
/** Revert to saved operation values. */
protected final void revertOperations() {
if (sameAsOperationsWi == null) {
return;
}
final ClusterStatus cs = getBrowser().getClusterStatus();
mSavedOperationsLock.lock();
boolean allAreDefaultValues = true;
boolean allSavedAreDefaultValues = true;
for (final String op : getResourceAgent().getOperationNames()) {
for (final String param
: getBrowser().getCRMOperationParams(op)) {
String defaultValue =
resourceAgent.getOperationDefault(op, param);
if (defaultValue == null) {
continue;
}
if (ClusterBrowser.HB_OP_IGNORE_DEFAULT.contains(op)) {
defaultValue = "";
}
mOperationsComboBoxHashReadLock.lock();
final Widget wi = operationsComboBoxHash.get(op, param);
mOperationsComboBoxHashReadLock.unlock();
String value = wi.getStringValue();
if (value == null || "".equals(value)) {
value = getOpDefaultsDefault(param);
}
if (value == null) {
value = "";
}
if (!defaultValue.equals(value)) {
allAreDefaultValues = false;
}
if (!defaultValue.equals(savedOperation.get(op, param))) {
allSavedAreDefaultValues = false;
}
}
}
boolean sameAs = false;
final ServiceInfo savedOpIdRef = savedOperationIdRef;
ServiceInfo operationIdRef = null;
final Info ref = sameAsOperationsWiValue();
if (ref instanceof ServiceInfo) {
operationIdRef = (ServiceInfo) ref;
}
if (!Tools.areEqual(operationIdRef, savedOpIdRef)) {
if (savedOpIdRef == null) {
if (allSavedAreDefaultValues) {
sameAsOperationsWi.setValue(
OPERATIONS_DEFAULT_VALUES_TEXT);
} else {
if (operationIdRef != null) {
sameAsOperationsWi.setValue(
Widget.NOTHING_SELECTED_INTERNAL);
}
}
} else {
sameAs = true;
sameAsOperationsWi.setValue(savedOpIdRef);
}
}
if (!sameAs) {
for (final String op : getResourceAgent().getOperationNames()) {
for (final String param
: getBrowser().getCRMOperationParams(op)) {
final String value = savedOperation.get(op, param);
mOperationsComboBoxHashReadLock.lock();
final Widget wi = operationsComboBoxHash.get(op, param);
mOperationsComboBoxHashReadLock.unlock();
if (wi != null) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
wi.setEnabled(savedOpIdRef == null);
}
});
if (value != null) {
wi.setValue(value);
}
}
}
}
}
mSavedOperationsLock.unlock();
}
/** Applies the changes to the service parameters. */
void apply(final Host dcHost, final boolean testOnly) {
if (!testOnly) {
Tools.invokeAndWait(new Runnable() {
@Override
public void run() {
getApplyButton().setEnabled(false);
getRevertButton().setEnabled(false);
}
});
}
getInfoPanel();
waitForInfoPanel();
/* TODO: make progress indicator per resource. */
if (!testOnly) {
setUpdated(true);
}
final String[] params = getParametersFromXML();
String cloneId = null;
String[] cloneParams = null;
boolean master = false;
final GroupInfo gInfo = groupInfo;
CloneInfo ci;
String[] groupParams = null;
if (gInfo == null) {
ci = getCloneInfo();
} else {
ci = gInfo.getCloneInfo();
groupParams = gInfo.getParametersFromXML();
}
final CloneInfo clInfo = ci;
if (clInfo != null) {
cloneId = clInfo.getHeartbeatId(testOnly);
cloneParams = clInfo.getParametersFromXML();
master = clInfo.getService().isMaster();
}
if (!testOnly) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
getApplyButton().setToolTipText("");
getWidget(GUI_ID, null).setEnabled(false);
if (clInfo != null) {
clInfo.getWidget(GUI_ID, null).setEnabled(false);
}
}
});
/* add myself to the hash with service name and id as
* keys */
getBrowser().removeFromServiceInfoHash(this);
final String oldHeartbeatId = getHeartbeatId(testOnly);
if (oldHeartbeatId != null) {
getBrowser().mHeartbeatIdToServiceLock();
getBrowser().getHeartbeatIdToServiceInfo().remove(
oldHeartbeatId);
getBrowser().mHeartbeatIdToServiceUnlock();
}
if (getService().isNew()) {
final String id = getComboBoxValue(GUI_ID);
getService().setIdAndCrmId(id);
if (clInfo != null) {
final String clid = clInfo.getComboBoxValue(GUI_ID);
clInfo.getService().setIdAndCrmId(clid);
}
if (typeRadioGroup != null) {
typeRadioGroup.setEnabled(false);
}
}
getBrowser().addNameToServiceInfoHash(this);
getBrowser().addToHeartbeatIdList(this);
}
if (!testOnly) {
addResourceBefore(dcHost, testOnly);
}
final Map<String, String> cloneMetaArgs =
new LinkedHashMap<String, String>();
final Map<String, String> groupMetaArgs =
new LinkedHashMap<String, String>();
final Map<String, String> pacemakerResAttrs =
getPacemakerResAttrs(testOnly);
final Map<String, String> pacemakerResArgs = getPacemakerResArgs();
final Map<String, String> pacemakerMetaArgs = getPacemakerMetaArgs();
final String raClass = getService().getResourceClass();
final String type = getName();
final String provider = resourceAgent.getProvider();
final String heartbeatId = getHeartbeatId(testOnly);
String groupId = null; /* for pacemaker */
if (gInfo != null) {
if (gInfo.getService().isNew()) {
gInfo.apply(dcHost, testOnly);
return;
}
groupId = gInfo.getHeartbeatId(testOnly);
}
String cloneMetaAttrsRefIds = null;
if (clInfo != null) {
cloneMetaAttrsRefIds = clInfo.getMetaAttrsRefId();
}
String groupMetaAttrsRefIds = null;
if (gInfo != null) {
groupMetaAttrsRefIds = gInfo.getMetaAttrsRefId();
}
final String refCRMId = getOperationsRefId();
savedOperationsId = refCRMId;
savedOperationIdRef = getBrowser().getServiceInfoFromCRMId(refCRMId);
final Info i = sameAsOperationsWiValue();
if (i == null || (i instanceof StringInfo)) {
savedOperationsId = null;
} else {
savedOperationIdRef = (ServiceInfo) i;
savedOperationsId = ((ServiceInfo) i).getService().getHeartbeatId();
}
if (getService().isNew()) {
if (clInfo != null) {
for (String param : cloneParams) {
if (GUI_ID.equals(param)
|| PCMK_ID.equals(param)) {
continue;
}
final String value = clInfo.getComboBoxValue(param);
if (value.equals(clInfo.getParamDefault(param))) {
continue;
}
if (!GUI_ID.equals(param) && !"".equals(value)) {
cloneMetaArgs.put(param, value);
}
}
}
if (gInfo != null) {
for (String param : groupParams) {
if (GUI_ID.equals(param)
|| PCMK_ID.equals(param)) {
continue;
}
final String value = gInfo.getComboBoxValue(param);
if (value.equals(gInfo.getParamDefault(param))) {
continue;
}
if (!GUI_ID.equals(param) && !"".equals(value)) {
groupMetaArgs.put(param, value);
}
}
}
String command = "-C";
if ((gInfo != null && !gInfo.getService().isNew())
|| (clInfo != null && !clInfo.getService().isNew())) {
command = "-U";
}
CRM.setParameters(dcHost,
command,
heartbeatId,
cloneId,
master,
cloneMetaArgs,
groupMetaArgs,
groupId,
pacemakerResAttrs,
pacemakerResArgs,
pacemakerMetaArgs,
null,
null,
getOperations(heartbeatId),
null,
getMetaAttrsRefId(),
cloneMetaAttrsRefIds,
groupMetaAttrsRefIds,
refCRMId,
resourceAgent.isStonith(),
testOnly);
if (gInfo == null) {
String hbId = heartbeatId;
if (clInfo != null) {
hbId = clInfo.getHeartbeatId(testOnly);
}
final List<Map<String, String>> colAttrsList =
new ArrayList<Map<String, String>>();
final List<Map<String, String>> ordAttrsList =
new ArrayList<Map<String, String>>();
final List<String> parentIds = new ArrayList<String>();
ServiceInfo infoForDependency;
if (clInfo == null) {
infoForDependency = this;
} else {
infoForDependency = clInfo;
}
final Set<ServiceInfo> parents =
getBrowser().getCRMGraph().getParents(
infoForDependency);
for (final ServiceInfo parentInfo : parents) {
if (parentInfo.isConstraintPH()) {
final boolean colocation = true;
final boolean order = true;
final Set<ServiceInfo> with =
new TreeSet<ServiceInfo>();
with.add(infoForDependency);
final Set<ServiceInfo> withFrom =
new TreeSet<ServiceInfo>();
((ConstraintPHInfo) parentInfo)
.addConstraintWithPlaceholder(
with,
withFrom,
colocation,
order,
dcHost,
!parentInfo.getService().isNew(),
testOnly);
} else {
final String parentId =
parentInfo.getService().getHeartbeatId();
parentIds.add(parentId);
final Map<String, String> colAttrs =
new LinkedHashMap<String, String>();
final Map<String, String> ordAttrs =
new LinkedHashMap<String, String>();
if (getBrowser().getCRMGraph().isColocation(
parentInfo,
infoForDependency)) {
colAttrs.put(CRMXML.SCORE_STRING,
CRMXML.INFINITY_STRING);
if (parentInfo.getService().isMaster()) {
colAttrs.put("with-rsc-role", "Master");
}
colAttrsList.add(colAttrs);
} else {
colAttrsList.add(null);
}
if (getBrowser().getCRMGraph().isOrder(
parentInfo,
infoForDependency)) {
ordAttrs.put(CRMXML.SCORE_STRING,
CRMXML.INFINITY_STRING);
if (parentInfo.getService().isMaster()) {
ordAttrs.put("first-action", "promote");
ordAttrs.put("then-action", "start");
}
ordAttrsList.add(ordAttrs);
} else {
ordAttrsList.add(null);
}
}
}
if (!parentIds.isEmpty()) {
CRM.setOrderAndColocation(dcHost,
hbId,
parentIds.toArray(
new String [parentIds.size()]),
colAttrsList,
ordAttrsList,
testOnly);
}
} else {
gInfo.resetPopup();
}
} else {
if (clInfo != null) {
for (String param : cloneParams) {
if (GUI_ID.equals(param)
|| PCMK_ID.equals(param)) {
continue;
}
final String value = clInfo.getComboBoxValue(param);
if (value.equals(clInfo.getParamDefault(param))) {
continue;
}
if (!"".equals(value)) {
cloneMetaArgs.put(param, value);
}
}
}
if (gInfo != null) {
for (String param : groupParams) {
if (GUI_ID.equals(param)
|| PCMK_ID.equals(param)) {
continue;
}
final String value = gInfo.getComboBoxValue(param);
if (value == null
|| value.equals(gInfo.getParamDefault(param))) {
continue;
}
if (!"".equals(value)) {
groupMetaArgs.put(param, value);
}
}
cloneId = null;
}
groupId = null; /* we don't want to replace the whole group */
//TODO: should not be called if only host locations have
//changed.
final ClusterStatus cs = getBrowser().getClusterStatus();
CRM.setParameters(
dcHost,
"-R",
heartbeatId,
cloneId,
master,
cloneMetaArgs,
groupMetaArgs,
groupId,
pacemakerResAttrs,
pacemakerResArgs,
pacemakerMetaArgs,
cs.getResourceInstanceAttrId(heartbeatId),
cs.getParametersNvpairsIds(heartbeatId),
getOperations(heartbeatId),
cs.getOperationsId(heartbeatId),
getMetaAttrsRefId(),
cloneMetaAttrsRefIds,
groupMetaAttrsRefIds,
refCRMId,
resourceAgent.isStonith(),
testOnly);
if (isFailed(testOnly)) {
cleanupResource(dcHost, testOnly);
}
}
if (gInfo == null) {
if (clInfo == null) {
setLocations(heartbeatId, dcHost, testOnly);
} else {
clInfo.setLocations(heartbeatId, dcHost, testOnly);
}
} else {
setLocations(heartbeatId, dcHost, testOnly);
}
if (!testOnly) {
storeComboBoxValues(params);
storeOperations();
if (clInfo != null) {
clInfo.storeComboBoxValues(cloneParams);
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setApplyButtons(null, params);
final DefaultMutableTreeNode node = getNode();
if (node != null) {
if (clInfo == null) {
getBrowser().reload(node, false);
} else {
getBrowser().reload(clInfo.getNode(), false);
getBrowser().reload(node, false);
}
getBrowser().getCRMGraph().repaint();
}
}
});
}
}
/** Removes order(s). */
public void removeOrder(final ServiceInfo parent,
final Host dcHost,
final boolean testOnly) {
if (getService().isNew() || parent.getService().isNew()) {
return;
}
if (!testOnly
&& !getService().isNew() && !parent.getService().isNew()) {
parent.setUpdated(true);
setUpdated(true);
}
final ClusterStatus clStatus = getBrowser().getClusterStatus();
String rscId;
if (isConstraintPH()) {
rscId = getId();
} else {
rscId = getHeartbeatId(testOnly);
}
if (isConstraintPH() || parent.isConstraintPH()) {
ConstraintPHInfo cphi = null;
if (isConstraintPH()) {
cphi = (ConstraintPHInfo) this;
} else {
cphi = (ConstraintPHInfo) parent;
}
final Map<CRMXML.RscSet, Map<String, String>> rscSetsOrdAttrs =
new LinkedHashMap<CRMXML.RscSet, Map<String, String>>();
final CRMXML.RscSetConnectionData rdata =
cphi.getRscSetConnectionDataOrd();
/** resource set */
final String ordId = rdata.getConstraintId();
String idToRemove;
if (isConstraintPH()) {
idToRemove = parent.getService().getHeartbeatId();
} else {
idToRemove = getService().getHeartbeatId();
}
CRMXML.RscSet modifiedRscSet = null;
final List<CRMXML.RscSet> ordRscSets =
clStatus.getRscSetsOrd(ordId);
if (ordRscSets != null) {
for (final CRMXML.RscSet rscSet : ordRscSets) {
if (rscSet.equals(rdata.getRscSet1())
|| rscSet.equals(rdata.getRscSet2())) {
final List<String> newRscIds =
new ArrayList<String>();
newRscIds.addAll(rscSet.getRscIds());
if (newRscIds.remove(idToRemove) && !testOnly) {
modifiedRscSet = rscSet;
}
if (!newRscIds.isEmpty()) {
final CRMXML.RscSet newRscSet =
new CRMXML.RscSet(
rscSet.getId(),
newRscIds,
rscSet.getSequential(),
rscSet.getRequireAll(),
rscSet.getOrderAction(),
rscSet.getColocationRole());
rscSetsOrdAttrs.put(newRscSet, null);
}
} else {
rscSetsOrdAttrs.put(rscSet, null);
}
}
}
if (!testOnly && rscSetsOrdAttrs.isEmpty()) {
cphi.getRscSetConnectionDataOrd().setConstraintId(null);
}
final Map<String, String> attrs =
new LinkedHashMap<String, String>();
final CRMXML.OrderData od = clStatus.getOrderData(ordId);
if (od != null) {
final String score = od.getScore();
attrs.put(CRMXML.SCORE_STRING, score);
}
if (!testOnly) {
///* so that it will not be removed */
cphi.setUpdated(false);
}
CRM.setRscSet(dcHost,
null,
false,
ordId,
false,
null,
rscSetsOrdAttrs,
attrs,
testOnly);
} else {
final String rscFirstId = parent.getHeartbeatId(testOnly);
final List<CRMXML.OrderData> allData =
clStatus.getOrderDatas(rscFirstId);
if (allData != null) {
for (final CRMXML.OrderData orderData : allData) {
final String orderId = orderData.getId();
final String rscThenId = orderData.getRscThen();
if (rscThenId.equals(getHeartbeatId(testOnly))) {
CRM.removeOrder(dcHost,
orderId,
testOnly);
}
}
}
}
}
/** Returns pacemaker id. */
final String getHeartbeatId(final boolean testOnly) {
String heartbeatId = getService().getHeartbeatId();
if (testOnly && heartbeatId == null) {
heartbeatId = getService().getCrmIdFromId(getComboBoxValue(GUI_ID));
}
return heartbeatId;
}
/** Adds order constraint from this service to the child. */
public void addOrder(final ServiceInfo child,
final Host dcHost,
final boolean testOnly) {
if (!testOnly
&& !getService().isNew() && !child.getService().isNew()) {
child.setUpdated(true);
setUpdated(true);
}
if (isConstraintPH() || child.isConstraintPH()) {
if (!testOnly) {
if (isConstraintPH()
&& ((ConstraintPHInfo) this).isReversedCol()) {
((ConstraintPHInfo) this).reverseOrder();
} else if (child.isConstraintPH()
&& ((ConstraintPHInfo) child).isReversedCol()) {
((ConstraintPHInfo) child).reverseOrder();
}
}
final ConstraintPHInfo cphi;
final ServiceInfo withService;
final Set<ServiceInfo> withFrom = new TreeSet<ServiceInfo>();
if (isConstraintPH()) {
cphi = (ConstraintPHInfo) this;
withService = child;
} else {
cphi = (ConstraintPHInfo) child;
withService = this;
withFrom.add(this);
}
final Set<ServiceInfo> with = new TreeSet<ServiceInfo>();
with.add(withService);
cphi.addConstraintWithPlaceholder(with,
withFrom,
false,
true,
dcHost,
!cphi.getService().isNew(),
testOnly);
} else {
final String childHbId = child.getHeartbeatId(testOnly);
final Map<String, String> attrs =
new LinkedHashMap<String, String>();
attrs.put(CRMXML.SCORE_STRING, CRMXML.INFINITY_STRING);
final CloneInfo chCI = child.getCloneInfo();
if (chCI != null
&& chCI.getService().isMaster()) {
attrs.put("first-action", "promote");
attrs.put("then-action", "start");
}
CRM.addOrder(dcHost,
null, /* order id */
getHeartbeatId(testOnly),
childHbId,
attrs,
testOnly);
}
}
/** Removes colocation(s). */
public void removeColocation(final ServiceInfo parent,
final Host dcHost,
final boolean testOnly) {
if (getService().isNew() || parent.getService().isNew()) {
return;
}
if (!testOnly
&& !getService().isNew() && !parent.getService().isNew()) {
parent.setUpdated(true);
setUpdated(true);
}
final ClusterStatus clStatus = getBrowser().getClusterStatus();
String rscId;
if (isConstraintPH()) {
rscId = getId();
} else {
rscId = getHeartbeatId(testOnly);
}
if (isConstraintPH() || parent.isConstraintPH()) {
final Map<CRMXML.RscSet, Map<String, String>> rscSetsColAttrs =
new LinkedHashMap<CRMXML.RscSet, Map<String, String>>();
ConstraintPHInfo cphi = null;
if (isConstraintPH()) {
cphi = (ConstraintPHInfo) this;
} else {
cphi = (ConstraintPHInfo) parent;
}
final CRMXML.RscSetConnectionData rdata =
cphi.getRscSetConnectionDataCol();
/** resource set */
final String colId = rdata.getConstraintId();
String idToRemove;
if (isConstraintPH()) {
idToRemove = parent.getService().getHeartbeatId();
} else {
idToRemove = getService().getHeartbeatId();
}
CRMXML.RscSet modifiedRscSet = null;
final List<CRMXML.RscSet> colRscSets =
clStatus.getRscSetsCol(colId);
if (colRscSets != null) {
for (final CRMXML.RscSet rscSet : colRscSets) {
if (rscSet.equals(rdata.getRscSet1())
|| rscSet.equals(rdata.getRscSet2())) {
final List<String> newRscIds =
new ArrayList<String>();
newRscIds.addAll(rscSet.getRscIds());
if (newRscIds.remove(idToRemove) && !testOnly) {
modifiedRscSet = rscSet;
}
if (!newRscIds.isEmpty()) {
final CRMXML.RscSet newRscSet =
new CRMXML.RscSet(
rscSet.getId(),
newRscIds,
rscSet.getSequential(),
rscSet.getRequireAll(),
rscSet.getOrderAction(),
rscSet.getColocationRole());
rscSetsColAttrs.put(newRscSet, null);
}
} else {
rscSetsColAttrs.put(rscSet, null);
}
}
}
if (!testOnly && rscSetsColAttrs.isEmpty()) {
cphi.getRscSetConnectionDataCol().setConstraintId(null);
}
final Map<String, String> attrs =
new LinkedHashMap<String, String>();
final CRMXML.ColocationData cd = clStatus.getColocationData(colId);
if (cd != null) {
final String score = cd.getScore();
attrs.put(CRMXML.SCORE_STRING, score);
}
if (!testOnly) {
cphi.setUpdated(false);
}
CRM.setRscSet(dcHost,
colId,
false,
null,
false,
rscSetsColAttrs,
null,
attrs,
testOnly);
} else {
final List<CRMXML.ColocationData> allData =
clStatus.getColocationDatas(rscId);
if (allData != null) {
for (final CRMXML.ColocationData colocationData
: allData) {
final String colId = colocationData.getId();
final String withRscId =
colocationData.getWithRsc();
if (withRscId.equals(
parent.getHeartbeatId(testOnly))) {
CRM.removeColocation(dcHost,
colId,
testOnly);
}
}
}
}
}
/**
* Adds colocation constraint from this service to the child. The
* child - child order is here important, in case colocation
* constraint is used along with order constraint.
*/
public void addColocation(final ServiceInfo child,
final Host dcHost,
final boolean testOnly) {
if (!testOnly
&& !getService().isNew() && !child.getService().isNew()) {
child.setUpdated(true);
setUpdated(true);
}
if (isConstraintPH() || child.isConstraintPH()) {
if (!testOnly) {
if (isConstraintPH()
&& ((ConstraintPHInfo) this).isReversedOrd()) {
((ConstraintPHInfo) this).reverseColocation();
} else if (child.isConstraintPH()
&& ((ConstraintPHInfo) child).isReversedOrd()) {
((ConstraintPHInfo) child).reverseColocation();
}
}
final ConstraintPHInfo cphi;
final ServiceInfo withService;
final Set<ServiceInfo> withFrom = new TreeSet<ServiceInfo>();
if (isConstraintPH()) {
cphi = (ConstraintPHInfo) this;
withService = child;
} else {
cphi = (ConstraintPHInfo) child;
withService = this;
withFrom.add(this);
}
final Set<ServiceInfo> with = new TreeSet<ServiceInfo>();
with.add(withService);
cphi.addConstraintWithPlaceholder(with,
withFrom,
true,
false,
dcHost,
!cphi.getService().isNew(),
testOnly);
} else {
final String childHbId = child.getHeartbeatId(testOnly);
final Map<String, String> attrs =
new LinkedHashMap<String, String>();
attrs.put(CRMXML.SCORE_STRING, CRMXML.INFINITY_STRING);
final CloneInfo pCI = child.getCloneInfo();
if (pCI != null
&& pCI.getService().isMaster()) {
attrs.put("with-rsc-role", "Master");
}
CRM.addColocation(dcHost,
null, /* col id */
childHbId,
getHeartbeatId(testOnly),
attrs,
testOnly);
}
}
/** Returns panel with graph. */
@Override
public JPanel getGraphicalView() {
return getBrowser().getCRMGraph().getGraphPanel();
}
/** Adds service panel to the position 'pos'. */
public ServiceInfo addServicePanel(final ResourceAgent newRA,
final Point2D pos,
final boolean colocation,
final boolean order,
final boolean reloadNode,
final boolean master,
final boolean testOnly) {
ServiceInfo newServiceInfo;
final String name = newRA.getName();
if (newRA.isFilesystem()) {
newServiceInfo = new FilesystemInfo(name, newRA, getBrowser());
} else if (newRA.isLinbitDrbd()) {
newServiceInfo = new LinbitDrbdInfo(name, newRA, getBrowser());
} else if (newRA.isDrbddisk()) {
newServiceInfo = new DrbddiskInfo(name, newRA, getBrowser());
} else if (newRA.isIPaddr()) {
newServiceInfo = new IPaddrInfo(name, newRA, getBrowser());
} else if (newRA.isVirtualDomain()) {
newServiceInfo = new VirtualDomainInfo(name, newRA, getBrowser());
} else if (newRA.isGroup()) {
newServiceInfo = new GroupInfo(newRA, getBrowser());
} else if (newRA.isClone()) {
String cloneName;
if (master) {
cloneName = ConfigData.PM_MASTER_SLAVE_SET_NAME;
} else {
cloneName = ConfigData.PM_CLONE_SET_NAME;
}
newServiceInfo = new CloneInfo(newRA,
cloneName,
master,
getBrowser());
} else {
newServiceInfo = new ServiceInfo(name, newRA, getBrowser());
}
addServicePanel(newServiceInfo,
pos,
colocation,
order,
reloadNode,
getBrowser().getDCHost(),
testOnly);
return newServiceInfo;
}
/**
* Adds service panel to the position 'pos'.
* TODO: is it used?
*/
public void addServicePanel(final ServiceInfo serviceInfo,
final Point2D pos,
final boolean colocation,
final boolean order,
final boolean reloadNode,
final Host dcHost,
final boolean testOnly) {
final ResourceAgent ra = serviceInfo.getResourceAgent();
if (ra != null) {
serviceInfo.getService().setResourceClass(ra.getResourceClass());
}
if (getBrowser().getCRMGraph().addResource(serviceInfo,
this,
pos,
colocation,
order,
testOnly)) {
Tools.waitForSwing();
/* edge added */
if (isConstraintPH() || serviceInfo.isConstraintPH()) {
final ConstraintPHInfo cphi;
final ServiceInfo withService;
final Set<ServiceInfo> withFrom = new TreeSet<ServiceInfo>();
if (isConstraintPH()) {
cphi = (ConstraintPHInfo) this;
withService = serviceInfo;
} else {
cphi = (ConstraintPHInfo) serviceInfo;
withService = this;
withFrom.add(this);
}
withFrom.addAll(getBrowser().getCRMGraph().getParents(cphi));
final Set<ServiceInfo> with = new TreeSet<ServiceInfo>();
with.add(withService);
cphi.addConstraintWithPlaceholder(with,
withFrom,
colocation,
order,
dcHost,
!cphi.getService().isNew(),
testOnly);
if (!testOnly) {
final PcmkRscSetsInfo prsi = cphi.getPcmkRscSetsInfo();
prsi.setApplyButtons(null, prsi.getParametersFromXML());
}
} else {
final String parentId = getHeartbeatId(testOnly);
final String heartbeatId = serviceInfo.getHeartbeatId(testOnly);
final List<Map<String, String>> colAttrsList =
new ArrayList<Map<String, String>>();
final List<Map<String, String>> ordAttrsList =
new ArrayList<Map<String, String>>();
final Map<String, String> colAttrs =
new LinkedHashMap<String, String>();
final Map<String, String> ordAttrs =
new LinkedHashMap<String, String>();
colAttrs.put(CRMXML.SCORE_STRING, CRMXML.INFINITY_STRING);
ordAttrs.put(CRMXML.SCORE_STRING, CRMXML.INFINITY_STRING);
if (getService().isMaster()) {
colAttrs.put("with-rsc-role", "Master");
ordAttrs.put("first-action", "promote");
ordAttrs.put("then-action", "start");
}
if (colocation) {
colAttrsList.add(colAttrs);
} else {
colAttrsList.add(null);
}
if (order) {
ordAttrsList.add(ordAttrs);
} else {
ordAttrsList.add(null);
}
if (!getService().isNew()
&& !serviceInfo.getService().isNew()) {
CRM.setOrderAndColocation(dcHost,
heartbeatId,
new String[]{parentId},
colAttrsList,
ordAttrsList,
testOnly);
}
}
} else {
getBrowser().addNameToServiceInfoHash(serviceInfo);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final DefaultMutableTreeNode newServiceNode =
new DefaultMutableTreeNode(serviceInfo);
serviceInfo.setNode(newServiceNode);
getBrowser().getServicesNode().add(newServiceNode);
if (reloadNode) {
getBrowser().reloadAndWait(
getBrowser().getServicesNode(), false);
getBrowser().reloadAndWait(newServiceNode, false);
}
}
});
getBrowser().reloadAllComboBoxes(serviceInfo);
}
if (reloadNode && ra != null && serviceInfo.getResource().isNew()) {
if (ra.isProbablyMasterSlave()) {
serviceInfo.changeType(MASTER_SLAVE_TYPE_STRING);
} else if (ra.isProbablyClone()) {
serviceInfo.changeType(CLONE_TYPE_STRING);
}
}
getBrowser().getCRMGraph().reloadServiceMenus();
if (reloadNode) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
getBrowser().getCRMGraph().scale();
}
});
}
}
/** Returns service that belongs to this info object. */
public Service getService() {
return (Service) getResource();
}
/** Starts resource in crm. */
void startResource(final Host dcHost, final boolean testOnly) {
if (!testOnly) {
setUpdated(true);
}
CRM.startResource(dcHost, getHeartbeatId(testOnly), testOnly);
}
/** Stops resource in crm. */
void stopResource(final Host dcHost, final boolean testOnly) {
if (!testOnly) {
setUpdated(true);
}
CRM.stopResource(dcHost, getHeartbeatId(testOnly), testOnly);
}
/** Puts a resource up in a group. */
void upResource(final Host dcHost, final boolean testOnly) {
final GroupInfo gi = groupInfo;
final DefaultMutableTreeNode giNode = gi.getNode();
if (giNode == null) {
return;
}
final DefaultMutableTreeNode node = getNode();
if (node == null) {
return;
}
final int index = giNode.getIndex(node);
if (index > 0) {
@SuppressWarnings("unchecked")
final Enumeration<DefaultMutableTreeNode> e = giNode.children();
final List<String> newOrder = new ArrayList<String>();
while (e.hasMoreElements()) {
final DefaultMutableTreeNode n = e.nextElement();
final ServiceInfo child = (ServiceInfo) n.getUserObject();
newOrder.add(child.getHeartbeatId(testOnly));
}
final String el = newOrder.remove(index);
newOrder.add(index - 1, el);
if (!testOnly) {
setUpdated(true);
}
gi.applyWhole(dcHost, false, newOrder, testOnly);
}
}
/** Puts a resource down in a group. */
void downResource(final Host dcHost, final boolean testOnly) {
final GroupInfo gi = groupInfo;
final DefaultMutableTreeNode giNode = gi.getNode();
if (giNode == null) {
return;
}
final DefaultMutableTreeNode node = getNode();
if (node == null) {
return;
}
final int index = giNode.getIndex(node);
if (index < giNode.getChildCount() - 1) {
@SuppressWarnings("unchecked")
final Enumeration<DefaultMutableTreeNode> e = giNode.children();
final List<String> newOrder = new ArrayList<String>();
while (e.hasMoreElements()) {
final DefaultMutableTreeNode n = e.nextElement();
final ServiceInfo child = (ServiceInfo) n.getUserObject();
newOrder.add(child.getHeartbeatId(testOnly));
}
final String el = newOrder.remove(index);
newOrder.add(index + 1, el);
if (!testOnly) {
setUpdated(true);
}
gi.applyWhole(dcHost, false, newOrder, testOnly);
}
}
/** Migrates resource in cluster from current location. */
void migrateResource(final String onHost,
final Host dcHost,
final boolean testOnly) {
if (!testOnly) {
setUpdated(true);
}
CRM.migrateResource(dcHost,
getHeartbeatId(testOnly),
onHost,
testOnly);
}
/** Migrates resource in heartbeat from current location. */
void migrateFromResource(final Host dcHost,
final String fromHost,
final boolean testOnly) {
if (!testOnly) {
setUpdated(true);
}
/* don't need fromHost, but m/s resources need it. */
CRM.migrateFromResource(dcHost,
getHeartbeatId(testOnly),
testOnly);
}
/**
* Migrates resource in cluster from current location with --force option.
*/
void forceMigrateResource(final String onHost,
final Host dcHost,
final boolean testOnly) {
if (!testOnly) {
setUpdated(true);
}
CRM.forceMigrateResource(dcHost,
getHeartbeatId(testOnly),
onHost,
testOnly);
}
/** Removes constraints created by resource migrate command. */
void unmigrateResource(final Host dcHost, final boolean testOnly) {
if (!testOnly) {
setUpdated(true);
}
CRM.unmigrateResource(dcHost, getHeartbeatId(testOnly), testOnly);
}
/** Cleans up the resource. */
void cleanupResource(final Host dcHost, final boolean testOnly) {
if (!testOnly) {
setUpdated(true);
}
final ClusterStatus cs = getBrowser().getClusterStatus();
final String rscId = getHeartbeatId(testOnly);
boolean failedClone = false;
for (final Host host : getBrowser().getClusterHosts()) {
final Set<String> failedClones =
cs.getFailedClones(host.getName(), rscId, testOnly);
if (failedClones == null) {
continue;
}
failedClone = true;
for (final String fc : failedClones) {
CRM.cleanupResource(dcHost,
rscId + ":" + fc,
new Host[]{host},
testOnly);
}
}
if (!failedClone) {
final List<Host> dirtyHosts = new ArrayList<Host>();
for (final Host host : getBrowser().getClusterHosts()) {
if (isInLRMOnHost(host.getName(), testOnly)
|| getFailCount(host.getName(), testOnly) != null) {
dirtyHosts.add(host);
}
}
if (!dirtyHosts.isEmpty()) {
CRM.cleanupResource(
dcHost,
rscId,
dirtyHosts.toArray(new Host[dirtyHosts.size()]),
testOnly);
}
}
}
/** Removes the service without confirmation dialog. */
protected void removeMyselfNoConfirm(final Host dcHost,
final boolean testOnly) {
if (!testOnly) {
if (!getService().isNew()) {
setUpdated(true);
}
getService().setRemoved(true);
cleanup();
}
final CloneInfo ci = getCloneInfo();
if (ci != null) {
ci.removeMyselfNoConfirm(dcHost, testOnly);
setCloneInfo(null);
}
final GroupInfo gi = groupInfo;
if (getService().isNew() && gi == null) {
if (!testOnly) {
getService().setNew(false);
getBrowser().getCRMGraph().killRemovedVertices();
}
} else {
final ClusterStatus cs = getBrowser().getClusterStatus();
if (gi == null) {
removeConstraints(dcHost, testOnly);
}
if (!getResourceAgent().isGroup()
&& !getResourceAgent().isClone()) {
String groupId = null; /* for pacemaker */
if (gi != null) {
/* get group id only if there is only one resource in a
* group.
*/
if (getService().isNew()) {
if (!testOnly) {
super.removeMyself(false);
}
} else {
final String group = gi.getHeartbeatId(testOnly);
final DefaultMutableTreeNode giNode = gi.getNode();
if (giNode != null) {
@SuppressWarnings("unchecked")
final Enumeration<DefaultMutableTreeNode> e =
giNode.children();
while (e.hasMoreElements()) {
final DefaultMutableTreeNode n =
e.nextElement();
final ServiceInfo child =
(ServiceInfo) n.getUserObject();
child.getService().setModified(true);
child.getService().doneModifying();
}
}
if (cs.getGroupResources(group, testOnly).size() == 1) {
if (!testOnly) {
gi.getService().setRemoved(true);
}
gi.removeMyselfNoConfirmFromChild(dcHost, testOnly);
groupId = group;
gi.getService().doneRemoving();
}
}
gi.resetPopup();
}
if (!getService().isNew()) {
String cloneId = null;
boolean master = false;
if (ci != null) {
cloneId = ci.getHeartbeatId(testOnly);
master = ci.getService().isMaster();
}
final boolean ret = CRM.removeResource(
dcHost,
getHeartbeatId(testOnly),
groupId,
cloneId,
master,
testOnly);
cleanupResource(dcHost, testOnly);
setUpdated(false); /* must be here, is not a clone anymore*/
if (!testOnly && !ret) {
Tools.progressIndicatorFailed(dcHost.getName(),
"removing failed");
}
}
}
}
if (!testOnly) {
getBrowser().removeFromServiceInfoHash(this);
infoPanel = null;
getService().doneRemoving();
}
}
/** Removes this service from the crm with confirmation dialog. */
@Override
public void removeMyself(final boolean testOnly) {
if (getService().isNew()) {
removeMyselfNoConfirm(getBrowser().getDCHost(), testOnly);
getService().setNew(false);
getService().doneRemoving();
return;
}
String desc = Tools.getString(
"ClusterBrowser.confirmRemoveService.Description");
desc = desc.replaceAll("@SERVICE@",
Matcher.quoteReplacement(toString()));
if (Tools.confirmDialog(
Tools.getString("ClusterBrowser.confirmRemoveService.Title"),
desc,
Tools.getString("ClusterBrowser.confirmRemoveService.Yes"),
Tools.getString("ClusterBrowser.confirmRemoveService.No"))) {
removeMyselfNoConfirm(getBrowser().getDCHost(), testOnly);
removeInfo();
getService().setNew(false);
}
}
/** Removes the service from some global hashes and lists. */
public void removeInfo() {
getBrowser().mHeartbeatIdToServiceLock();
getBrowser().getHeartbeatIdToServiceInfo().remove(
getService().getHeartbeatId());
getBrowser().mHeartbeatIdToServiceUnlock();
getBrowser().removeFromServiceInfoHash(this);
final CloneInfo ci = cloneInfo;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
removeNodeAndWait();
if (ci != null) {
ci.removeNodeAndWait();
}
}
});
super.removeMyself(false);
}
/** Sets this service as part of a group. */
void setGroupInfo(final GroupInfo groupInfo) {
this.groupInfo = groupInfo;
}
/** Sets this service as part of a clone set. */
void setCloneInfo(final CloneInfo cloneInfo) {
this.cloneInfo = cloneInfo;
}
/**
* Returns the group to which this service belongs or null, if it is
* not in any group.
*/
public GroupInfo getGroupInfo() {
return groupInfo;
}
/**
* Returns the clone set to which this service belongs
* or null, if it is not in such set.
*/
CloneInfo getCloneInfo() {
return cloneInfo;
}
/** Adds existing service menu item for every member of a group. */
protected void addExistingGroupServiceMenuItems(
final ServiceInfo asi,
final MyListModel<MyMenuItem> dlm,
final Map<MyMenuItem, ButtonCallback> callbackHash,
final MyList<MyMenuItem> list,
final JCheckBox colocationWi,
final JCheckBox orderWi,
final List<JDialog> popups,
final boolean testOnly) {
/* empty */
}
/** Adds existing service menu item. */
protected void addExistingServiceMenuItem(
final String name,
final ServiceInfo asi,
final MyListModel<MyMenuItem> dlm,
final Map<MyMenuItem, ButtonCallback> callbackHash,
final MyList<MyMenuItem> list,
final JCheckBox colocationWi,
final JCheckBox orderWi,
final List<JDialog> popups,
final boolean testOnly) {
final MyMenuItem mmi = new MyMenuItem(name,
null,
null,
new AccessMode(
ConfigData.AccessType.ADMIN,
false),
new AccessMode(
ConfigData.AccessType.OP,
false)) {
private static final long serialVersionUID = 1L;
@Override
public void action() {
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
hidePopup();
for (final JDialog otherP : popups) {
otherP.dispose();
}
addServicePanel(asi,
null,
colocationWi.isSelected(),
orderWi.isSelected(),
true,
getBrowser().getDCHost(),
testOnly);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
repaint();
}
});
}
});
thread.start();
}
};
dlm.addElement(mmi);
final ClusterBrowser.ClMenuItemCallback mmiCallback =
getBrowser().new ClMenuItemCallback(list, null) {
@Override
public void action(final Host dcHost) {
addServicePanel(asi,
null,
colocationWi.isSelected(),
orderWi.isSelected(),
true,
dcHost,
true); /* test only */
}
};
callbackHash.put(mmi, mmiCallback);
}
/** Returns existing service manu item. */
private MyMenu getExistingServiceMenuItem(final String name,
final boolean enableForNew,
final boolean testOnly) {
final ServiceInfo thisClass = this;
return new MyMenu(name,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
private final Lock mUpdateLock = new ReentrantLock();
@Override
public String enablePredicate() {
if (getBrowser().clStatusFailed()) {
return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
} else if (getService().isRemoved()) {
return IS_BEING_REMOVED_STRING;
} else if (getService().isOrphaned()) {
return IS_ORPHANED_STRING;
} else if (!enableForNew && getService().isNew()) {
return IS_NEW_STRING;
}
if (getBrowser().getExistingServiceList(thisClass).size()
== 0) {
return "<<empty;>>";
}
return null;
}
@Override
public void update() {
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
if (mUpdateLock.tryLock()) {
try {
updateThread();
} finally {
mUpdateLock.unlock();
}
}
}
});
t.start();
}
private void updateThread() {
final JCheckBox colocationWi = new JCheckBox("Colo", true);
final JCheckBox orderWi = new JCheckBox("Order", true);
colocationWi.setBackground(ClusterBrowser.STATUS_BACKGROUND);
colocationWi.setPreferredSize(colocationWi.getMinimumSize());
orderWi.setBackground(ClusterBrowser.STATUS_BACKGROUND);
orderWi.setPreferredSize(orderWi.getMinimumSize());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setEnabled(false);
}
});
Tools.invokeAndWait(new Runnable() {
@Override
public void run() {
removeAll();
}
});
final MyListModel<MyMenuItem> dlm =
new MyListModel<MyMenuItem>();
final Map<MyMenuItem, ButtonCallback> callbackHash =
new HashMap<MyMenuItem, ButtonCallback>();
final MyList<MyMenuItem> list =
new MyList<MyMenuItem>(dlm, getBackground());
final List<JDialog> popups = new ArrayList<JDialog>();
for (final ServiceInfo asi
: getBrowser().getExistingServiceList(thisClass)) {
if (asi.isConstraintPH() && isConstraintPH()) {
continue;
}
if (asi.getCloneInfo() != null
|| asi.getGroupInfo() != null) {
/* skip services that are clones or in groups. */
continue;
}
addExistingServiceMenuItem(asi.toString(),
asi,
dlm,
callbackHash,
list,
colocationWi,
orderWi,
popups,
testOnly);
asi.addExistingGroupServiceMenuItems(thisClass,
dlm,
callbackHash,
list,
colocationWi,
orderWi,
popups,
testOnly);
}
final JPanel colOrdPanel =
new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
colOrdPanel.setBackground(ClusterBrowser.STATUS_BACKGROUND);
colOrdPanel.add(colocationWi);
colOrdPanel.add(orderWi);
final MyMenu thisM = this;
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
final boolean ret =
Tools.getScrollingMenu(name,
colOrdPanel,
thisM,
dlm,
list,
thisClass,
popups,
callbackHash);
if (!ret) {
setEnabled(false);
}
}
});
} catch (final InterruptedException ix) {
Thread.currentThread().interrupt();
} catch (final InvocationTargetException x) {
Tools.printStackTrace();
}
super.update();
}
};
}
/** Adds Linbit DRBD RA menu item. It is called in swing thread. */
private void addDrbdLinbitMenu(final MyMenu menu,
final CRMXML crmXML,
final Point2D pos,
final ResourceAgent fsService,
final boolean testOnly) {
final MyMenuItem ldMenuItem = new MyMenuItem(
Tools.getString("ClusterBrowser.linbitDrbdMenuName"),
null,
null,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public void action() {
hidePopup();
if (!getBrowser().linbitDrbdConfirmDialog()) {
return;
}
final FilesystemInfo fsi = (FilesystemInfo)
addServicePanel(
fsService,
getPos(),
true, /* colocation */
true, /* order */
true,
false,
testOnly);
fsi.setDrbddiskIsPreferred(false);
getBrowser().getCRMGraph().repaint();
}
};
if (getBrowser().atLeastOneDrbddisk()
|| !crmXML.isLinbitDrbdPresent()) {
ldMenuItem.setEnabled(false);
}
ldMenuItem.setPos(pos);
menu.add(ldMenuItem);
}
/** Adds drbddisk RA menu item. It is called in swing thread. */
private void addDrbddiskMenu(final MyMenu menu,
final CRMXML crmXML,
final Point2D pos,
final ResourceAgent fsService,
final boolean testOnly) {
final ResourceAgent drbddiskService = crmXML.getHbDrbddisk();
final MyMenuItem ddMenuItem = new MyMenuItem(
Tools.getString("ClusterBrowser.DrbddiskMenuName"),
null,
null,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public void action() {
hidePopup();
final FilesystemInfo fsi = (FilesystemInfo) addServicePanel(
fsService,
getPos(),
true, /* colocation */
true, /* order */
true,
false,
testOnly);
fsi.setDrbddiskIsPreferred(true);
getBrowser().getCRMGraph().repaint();
}
};
if (getBrowser().isOneLinbitDrbd()
|| !crmXML.isDrbddiskPresent()) {
ddMenuItem.setEnabled(false);
}
ddMenuItem.setPos(pos);
menu.add(ddMenuItem);
}
/** Adds Ipaddr RA menu item. It is called in swing thread. */
private void addIpMenu(final MyMenu menu,
final Point2D pos,
final ResourceAgent ipService,
final boolean testOnly) {
final MyMenuItem ipMenuItem =
new MyMenuItem(ipService.getMenuName(),
null,
null,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public void action() {
hidePopup();
addServicePanel(ipService,
getPos(),
true, /* colocation */
true, /* order */
true,
false,
testOnly);
getBrowser().getCRMGraph().repaint();
}
};
ipMenuItem.setPos(pos);
menu.add(ipMenuItem);
}
/** Adds Filesystem RA menu item. It is called in swing thread. */
private void addFilesystemMenu(final MyMenu menu,
final Point2D pos,
final ResourceAgent fsService,
final boolean testOnly) {
final MyMenuItem fsMenuItem =
new MyMenuItem(fsService.getMenuName(),
null,
null,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public void action() {
hidePopup();
addServicePanel(fsService,
getPos(),
true, /* colocation */
true, /* order */
true,
false,
testOnly);
getBrowser().getCRMGraph().repaint();
}
};
fsMenuItem.setPos(pos);
menu.add(fsMenuItem);
}
/** Adds resource agent RA menu item. It is called in swing thread. */
private void addResourceAgentMenu(final ResourceAgent ra,
final MyListModel<MyMenuItem> dlm,
final Point2D pos,
final List<JDialog> popups,
final JCheckBox colocationWi,
final JCheckBox orderWi,
final boolean testOnly) {
final MyMenuItem mmi =
new MyMenuItem(
ra.getMenuName(),
null,
null,
new AccessMode(ConfigData.AccessType.ADMIN,
false),
new AccessMode(ConfigData.AccessType.OP,
false)) {
private static final long serialVersionUID = 1L;
@Override
public void action() {
hidePopup();
for (final JDialog otherP : popups) {
otherP.dispose();
}
if (ra.isLinbitDrbd()
&&
!getBrowser().linbitDrbdConfirmDialog()) {
return;
} else if (ra.isHbDrbd()
&& !getBrowser().hbDrbdConfirmDialog()) {
return;
}
addServicePanel(ra,
getPos(),
colocationWi.isSelected(),
orderWi.isSelected(),
true,
false,
testOnly);
getBrowser().getCRMGraph().repaint();
}
};
mmi.setPos(pos);
dlm.addElement(mmi);
}
/** Adds new Service and dependence. */
private MyMenu getAddServiceMenuItem(final boolean testOnly,
final String name) {
final ServiceInfo thisClass = this;
return new MyMenu(name,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
private final Lock mUpdateLock = new ReentrantLock();
@Override
public String enablePredicate() {
if (getBrowser().clStatusFailed()) {
return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
} else if (getService().isRemoved()) {
return IS_BEING_REMOVED_STRING;
} else if (getService().isOrphaned()) {
return IS_ORPHANED_STRING;
} else if (getService().isNew()) {
return IS_NEW_STRING;
}
return null;
}
@Override
public void update() {
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
if (mUpdateLock.tryLock()) {
try {
updateThread();
} finally {
mUpdateLock.unlock();
}
}
}
});
t.start();
}
private void updateThread() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setEnabled(false);
}
});
Tools.invokeAndWait(new Runnable() {
@Override
public void run() {
removeAll();
}
});
final Point2D pos = getPos();
final CRMXML crmXML = getBrowser().getCRMXML();
final ResourceAgent fsService =
crmXML.getResourceAgent("Filesystem",
ResourceAgent.HEARTBEAT_PROVIDER,
ResourceAgent.OCF_CLASS);
final MyMenu thisMenu = this;
if (crmXML.isLinbitDrbdPresent()) { /* just skip it, if it
is not */
final ResourceAgent linbitDrbdService =
crmXML.getHbLinbitDrbd();
/* Linbit:DRBD */
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
addDrbdLinbitMenu(thisMenu,
crmXML,
pos,
fsService,
testOnly);
}
});
} catch (final InterruptedException ix) {
Thread.currentThread().interrupt();
} catch (final InvocationTargetException x) {
Tools.printStackTrace();
}
}
if (crmXML.isDrbddiskPresent()) { /* just skip it,
if it is not */
/* drbddisk */
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
addDrbddiskMenu(thisMenu,
crmXML,
pos,
fsService,
testOnly);
}
});
} catch (final InterruptedException ix) {
Thread.currentThread().interrupt();
} catch (final InvocationTargetException x) {
Tools.printStackTrace();
}
}
final ResourceAgent ipService = crmXML.getResourceAgent(
"IPaddr2",
ResourceAgent.HEARTBEAT_PROVIDER,
ResourceAgent.OCF_CLASS);
if (ipService != null) { /* just skip it, if it is not*/
/* ipaddr */
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
addIpMenu(thisMenu,
pos,
ipService,
testOnly);
}
});
} catch (final InterruptedException ix) {
Thread.currentThread().interrupt();
} catch (final InvocationTargetException x) {
Tools.printStackTrace();
}
}
if (fsService != null) { /* just skip it, if it is not*/
/* Filesystem */
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
addFilesystemMenu(thisMenu,
pos,
fsService,
testOnly);
}
});
} catch (final InterruptedException ix) {
Thread.currentThread().interrupt();
} catch (final InvocationTargetException x) {
Tools.printStackTrace();
}
}
final List<JDialog> popups = new ArrayList<JDialog>();
for (final String cl : ClusterBrowser.HB_CLASSES) {
final List<ResourceAgent> services = getAddServiceList(cl);
if (services.isEmpty()) {
/* no services, don't show */
continue;
}
final JCheckBox colocationWi = new JCheckBox("Colo", true);
final JCheckBox orderWi = new JCheckBox("Order", true);
colocationWi.setBackground(
ClusterBrowser.STATUS_BACKGROUND);
colocationWi.setPreferredSize(
colocationWi.getMinimumSize());
orderWi.setBackground(ClusterBrowser.STATUS_BACKGROUND);
orderWi.setPreferredSize(orderWi.getMinimumSize());
final JPanel colOrdPanel =
new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
colOrdPanel.setBackground(ClusterBrowser.STATUS_BACKGROUND);
colOrdPanel.add(colocationWi);
colOrdPanel.add(orderWi);
boolean mode = !AccessMode.ADVANCED;
if (ResourceAgent.UPSTART_CLASS.equals(cl)
|| ResourceAgent.SYSTEMD_CLASS.equals(cl)) {
mode = AccessMode.ADVANCED;
}
if (ResourceAgent.LSB_CLASS.equals(cl)
&& !getAddServiceList(
ResourceAgent.SERVICE_CLASS).isEmpty()) {
mode = AccessMode.ADVANCED;
}
final MyMenu classItem = new MyMenu(
ClusterBrowser.getClassMenu(cl),
new AccessMode(ConfigData.AccessType.ADMIN, mode),
new AccessMode(ConfigData.AccessType.OP, mode));
final MyListModel<MyMenuItem> dlm =
new MyListModel<MyMenuItem>();
for (final ResourceAgent ra : services) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
addResourceAgentMenu(ra,
dlm,
pos,
popups,
colocationWi,
orderWi,
testOnly);
}
});
} catch (final InterruptedException ix) {
Thread.currentThread().interrupt();
} catch (final InvocationTargetException x) {
Tools.printStackTrace();
}
}
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
final boolean ret = Tools.getScrollingMenu(
ClusterBrowser.getClassMenu(cl),
colOrdPanel,
classItem,
dlm,
new MyList<MyMenuItem>(dlm,
getBackground()),
thisClass,
popups,
null);
if (!ret) {
classItem.setEnabled(false);
}
thisMenu.add(classItem);
}
});
} catch (final InterruptedException ix) {
Thread.currentThread().interrupt();
} catch (final InvocationTargetException x) {
Tools.printStackTrace();
}
}
super.update();
}
};
}
/** Adds menu items with dependend services and groups. */
protected void addDependencyMenuItems(final List<UpdatableItem> items,
final boolean enableForNew,
final boolean testOnly) {
/* add new group and dependency*/
final MyMenuItem addGroupMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.AddDependentGroup"),
null,
null,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public String enablePredicate() {
if (getBrowser().clStatusFailed()) {
return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
} else if (getService().isRemoved()) {
return IS_BEING_REMOVED_STRING;
} else if (getService().isOrphaned()) {
return IS_ORPHANED_STRING;
} else if (getService().isNew()) {
return IS_NEW_STRING;
}
return null;
}
@Override
public void action() {
hidePopup();
final StringInfo gi = new StringInfo(
ConfigData.PM_GROUP_NAME,
ConfigData.PM_GROUP_NAME,
getBrowser());
final CRMXML crmXML = getBrowser().getCRMXML();
addServicePanel(crmXML.getHbGroup(),
getPos(),
false, /* colocation only */
false, /* order only */
true,
false,
testOnly);
getBrowser().getCRMGraph().repaint();
}
};
items.add((UpdatableItem) addGroupMenuItem);
/* add new service and dependency*/
final MyMenu addServiceMenuItem = getAddServiceMenuItem(
testOnly,
Tools.getString("ClusterBrowser.Hb.AddDependency"));
items.add((UpdatableItem) addServiceMenuItem);
/* add existing service dependency*/
final MyMenu existingServiceMenuItem = getExistingServiceMenuItem(
Tools.getString("ClusterBrowser.Hb.AddStartBefore"),
enableForNew,
testOnly);
items.add((UpdatableItem) existingServiceMenuItem);
}
/**
* Returns list of items for service popup menu with actions that can
* be executed on the heartbeat services.
*/
@Override
public List<UpdatableItem> createPopup() {
final List<UpdatableItem> items = new ArrayList<UpdatableItem>();
final boolean testOnly = false;
final CloneInfo ci = getCloneInfo();
if (ci == null) {
addDependencyMenuItems(items, false, testOnly);
}
/* start resource */
final MyMenuItem startMenuItem =
new MyMenuItem(Tools.getString("ClusterBrowser.Hb.StartResource"),
START_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public final String enablePredicate() {
if (getBrowser().clStatusFailed()) {
return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
} else if (isStarted(testOnly)) {
return Tools.getString("ServiceInfo.AlreadyStarted");
} else {
return getService().isAvailableWithText();
}
}
@Override
public void action() {
hidePopup();
startResource(getBrowser().getDCHost(), testOnly);
}
};
final ClusterBrowser.ClMenuItemCallback startItemCallback =
getBrowser().new ClMenuItemCallback(startMenuItem, null) {
@Override
public void action(final Host dcHost) {
startResource(dcHost, true); /* testOnly */
}
};
addMouseOverListener(startMenuItem, startItemCallback);
items.add((UpdatableItem) startMenuItem);
/* stop resource */
final MyMenuItem stopMenuItem =
new MyMenuItem(Tools.getString("ClusterBrowser.Hb.StopResource"),
STOP_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public String enablePredicate() {
if (getBrowser().clStatusFailed()) {
return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
} else if (isStopped(testOnly)) {
return Tools.getString("ServiceInfo.AlreadyStopped");
} else {
return getService().isAvailableWithText();
}
}
@Override
public void action() {
hidePopup();
stopResource(getBrowser().getDCHost(), testOnly);
}
};
final ClusterBrowser.ClMenuItemCallback stopItemCallback =
getBrowser().new ClMenuItemCallback(stopMenuItem, null) {
@Override
public void action(final Host dcHost) {
stopResource(dcHost, true); /* testOnly */
}
};
addMouseOverListener(stopMenuItem, stopItemCallback);
items.add((UpdatableItem) stopMenuItem);
/* up group resource */
final MyMenuItem upMenuItem =
new MyMenuItem(Tools.getString("ClusterBrowser.Hb.UpResource"),
GROUP_UP_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public boolean visiblePredicate() {
return groupInfo != null;
}
@Override
public String enablePredicate() {
if (getResource().isNew()) {
return IS_NEW_STRING;
}
final GroupInfo gi = groupInfo;
if (gi == null) {
return "no";
}
if (getBrowser().clStatusFailed()) {
return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
}
final DefaultMutableTreeNode giNode = gi.getNode();
if (giNode == null) {
return "no";
}
final DefaultMutableTreeNode node = getNode();
if (node == null) {
return "no";
}
final int index = giNode.getIndex(node);
if (index == 0) {
return "already up";
}
return null;
}
@Override
public void action() {
hidePopup();
upResource(getBrowser().getDCHost(), testOnly);
}
};
final ClusterBrowser.ClMenuItemCallback upItemCallback =
getBrowser().new ClMenuItemCallback(upMenuItem, null) {
@Override
public void action(final Host dcHost) {
upResource(dcHost, true); /* testOnly */
}
};
addMouseOverListener(upMenuItem, upItemCallback);
items.add((UpdatableItem) upMenuItem);
/* down group resource */
final MyMenuItem downMenuItem =
new MyMenuItem(Tools.getString("ClusterBrowser.Hb.DownResource"),
GROUP_DOWN_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public boolean visiblePredicate() {
return groupInfo != null;
}
@Override
public String enablePredicate() {
if (getResource().isNew()) {
return IS_NEW_STRING;
}
final GroupInfo gi = groupInfo;
if (gi == null) {
return "no";
}
if (getBrowser().clStatusFailed()) {
return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
}
final DefaultMutableTreeNode giNode = gi.getNode();
if (giNode == null) {
return "no";
}
final DefaultMutableTreeNode node = getNode();
if (node == null) {
return "no";
}
final int index = giNode.getIndex(node);
if (index >= giNode.getChildCount() - 1) {
return "already down";
}
return null;
}
@Override
public void action() {
hidePopup();
downResource(getBrowser().getDCHost(), testOnly);
}
};
final ClusterBrowser.ClMenuItemCallback downItemCallback =
getBrowser().new ClMenuItemCallback(downMenuItem, null) {
@Override
public void action(final Host dcHost) {
downResource(dcHost, true); /* testOnly */
}
};
addMouseOverListener(downMenuItem, downItemCallback);
items.add((UpdatableItem) downMenuItem);
/* clean up resource */
final MyMenuItem cleanupMenuItem =
new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.CleanUpFailedResource"),
SERVICE_RUNNING_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
Tools.getString("ClusterBrowser.Hb.CleanUpResource"),
SERVICE_RUNNING_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public boolean predicate() {
return getService().isAvailable()
&& isOneFailed(testOnly);
}
@Override
public String enablePredicate() {
if (getBrowser().clStatusFailed()) {
return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
} else if (!isOneFailedCount(testOnly)) {
return "no fail count";
} else {
return getService().isAvailableWithText();
}
}
@Override
public void action() {
hidePopup();
cleanupResource(getBrowser().getDCHost(), testOnly);
}
};
/* cleanup ignores CIB_file */
items.add((UpdatableItem) cleanupMenuItem);
/* manage resource */
final MyMenuItem manageMenuItem =
new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.ManageResource"),
MANAGE_BY_CRM_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
Tools.getString("ClusterBrowser.Hb.UnmanageResource"),
UNMANAGE_BY_CRM_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public boolean predicate() {
return !isManaged(testOnly);
}
@Override
public String enablePredicate() {
if (getBrowser().clStatusFailed()) {
return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
} else {
return getService().isAvailableWithText();
}
}
@Override
public void action() {
hidePopup();
if (this.getText().equals(Tools.getString(
"ClusterBrowser.Hb.ManageResource"))) {
setManaged(true, getBrowser().getDCHost(), testOnly);
} else {
setManaged(false, getBrowser().getDCHost(), testOnly);
}
}
};
final ClusterBrowser.ClMenuItemCallback manageItemCallback =
getBrowser().new ClMenuItemCallback(manageMenuItem, null) {
@Override
public void action(final Host dcHost) {
setManaged(!isManaged(false),
dcHost, true); /* testOnly */
}
};
addMouseOverListener(manageMenuItem, manageItemCallback);
items.add((UpdatableItem) manageMenuItem);
addMigrateMenuItems(items);
if (ci == null) {
/* remove service */
final MyMenuItem removeMenuItem = new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.RemoveService"),
ClusterBrowser.REMOVE_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public String enablePredicate() {
if (getService().isNew()) {
return null;
}
if (getBrowser().clStatusFailed()) {
return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
} else if (getService().isRemoved()) {
return IS_BEING_REMOVED_STRING;
} else if (isRunning(testOnly)
&& !Tools.getConfigData().isAdvancedMode()) {
return "cannot remove running resource<br>"
+ "(advanced mode only)";
}
if (groupInfo == null) {
return null;
}
final ClusterStatus cs = getBrowser().getClusterStatus();
final List<String> gr = cs.getGroupResources(
groupInfo.getHeartbeatId(testOnly),
testOnly);
if (gr != null && gr.size() > 1) {
return null;
} else {
return "you can remove the group";
}
}
@Override
public void action() {
hidePopup();
if (getService().isOrphaned()) {
cleanupResource(getBrowser().getDCHost(), testOnly);
} else {
removeMyself(false);
}
getBrowser().getCRMGraph().repaint();
}
};
final ServiceInfo thisClass = this;
final ClusterBrowser.ClMenuItemCallback removeItemCallback =
getBrowser().new ClMenuItemCallback(removeMenuItem, null) {
@Override
public final boolean isEnabled() {
return super.isEnabled() && !getService().isNew();
}
@Override
public final void action(final Host dcHost) {
removeMyselfNoConfirm(dcHost, true); /* test only */
}
};
addMouseOverListener(removeMenuItem, removeItemCallback);
items.add((UpdatableItem) removeMenuItem);
}
/* view log */
final MyMenuItem viewLogMenu = new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.ViewServiceLog"),
LOGFILE_ICON,
null,
new AccessMode(ConfigData.AccessType.RO, false),
new AccessMode(ConfigData.AccessType.RO, false)) {
private static final long serialVersionUID = 1L;
@Override
public String enablePredicate() {
if (getService().isNew()) {
return IS_NEW_STRING;
} else {
return null;
}
}
@Override
public void action() {
hidePopup();
ServiceLogs l = new ServiceLogs(getBrowser().getCluster(),
getNameForLog(),
getService().getHeartbeatId());
l.showDialog();
}
};
items.add(viewLogMenu);
/* more migrate options */
final MyMenu migrateSubmenu = new MyMenu(
Tools.getString("ClusterBrowser.MigrateSubmenu"),
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public String enablePredicate() {
return null; //TODO: enable only if it has items
}
};
items.add(migrateSubmenu);
addMoreMigrateMenuItems(migrateSubmenu);
/* config files */
final MyMenu filesSubmenu = new MyMenu(
Tools.getString("ClusterBrowser.FilesSubmenu"),
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override
public String enablePredicate() {
return null; //TODO: enable only if it has items
}
@Override
public void update() {
super.update();
final MyMenu self = this;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
removeAll();
addFilesMenuItems(self);
}
});
}
};
items.add(filesSubmenu);
return items;
}
/** Adds migrate and unmigrate menu items. */
protected void addMigrateMenuItems(final List<UpdatableItem> items) {
/* migrate resource */
final boolean testOnly = false;
final ServiceInfo thisClass = this;
for (final Host host : getBrowser().getClusterHosts()) {
final String hostName = host.getName();
final MyMenuItem migrateFromMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.MigrateFromResource")
+ " " + hostName,
MIGRATE_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
Tools.getString(
"ClusterBrowser.Hb.MigrateFromResource")
+ " " + hostName + " (offline)",
MIGRATE_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public boolean predicate() {
return host.isClStatus();
}
@Override
public boolean visiblePredicate() {
return !host.isClStatus()
|| enablePredicate() == null;
}
@Override
public String enablePredicate() {
final List<String> runningOnNodes =
getRunningOnNodes(testOnly);
if (runningOnNodes == null
|| runningOnNodes.size() < 1) {
return "must run";
}
boolean runningOnNode = false;
for (final String ron : runningOnNodes) {
if (hostName.toLowerCase(Locale.US).equals(
ron.toLowerCase(Locale.US))) {
runningOnNode = true;
break;
}
}
if (!getBrowser().clStatusFailed()
&& getService().isAvailable()
&& runningOnNode
&& host.isClStatus()) {
return null;
} else {
return ""; /* is not visible anyway */
}
}
@Override
public void action() {
hidePopup();
migrateFromResource(getBrowser().getDCHost(),
hostName,
testOnly);
}
};
final ClusterBrowser.ClMenuItemCallback migrateItemCallback =
getBrowser().new ClMenuItemCallback(migrateFromMenuItem, null) {
@Override
public void action(final Host dcHost) {
migrateFromResource(dcHost, hostName, true); /* testOnly */
}
};
addMouseOverListener(migrateFromMenuItem, migrateItemCallback);
items.add(migrateFromMenuItem);
}
/* unmigrate resource */
final MyMenuItem unmigrateMenuItem =
new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.UnmigrateResource"),
UNMIGRATE_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public boolean visiblePredicate() {
return enablePredicate() == null;
}
@Override
public String enablePredicate() {
// TODO: if it was migrated
if (!getBrowser().clStatusFailed()
&& getService().isAvailable()
&& (getMigratedTo(testOnly) != null
|| getMigratedFrom(testOnly) != null)) {
return null;
} else {
return ""; /* it's not visible anyway */
}
}
@Override
public void action() {
hidePopup();
unmigrateResource(getBrowser().getDCHost(), testOnly);
}
};
final ClusterBrowser.ClMenuItemCallback unmigrateItemCallback =
getBrowser().new ClMenuItemCallback(unmigrateMenuItem, null) {
@Override
public void action(final Host dcHost) {
unmigrateResource(dcHost, true); /* testOnly */
}
};
addMouseOverListener(unmigrateMenuItem, unmigrateItemCallback);
items.add((UpdatableItem) unmigrateMenuItem);
}
/** Adds "migrate from" and "force migrate" menuitems to the submenu. */
protected void addMoreMigrateMenuItems(final MyMenu submenu) {
final boolean testOnly = false;
final ServiceInfo thisClass = this;
for (final Host host : getBrowser().getClusterHosts()) {
final String hostName = host.getName();
final MyMenuItem migrateMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.MigrateResource")
+ " " + hostName,
MIGRATE_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
Tools.getString(
"ClusterBrowser.Hb.MigrateResource")
+ " " + hostName + " (offline)",
MIGRATE_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public boolean predicate() {
return host.isClStatus();
}
@Override
public boolean visiblePredicate() {
return !host.isClStatus()
|| enablePredicate() == null;
}
@Override
public String enablePredicate() {
final List<String> runningOnNodes =
getRunningOnNodes(testOnly);
if (runningOnNodes == null
|| runningOnNodes.isEmpty()) {
return Tools.getString(
"ServiceInfo.NotRunningAnywhere");
}
final String runningOnNode =
runningOnNodes.get(0).toLowerCase(Locale.US);
if (getBrowser().clStatusFailed()
|| !host.isClStatus()) {
return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
} else {
final String tp =
getService().isAvailableWithText();
if (tp != null) {
return tp;
}
}
if (hostName.toLowerCase(Locale.US).equals(
runningOnNode)) {
return Tools.getString(
"ServiceInfo.AlreadyRunningOnNode");
} else {
return null;
}
}
@Override
public void action() {
hidePopup();
migrateResource(hostName,
getBrowser().getDCHost(),
testOnly);
}
};
final ClusterBrowser.ClMenuItemCallback migrateItemCallback =
getBrowser().new ClMenuItemCallback(migrateMenuItem, null) {
@Override
public void action(final Host dcHost) {
migrateResource(hostName, dcHost, true); /* testOnly */
}
};
addMouseOverListener(migrateMenuItem, migrateItemCallback);
submenu.add(migrateMenuItem);
}
for (final Host host : getBrowser().getClusterHosts()) {
final String hostName = host.getName();
final MyMenuItem forceMigrateMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.ForceMigrateResource")
+ " " + hostName,
MIGRATE_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
Tools.getString(
"ClusterBrowser.Hb.ForceMigrateResource")
+ " " + hostName + " (offline)",
MIGRATE_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override
public boolean predicate() {
return host.isClStatus();
}
@Override
public boolean visiblePredicate() {
return !host.isClStatus()
|| enablePredicate() == null;
}
@Override
public String enablePredicate() {
final List<String> runningOnNodes =
getRunningOnNodes(testOnly);
if (runningOnNodes == null
|| runningOnNodes.isEmpty()) {
return Tools.getString(
"ServiceInfo.NotRunningAnywhere");
}
final String runningOnNode =
runningOnNodes.get(0).toLowerCase(Locale.US);
if (!getBrowser().clStatusFailed()
&& getService().isAvailable()
&& !hostName.toLowerCase(Locale.US).equals(
runningOnNode)
&& host.isClStatus()) {
return null;
} else {
return "";
}
}
@Override
public void action() {
hidePopup();
forceMigrateResource(hostName,
getBrowser().getDCHost(),
testOnly);
}
};
final ClusterBrowser.ClMenuItemCallback forceMigrateItemCallback =
getBrowser().new ClMenuItemCallback(forceMigrateMenuItem,
null) {
@Override
public void action(final Host dcHost) {
forceMigrateResource(hostName, dcHost, true); /* testOnly */
}
};
addMouseOverListener(forceMigrateMenuItem,
forceMigrateItemCallback);
submenu.add(forceMigrateMenuItem);
}
}
/** Return config files defined in DistResource config files. */
private List<String> getConfigFiles() {
String raName;
final ServiceInfo cs = getContainedService();
if (cs == null) {
raName = getResourceAgent().getRAString();
} else {
raName = cs.getResourceAgent().getRAString();
}
final Host[] hosts = getBrowser().getCluster().getHostsArray();
final List<String> cfs =
new ArrayList<String>(hosts[0].getDistStrings(raName + ".files"));
final List<String> params =
new ArrayList<String>(hosts[0].getDistStrings(raName + ".params"));
params.add("configfile");
params.add("config");
params.add("conffile");
for (final String param : params) {
String value;
if (cs == null) {
final Widget wi = getWidget(param, null);
if (wi == null) {
value = getParamSaved(param);
} else {
value = wi.getStringValue();
}
} else {
final Widget wi = cs.getWidget(param, null);
if (wi == null) {
value = cs.getParamSaved(param);
} else {
value = wi.getStringValue();
}
}
if (value != null && !"".equals(value)) {
cfs.add(value);
}
}
return cfs;
}
/** Adds config files menuitems to the submenu. */
protected void addFilesMenuItems(final MyMenu submenu) {
final boolean testOnly = false;
final ServiceInfo thisClass = this;
final List<String> configFiles = getConfigFiles();
for (final String configFile : configFiles) {
final MyMenuItem fileItem =
new MyMenuItem(
configFile,
null,
null,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override
public boolean predicate() {
return true;
}
@Override
public boolean visiblePredicate() {
return true;
}
@Override
public String enablePredicate() {
return null;
}
@Override
public void action() {
final EditConfig ed =
new EditConfig(configFile,
getBrowser().getCluster().getHosts());
ed.showDialog();
}
};
submenu.add(fileItem);
}
}
/** Returns tool tip for the service. */
@Override
public String getToolTipText(final boolean testOnly) {
String nodeString = null;
final List<String> nodes = getRunningOnNodes(testOnly);
if (nodes != null && !nodes.isEmpty()) {
nodeString =
Tools.join(", ", nodes.toArray(new String[nodes.size()]));
}
final Host[] hosts = getBrowser().getCluster().getHostsArray();
if (getBrowser().allHostsDown()) {
nodeString = "unknown";
}
final StringBuilder sb = new StringBuilder(200);
sb.append("<b>");
sb.append(toString());
String textOn;
String textNotOn;
if (getResourceAgent().isFilesystem()) {
textOn = Tools.getString("ServiceInfo.Filesystem.MoutedOn");
textNotOn = Tools.getString("ServiceInfo.Filesystem.NotMounted");
} else {
textOn = Tools.getString("ServiceInfo.Filesystem.RunningOn");
textNotOn = Tools.getString("ServiceInfo.Filesystem.NotRunning");
}
if (isFailed(testOnly)) {
sb.append("</b> <b>Failed</b>");
} else if (isStopped(testOnly)
|| nodeString == null) {
sb.append("</b> " + textNotOn);
} else {
sb.append("</b> " + textOn + ": ");
sb.append(nodeString);
}
if (!isManaged(testOnly)) {
sb.append(" (unmanaged)");
}
final Map<String, String> scores =
getBrowser().getClusterStatus().getAllocationScores(
getHeartbeatId(testOnly),
testOnly);
for (final String h : scores.keySet()) {
sb.append("<br>allocation score on ");
sb.append(h);
sb.append(": ");
sb.append(scores.get(h));
}
return sb.toString();
}
/** Returns heartbeat service class. */
public ResourceAgent getResourceAgent() {
return resourceAgent;
}
/** Sets whether the info object is being updated. */
@Override
public void setUpdated(final boolean updated) {
final GroupInfo gi = groupInfo;
if (gi != null) {
gi.setUpdated(updated);
return;
}
final CloneInfo ci = cloneInfo;
if (ci != null) {
ci.setUpdated(updated);
return;
}
if (updated && !isUpdated()) {
getBrowser().getCRMGraph().startAnimation(this);
} else if (!updated) {
getBrowser().getCRMGraph().stopAnimation(this);
}
super.setUpdated(updated);
}
/** Returns text that appears in the corner of the graph. */
public Subtext getRightCornerTextForGraph(final boolean testOnly) {
if (getService().isOrphaned()) {
if (isFailed(testOnly)) {
return ORPHANED_FAILED_SUBTEXT;
} else {
return ORPHANED_SUBTEXT;
}
} else if (!isManaged(testOnly)) {
return UNMANAGED_SUBTEXT;
} else if (getMigratedTo(testOnly) != null
|| getMigratedFrom(testOnly) != null) {
return MIGRATED_SUBTEXT;
}
return null;
}
/** Returns text with lines as array that appears in the cluster graph. */
public Subtext[] getSubtextsForGraph(final boolean testOnly) {
Color color = null;
final List<Subtext> texts = new ArrayList<Subtext>();
String textOn;
String textNotOn;
if (getResourceAgent().isFilesystem()) {
textOn = Tools.getString("ServiceInfo.Filesystem.MoutedOn");
textNotOn = Tools.getString("ServiceInfo.Filesystem.NotMounted");
} else {
textOn = Tools.getString("ServiceInfo.Filesystem.RunningOn");
textNotOn = Tools.getString("ServiceInfo.Filesystem.NotRunning");
}
if (getService().isOrphaned()) {
texts.add(new Subtext("...",
null,
Color.BLACK));
} else if (getResource().isNew()) {
texts.add(new Subtext(textNotOn + " (new)",
ClusterBrowser.FILL_PAINT_STOPPED,
Color.BLACK));
} else if (isFailed(testOnly)) {
texts.add(new Subtext(textNotOn,
null,
Color.BLACK));
} else if (isStopped(testOnly) && !isRunning(testOnly)) {
texts.add(new Subtext("stopped",
ClusterBrowser.FILL_PAINT_STOPPED,
Color.BLACK));
} else {
Color textColor = Color.BLACK;
String runningOnNodeString = null;
if (getBrowser().allHostsDown()) {
runningOnNodeString = "unknown";
} else {
final List<String> runningOnNodes = getRunningOnNodes(testOnly);
if (runningOnNodes != null
&& !runningOnNodes.isEmpty()) {
runningOnNodeString = runningOnNodes.get(0);
if (resourceAgent.isPingService()
&& "0".equals(
getPingCount(runningOnNodeString, testOnly))) {
color = Color.RED;
textColor = Color.WHITE;
} else {
color = getBrowser().getCluster().getHostColors(
runningOnNodes).get(0);
}
}
}
if (runningOnNodeString == null) {
texts.add(new Subtext(textNotOn,
ClusterBrowser.FILL_PAINT_STOPPED,
textColor));
} else {
texts.add(new Subtext(textOn + ": " + runningOnNodeString
+ getPingCountString(runningOnNodeString,
testOnly),
color,
textColor));
}
}
if (isOneFailedCount(testOnly)) {
for (final Host host : getBrowser().getClusterHosts()) {
if (host.isClStatus()
&& getFailCount(host.getName(), testOnly) != null) {
texts.add(new Subtext(ClusterBrowser.IDENT_4
+ host.getName()
+ getFailCountString(
host.getName(),
testOnly),
null,
Color.BLACK));
}
}
}
return texts.toArray(new Subtext[texts.size()]);
}
/** Returns null, when this service is not a clone. */
public ServiceInfo getContainedService() {
return null;
}
/** Returns type radio group. */
Widget getTypeRadioGroup() {
return typeRadioGroup;
}
/** Returns units. */
@Override
protected final Unit[] getUnits() {
return new Unit[]{
new Unit("", "s", "Second", "Seconds"), /* default unit */
new Unit("ms", "ms", "Millisecond", "Milliseconds"),
new Unit("us", "us", "Microsecond", "Microseconds"),
new Unit("s", "s", "Second", "Seconds"),
new Unit("min", "m", "Minute", "Minutes"),
new Unit("h", "h", "Hour", "Hours")
};
}
/** Returns whether it is slave on all nodes. */
protected boolean isSlaveOnAllNodes(final boolean testOnly) {
return false;
}
/** Returns text that appears above the icon in the graph. */
public String getIconTextForGraph(final boolean testOnly) {
if (getBrowser().allHostsDown()) {
return Tools.getString("ClusterBrowser.Hb.NoInfoAvailable");
}
final Host dcHost = getBrowser().getDCHost();
if (getService().isNew()) {
return "new...";
} else if (getService().isOrphaned()) {
return "";
} else if (isEnslaved(testOnly)) {
if (isSlaveOnAllNodes(testOnly)) {
return "";
} else {
return Tools.getString("ClusterBrowser.Hb.Enslaving");
}
} else if (isStarted(testOnly)) {
if (isRunning(testOnly)) {
final List<Host> migratedTo = getMigratedTo(testOnly);
if (migratedTo == null) {
final List<Host> migratedFrom = getMigratedFrom(testOnly);
if (migratedFrom != null) {
final List<String> runningOnNodes =
getRunningOnNodes(testOnly);
boolean alreadyThere = false;
if (runningOnNodes == null) {
alreadyThere = true;
} else {
alreadyThere = true;
for (final Host mfrom : migratedFrom) {
if (runningOnNodes.contains(mfrom.getName())) {
alreadyThere = false;
}
}
}
if (!alreadyThere) {
return Tools.getString(
"ClusterBrowser.Hb.Migrating");
}
}
} else {
final List<String> runningOnNodes =
getRunningOnNodes(testOnly);
if (runningOnNodes != null) {
boolean alreadyThere = false;
for (final Host mto : migratedTo) {
if (runningOnNodes.contains(mto.getName())) {
alreadyThere = true;
}
if (!alreadyThere) {
return Tools.getString(
"ClusterBrowser.Hb.Migrating");
}
}
}
}
return null;
} else if (isFailed(testOnly)) {
return Tools.getString("ClusterBrowser.Hb.StartingFailed");
} else if (isGroupStopped(testOnly)) {
return Tools.getString("ClusterBrowser.Hb.GroupStopped");
} else {
return Tools.getString("ClusterBrowser.Hb.Starting");
}
} else if (isStopped(testOnly)) {
if (isRunning(testOnly)) {
return Tools.getString("ClusterBrowser.Hb.Stopping");
} else {
return null;
}
}
return null;
}
/** Returns hash with saved operations. */
MultiKeyMap<String, String> getSavedOperation() {
return savedOperation;
}
/** Reload combo boxes. */
public void reloadComboBoxes() {
if (sameAsOperationsWi != null) {
String defaultOpIdRef = null;
final Info savedOpIdRef = sameAsOperationsWiValue();
if (savedOpIdRef != null) {
defaultOpIdRef = savedOpIdRef.toString();
}
final String idRef = defaultOpIdRef;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
sameAsOperationsWi.reloadComboBox(
idRef,
getSameServicesOperations());
}
});
}
if (sameAsMetaAttrsWi != null) {
String defaultMAIdRef = null;
final Info savedMAIdRef = sameAsMetaAttrsWiValue();
if (savedMAIdRef != null) {
defaultMAIdRef = savedMAIdRef.toString();
}
final String idRef = defaultMAIdRef;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
sameAsMetaAttrsWi.reloadComboBox(
idRef,
getSameServicesMetaAttrs());
}
});
}
}
/** Returns whether info panel is already created. */
boolean isInfoPanelOk() {
return infoPanel != null;
}
/** Connects with VMSVirtualDomainInfo object. */
public VMSVirtualDomainInfo connectWithVMS() {
/* for VirtualDomainInfo */
return null;
}
/** Whether this class is a constraint placeholder. */
public boolean isConstraintPH() {
return false;
}
/** Remove constraints of this service. */
void removeConstraints(final Host dcHost, final boolean testOnly) {
final ClusterStatus cs = getBrowser().getClusterStatus();
final HbConnectionInfo[] hbcis =
getBrowser().getCRMGraph().getHbConnections(this);
for (final HbConnectionInfo hbci : hbcis) {
if (hbci != null) {
getBrowser().getCRMGraph().removeOrder(hbci, dcHost, testOnly);
getBrowser().getCRMGraph().removeColocation(hbci,
dcHost,
testOnly);
}
}
for (final String locId : cs.getLocationIds(
getHeartbeatId(testOnly),
testOnly)) {
CRM.removeLocation(dcHost,
locId,
getHeartbeatId(testOnly),
testOnly);
}
}
/**
* Returns value of the same as drop down menu as an info object or null.
*/
final Info sameAsOperationsWiValue() {
if (sameAsOperationsWi == null) {
return null;
}
Info i = null;
final Object o = sameAsOperationsWi.getValue();
if (o instanceof Info) {
i = (Info) o;
}
return i;
}
/**
* Returns value of the same as drop down menu as an info object or null.
*/
final Info sameAsMetaAttrsWiValue() {
if (sameAsMetaAttrsWi == null) {
return null;
}
Info i = null;
final Object o = sameAsMetaAttrsWi.getValue();
if (o instanceof Info) {
i = (Info) o;
}
return i;
}
/** Store operation values. */
final void storeOperations() {
mSavedOperationsLock.lock();
for (final String op : getResourceAgent().getOperationNames()) {
for (final String param : getBrowser().getCRMOperationParams(op)) {
final String defaultValue =
resourceAgent.getOperationDefault(op, param);
if (defaultValue == null) {
continue;
}
mOperationsComboBoxHashReadLock.lock();
final Widget wi = operationsComboBoxHash.get(op, param);
mOperationsComboBoxHashReadLock.unlock();
savedOperation.put(op, param, wi.getStringValue());
}
}
mSavedOperationsLock.unlock();
}
/** Returns score combo box. */
protected final Map<HostInfo, Widget> getScoreComboBoxHash() {
return scoreComboBoxHash;
}
/** Returns ping combo box. */
public final Widget getPingComboBox() {
return pingComboBox;
}
/** Sets ping combo box. */
protected final void setPingComboBox(final Widget pingComboBox) {
this.pingComboBox = pingComboBox;
}
/** Return operation combo box. */
public final Widget getOperationsComboBox(final String op,
final String param) {
mOperationsComboBoxHashReadLock.lock();
final Widget wi = operationsComboBoxHash.get(op, param);
mOperationsComboBoxHashReadLock.unlock();
return wi;
}
/** Return same as operations combo box. */
public final Widget getSameAsOperationsWi() {
return sameAsOperationsWi;
}
}
| [
"[email protected]"
] | |
7397ce29ea27c8e4e42345e3af5209c61cb7b08f | 5d00b27e4022698c2dc56ebbc63263f3c44eea83 | /gen/com/ah/xml/be/config/ApplicationObj.java | 0693d4a163d75052e5b636d6eac28652326f324e | [] | no_license | Aliing/WindManager | ac5b8927124f992e5736e34b1b5ebb4df566770a | f66959dcaecd74696ae8bc764371c9a2aa421f42 | refs/heads/master | 2020-12-27T23:57:43.988113 | 2014-07-28T17:58:46 | 2014-07-28T17:58:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,690 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.07.01 at 11:29:17 AM CST
//
package com.ah.xml.be.config;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for application-obj complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="application-obj">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="identification" type="{http://www.aerohive.com/configuration/others}application-identification" minOccurs="0"/>
* <element name="reporting" type="{http://www.aerohive.com/configuration/others}application-reporting" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "application-obj", propOrder = {
"identification",
"reporting"
})
public class ApplicationObj {
protected ApplicationIdentification identification;
protected ApplicationReporting reporting;
/**
* Gets the value of the identification property.
*
* @return
* possible object is
* {@link ApplicationIdentification }
*
*/
public ApplicationIdentification getIdentification() {
return identification;
}
/**
* Sets the value of the identification property.
*
* @param value
* allowed object is
* {@link ApplicationIdentification }
*
*/
public void setIdentification(ApplicationIdentification value) {
this.identification = value;
}
/**
* Gets the value of the reporting property.
*
* @return
* possible object is
* {@link ApplicationReporting }
*
*/
public ApplicationReporting getReporting() {
return reporting;
}
/**
* Sets the value of the reporting property.
*
* @param value
* allowed object is
* {@link ApplicationReporting }
*
*/
public void setReporting(ApplicationReporting value) {
this.reporting = value;
}
}
| [
"[email protected]"
] | |
75a06a24706a8a3f941d16113454c0c55ee4c103 | 001307bfea66fad1cc904ccbf8c160d5cb39083a | /myb-mos/src/main/java/com/myb/mos/VO/EmployeeVO.java | d1cdeeedcfca84ca29943efa8c8062218c4ef4c0 | [] | no_license | yan-huan/mos | 4c56f1f66aa94c2fc7042140bcaa1e132b39db9a | 6e2f3e4c769b96ea5f62222ce8abc8e13b69d044 | refs/heads/master | 2020-05-29T09:13:40.533844 | 2017-10-18T02:25:23 | 2017-10-18T02:25:23 | 68,894,559 | 0 | 0 | null | 2016-09-22T07:10:58 | 2016-09-22T07:10:57 | null | UTF-8 | Java | false | false | 3,501 | java | package com.myb.mos.VO;
import com.myb.framework.data.EntityBase;
public class EmployeeVO extends EntityBase{
private int empId;//
private int parentId;//直属上级Id
private java.lang.String empName;//
private java.lang.String account;//登录账号
private java.lang.String empCode;//员工编号
private java.lang.Integer dutyId;//岗位Id
private java.lang.String parentName;//冗余直属上级姓名
private java.lang.String depName;//冗余部门名称
private java.lang.String cityPermission;//城市权限 可以设置多个城市以空格间隔
private int isUsed;//
private int cityId;//
private java.util.Date createTime;//
private java.lang.String userName;//
private java.lang.String passWord;//
private int status;//
private int ran;//
private String entryTime;//入职时间
private String QuitTime;//退出时间
private String preferPwd;//原来密码
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public java.lang.String getEmpName() {
return empName;
}
public void setEmpName(java.lang.String empName) {
this.empName = empName;
}
public java.lang.String getAccount() {
return account;
}
public void setAccount(java.lang.String account) {
this.account = account;
}
public java.lang.String getEmpCode() {
return empCode;
}
public void setEmpCode(java.lang.String empCode) {
this.empCode = empCode;
}
public java.lang.Integer getDutyId() {
return dutyId;
}
public void setDutyId(java.lang.Integer dutyId) {
this.dutyId = dutyId;
}
public java.lang.String getParentName() {
return parentName;
}
public void setParentName(java.lang.String parentName) {
this.parentName = parentName;
}
public java.lang.String getDepName() {
return depName;
}
public void setDepName(java.lang.String depName) {
this.depName = depName;
}
public java.lang.String getCityPermission() {
return cityPermission;
}
public void setCityPermission(java.lang.String cityPermission) {
this.cityPermission = cityPermission;
}
public int getIsUsed() {
return isUsed;
}
public void setIsUsed(int isUsed) {
this.isUsed = isUsed;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public java.util.Date getCreateTime() {
return createTime;
}
public void setCreateTime(java.util.Date createTime) {
this.createTime = createTime;
}
public java.lang.String getUserName() {
return userName;
}
public void setUserName(java.lang.String userName) {
this.userName = userName;
}
public java.lang.String getPassWord() {
return passWord;
}
public void setPassWord(java.lang.String passWord) {
this.passWord = passWord;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getRan() {
return ran;
}
public void setRan(int ran) {
this.ran = ran;
}
public String getEntryTime() {
return entryTime;
}
public void setEntryTime(String entryTime) {
this.entryTime = entryTime;
}
public String getQuitTime() {
return QuitTime;
}
public void setQuitTime(String quitTime) {
QuitTime = quitTime;
}
public String getPreferPwd() {
return preferPwd;
}
public void setPreferPwd(String preferPwd) {
this.preferPwd = preferPwd;
}
}
| [
"[email protected]"
] | |
5376222332c5a2a32bc065835afa1ff214c0e153 | 7ddeae08c021cb9a13612307f212f0356e233956 | /src/main/java/com/ninos/hotelbookings/service/errorhandlers/GlobalExceptionHandler.java | eb117de12a11621bd5c22965f1de5156315c898a | [
"MIT"
] | permissive | spyridon-ninos/hotel-bookings | 86d227b5b79ed5b7a4bb093c2f851d68c68f2db5 | a1115fb9c86f7b9b198681a158d5ae927ec0314b | refs/heads/master | 2023-06-25T22:30:40.672881 | 2021-07-18T20:46:17 | 2021-07-18T20:46:17 | 387,260,223 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,775 | java | package com.ninos.hotelbookings.service.errorhandlers;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
/**
* global HTTP endpoints exception handler
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = {
IllegalArgumentException.class,
ValidationException.class,
HttpRequestMethodNotSupportedException.class,
MethodArgumentNotValidException.class,
InvalidMediaTypeException.class,
ConstraintViolationException.class,
InvalidFormatException.class
})
public ResponseEntity<Void> handleInvalidInputExceptions(Exception ex) {
logger.error("Received a bad request exception: {}", ex.getMessage());
logger.debug("{}", ex.getMessage(), ex);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Void> handleGeneralException(Exception ex) {
logger.error("{}", ex.getMessage(), ex);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
| [
"no email"
] | no email |
879c6f81a1dcac61d19e1a11595d52cf56fe7874 | 7b733e23cefd907fc96d1cb93cbaf2777bcb12eb | /webserviceClient/src/com/mysever/HelloWorldServiceLocator.java | 5da61d4c89ee3db6723ad7a623f704ebe6ae08e6 | [] | no_license | liuxiang/webService_axis | 8d4769f18948a5a789aca295a7fc6826eb7881ca | f64819edf9662cd23680b79b91f420f8b09d450a | refs/heads/master | 2021-01-02T22:18:52.623409 | 2015-02-05T14:28:00 | 2015-02-05T14:28:00 | 30,359,053 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,265 | java | /**
* HelloWorldServiceLocator.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.mysever;
public class HelloWorldServiceLocator extends org.apache.axis.client.Service implements com.mysever.HelloWorldService {
public HelloWorldServiceLocator() {
}
public HelloWorldServiceLocator(org.apache.axis.EngineConfiguration config) {
super(config);
}
public HelloWorldServiceLocator(java.lang.String wsdlLoc, javax.xml.namespace.QName sName) throws javax.xml.rpc.ServiceException {
super(wsdlLoc, sName);
}
// Use to get a proxy class for HelloWorld
private java.lang.String HelloWorld_address = "http://localhost:8080/webservice/services/HelloWorld";
public java.lang.String getHelloWorldAddress() {
return HelloWorld_address;
}
// The WSDD service name defaults to the port name.
private java.lang.String HelloWorldWSDDServiceName = "HelloWorld";
public java.lang.String getHelloWorldWSDDServiceName() {
return HelloWorldWSDDServiceName;
}
public void setHelloWorldWSDDServiceName(java.lang.String name) {
HelloWorldWSDDServiceName = name;
}
public com.mysever.HelloWorld getHelloWorld() throws javax.xml.rpc.ServiceException {
java.net.URL endpoint;
try {
endpoint = new java.net.URL(HelloWorld_address);
}
catch (java.net.MalformedURLException e) {
throw new javax.xml.rpc.ServiceException(e);
}
return getHelloWorld(endpoint);
}
public com.mysever.HelloWorld getHelloWorld(java.net.URL portAddress) throws javax.xml.rpc.ServiceException {
try {
com.mysever.HelloWorldSoapBindingStub _stub = new com.mysever.HelloWorldSoapBindingStub(portAddress, this);
_stub.setPortName(getHelloWorldWSDDServiceName());
return _stub;
}
catch (org.apache.axis.AxisFault e) {
return null;
}
}
public void setHelloWorldEndpointAddress(java.lang.String address) {
HelloWorld_address = address;
}
/**
* For the given interface, get the stub implementation.
* If this service has no port for the given interface,
* then ServiceException is thrown.
*/
public java.rmi.Remote getPort(Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
try {
if (com.mysever.HelloWorld.class.isAssignableFrom(serviceEndpointInterface)) {
com.mysever.HelloWorldSoapBindingStub _stub = new com.mysever.HelloWorldSoapBindingStub(new java.net.URL(HelloWorld_address), this);
_stub.setPortName(getHelloWorldWSDDServiceName());
return _stub;
}
}
catch (java.lang.Throwable t) {
throw new javax.xml.rpc.ServiceException(t);
}
throw new javax.xml.rpc.ServiceException("There is no stub implementation for the interface: " + (serviceEndpointInterface == null ? "null" : serviceEndpointInterface.getName()));
}
/**
* For the given interface, get the stub implementation.
* If this service has no port for the given interface,
* then ServiceException is thrown.
*/
public java.rmi.Remote getPort(javax.xml.namespace.QName portName, Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
if (portName == null) {
return getPort(serviceEndpointInterface);
}
java.lang.String inputPortName = portName.getLocalPart();
if ("HelloWorld".equals(inputPortName)) {
return getHelloWorld();
}
else {
java.rmi.Remote _stub = getPort(serviceEndpointInterface);
((org.apache.axis.client.Stub) _stub).setPortName(portName);
return _stub;
}
}
public javax.xml.namespace.QName getServiceName() {
return new javax.xml.namespace.QName("http://mysever.com", "HelloWorldService");
}
private java.util.HashSet ports = null;
public java.util.Iterator getPorts() {
if (ports == null) {
ports = new java.util.HashSet();
ports.add(new javax.xml.namespace.QName("http://mysever.com", "HelloWorld"));
}
return ports.iterator();
}
/**
* Set the endpoint address for the specified port name.
*/
public void setEndpointAddress(java.lang.String portName, java.lang.String address) throws javax.xml.rpc.ServiceException {
if ("HelloWorld".equals(portName)) {
setHelloWorldEndpointAddress(address);
}
else
{ // Unknown Port Name
throw new javax.xml.rpc.ServiceException(" Cannot set Endpoint Address for Unknown Port" + portName);
}
}
/**
* Set the endpoint address for the specified port name.
*/
public void setEndpointAddress(javax.xml.namespace.QName portName, java.lang.String address) throws javax.xml.rpc.ServiceException {
setEndpointAddress(portName.getLocalPart(), address);
}
}
| [
"[email protected]"
] | |
e90853e0b8f6eb1f6252964e1abdbaaf83f3a28e | 71d8c5cb64895f45276c817b8a6e78cf68153a46 | /Reduce.java | a33932bb1df916917aa9a563f839a5f907f742d4 | [] | no_license | MalathyB/Assignment_4.5 | d1e4b58495f46361156138c02a8a75d7643faa85 | 3831a86bdb47c1e76b0240f02c0ca537208e9223 | refs/heads/master | 2021-01-18T04:29:37.558608 | 2017-03-08T03:26:47 | 2017-03-08T03:26:47 | 84,273,988 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 546 | java | package mapreduce;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class Reduce extends Reducer<Text, IntWritable, Text, IntWritable>
{
IntWritable outValue = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException
{
int sum = 0;
for (IntWritable value : values) {
sum += value.get();
}
outValue.set(sum);
context.write(key, outValue);
}
} | [
"[email protected]"
] | |
bcca65f6bd2da51f88b793c88211e8dab592ae12 | ab577d27ac3f24b2f5dd20019620e040163d5fd4 | /palindrome.java | e68dbcdc9a5343ba3b6a4adcc11399a23ecec0bf | [] | no_license | DeepakAarthi/aart | be30204bc6e4c5cec5c89f8515dcebafec1e8992 | 66321d498b89b538ce259be5c6bb30f3c38bec40 | refs/heads/master | 2021-04-12T10:20:50.030787 | 2017-07-22T06:25:01 | 2017-07-22T06:25:01 | 94,528,995 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 448 | java |
import java.util.Scanner;
class Palindrome
{
public static void main(String[] args)
{
int a,no,b,temp=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter any num: ");
no=s.nextInt();
b=no;
while(no>0)
{
a=no%10;
no=no/10;
temp=temp*10+a;
}
if(temp==b)
{
System.out.println("Palindrome");
}
else
{
System.out.println("not Palindrome");
}
}
}
}
}
| [
"[email protected]"
] | |
12d5dbc542774d9efa3c0e8692160184b34be099 | 17055fa42a789fb480b2fd1b5c10695de860e124 | /src/main/java/ru/itsjava/oop/inheritance/Child.java | a49645afdb5e446af081d69d34731a6f414390a9 | [] | no_license | Vkuznecov0102/java-foundations-online | 948f8407c315ed73bdb05a24b1e14741b389383b | b333ea9c0f2a092ca0a5f1a5009aa4d0f2751ba0 | refs/heads/master | 2023-01-11T07:03:36.307559 | 2020-11-10T15:00:51 | 2020-11-10T15:00:51 | 311,680,318 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 181 | java | package ru.itsjava.oop.inheritance;
public class Child implements Father,Mother {
@Override
public void giveLove() {
System.out.println("Child loves you");
}
}
| [
"[email protected]"
] | |
25d28fad674c825f628bb5b865531d87ad5a3cbc | 403e9e33c35d28f93cb4efc8ec73fed9fbc30e86 | /src/main/java/com/vaadin/lazyloadwrapper/widgetset/client/ui/LLWPoller.java | 4fcf17a1d9ea636d84118e30341892093be4e0dd | [] | no_license | Silvermedia/vaadin-lazyloadwrapper | b56dda82642d078191b1eab786ca73ecbf72c5c2 | 3b3c3322e2307854e7781b4afb053dc9b41a3eaf | refs/heads/master | 2021-01-18T09:36:42.373541 | 2018-03-08T15:54:32 | 2018-03-08T15:54:32 | 50,988,813 | 0 | 1 | null | 2018-03-08T15:50:31 | 2016-02-03T09:26:54 | Java | UTF-8 | Java | false | false | 1,571 | java | package com.vaadin.lazyloadwrapper.widgetset.client.ui;
import java.util.ArrayList;
import com.google.gwt.user.client.Timer;
/**
* The static poller that's shared with all LLW:s in an application. When the
* poller is triggered, all LLW instances will be called to check their
* visibility.
*/
public class LLWPoller extends Timer {
ArrayList<LazyLoadWrapperConnector> listeners = new ArrayList<LazyLoadWrapperConnector>();
@Override
public void run() {
// long start = System.currentTimeMillis();
for (LazyLoadWrapperConnector llw : new ArrayList<LazyLoadWrapperConnector>(
listeners)) {
llw.checkVisibility();
}
// long stop = System.currentTimeMillis();
// VConsole.log("Checking LLW visibility for all LLW:s took: "
// + (stop - start) + " ms");
}
/**
* Register a lazy load wrapper to the master poller
*
* @param llw
* - the LLW instance to be registered
*/
public synchronized void addLLW(LazyLoadWrapperConnector llw) {
if (!listeners.contains(llw)) {
listeners.add(llw);
}
if (listeners.size() == 1) {
scheduleRepeating(1250);
}
}
/**
* Remove a llw from the master poller.
*
* @param llw
* - the instance of the llw to be removed.
*/
public synchronized void removeLLW(LazyLoadWrapperConnector llw) {
listeners.remove(llw);
if (listeners.isEmpty()) {
cancel();
}
}
} | [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.