blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
listlengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
listlengths
1
1
author
stringlengths
0
161
ec27a7c2cc4f37e68b8afeb887023853d6a4caaf
03f03207489b804acd304afc6c20c6a5270a3f75
/servlet_default/src/com/servlet/service/IMemberServiceImpl.java
c4b76a823fb92a86bef25a7e855cdd3bb52644a4
[]
no_license
Straingers/DDIT_JSPServlet
fcca8c66666caeaca1258c0c7f660dea5a86f14a
7c865595f5decd710cc1324e0a67011e484c7d5e
refs/heads/master
2023-07-08T21:56:57.761273
2021-07-28T03:23:38
2021-07-28T03:23:38
390,196,109
0
0
null
null
null
null
UTF-8
Java
false
false
1,289
java
package com.servlet.service; import java.sql.SQLException; import com.ibatis.sqlmap.client.SqlMapClient; import com.servlet.dao.IMemberDao; import com.servlet.dao.IMemberDaoImpl; import com.servlet.dto.MemberVO; import com.servlet.util.SqlMapClientUtil; public class IMemberServiceImpl implements IMemberService { private IMemberDao memberDao; private SqlMapClient smc; private static IMemberService memberService; public IMemberServiceImpl() { memberDao = IMemberDaoImpl.getInstance(); smc = SqlMapClientUtil.getInstance(); } public static IMemberService getInstance() { if(memberService == null) { memberService = new IMemberServiceImpl(); } return memberService; } @Override public MemberVO getMember(String memId) { MemberVO mv = new MemberVO(); try { mv = memberDao.getMember(smc, memId); } catch (SQLException e) { e.printStackTrace(); } return mv; } @Override public int MemIdCheck(String memId) { int cnt = 0; try { cnt = memberDao.MemIdCheck(smc, memId); } catch (SQLException e) { e.printStackTrace(); } return cnt; } @Override public int memberSign(MemberVO mv) { int cnt = 0; try { cnt = memberDao.memberSign(smc, mv); } catch (SQLException e) { e.printStackTrace(); } return cnt; } }
303c8a5faee9c32d65515db3813c42560758c6e8
6500848c3661afda83a024f9792bc6e2e8e8a14e
/gp_JADX/com/google/android/gms/internal/fz.java
46647a843f31adb09719ec208b998cf22b54b776
[]
no_license
enaawy/gproject
fd71d3adb3784d12c52daf4eecd4b2cb5c81a032
91cb88559c60ac741d4418658d0416f26722e789
refs/heads/master
2021-09-03T03:49:37.813805
2018-01-05T09:35:06
2018-01-05T09:35:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,057
java
package com.google.android.gms.internal; import android.os.Build.VERSION; import android.os.ConditionVariable; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; public class fz { public static final ConditionVariable f26765b = new ConditionVariable(); public static volatile xs f26766c = null; public static volatile Random f26767e = null; public jp f26768a; public volatile Boolean f26769d; public fz(jp jpVar) { this.f26768a = jpVar; jpVar.f27074d.execute(new ga(this)); } public static int m24381a() { try { return VERSION.SDK_INT >= 21 ? ThreadLocalRandom.current().nextInt() : m24383b().nextInt(); } catch (RuntimeException e) { return m24383b().nextInt(); } } private static Random m24383b() { if (f26767e == null) { synchronized (fz.class) { if (f26767e == null) { f26767e = new Random(); } } } return f26767e; } }
d4e295d4b25b8c8fe53f567a9d6278b87269c9dc
4266e5085a5632df04c63dc3b11b146ef4be40fa
/evaluations/evaluation2/purchases/src/test/java/academy/everyonecodes/steampurchases/endpoint/GamesEndpointTest.java
3478a905bd5a2b50ca06bc8c482bbabc12d2d2e9
[]
no_license
uanave/springboot-module
ab918e8e4d6b228dcabcfb1b040458eb9c705977
3842925501ef3f08add19ca7ed055a3f84260088
refs/heads/master
2022-12-27T17:29:22.130619
2020-10-13T14:04:33
2020-10-13T14:04:33
246,023,900
0
0
null
null
null
null
UTF-8
Java
false
false
977
java
package academy.everyonecodes.steampurchases.endpoint; import academy.everyonecodes.steampurchases.persistence.domain.Game; import academy.everyonecodes.steampurchases.logic.PurchaseService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.web.client.TestRestTemplate; import static org.mockito.Mockito.verify; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @SpringBootTest(webEnvironment = RANDOM_PORT) class GamesEndpointTest { @Autowired TestRestTemplate testRestTemplate; @MockBean PurchaseService purchaseService; @Test void getAllGames() { String url = "/games"; testRestTemplate.getForObject(url, Game[].class); verify(purchaseService).findAllGames(); } }
6834eb590ef7c5a40e0dcec078035b14ad6236a1
a8f8fb716878159e7344c8011720f08c1120c64e
/src/main/java/com/taco/main/event/LoadAllEvent.java
9d80609cbd7350c44ca775d56a09adeaeaa9247b
[]
no_license
g6843/taco
406e8221f1459df9678dfbcc9e6e3fab128ff3a5
08da5e4622381230c6a7f449600a55831553d9da
refs/heads/master
2021-07-07T21:18:55.503689
2017-10-05T02:46:59
2017-10-05T02:46:59
105,841,838
0
0
null
null
null
null
UTF-8
Java
false
false
61
java
package com.taco.main.event; public class LoadAllEvent { }
56bcb6fa382d64350f5caa7aaba58a3a49fcd1f5
e7f6c4ddd75f604e540acd5471ca5666c71f1e22
/algamoney-api/src/main/java/com/example/algamoney/api/repository/listener/LancamentoAnexoListener.java
36930136349304784dca45054a6f166103898fcd
[]
no_license
lcarrafabr/algamoney-api
72e88ef65d27237fffb7b58079699c892681c88d
3464685929e619680eeaebfdfc20e079ea5e7c70
refs/heads/master
2022-07-03T12:43:34.481795
2020-11-11T15:20:33
2020-11-11T15:20:33
228,721,152
0
0
null
2022-06-21T04:06:26
2019-12-17T23:47:48
Java
UTF-8
Java
false
false
589
java
package com.example.algamoney.api.repository.listener; import javax.persistence.PostLoad; import org.springframework.util.StringUtils; import com.example.algamoney.api.AlgamoneyApiApplication; import com.example.algamoney.api.model.Lancamento; import com.example.algamoney.api.storage.S3; public class LancamentoAnexoListener { @PostLoad public void postLoad(Lancamento lancamento) { if(StringUtils.hasText(lancamento.getAnexo())) { S3 s3 = AlgamoneyApiApplication.getBean(S3.class); lancamento.setUrlAnexo(s3.configurarURL(lancamento.getAnexo())); } } }
1b840875560c88da4cd88ae796702009a7f482e3
74d891d91fa3882ef319b1dae26648cb91e90388
/src/main/java/com/engineerskasa/demo/Employee/EmployeeDAO.java
34d180e3643e58087c84c0873a22cf14ac9e3776
[]
no_license
dedongh/spring-shop
95af0cd6a6e30d0955ff5207c865ca13b3dc7058
cc72050f03ec61619f3a02356b253ffdfc2c10c0
refs/heads/master
2021-03-23T18:08:05.253936
2020-03-16T23:51:57
2020-03-16T23:51:57
247,473,642
0
0
null
null
null
null
UTF-8
Java
false
false
800
java
package com.engineerskasa.demo.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class EmployeeDAO { @Autowired EmployeeRepo employeeRepo; // save employee public void save(Employee employee) { employeeRepo.save(employee); } // get all employees public List<Employee> findAll() { return employeeRepo.findAll(); } // get single employee public Employee findOneEmployee(Integer employee_id) { return employeeRepo.findById(employee_id).get(); //return employeeRepo.findOne(employee_id); } // delete an employee public void delete(Integer employee) { employeeRepo.deleteById(employee); } }
0a16ec6ccf5cd19291beb8cc33e65b16bfc35576
c7680266a31ffd7a39784d486b68a90755d87c6e
/src/test/java/com/viewol/dao/RecommendScheduleDAOImplTest.java
473e569e60daec20695805fe5cda6920222016c2
[]
no_license
viewolspace/viewol_service
6c4fd3874227a61fd27160e27ec6b4959105955f
9757ad8c17f29aa542b4284691c9ddc3a22c5e98
refs/heads/master
2023-07-20T19:01:32.762411
2023-07-06T05:33:21
2023-07-06T05:58:26
138,834,688
0
0
null
null
null
null
UTF-8
Java
false
false
850
java
package com.viewol.dao; import com.viewol.base.BaseTestClass; import com.viewol.pojo.RecommendSchedule; import org.junit.Test; import java.util.Date; /** * Created by lenovo on 2018/6/28. */ public class RecommendScheduleDAOImplTest extends BaseTestClass { private IRecommendScheduleDAO dao = (IRecommendScheduleDAO)getInstance("recommendScheduleDAO"); private RecommendSchedule getRecommendSchedule(){ RecommendSchedule r = new RecommendSchedule(); r.setScheduleId(1); r.setType(RecommendSchedule.TYPE_TOP); r.setsTime(new Date()); r.seteTime(new Date()); return r; } @Test public void addRecommendSchedule(){ dao.addRecommendSchedule(getRecommendSchedule()); } @Test public void delRecommendSchedule(){ dao.delRecommendSchedule(1); } }
661c823eaffe544b40a7eebeda617ff6616b50ca
90925e19f179770188f43fb2f1c01808ba7b78d3
/src/gramatica/java_cup/production.java
d37d4f8f587109785f231dd0dfc9d967e6fd43b4
[]
no_license
fabioalmeid/tp01ftc
5e4a71cb7e71ff3ed57b2300b61159e6c247fd64
8e6bb7529450deabfa85dcda2aec61f51f4bddde
refs/heads/master
2016-09-06T07:37:07.035253
2013-09-17T00:31:24
2013-09-17T00:31:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
23,460
java
package gramatica.java_cup; import java.util.Hashtable; import java.util.Enumeration; /** This class represents a production in the grammar. It contains * a LHS non terminal, and an array of RHS symbols. As various * transformations are done on the RHS of the production, it may shrink. * As a result a separate length is always maintained to indicate how much * of the RHS array is still valid.<p> * * I addition to construction and manipulation operations, productions provide * methods for factoring out actions (see remove_embedded_actions()), for * computing the nullability of the production (i.e., can it derive the empty * string, see check_nullable()), and operations for computing its first * set (i.e., the set of terminals that could appear at the beginning of some * string derived from the production, see check_first_set()). * * @see gramatica.java_cup.production_part * @see gramatica.java_cup.symbol_part * @see gramatica.java_cup.action_part * @version last updated: 7/3/96 * @author Frank Flannery */ public class production { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Full constructor. This constructor accepts a LHS non terminal, * an array of RHS parts (including terminals, non terminals, and * actions), and a string for a final reduce action. It does several * manipulations in the process of creating a production object. * After some validity checking it translates labels that appear in * actions into code for accessing objects on the runtime parse stack. * It them merges adjacent actions if they appear and moves any trailing * action into the final reduce actions string. Next it removes any * embedded actions by factoring them out with new action productions. * Finally it assigns a unique index to the production.<p> * * Factoring out of actions is accomplished by creating new "hidden" * non terminals. For example if the production was originally: <pre> * A ::= B {action} C D * </pre> * then it is factored into two productions:<pre> * A ::= B X C D * X ::= {action} * </pre> * (where X is a unique new non terminal). This has the effect of placing * all actions at the end where they can be handled as part of a reduce by * the parser. */ public production( non_terminal lhs_sym, production_part rhs_parts[], int rhs_l, String action_str) throws internal_error { int i; action_part tail_action; String declare_str; int rightlen = rhs_l; /* remember the length */ if (rhs_l >= 0) _rhs_length = rhs_l; else if (rhs_parts != null) _rhs_length = rhs_parts.length; else _rhs_length = 0; /* make sure we have a valid left-hand-side */ if (lhs_sym == null) throw new internal_error( "Attempt to construct a production with a null LHS"); /* I'm not translating labels anymore, I'm adding code to declare labels as valid variables. This way, the users code string is untouched 6/96 frankf */ /* check if the last part of the right hand side is an action. If it is, it won't be on the stack, so we don't want to count it in the rightlen. Then when we search down the stack for a Symbol, we don't try to search past action */ if (rhs_l > 0) { if (rhs_parts[rhs_l - 1].is_action()) { rightlen = rhs_l - 1; } else { rightlen = rhs_l; } } /* get the generated declaration code for the necessary labels. */ declare_str = declare_labels( rhs_parts, rightlen, action_str); if (action_str == null) action_str = declare_str; else action_str = declare_str + action_str; /* count use of lhs */ lhs_sym.note_use(); /* create the part for left-hand-side */ _lhs = new symbol_part(lhs_sym); /* merge adjacent actions (if any) */ _rhs_length = merge_adjacent_actions(rhs_parts, _rhs_length); /* strip off any trailing action */ tail_action = strip_trailing_action(rhs_parts, _rhs_length); if (tail_action != null) _rhs_length--; /* Why does this run through the right hand side happen over and over? here a quick combination of two prior runs plus one I wanted of my own frankf 6/25/96 */ /* allocate and copy over the right-hand-side */ /* count use of each rhs symbol */ _rhs = new production_part[_rhs_length]; for (i=0; i<_rhs_length; i++) { _rhs[i] = rhs_parts[i]; if (!_rhs[i].is_action()) { ((symbol_part)_rhs[i]).the_symbol().note_use(); if (((symbol_part)_rhs[i]).the_symbol() instanceof terminal) { _rhs_prec = ((terminal)((symbol_part)_rhs[i]).the_symbol()).precedence_num(); _rhs_assoc = ((terminal)((symbol_part)_rhs[i]).the_symbol()).precedence_side(); } } } /*now action string is really declaration string, so put it in front! 6/14/96 frankf */ if (action_str == null) action_str = ""; if (tail_action != null && tail_action.code_string() != null) action_str = action_str + "\t\t" + tail_action.code_string(); /* stash the action */ _action = new action_part(action_str); /* rewrite production to remove any embedded actions */ remove_embedded_actions(); /* assign an index */ _index = next_index++; /* put us in the global collection of productions */ _all.put(new Integer(_index),this); /* put us in the production list of the lhs non terminal */ lhs_sym.add_production(this); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Constructor with no action string. */ public production( non_terminal lhs_sym, production_part rhs_parts[], int rhs_l) throws internal_error { this(lhs_sym,rhs_parts,rhs_l,null); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /* Constructor with precedence and associativity of production contextually define */ public production( non_terminal lhs_sym, production_part rhs_parts[], int rhs_l, String action_str, int prec_num, int prec_side) throws internal_error { this(lhs_sym,rhs_parts,rhs_l,action_str); /* set the precedence */ set_precedence_num(prec_num); set_precedence_side(prec_side); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /* Constructor w/ no action string and contextual precedence defined */ public production( non_terminal lhs_sym, production_part rhs_parts[], int rhs_l, int prec_num, int prec_side) throws internal_error { this(lhs_sym,rhs_parts,rhs_l,null); /* set the precedence */ set_precedence_num(prec_num); set_precedence_side(prec_side); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /*-----------------------------------------------------------*/ /*--- (Access to) Static (Class) Variables ------------------*/ /*-----------------------------------------------------------*/ /** Table of all productions. Elements are stored using their index as * the key. */ protected static Hashtable _all = new Hashtable(); /** Access to all productions. */ public static Enumeration all() {return _all.elements();} /** Lookup a production by index. */ public static production find(int indx) { return (production) _all.get(new Integer(indx)); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Total number of productions. */ public static int number() {return _all.size();} /** Static counter for assigning unique index numbers. */ protected static int next_index; /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** The left hand side non-terminal. */ protected symbol_part _lhs; /** The left hand side non-terminal. */ public symbol_part lhs() {return _lhs;} /** The precedence of the rule */ protected int _rhs_prec = -1; protected int _rhs_assoc = -1; /** Access to the precedence of the rule */ public int precedence_num() { return _rhs_prec; } public int precedence_side() { return _rhs_assoc; } /** Setting the precedence of a rule */ public void set_precedence_num(int prec_num) { _rhs_prec = prec_num; } public void set_precedence_side(int prec_side) { _rhs_assoc = prec_side; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** A collection of parts for the right hand side. */ protected production_part _rhs[]; /** Access to the collection of parts for the right hand side. */ public production_part rhs(int indx) throws internal_error { if (indx >= 0 && indx < _rhs_length) return _rhs[indx]; else throw new internal_error( "Index out of range for right hand side of production"); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** How much of the right hand side array we are presently using. */ protected int _rhs_length; /** How much of the right hand side array we are presently using. */ public int rhs_length() {return _rhs_length;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** An action_part containing code for the action to be performed when we * reduce with this production. */ protected action_part _action; /** An action_part containing code for the action to be performed when we * reduce with this production. */ public action_part action() {return _action;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Index number of the production. */ protected int _index; /** Index number of the production. */ public int index() {return _index;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Count of number of reductions using this production. */ protected int _num_reductions = 0; /** Count of number of reductions using this production. */ public int num_reductions() {return _num_reductions;} /** Increment the count of reductions with this non-terminal */ public void note_reduction_use() {_num_reductions++;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Is the nullability of the production known or unknown? */ protected boolean _nullable_known = false; /** Is the nullability of the production known or unknown? */ public boolean nullable_known() {return _nullable_known;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Nullability of the production (can it derive the empty string). */ protected boolean _nullable = false; /** Nullability of the production (can it derive the empty string). */ public boolean nullable() {return _nullable;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** First set of the production. This is the set of terminals that * could appear at the front of some string derived from this production. */ protected terminal_set _first_set = new terminal_set(); /** First set of the production. This is the set of terminals that * could appear at the front of some string derived from this production. */ public terminal_set first_set() {return _first_set;} /*-----------------------------------------------------------*/ /*--- Static Methods ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Determine if a given character can be a label id starter. * @param c the character in question. */ protected static boolean is_id_start(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '_'); //later need to handle non-8-bit chars here } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if a character can be in a label id. * @param c the character in question. */ protected static boolean is_id_char(char c) { return is_id_start(c) || (c >= '0' && c <= '9'); } /*-----------------------------------------------------------*/ /*--- General Methods ---------------------------------------*/ /*-----------------------------------------------------------*/ /** Return label declaration code * @param labelname the label name * @param stack_type the stack type of label? * @author frankf */ protected String make_declaration( String labelname, String stack_type, int offset) { String ret; /* Put in the left/right value labels */ if (emit.lr_values()) ret = "\t\tint " + labelname + "left = ((java_cup.runtime.Symbol)" + emit.pre("stack") + ".elementAt(" + emit.pre("top") + "-" + offset + ")).left;\n" + "\t\tint " + labelname + "right = ((java_cup.runtime.Symbol)" + emit.pre("stack") + ".elementAt(" + emit.pre("top") + "-" + offset + ")).right;\n"; else ret = ""; /* otherwise, just declare label. */ return ret + "\t\t" + stack_type + " " + labelname + " = (" + stack_type + ")((" + "java_cup.runtime.Symbol) " + emit.pre("stack") + ".elementAt(" + emit.pre("top") + "-" + offset + ")).value;\n"; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Declare label names as valid variables within the action string * @param rhs array of RHS parts. * @param rhs_len how much of rhs to consider valid. * @param final_action the final action string of the production. * @param lhs_type the object type associated with the LHS symbol. */ protected String declare_labels( production_part rhs[], int rhs_len, String final_action) { String declaration = ""; symbol_part part; action_part act_part; int pos; /* walk down the parts and extract the labels */ for (pos = 0; pos < rhs_len; pos++) { if (!rhs[pos].is_action()) { part = (symbol_part)rhs[pos]; /* if it has a label, make declaration! */ if (part.label() != null) { declaration = declaration + make_declaration(part.label(), part.the_symbol().stack_type(), rhs_len-pos-1); } } } return declaration; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Helper routine to merge adjacent actions in a set of RHS parts * @param rhs_parts array of RHS parts. * @param len amount of that array that is valid. * @return remaining valid length. */ protected int merge_adjacent_actions(production_part rhs_parts[], int len) { int from_loc, to_loc, merge_cnt; /* bail out early if we have no work to do */ if (rhs_parts == null || len == 0) return 0; merge_cnt = 0; to_loc = -1; for (from_loc=0; from_loc<len; from_loc++) { /* do we go in the current position or one further */ if (to_loc < 0 || !rhs_parts[to_loc].is_action() || !rhs_parts[from_loc].is_action()) { /* next one */ to_loc++; /* clear the way for it */ if (to_loc != from_loc) rhs_parts[to_loc] = null; } /* if this is not trivial? */ if (to_loc != from_loc) { /* do we merge or copy? */ if (rhs_parts[to_loc] != null && rhs_parts[to_loc].is_action() && rhs_parts[from_loc].is_action()) { /* merge */ rhs_parts[to_loc] = new action_part( ((action_part)rhs_parts[to_loc]).code_string() + ((action_part)rhs_parts[from_loc]).code_string()); merge_cnt++; } else { /* copy */ rhs_parts[to_loc] = rhs_parts[from_loc]; } } } /* return the used length */ return len - merge_cnt; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Helper routine to strip a trailing action off rhs and return it * @param rhs_parts array of RHS parts. * @param len how many of those are valid. * @return the removed action part. */ protected action_part strip_trailing_action( production_part rhs_parts[], int len) { action_part result; /* bail out early if we have nothing to do */ if (rhs_parts == null || len == 0) return null; /* see if we have a trailing action */ if (rhs_parts[len-1].is_action()) { /* snip it out and return it */ result = (action_part)rhs_parts[len-1]; rhs_parts[len-1] = null; return result; } else return null; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Remove all embedded actions from a production by factoring them * out into individual action production using new non terminals. * if the original production was: <pre> * A ::= B {action1} C {action2} D * </pre> * then it will be factored into: <pre> * A ::= B NT$1 C NT$2 D * NT$1 ::= {action1} * NT$2 ::= {action2} * </pre> * where NT$1 and NT$2 are new system created non terminals. */ /* the declarations added to the parent production are also passed along, as they should be perfectly valid in this code string, since it was originally a code string in the parent, not on its own. frank 6/20/96 */ protected void remove_embedded_actions( ) throws internal_error { non_terminal new_nt; production new_prod; String declare_str; /* walk over the production and process each action */ for (int act_loc = 0; act_loc < rhs_length(); act_loc++) if (rhs(act_loc).is_action()) { declare_str = declare_labels( _rhs, act_loc, ""); /* create a new non terminal for the action production */ new_nt = non_terminal.create_new(); new_nt.is_embedded_action = true; /* 24-Mar-1998, CSA */ /* create a new production with just the action */ new_prod = new action_production(this, new_nt, null, 0, declare_str + ((action_part)rhs(act_loc)).code_string()); /* replace the action with the generated non terminal */ _rhs[act_loc] = new symbol_part(new_nt); } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Check to see if the production (now) appears to be nullable. * A production is nullable if its RHS could derive the empty string. * This results when the RHS is empty or contains only non terminals * which themselves are nullable. */ public boolean check_nullable() throws internal_error { production_part part; symbol sym; int pos; /* if we already know bail out early */ if (nullable_known()) return nullable(); /* if we have a zero size RHS we are directly nullable */ if (rhs_length() == 0) { /* stash and return the result */ return set_nullable(true); } /* otherwise we need to test all of our parts */ for (pos=0; pos<rhs_length(); pos++) { part = rhs(pos); /* only look at non-actions */ if (!part.is_action()) { sym = ((symbol_part)part).the_symbol(); /* if its a terminal we are definitely not nullable */ if (!sym.is_non_term()) return set_nullable(false); /* its a non-term, is it marked nullable */ else if (!((non_terminal)sym).nullable()) /* this one not (yet) nullable, so we aren't */ return false; } } /* if we make it here all parts are nullable */ return set_nullable(true); } /** set (and return) nullability */ boolean set_nullable(boolean v) { _nullable_known = true; _nullable = v; return v; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Update (and return) the first set based on current NT firsts. * This assumes that nullability has already been computed for all non * terminals and productions. */ public terminal_set check_first_set() throws internal_error { int part; symbol sym; /* walk down the right hand side till we get past all nullables */ for (part=0; part<rhs_length(); part++) { /* only look at non-actions */ if (!rhs(part).is_action()) { sym = ((symbol_part)rhs(part)).the_symbol(); /* is it a non-terminal?*/ if (sym.is_non_term()) { /* add in current firsts from that NT */ _first_set.add(((non_terminal)sym).first_set()); /* if its not nullable, we are done */ if (!((non_terminal)sym).nullable()) break; } else { /* its a terminal -- add that to the set */ _first_set.add((terminal)sym); /* we are done */ break; } } } /* return our updated first set */ return first_set(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Equality comparison. */ public boolean equals(production other) { if (other == null) return false; return other._index == _index; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Generic equality comparison. */ public boolean equals(Object other) { if (!(other instanceof production)) return false; else return equals((production)other); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Produce a hash code. */ public int hashCode() { /* just use a simple function of the index */ return _index*13; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Convert to a string. */ public String toString() { String result; /* catch any internal errors */ try { result = "production [" + index() + "]: "; result += ((lhs() != null) ? lhs().toString() : "$$NULL-LHS$$"); result += " :: = "; for (int i = 0; i<rhs_length(); i++) result += rhs(i) + " "; result += ";"; if (action() != null && action().code_string() != null) result += " {" + action().code_string() + "}"; if (nullable_known()) if (nullable()) result += "[NULLABLE]"; else result += "[NOT NULLABLE]"; } catch (internal_error e) { /* crash on internal error since we can't throw it from here (because superclass does not throw anything. */ e.crash(); result = null; } return result; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Convert to a simpler string. */ public String to_simple_string() throws internal_error { String result; result = ((lhs() != null) ? lhs().the_symbol().name() : "NULL_LHS"); result += " ::= "; for (int i = 0; i < rhs_length(); i++) if (!rhs(i).is_action()) result += ((symbol_part)rhs(i)).the_symbol().name() + " "; return result; } /*-----------------------------------------------------------*/ }
82174bd1fc15b1318b54b5770f6468271ab21363
7f48c50e05bc6571ad3798eb94c9d54cdfbe09b6
/src/test/java/com/trifacta/pageObjects/Google.java
a0ad3f58df430bedd443c99353f97dfe16b99d4c
[]
no_license
tarunpatnala/Trifacta-Application-Automation-Demo
e05e8d2dae8760c011c154feb5516936aa5b1622
b37ff873147e20e36a8d429908780b1c285ce669
refs/heads/Develop
2023-06-01T21:54:49.104575
2021-06-22T04:13:40
2021-06-22T04:13:40
378,652,778
0
0
null
2023-09-03T11:33:46
2021-06-20T13:32:18
HTML
UTF-8
Java
false
false
738
java
package com.trifacta.pageObjects; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import com.trifacta.utilities.BaseClass; public class Google extends BaseClass { @FindBy(xpath = "//input[@class='gLFyf gsfi']") WebElement SearchBar; @FindBy(xpath = "//body/div[2]/div[3]/form[1]/div[1]/div[1]/div[3]/center[1]/input[1]") WebElement SearchButton; public Google() { PageFactory.initElements(driver, this); } public void txtSearchBar(String text) { SearchBar.sendKeys(text); } public void hitSearch() { SearchButton.click(); } public void hitEnter() { SearchBar.sendKeys(Keys.ENTER); } }
d7728053474c6dcddb5aea20df93012da9d45ddc
e01f0102f5967e03077232de677a23b6d0f3d68e
/app/src/test/java/com/vitoksmile/library/view/controlview/app/ExampleUnitTest.java
32f5c281bbb6c8e4fdbf3800f260998c32bc4791
[ "Apache-2.0" ]
permissive
vitoksmile/ControlView
53ecd6e38ff932606d60794bdf5ecb650d7091e9
1f8efa4ef32af337e2b1218ab85c41bc48393470
refs/heads/master
2021-01-22T05:47:50.687599
2017-06-10T13:10:02
2017-06-10T13:10:02
92,498,382
0
0
null
null
null
null
UTF-8
Java
false
false
421
java
package com.vitoksmile.library.view.controlview.app; 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() throws Exception { assertEquals(4, 2 + 2); } }
1dbe7cba5f185f2c6d8e1d23ac0c442a720acae1
6d75ce4d50d352272d6354525c28e3d34cc57a0c
/tests/src/test/java/net/cactusthorn/config/tests/defaultvalue/DefaultValuesTest.java
00eac140607f1c4e32876b255eac2484ec36c64c
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
fossabot/net.cactusthorn.config
2f1a206397c7fa62f22b29acd84c9b5efe2dd760
93e26837bbeae1630512de4a82bcb2545427bf7d
refs/heads/main
2023-05-13T17:38:16.396969
2021-05-26T09:38:53
2021-05-26T09:38:53
370,980,641
0
0
BSD-3-Clause
2021-05-26T09:38:48
2021-05-26T09:38:47
null
UTF-8
Java
false
false
1,972
java
/* * Copyright (C) 2021, Alexei Khatskevich * * Licensed under the BSD 3-Clause license. * You may obtain a copy of the License at * * https://github.com/Gmugra/net.cactusthorn.config/blob/main/LICENSE * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.cactusthorn.config.tests.defaultvalue; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import net.cactusthorn.config.core.ConfigFactory; public class DefaultValuesTest { private static DefaultValues config; @BeforeAll static void setUp() { config = ConfigFactory.builder().build().create(DefaultValues.class); } @Test public void str() { assertEquals("string", config.str()); } @Test public void list() { assertEquals(3, config.list().size()); assertEquals("A", config.list().get(0)); assertEquals("B", config.list().get(1)); assertEquals("C", config.list().get(2)); } @Test public void set() { assertEquals(2, config.set().size()); } @Test public void sorted() { assertEquals(2, config.sorted().size()); assertEquals("B", config.sorted().iterator().next()); } }
183a5de7b0aad08cf5a1e49a8a9d4c5d2f34d1e4
c8c729a3f80cb201e2cb978d66c4b25795004cfc
/app/src/test/java/com/example/student/myoshimen/ExampleUnitTest.java
d424df12547cff5f8ede50e122840e08bdcae9fe
[]
no_license
taitsutaitsu/MyOshimen
384b2fd9a4baeadb6dbeeaeaa332729514949f23
57ed2b8f438ff4abc9403bd3a7c37352be0895fa
refs/heads/master
2020-04-02T02:51:53.299095
2018-10-29T14:50:56
2018-10-29T14:50:56
153,932,394
0
0
null
2018-10-29T14:50:57
2018-10-20T17:47:15
Java
UTF-8
Java
false
false
390
java
package com.example.student.myoshimen; 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); } }
0ae826a3eaa8d4c3ef44bb68d0a059d9cbaca5cc
9444e1a9071791f04a47ced7236a18be92d14712
/DialogX/src/main/java/com/kongzue/dialogx/util/views/BottomDialogListView.java
0796be695e4ea7bcebb8b39152d89f9ca1a8ed7d
[ "Apache-2.0" ]
permissive
sonpxp/DialogX
466d058c89267c82627357c3d05ea38a23bd9ac1
1c29f631551df6e2473a1d78b4a3f33b596e1c68
refs/heads/master
2023-06-16T14:38:56.934923
2021-07-14T10:42:21
2021-07-14T10:42:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,089
java
package com.kongzue.dialogx.util.views; import android.content.Context; import android.content.res.Resources; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ScrollView; import androidx.annotation.RequiresApi; import com.kongzue.dialogx.dialogs.BottomDialog; import com.kongzue.dialogx.interfaces.BottomMenuListViewTouchEvent; /** * @author: Kongzue * @github: https://github.com/kongzue/ * @homepage: http://kongzue.com/ * @mail: [email protected] * @createTime: 2020/10/6 23:42 */ public class BottomDialogListView extends ListView { private BottomMenuListViewTouchEvent bottomMenuListViewTouchEvent; public BottomDialogListView(Context context) { super(context); } public BottomDialogListView(Context context, AttributeSet attrs) { super(context, attrs); } public BottomDialogListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } private BottomDialog.DialogImpl dialogImpl; public BottomDialogListView(BottomDialog.DialogImpl dialog, Context context) { super(context); dialogImpl = dialog; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(dip2px(55) * size + size, MeasureSpec.EXACTLY)); //super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(expandSpec, MeasureSpec.AT_MOST)); } private int dip2px(float dpValue) { final float scale = Resources.getSystem().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } private int mPosition; private float touchDownY; @Override public boolean dispatchTouchEvent(MotionEvent ev) { final int actionMasked = ev.getActionMasked() & MotionEvent.ACTION_MASK; if (actionMasked == MotionEvent.ACTION_DOWN) { touchDownY = ev.getY(); if (bottomMenuListViewTouchEvent != null) { bottomMenuListViewTouchEvent.down(ev); } mPosition = pointToPosition((int) ev.getX(), (int) ev.getY()); return super.dispatchTouchEvent(ev); } if (actionMasked == MotionEvent.ACTION_MOVE) { if (bottomMenuListViewTouchEvent != null) { bottomMenuListViewTouchEvent.move(ev); } if (Math.abs(touchDownY - ev.getY()) > dip2px(5)) { ev.setAction(MotionEvent.ACTION_CANCEL); dispatchTouchEvent(ev); return false; } return true; } if (actionMasked == MotionEvent.ACTION_UP || actionMasked == MotionEvent.ACTION_CANCEL) { if (bottomMenuListViewTouchEvent != null) { bottomMenuListViewTouchEvent.up(ev); } if (pointToPosition((int) ev.getX(), (int) ev.getY()) == mPosition) { super.dispatchTouchEvent(ev); } else { setPressed(false); invalidate(); } } return super.dispatchTouchEvent(ev); } public BottomMenuListViewTouchEvent getBottomMenuListViewTouchEvent() { return bottomMenuListViewTouchEvent; } private int size = 1; @Override public void setAdapter(ListAdapter adapter) { size = adapter.getCount(); super.setAdapter(adapter); } public BottomDialogListView setBottomMenuListViewTouchEvent(BottomMenuListViewTouchEvent bottomMenuListViewTouchEvent) { this.bottomMenuListViewTouchEvent = bottomMenuListViewTouchEvent; return this; } }
dba50291f2be0e41e32fc3a4338332450b7ee21f
c407f0902550c29d7e19704683b071412d3a19da
/src/main/java/com/pika/bq/BlockingQueueDemo.java
937832aad635a97a3a4256dcb9211ea1b607f691
[]
no_license
Ambrose829/juc
c4a4d048abc7ce5997bcb732734a4ad2f651d7f4
2f56786930ac653caa14afe6a16fd1b6ad1cd323
refs/heads/master
2022-12-23T15:36:28.136539
2020-09-30T14:19:34
2020-09-30T14:19:34
299,265,010
0
0
null
null
null
null
UTF-8
Java
false
false
515
java
package com.pika.bq; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; /** * @author Pika * @create 2020/9/28 * @since 1.0.0 * ArrayBlockingQueue:是一个基于数组的有界阻塞队列 * * 阻塞队列 * 阻塞队列有没有好的一面 * * 不得不阻塞,你如何管理 */ public class BlockingQueueDemo { public static void main(String[] args) { // List list = null; ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3); } }
bdcf02fb56abcfc679e142b808dea6b975d3310d
d5e98e3a3c66e961c1b4acaf4ba7af0aa65f76e1
/153 find minimum in rotated sorted array/findMin.java
83bbb1a35030602c4f3b06ed3d946a9c6c0e9874
[]
no_license
ErkangXu/Leetcode
0d21f7fa262498baf5f19b68b6e4f86aa7413583
8403f18a0729a21c190c41d56b68c11c5aa37a0a
refs/heads/master
2016-09-10T13:29:50.204424
2015-11-20T04:02:28
2015-11-20T04:02:28
32,872,834
0
0
null
null
null
null
UTF-8
Java
false
false
530
java
public class Solution { public int findMinHelper(int[] list, int start, int end) { if(list[start]<=list[end]) return list[start]; int mid = (start+end)/2; if(list[start]<=list[mid]) { return findMinHelper(list, mid+1, end); } else return findMinHelper(list, start, mid); } public int findMin(int[] nums) { int len = nums.length; return findMinHelper(nums, 0, len-1); // need to consider when it didn't rotate (includes when there is only one element) } }
f8f527d06b3f1773249eef8b0fe02a275d26b4cf
40069441a3d0cf5efba8957d64c5a8ae995fc46c
/functionalj-types/src/test/java/functionalj/types/choice/generator/GeneratorTest.java
8e8c27d6b8be2faf6e5d298bf110385363fa27de
[ "MIT" ]
permissive
NawaMan/FunctionalJ
2fbec389e91838df5d1818f7c2ff8bf5d883620a
6fe15ece3aa0bf40426cf486cd700d599f98d382
refs/heads/master
2023-08-27T11:18:24.828025
2023-07-21T05:43:48
2023-07-21T05:43:48
125,157,861
48
5
MIT
2023-01-28T02:20:29
2018-03-14T05:05:34
Java
UTF-8
Java
false
false
32,409
java
// ============================================================================ // Copyright (c) 2017-2023 Nawapunth Manusitthipol (NawaMan - http://nawaman.net). // ---------------------------------------------------------------------------- // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // ============================================================================ package functionalj.types.choice.generator; import static functionalj.types.choice.generator.model.Method.Kind.DEFAULT; import static functionalj.types.choice.generator.model.Method.Kind.STATIC; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.stream.Collectors.joining; import static org.junit.Assert.assertEquals; import java.util.Objects; import java.util.stream.Collectors; import org.junit.Test; import functionalj.types.Generic; import functionalj.types.Serialize; import functionalj.types.Type; import functionalj.types.choice.generator.model.Case; import functionalj.types.choice.generator.model.CaseParam; import functionalj.types.choice.generator.model.Method; import functionalj.types.choice.generator.model.Method.Kind; import functionalj.types.choice.generator.model.MethodParam; import functionalj.types.choice.generator.model.SourceSpec; import lombok.val; import lombok.experimental.ExtensionMethod; @ExtensionMethod(functionalj.types.choice.generator.Utils.class) public class GeneratorTest { @Test public void testToCamelCase() { assertEquals("rgbColor", "RGBColor".toCamelCase()); assertEquals("rgb", "RGB".toCamelCase()); assertEquals("white", "White".toCamelCase()); } @Test public void testSubClassConstructor_noParams() { val sourceSpec = new SourceSpec("Color", new Type("p1.p2", "ColorSpec"), emptyList()); val target = new TargetClass(sourceSpec); val sub = new SubClassConstructor(target, new Case("White")); val lines = sub.lines().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")); assertEquals("public static final White white = White.instance;\n" + "public static final White White() {\n" + " return White.instance;\n" + "}", lines); assertEquals("new functionalj.types.choice.generator.model.SourceSpec(" + "\"Color\", " + "new functionalj.types.Type(" + "\"p1.p2\", " + "null, " + "\"ColorSpec\", " + "java.util.Collections.emptyList()), " + "null, " + "false, " + "\"__tagged\", " + "functionalj.types.Serialize.To.NOTHING, " + "java.util.Collections.emptyList(), " + "java.util.Collections.emptyList(), " + "java.util.Collections.emptyList(), " + "java.util.Collections.emptyList())", sourceSpec.toCode()); } @Test public void testSubClassConstructor_withParams() { val sourceSpec = new SourceSpec("Color", new Type("p1.p2", "EncloserClass", "ColorSpec"), emptyList()); val target = new TargetClass(sourceSpec); val sub = new SubClassConstructor(target, new Case("RGB", "__validateRGB", asList(new CaseParam("r", new Type("int"), false), new CaseParam("g", new Type("int"), false), new CaseParam("b", new Type("int"), false)))); val lines = sub.lines().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")); assertEquals("public static final RGB RGB(int r, int g, int b) {\n" + " ColorSpec.__validateRGB(r, g, b);\n" + " return new RGB(r, g, b);\n" + "}", lines); assertEquals("new functionalj.types.choice.generator.model.SourceSpec(" + "\"Color\", " + "new functionalj.types.Type(" + "\"p1.p2\", " + "\"EncloserClass\", " + "\"ColorSpec\", " + "java.util.Collections.emptyList()), " + "null, " + "false, " + "\"__tagged\", " + "functionalj.types.Serialize.To.NOTHING, " + "java.util.Collections.emptyList(), " + "java.util.Collections.emptyList(), " + "java.util.Collections.emptyList(), " + "java.util.Collections.emptyList()" + ")", sourceSpec.toCode()); } @Test public void testSubClassConstructor_withParams_withGeneric() { val sourceType = new Type("p1.p2", null, "Next", asList(new Generic("D"))); val sourceSpec = new SourceSpec("Coroutine", sourceType, "spec", false, null, Serialize.To.NOTHING, asList(new Generic("D")), emptyList(), emptyList(), emptyList()); val target = new TargetClass(sourceSpec); val sub = new SubClassDefinition(target, new Case("Next", asList(new CaseParam("next", new Type("functionalj.function", null, "Func1", asList(new Generic("D"), new Generic("Coroutine<D>"))), false)))); val lines = sub.lines().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")); assertEquals("public static final class Next<D> extends Coroutine<D> {\n" + " public static final Next.NextLens<Next> theNext = new Next.NextLens<>(\"theNext\", LensSpec.of(Next.class));\n" + " public static final Next.NextLens<Next> eachNext = theNext;\n" + " private Func1<D,Coroutine<D>> next;\n" + " private Next(Func1<D,Coroutine<D>> next) {\n" + " this.next = $utils.notNull(next);\n" + " }\n" + " public Func1<D,Coroutine<D>> next() { return next; }\n" + " public Next<D> withNext(Func1<D,Coroutine<D>> next) { return new Next<D>(next); }\n" + " public static class NextLens<HOST> extends ObjectLensImpl<HOST, Coroutine.Next> {\n" + " \n" + " public final ObjectLens<HOST, Object> next = (ObjectLens)createSubLens(\"next\", Coroutine.Next::next, Coroutine.Next::withNext, ObjectLens::of);\n" + " \n" + " public NextLens(String name, LensSpec<HOST, Coroutine.Next> spec) {\n" + " super(name, spec);\n" + " }\n" + " \n" + " }\n" + " public java.util.Map<String, Object> __toMap() {\n" + " java.util.Map<String, Object> map = new java.util.HashMap<>();\n" + " map.put(\"__tagged\", $utils.toMapValueObject(\"Next\"));\n" + " map.put(\"next\", this.next);\n" + " return map;\n" + " }\n" + " static private functionalj.map.FuncMap<String, functionalj.types.choice.generator.model.CaseParam> __schema__ = functionalj.map.FuncMap.<String, functionalj.types.choice.generator.model.CaseParam>newMap()\n" + " .with(\"next\", new functionalj.types.choice.generator.model.CaseParam(\"next\", new functionalj.types.Type(\"functionalj.function\", null, \"Func1\", java.util.Arrays.asList(new functionalj.types.Generic(\"D\", \"D\", java.util.Arrays.asList(new functionalj.types.Type(null, null, \"D\", java.util.Collections.emptyList()))), new functionalj.types.Generic(\"Coroutine<D>\", \"Coroutine<D>\", java.util.Arrays.asList(new functionalj.types.Type(null, null, \"Coroutine<D>\", java.util.Collections.emptyList()))))), false, null))\n" + " .build();\n" + " public static java.util.Map<String, functionalj.types.choice.generator.model.CaseParam> getCaseSchema() {\n" + " return __schema__;\n" + " }\n" + " public static Next caseFromMap(java.util.Map<String, ? extends Object> map) {\n" + " return Next(\n" + " (Func1<D, Coroutine<D>>)$utils.extractPropertyFromMap(Next.class, Func1.class, map, __schema__, \"next\")\n" + " );\n" + " }\n" + "}", lines); assertEquals("new functionalj.types.choice.generator.model.SourceSpec(\"Coroutine\", new functionalj.types.Type(\"p1.p2\", null, \"Next\", java.util.Arrays.asList(new functionalj.types.Generic(\"D\", \"D\", java.util.Arrays.asList(new functionalj.types.Type(null, null, \"D\", java.util.Collections.emptyList()))))), \"spec\", false, \"__tagged\", functionalj.types.Serialize.To.NOTHING, java.util.Arrays.asList(new functionalj.types.Generic(\"D\", \"D\", java.util.Arrays.asList(new functionalj.types.Type(null, null, \"D\", java.util.Collections.emptyList())))), java.util.Collections.emptyList(), java.util.Collections.emptyList(), java.util.Collections.emptyList())", sourceSpec.toCode()); } @Test public void testSubClassDefinition_noParams() { val target = new TargetClass(new SourceSpec("Color", new Type("p1.p2", "ColorSpec"), emptyList())); val sub = new SubClassDefinition(target, new Case("White")); val lines = sub.lines().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")); assertEquals("public static final class White extends Color {\n" + " public static final White.WhiteLens<White> theWhite = new White.WhiteLens<>(\"theWhite\", LensSpec.of(White.class));\n" + " public static final White.WhiteLens<White> eachWhite = theWhite;\n" + " private static final White instance = new White();\n" + " private White() {}\n" + " public static class WhiteLens<HOST> extends ObjectLensImpl<HOST, Color.White> {\n" + " \n" + " public WhiteLens(String name, LensSpec<HOST, Color.White> spec) {\n" + " super(name, spec);\n" + " }\n" + " \n" + " }\n" + " public java.util.Map<String, Object> __toMap() {\n" + " return java.util.Collections.singletonMap(\"__tagged\", $utils.toMapValueObject(\"White\"));\n" + " }\n" + " static private functionalj.map.FuncMap<String, functionalj.types.choice.generator.model.CaseParam> __schema__ = functionalj.map.FuncMap.<String, functionalj.types.choice.generator.model.CaseParam>empty();\n" + " public static java.util.Map<String, functionalj.types.choice.generator.model.CaseParam> getCaseSchema() {\n" + " return __schema__;\n" + " }\n" + " public static White caseFromMap(java.util.Map<String, ? extends Object> map) {\n" + " return White(\n" + " );\n" + " }\n" + "}", lines); } @Test public void testSubClassDefinition_withParams() { val target = new TargetClass(new SourceSpec("Color", new Type("p1.p2", "ColorSpec"), emptyList())); val sub = new SubClassDefinition(target, new Case("RGB", "__validateRGB", asList(new CaseParam("r", new Type("int"), false), new CaseParam("g", new Type("int"), false), new CaseParam("b", new Type("int"), false)))); val lines = sub.lines().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")); assertEquals("public static final class RGB extends Color {\n" + " public static final RGB.RGBLens<RGB> theRGB = new RGB.RGBLens<>(\"theRGB\", LensSpec.of(RGB.class));\n" + " public static final RGB.RGBLens<RGB> eachRGB = theRGB;\n" + " private int r;\n" + " private int g;\n" + " private int b;\n" + " private RGB(int r, int g, int b) {\n" + " this.r = r;\n" + " this.g = g;\n" + " this.b = b;\n" + " }\n" + " public int r() { return r; }\n" + " public int g() { return g; }\n" + " public int b() { return b; }\n" + " public RGB withR(int r) { return new RGB(r, g, b); }\n" + " public RGB withG(int g) { return new RGB(r, g, b); }\n" + " public RGB withB(int b) { return new RGB(r, g, b); }\n" + " public static class RGBLens<HOST> extends ObjectLensImpl<HOST, Color.RGB> {\n" + " \n" + " public final IntegerLens<HOST> r = createSubLensInt(\"r\", Color.RGB::r, Color.RGB::withR);\n" + " public final IntegerLens<HOST> g = createSubLensInt(\"g\", Color.RGB::g, Color.RGB::withG);\n" + " public final IntegerLens<HOST> b = createSubLensInt(\"b\", Color.RGB::b, Color.RGB::withB);\n" + " \n" + " public RGBLens(String name, LensSpec<HOST, Color.RGB> spec) {\n" + " super(name, spec);\n" + " }\n" + " \n" + " }\n" + " public java.util.Map<String, Object> __toMap() {\n" + " java.util.Map<String, Object> map = new java.util.HashMap<>();\n" + " map.put(\"__tagged\", $utils.toMapValueObject(\"RGB\"));\n" + " map.put(\"r\", this.r);\n" + " map.put(\"g\", this.g);\n" + " map.put(\"b\", this.b);\n" + " return map;\n" + " }\n" + " static private functionalj.map.FuncMap<String, functionalj.types.choice.generator.model.CaseParam> __schema__ = functionalj.map.FuncMap.<String, functionalj.types.choice.generator.model.CaseParam>newMap()\n" + " .with(\"r\", new functionalj.types.choice.generator.model.CaseParam(\"r\", new functionalj.types.Type(null, null, \"int\", java.util.Collections.emptyList()), false, null))\n" + " .with(\"g\", new functionalj.types.choice.generator.model.CaseParam(\"g\", new functionalj.types.Type(null, null, \"int\", java.util.Collections.emptyList()), false, null))\n" + " .with(\"b\", new functionalj.types.choice.generator.model.CaseParam(\"b\", new functionalj.types.Type(null, null, \"int\", java.util.Collections.emptyList()), false, null))\n" + " .build();\n" + " public static java.util.Map<String, functionalj.types.choice.generator.model.CaseParam> getCaseSchema() {\n" + " return __schema__;\n" + " }\n" + " public static RGB caseFromMap(java.util.Map<String, ? extends Object> map) {\n" + " return RGB(\n" + " (int)$utils.extractPropertyFromMap(RGB.class, int.class, map, __schema__, \"r\"),\n" + " (int)$utils.extractPropertyFromMap(RGB.class, int.class, map, __schema__, \"g\"),\n" + " (int)$utils.extractPropertyFromMap(RGB.class, int.class, map, __schema__, \"b\")\n" + " );\n" + " }\n" + "}", lines); } @Test public void testSubClassDefinition_withParams_withGeneric() { val sourceType = new Type("p1.p2", null, "Next", asList(new Generic("D"))); val target = new TargetClass(new SourceSpec("Coroutine", sourceType, "spec", false, null, Serialize.To.NOTHING, asList(new Generic("D")), emptyList(), emptyList(), emptyList())); val sub = new SubClassDefinition(target, new Case("Next", asList(new CaseParam("next", new Type("functionalj.function", null, "Func1", asList(new Generic("D"), new Generic("Coroutine<D>"))), false)))); val lines = sub.lines().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")); assertEquals("public static final class Next<D> extends Coroutine<D> {\n" + " public static final Next.NextLens<Next> theNext = new Next.NextLens<>(\"theNext\", LensSpec.of(Next.class));\n" + " public static final Next.NextLens<Next> eachNext = theNext;\n" + " private Func1<D,Coroutine<D>> next;\n" + " private Next(Func1<D,Coroutine<D>> next) {\n" + " this.next = $utils.notNull(next);\n" + " }\n" + " public Func1<D,Coroutine<D>> next() { return next; }\n" + " public Next<D> withNext(Func1<D,Coroutine<D>> next) { return new Next<D>(next); }\n" + " public static class NextLens<HOST> extends ObjectLensImpl<HOST, Coroutine.Next> {\n" + " \n" + " public final ObjectLens<HOST, Object> next = (ObjectLens)createSubLens(\"next\", Coroutine.Next::next, Coroutine.Next::withNext, ObjectLens::of);\n" + " \n" + " public NextLens(String name, LensSpec<HOST, Coroutine.Next> spec) {\n" + " super(name, spec);\n" + " }\n" + " \n" + " }\n" + " public java.util.Map<String, Object> __toMap() {\n" + " java.util.Map<String, Object> map = new java.util.HashMap<>();\n" + " map.put(\"__tagged\", $utils.toMapValueObject(\"Next\"));\n" + " map.put(\"next\", this.next);\n" + " return map;\n" + " }\n" + " static private functionalj.map.FuncMap<String, functionalj.types.choice.generator.model.CaseParam> __schema__ = functionalj.map.FuncMap.<String, functionalj.types.choice.generator.model.CaseParam>newMap()\n" + " .with(\"next\", new functionalj.types.choice.generator.model.CaseParam(\"next\", new functionalj.types.Type(\"functionalj.function\", null, \"Func1\", java.util.Arrays.asList(new functionalj.types.Generic(\"D\", \"D\", java.util.Arrays.asList(new functionalj.types.Type(null, null, \"D\", java.util.Collections.emptyList()))), new functionalj.types.Generic(\"Coroutine<D>\", \"Coroutine<D>\", java.util.Arrays.asList(new functionalj.types.Type(null, null, \"Coroutine<D>\", java.util.Collections.emptyList()))))), false, null))\n" + " .build();\n" + " public static java.util.Map<String, functionalj.types.choice.generator.model.CaseParam> getCaseSchema() {\n" + " return __schema__;\n" + " }\n" + " public static Next caseFromMap(java.util.Map<String, ? extends Object> map) {\n" + " return Next(\n" + " (Func1<D, Coroutine<D>>)$utils.extractPropertyFromMap(Next.class, Func1.class, map, __schema__, \"next\")\n" + " );\n" + " }\n" + "}", lines); } @Test public void testSwitchClass_simple_notLast() { val target = new TargetClass(new SourceSpec("Color", new Type("p1.p2", "ColorSpec"), emptyList())); val sub = new SwitchClass(target, false, asList(new Case("White"), new Case("Black"), new Case("RGB", "__validateRGB", asList(new CaseParam("r", new Type("int"), false), new CaseParam("g", new Type("int"), false), new CaseParam("b", new Type("int"), false))))); val lines = sub.lines().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")); assertEquals("public static class ColorSwitchWhiteBlackRGB<TARGET> extends ChoiceTypeSwitch<Color, TARGET> {\n" + " private ColorSwitchWhiteBlackRGB(Color theValue, Function<Color, ? extends TARGET> theAction) { super(theValue, theAction); }\n" + " \n" + " public ColorSwitchBlackRGB<TARGET> white(Function<? super White, ? extends TARGET> theAction) {\n" + " Function<Color, TARGET> oldAction = (Function<Color, TARGET>)$action;\n" + " Function<Color, TARGET> newAction =\n" + " ($action != null)\n" + " ? oldAction : \n" + " ($value instanceof White)\n" + " ? (Function<Color, TARGET>)(d -> theAction.apply((White)d))\n" + " : oldAction;\n" + " \n" + " return new ColorSwitchBlackRGB<TARGET>($value, newAction);\n" + " }\n" + " public ColorSwitchBlackRGB<TARGET> white(Supplier<? extends TARGET> theSupplier) {\n" + " return white(d->theSupplier.get());\n" + " }\n" + " public ColorSwitchBlackRGB<TARGET> white(TARGET theValue) {\n" + " return white(d->theValue);\n" + " }\n" + "}", lines); } @Test public void testSwitchClass_simple_last() { val target = new TargetClass(new SourceSpec("Color", new Type("p1.p2", "ColorSpec"), emptyList())); val sub = new SwitchClass(target, false, asList(new Case("White"))); val lines = sub.lines().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")); assertEquals("public static class ColorSwitchWhite<TARGET> extends ChoiceTypeSwitch<Color, TARGET> {\n" + " private ColorSwitchWhite(Color theValue, Function<Color, ? extends TARGET> theAction) { super(theValue, theAction); }\n" + " \n" + " public TARGET white(Function<? super White, ? extends TARGET> theAction) {\n" + " Function<Color, TARGET> oldAction = (Function<Color, TARGET>)$action;\n" + " Function<Color, TARGET> newAction =\n" + " ($action != null)\n" + " ? oldAction : \n" + " ($value instanceof White)\n" + " ? (Function<Color, TARGET>)(d -> theAction.apply((White)d))\n" + " : oldAction;\n" + " \n" + " return newAction.apply($value);\n" + " }\n" + " public TARGET white(Supplier<? extends TARGET> theSupplier) {\n" + " return white(d->theSupplier.get());\n" + " }\n" + " public TARGET white(TARGET theValue) {\n" + " return white(d->theValue);\n" + " }\n" + "}", lines); } @Test public void testSubCheckMethod() { val target = new TargetClass(new SourceSpec("Color", new Type("p1.p2", "ColorSpec"), emptyList())); val sub = new SubCheckMethod(target, asList(new Case("White", emptyList()), new Case("Black", emptyList()), new Case("RGB", "__validateRGB", asList(new CaseParam("r", new Type("int"), false), new CaseParam("g", new Type("int"), false), new CaseParam("b", new Type("int"), false))))); val lines = sub.lines().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")); assertEquals("public boolean isWhite() { return this instanceof White; }\n" + "public Result<White> asWhite() { return Result.valueOf(this).filter(White.class).map(White.class::cast); }\n" + "public Color ifWhite(Consumer<White> action) { if (isWhite()) action.accept((White)this); return this; }\n" + "public Color ifWhite(Runnable action) { if (isWhite()) action.run(); return this; }\n" + "public boolean isBlack() { return this instanceof Black; }\n" + "public Result<Black> asBlack() { return Result.valueOf(this).filter(Black.class).map(Black.class::cast); }\n" + "public Color ifBlack(Consumer<Black> action) { if (isBlack()) action.accept((Black)this); return this; }\n" + "public Color ifBlack(Runnable action) { if (isBlack()) action.run(); return this; }\n" + "public boolean isRGB() { return this instanceof RGB; }\n" + "public Result<RGB> asRGB() { return Result.valueOf(this).filter(RGB.class).map(RGB.class::cast); }\n" + "public Color ifRGB(Consumer<RGB> action) { if (isRGB()) action.accept((RGB)this); return this; }\n" + "public Color ifRGB(Runnable action) { if (isRGB()) action.run(); return this; }", lines); } @Test public void testSourceMethods() { val target = new TargetClass(new SourceSpec("Color", new Type("p1.p2", "ColorSpec"), "spec", true, null, Serialize.To.NOTHING, emptyList(), emptyList(), asList(new Method(Kind.DEFAULT, "equals", new Type("boolean"), asList(new MethodParam("c", new Type("p1.p2", "Color")), new MethodParam("obj", Type.OBJECT))), new Method(DEFAULT, "thisName", Type.STRING, asList(new MethodParam("c", new Type("p1.p2", null, "Color")), new MethodParam("c2", new Type("p1.p2", null, "Color")), new MethodParam("s", Type.STRING)), asList(new Generic("T", "T extends Exception", asList(new Type("Exception")))), asList(new Type("T"))), new Method(DEFAULT, "thisSelf", new Type("p1.p2", null, "Color"), asList(new MethodParam("c", new Type("p1.p2", null, "Color")), new MethodParam("c2", new Type("p1.p2", null, "Color")), new MethodParam("s", Type.STRING))), new Method(Kind.STATIC, "toRGBString", new Type("boolean"), asList(new MethodParam("c", new Type("p1.p2", "Color"))))), emptyList())); val sub = new SourceMethod(target); val lines = sub.lines().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")); assertEquals("public boolean equals(java.lang.Object obj) {\n" + " return __spec.equals(Self.wrap(this), obj);\n" + "}\n" + "public <T extends Exception> java.lang.String thisName(p1.p2.Color c2, java.lang.String s) throws T {\n" + " return __spec.thisName(Self.wrap(this), Self.wrap(c2), s);\n" + "}\n" + "public p1.p2.Color thisSelf(p1.p2.Color c2, java.lang.String s) {\n" + " return functionalj.types.choice.Self.unwrap(__spec.thisSelf(Self.wrap(this), Self.wrap(c2), s));\n" + "}\n" + "public static boolean toRGBString(p1.p2.Color c) {\n" + " return p1.p2.ColorSpec.toRGBString(c);\n" + "}", lines); } @Test public void testTargetTypeGeneral_expand() { val target = new TargetClass(new SourceSpec("Color", new Type("p1.p2", "ColorSpec"), emptyList())); val sub = new TargetTypeGeneral(target, asList(new Case("White", emptyList()), new Case("Black", emptyList()), new Case("RGB", "__validateRGB", asList(new CaseParam("r", new Type("int"), false), new CaseParam("g", new Type("int"), false), new CaseParam("b", new Type("int"), false))))); val lines = sub.lines().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")); assertEquals("public java.util.Map<java.lang.String, java.util.Map<java.lang.String, functionalj.types.choice.generator.model.CaseParam>> __getSchema() {\n" + " return getChoiceSchema();\n" + "}\n" + "\n" + "private final transient ColorFirstSwitch __switch = new ColorFirstSwitch(this);\n" + "@Override public ColorFirstSwitch match() {\n" + " return __switch;\n" + "}\n" + "\n" + "private volatile String toString = null;\n" + "@Override\n" + "public String toString() {\n" + " if (toString != null)\n" + " return toString;\n" + " synchronized(this) {\n" + " if (toString != null)\n" + " return toString;\n" + " toString = $utils.Match(this)\n" + " .white(__ -> \"White\")\n" + " .black(__ -> \"Black\")\n" + " .rgb(rgb -> \"RGB(\" + String.format(\"%1$s,%2$s,%3$s\", rgb.r,rgb.g,rgb.b) + \")\")\n" + " ;\n" + " return toString;\n" + " }\n" + "}\n" + "\n" + "@Override\n" + "public int hashCode() {\n" + " return toString().hashCode();\n" + "}\n" + "\n" + "@Override\n" + "public boolean equals(Object obj) {\n" + " if (!(obj instanceof Color))\n" + " return false;\n" + " \n" + " if (this == obj)\n" + " return true;\n" + " \n" + " String objToString = obj.toString();\n" + " String thisToString = this.toString();\n" + " return thisToString.equals(objToString);\n" + "}", lines); } @Test public void testTargetTypeGeneral_withMethods() { val colorType = new Type("p1.p2", "Color"); val target = new TargetClass(new SourceSpec("Color", new Type("p1.p2", "ColorSpec"), "spec", true, null, Serialize.To.NOTHING, emptyList(), emptyList(), asList(new Method(DEFAULT, "equals", new Type("boolean"), asList(new MethodParam("c", colorType), new MethodParam("obj", Type.OBJECT))), new Method(DEFAULT, "toString", Type.STRING, asList(new MethodParam("c", colorType))), new Method(DEFAULT, "hashCode", new Type("int"), asList(new MethodParam("c", colorType))), new Method(DEFAULT, "thisMethod", Type.STRING, asList(new MethodParam("c", colorType), new MethodParam("c2", colorType), new MethodParam("s", Type.STRING))), new Method(DEFAULT, "thisString", Type.STRING, asList(new MethodParam("s", Type.STRING))), new Method(STATIC, "staticName", Type.STRING, asList(new MethodParam("c", colorType), new MethodParam("c2", colorType), new MethodParam("s", Type.STRING)))), emptyList())); val choices = asList(new Case("White", emptyList()), new Case("Black", emptyList()), new Case("RGB", asList(new CaseParam("r", new Type("int"), false), new CaseParam("g", new Type("int"), false), new CaseParam("b", new Type("int"), false)))); assertEquals("boolean equals(p1.p2.Color, java.lang.Object)\n" + "java.lang.String toString(p1.p2.Color)\n" + "int hashCode(p1.p2.Color)\n" + "java.lang.String thisMethod(p1.p2.Color, p1.p2.Color, java.lang.String)\n" + "java.lang.String thisString(java.lang.String)\n" + "static java.lang.String staticName(p1.p2.Color, p1.p2.Color, java.lang.String)", target.spec.methods.stream().map(m -> m.signature).collect(joining("\n"))); assertEquals("public java.util.Map<java.lang.String, java.util.Map<java.lang.String, functionalj.types.choice.generator.model.CaseParam>> __getSchema() {\n" + " return getChoiceSchema();\n" + "}\n" + "\n" + "private final transient ColorFirstSwitch __switch = new ColorFirstSwitch(this);\n" + "@Override public ColorFirstSwitch match() {\n" + " return __switch;\n" + "}\n" + "\n" + "\n" + "", new TargetTypeGeneral(target, choices).lines().stream().filter(Objects::nonNull).collect(Collectors.joining("\n"))); assertEquals("public boolean equals(java.lang.Object obj) {\n" + " return __spec.equals(Self.wrap(this), obj);\n" + "}\n" + "public java.lang.String toString() {\n" + " return __spec.toString(Self.wrap(this));\n" + "}\n" + "public int hashCode() {\n" + " return __spec.hashCode(Self.wrap(this));\n" + "}\n" + "public java.lang.String thisMethod(p1.p2.Color c2, java.lang.String s) {\n" + " return __spec.thisMethod(Self.wrap(this), Self.wrap(c2), s);\n" + "}\n" + "public java.lang.String thisString(java.lang.String s) {\n" + " return __spec.thisString(s);\n" + "}\n" + "public static java.lang.String staticName(p1.p2.Color c, p1.p2.Color c2, java.lang.String s) {\n" + " return p1.p2.ColorSpec.staticName(c, c2, s);\n" + "}", new SourceMethod(target).lines().stream().filter(Objects::nonNull).collect(Collectors.joining("\n"))); } @Test public void testSubClassDefinition_withPublicField() { val sourceType = new Type("p1.p2", null, "Next", asList(new Generic("D"))); val target = new TargetClass(new SourceSpec("Coroutine", sourceType, "spec", true, null, Serialize.To.NOTHING, asList(new Generic("D")), emptyList(), emptyList(), emptyList())); val sub = new SubClassDefinition(target, new Case("Next", asList(new CaseParam("next", new Type("functionalj.function", null, "Func1", asList(new Generic("D"), new Generic("Coroutine<D>"))), false)))); val lines = sub.lines().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")); assertEquals("public static final class Next<D> extends Coroutine<D> {\n" + " public static final Next.NextLens<Next> theNext = new Next.NextLens<>(\"theNext\", LensSpec.of(Next.class));\n" + " public static final Next.NextLens<Next> eachNext = theNext;\n" + " public Func1<D,Coroutine<D>> next;\n" + " private Next(Func1<D,Coroutine<D>> next) {\n" + " this.next = $utils.notNull(next);\n" + " }\n" + " public Func1<D,Coroutine<D>> next() { return next; }\n" + " public Next<D> withNext(Func1<D,Coroutine<D>> next) { return new Next<D>(next); }\n" + " public static class NextLens<HOST> extends ObjectLensImpl<HOST, Coroutine.Next> {\n" + " \n" + " public final ObjectLens<HOST, Object> next = (ObjectLens)createSubLens(\"next\", Coroutine.Next::next, Coroutine.Next::withNext, ObjectLens::of);\n" + " \n" + " public NextLens(String name, LensSpec<HOST, Coroutine.Next> spec) {\n" + " super(name, spec);\n" + " }\n" + " \n" + " }\n" + " public java.util.Map<String, Object> __toMap() {\n" + " java.util.Map<String, Object> map = new java.util.HashMap<>();\n" + " map.put(\"__tagged\", $utils.toMapValueObject(\"Next\"));\n" + " map.put(\"next\", this.next);\n" + " return map;\n" + " }\n" + " static private functionalj.map.FuncMap<String, functionalj.types.choice.generator.model.CaseParam> __schema__ = functionalj.map.FuncMap.<String, functionalj.types.choice.generator.model.CaseParam>newMap()\n" + " .with(\"next\", new functionalj.types.choice.generator.model.CaseParam(\"next\", new functionalj.types.Type(\"functionalj.function\", null, \"Func1\", java.util.Arrays.asList(new functionalj.types.Generic(\"D\", \"D\", java.util.Arrays.asList(new functionalj.types.Type(null, null, \"D\", java.util.Collections.emptyList()))), new functionalj.types.Generic(\"Coroutine<D>\", \"Coroutine<D>\", java.util.Arrays.asList(new functionalj.types.Type(null, null, \"Coroutine<D>\", java.util.Collections.emptyList()))))), false, null))\n" + " .build();\n" + " public static java.util.Map<String, functionalj.types.choice.generator.model.CaseParam> getCaseSchema() {\n" + " return __schema__;\n" + " }\n" + " public static Next caseFromMap(java.util.Map<String, ? extends Object> map) {\n" + " return Next(\n" + " (Func1<D, Coroutine<D>>)$utils.extractPropertyFromMap(Next.class, Func1.class, map, __schema__, \"next\")\n" + " );\n" + " }\n" + "}", lines); } }
c7005e3e650722144ceddff54b32b6177f6a1d33
54e24affa81b419bd63bfabf7101a00af88a7638
/app/src/main/java/com/example/aaron/asynktask/MainActivity.java
0008bf43261a1fe64dc60034d69703c9348f29a3
[]
no_license
AaronRevilla/FireFlies.AsynkTask
e1f5a76dd8ffdf45d6e4d14170b4407ab110b147
7aa6ab55b0df873aae4d42dca0ff38b1b4e54c6a
refs/heads/master
2021-01-12T13:58:12.699395
2016-09-26T15:55:28
2016-09-26T15:55:28
69,257,276
0
0
null
null
null
null
UTF-8
Java
false
false
2,565
java
package com.example.aaron.asynktask; import android.os.AsyncTask; import android.support.v4.text.TextDirectionHeuristicCompat; import android.support.v4.view.AsyncLayoutInflater; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import org.w3c.dom.Text; public class MainActivity extends AppCompatActivity { TextView tv; TextView tv2; int idx = 10; boolean taskRunning = false; Task2 task2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = ((TextView) findViewById(R.id.textView)); tv2 = ((TextView) findViewById(R.id.textView2)); task2 = new Task2(); } public void goButton(View view) { startThread(); } public void startThread(){ tv.setText("Working ..."); //Execute a thread in serial way //new MFAT().execute(idx); //Execute a thread in parallel way taskRunning = true; task2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Object[]{idx, tv, tv2}); idx++; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if(taskRunning){ task2.cancel(true); } outState.putBoolean("key", taskRunning); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); taskRunning = savedInstanceState.getBoolean("key", false); if(taskRunning){ startThread(); } } /* class MFAT extends AsyncTask<Integer, Integer, String>{ @Override protected String doInBackground(Integer... integer) {//Void ... it equals to Void[] for(int i = 1; i < integer[0]*10; i++) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } publishProgress(i); } return "Done "+ integer[0]; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); tv.setText(s); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); tv2.setText(values[0].toString()); } } */ }
2e058a21812912f9da21d25281ab694a28595828
5b3de1ddc577663a6cf0338f33320f5c1a4d8f79
/src/main/java/webbanvali/repository/BinhLuanRepository.java
2b6f7dd2522959c97d966a1a33d1cec1e07ea1c7
[]
no_license
kage1011/WebBanHang
3d7d23442bfe71bbcb0bb21cde255f3b4ae67169
8390216f19fb7744896b9aa2f80cf28ebe1ba514
refs/heads/main
2023-07-29T05:34:48.231602
2021-08-22T15:36:55
2021-08-22T15:36:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
953
java
package webbanvali.repository; import java.util.List; import java.util.Optional; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import webbanvali.entity.BinhLuan; import webbanvali.entity.BinhLuan_PK; import webbanvali.entity.HoaDon; import webbanvali.entity.Vali; public interface BinhLuanRepository extends JpaRepository<BinhLuan, BinhLuan_PK> { // lấy tất cả comment theo email cua nguoi dung List<BinhLuan> findAllByNguoiDungEmail(String email); // tìm comment theo valiID va nguoiDungId @Query(value = "select count(*) from binh_luan\r\n" + "where day(thoi_gian_binh_luan) = day(now())\r\n" + "and month(thoi_gian_binh_luan) = month(now())\r\n" + "and year(thoi_gian_binh_luan) = year(now())", nativeQuery = true) int getSoBinhLuanMoiNhat(); }
069a1d46baee4ec29c6966ebb45164af5f0f5fe3
3afa3b8411c2901b9f91fce6f2f8dafefeaf489b
/ambassadorsdk/src/main/java/com/ambassador/ambassadorsdk/internal/factories/ResourceFactory.java
78f4802775f4752f1bbb35f182e00965db9f7f25
[]
no_license
AmbassadorGraveyard/ambassador-android-sdk
3e3a7a06a79f69f4157d25228c30911fd83c3867
a02a246e5874a2e8566fa52424c00d6211f78e77
refs/heads/master
2022-06-18T16:06:01.032547
2018-12-21T21:21:31
2018-12-21T21:21:31
39,512,931
0
0
null
null
null
null
UTF-8
Java
false
false
558
java
package com.ambassador.ambassadorsdk.internal.factories; import android.support.annotation.ColorRes; import android.support.annotation.StringRes; import com.ambassador.ambassadorsdk.internal.utils.res.ColorResource; import com.ambassador.ambassadorsdk.internal.utils.res.StringResource; public final class ResourceFactory { public static ColorResource getColor(@ColorRes int resId) { return new ColorResource(resId); } public static StringResource getString(@StringRes int resId) { return new StringResource(resId); } }
e3f434c299474263b089cc0405ede472e3ef1756
3a9a6ff168829781efc158f9c0553ef3cd88f3d4
/src/main/java/fi/budokwai/isoveli/malli/validointi/UniikkiHenkilö.java
4b61e56fc2d3c58a0dccafb4e815b304628f86e1
[]
no_license
nickarls/Isoveli
1d43f79f694d4ec5a97f16fa0cf58835e69230c4
9f5e15ae0f6b880ea579a8bc6711ccea9cf825a8
refs/heads/master
2016-09-06T12:34:06.981606
2015-08-06T06:42:57
2015-08-06T06:42:57
24,055,007
0
0
null
null
null
null
ISO-8859-2
Java
false
false
615
java
package fi.budokwai.isoveli.malli.validointi; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Documented @Constraint(validatedBy = UniikkiHenkilöValidator.class) @Target(TYPE) @Retention(RUNTIME) public @interface UniikkiHenkilö { String message() default ""; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
0b820b81fec480369396548f8d8a516dd45ab5ad
f02bcbb187df5a697d6893308444244b1b84bed3
/app/src/test/java/com/example/clockbmd/ExampleUnitTest.java
24812b8c4e7f1578c2a1b0477ff3f147286a6ffd
[]
no_license
bmd0219/SpiderInductions-AppDevNative-Task1
9a3dc67f1f1080df4ee326a09a3ecc12318f08ff
a482ec8ca52c5fc0be156e207b21cd3b5f096946
refs/heads/master
2022-12-19T02:05:28.293408
2020-09-11T13:44:26
2020-09-11T13:44:26
289,717,726
0
0
null
null
null
null
UTF-8
Java
false
false
381
java
package com.example.clockbmd; 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); } }
999c770dff47ac4b25d33a74518152fa1bc715f5
47ec8722c98292ce33e98486fb3af6c6fd3f514a
/src/swu/zhj/util/DateDown.java
2a2e260259c9ed974024aedeccd98552f3dcab67
[]
no_license
zhuhaojie-cloud/studentservice
5b1b26d9884a47c7345da159703f3e01e9f10ce9
cb214a09ddb165ebdb5de1021d5e7831a2b0d791
refs/heads/master
2022-04-21T00:16:42.826593
2020-04-17T08:29:11
2020-04-17T08:29:11
254,530,602
0
1
null
null
null
null
GB18030
Java
false
false
965
java
package swu.zhj.util; import java.util.Calendar; import java.util.Date; public class DateDown { //倒计时,返回剩余时间 static int time = 60 * 60 * 60; static Calendar c; static long endTime; static Date date; static long startTime; static long midTime; private static void time1() { c = Calendar.getInstance(); c.set(2019, 3,22, 19, 0, 0);// 注意月份的设置,0-11表示1-12月 endTime = c.getTimeInMillis(); date = new Date(); startTime = date.getTime(); midTime = (endTime - startTime) / 1000; while (time > 0) { time--; try { Thread.sleep(1000); int hh = time / 60 / 60 % 60; int mm = time / 60 % 60; int ss = time % 60; System.out.println("还剩" + hh + "小时" + mm + "分钟" + ss + "秒"); } catch (InterruptedException e) { e.printStackTrace(); } } } }
fa690e9e08c6c1dffe3d72ecc410eea26a66d6d6
33a63a183246febbb4e3813441067038777c403d
/atlas-update/src/main/java/com/taobao/atlas/dex/util/ExceptionWithContext.java
a4213636e2ce2dcf8538bbfc432b6d893916589b
[ "Apache-2.0" ]
permissive
wwjiang007/atlas
95117cc4d095d20e6988fc2134c0899cb54abcc9
afaa61796bb6b26fe373e31a4fc57fdd16fa0a44
refs/heads/master
2023-04-13T22:41:18.035080
2021-04-24T09:05:41
2021-04-24T09:05:41
115,571,324
0
0
Apache-2.0
2021-04-24T09:05:42
2017-12-28T01:21:17
Java
UTF-8
Java
false
false
4,097
java
/* * Copyright (C) 2007 The Android Open Source Project * * 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.taobao.atlas.dex.util; import java.io.PrintStream; import java.io.PrintWriter; /** * Exception which carries around structured context. */ public class ExceptionWithContext extends RuntimeException { /** {@code non-null;} human-oriented context of the exception */ private StringBuffer context; /** * Augments the given exception with the given context, and return the * result. The result is either the given exception if it was an * {@link ExceptionWithContext}, or a newly-constructed exception if it * was not. * * @param ex {@code non-null;} the exception to augment * @param str {@code non-null;} context to add * @return {@code non-null;} an appropriate instance */ public static ExceptionWithContext withContext(Throwable ex, String str) { ExceptionWithContext ewc; if (ex instanceof ExceptionWithContext) { ewc = (ExceptionWithContext) ex; } else { ewc = new ExceptionWithContext(ex); } ewc.addContext(str); return ewc; } /** * Constructs an instance. * * @param message human-oriented message */ public ExceptionWithContext(String message) { this(message, null); } /** * Constructs an instance. * * @param cause {@code null-ok;} exception that caused this one */ public ExceptionWithContext(Throwable cause) { this(null, cause); } /** * Constructs an instance. * * @param message human-oriented message * @param cause {@code null-ok;} exception that caused this one */ public ExceptionWithContext(String message, Throwable cause) { super((message != null) ? message : (cause != null) ? cause.getMessage() : null, cause); if (cause instanceof ExceptionWithContext) { String ctx = ((ExceptionWithContext) cause).context.toString(); context = new StringBuffer(ctx.length() + 200); context.append(ctx); } else { context = new StringBuffer(200); } } /** {@inheritDoc} */ @Override public void printStackTrace(PrintStream out) { super.printStackTrace(out); out.println(context); } /** {@inheritDoc} */ @Override public void printStackTrace(PrintWriter out) { super.printStackTrace(out); out.println(context); } /** * Adds a line of context to this instance. * * @param str {@code non-null;} new context */ public void addContext(String str) { if (str == null) { throw new NullPointerException("str == null"); } context.append(str); if (!str.endsWith("\n")) { context.append('\n'); } } /** * Gets the context. * * @return {@code non-null;} the context */ public String getContext() { return context.toString(); } /** * Prints the message and context. * * @param out {@code non-null;} where to print to */ public void printContext(PrintStream out) { out.println(getMessage()); out.print(context); } /** * Prints the message and context. * * @param out {@code non-null;} where to print to */ public void printContext(PrintWriter out) { out.println(getMessage()); out.print(context); } }
99015021b288e23ae0e4c36cab2a201f2b1af065
f0d25d83176909b18b9989e6fe34c414590c3599
/app/src/main/java/com/tencent/kgvmp/e/g.java
c3a0e6f06ec1f74d65b9596f8790a55fe098d112
[]
no_license
lycfr/lq
e8dd702263e6565486bea92f05cd93e45ef8defc
123914e7c0d45956184dc908e87f63870e46aa2e
refs/heads/master
2022-04-07T18:16:31.660038
2020-02-23T03:09:18
2020-02-23T03:09:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
331
java
package com.tencent.kgvmp.e; import com.amazonaws.services.s3.internal.Constants; public class g { public static boolean a(String str) { return str == null || str.compareTo(Constants.NULL_VERSION_ID) == 0; } public static boolean b(String str) { return str == null || str.compareTo("") == 0; } }
e14264dc0d17653dfe9638fb10b4ca606c33e2b7
966cee64ad37e7f29da56e0863ce8d4eac9d09cb
/src/main/java/com/nino/chat/server/context/ServerContext.java
df8954f175b8c9bbcdd55cbfcaaf0d3affa340dc
[]
no_license
jack199322zx/chatserver
ca1f1358cca06f4fea9880ff0972e5eb6ca4efd6
6e520a325576fe3334b108eb7af12cfd1b680322
refs/heads/master
2020-03-28T13:36:50.103304
2018-09-12T03:27:15
2018-09-12T03:27:15
148,410,832
1
0
null
null
null
null
UTF-8
Java
false
false
228
java
package com.nino.chat.server.context; import com.nino.chat.server.model.Message; /** * @author ss * @date 2018/9/11 13:57 */ public interface ServerContext { void startUp(); void publishMessage(Message message); }
15023a8e08ebf2786718546ad75920a14281a5ed
6fc1240c9ae2a7b3d8eead384668e1f4b58d47da
/assignments/suntaj/unit3/HW15JTable/HW15TABLE/src/ec/edu/espe/jtable/view/StudentJtable.java
b4baec08873e36513953602cbc6608e4cd933c36
[]
no_license
elascano/ESPE202105-OOP-TC-3730
38028e870d4de004cbbdf82fc5f8578126f8ca32
4275a03d410cf6f1929b1794301823e990fa0ef4
refs/heads/main
2023-08-09T13:24:26.898865
2021-09-13T17:08:10
2021-09-13T17:08:10
371,089,640
3
0
null
null
null
null
UTF-8
Java
false
false
8,411
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 ec.edu.espe.jtable.view; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.Mongo; import java.net.UnknownHostException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.table.DefaultTableModel; /** * * @author Gabriela Sunta Future'sProgrammersTech ESPE- DCCO */ public class StudentJtable extends javax.swing.JFrame { DB DataBase; DBCollection db; BasicDBObject document = new BasicDBObject(); DefaultTableModel tb = new DefaultTableModel(); /** * Creates new form StudentJtable */ public StudentJtable() { initComponents(); try { Mongo mongo; mongo = new Mongo("localhost", 27017); DataBase = mongo.getDB("studentdatabase"); db = DataBase.getCollection("students"); System.out.println("successful connection"); } catch (UnknownHostException ex) { Logger.getLogger(StudentJtable.class.getName()).log(Level.SEVERE, null, ex); } } /** * 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() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); btnOK = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); tbStudent = new javax.swing.JTable(); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 24)); // NOI18N jLabel1.setText("Student Information"); btnOK.setText("OK"); btnOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnOKActionPerformed(evt); } }); tbStudent.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); jScrollPane2.setViewportView(tbStudent); 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.LEADING) .addGroup(layout.createSequentialGroup() .addGap(36, 36, 36) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 743, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(291, 291, 291) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addGap(368, 368, 368) .addComponent(btnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(208, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(35, 35, 35) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(45, 45, 45) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(59, 59, 59) .addComponent(btnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(67, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed // TODO add your handling code here: DBCursor cursor1 = db.find(); DBCursor cursor2 = db.find(); DBCursor cursor3 = db.find(); DBCursor cursor4 = db.find(); DBCursor cursor5 = db.find(); DBCursor cursor6= db.find(); DBCursor cursor7 = db.find(); DBCursor cursor8 = db.find(); DBCursor cursor9 = db.find(); tb.addColumn("ID"); tb.addColumn("Name"); tb.addColumn("University name"); tb.addColumn("Career"); tb.addColumn("Subject"); tb.addColumn("Nrc"); tb.addColumn("Student Code"); tb.addColumn("Gender"); tb.addColumn("Marital Status"); while(cursor1.hasNext()){ tb.addRow(new Object[] {cursor1.next().get("ID"),cursor2.next().get("Name"),cursor3.next().get("University name"),cursor4.next().get("Career"),cursor5.next().get("Subject"),cursor6.next().get("Nrc"),cursor7.next().get("Student Code"),cursor8.next().get("Gender"),cursor9.next().get("Marital Status")}); tbStudent.setModel(tb); } }//GEN-LAST:event_btnOKActionPerformed /** * @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(StudentJtable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(StudentJtable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(StudentJtable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(StudentJtable.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 StudentJtable().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnOK; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable1; private javax.swing.JTable tbStudent; // End of variables declaration//GEN-END:variables }
4dde757bfb6a11dfb3182daafa77336805587139
6bc225515a0b5eaa5128bb39895c19c1b51eb0d9
/src/main/java/com/github/fastjdbc/bean/ConnectionPool.java
96cf0a13e17e1787d884306c351c8d01f28716d1
[ "Apache-2.0" ]
permissive
xiewenda/fastjdbc
fa92e05586d07c9f30c27c229ada807788a64964
7628b2e46887d6280f44421549577a64e62e9c32
refs/heads/master
2020-07-07T21:20:33.489672
2019-08-20T15:31:27
2019-08-20T15:31:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,811
java
/* * Copyright 2018 fastjdbc * * 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.github.fastjdbc.bean; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; /** * <p>A connection pool class.</p> * <p>You should call {@link #init(DataSource, Map, Logger)} method to init the global connection pool * on system start only one time.</p> * * @since 1.0 */ public class ConnectionPool { /** * The logger object for print log. * * @since 2.0 */ private static Logger LOGGER; /** * Master database connection pool. * * @since 1.0 */ private static DataSource MASTER_POOL; /** * Default slave database connection pool. * * @since 1.0 */ private static DataSource DEFAULT_SLAVE_POOL; /** * Slave databases connection pool map, key is pool name, value is {@link DataSource} object. * * @since 1.0 */ private static Map<String, DataSource> POOL_MAP = new HashMap<>(); /** * <p>Initialization method for init global connection pool.</p> * * @param masterPool master datasource * @param slavePoolMap map of slave datasource, key is slave pool name, value is datasource object * @param logger logger object for print log * @since 1.0 */ public static synchronized void init(DataSource masterPool, Map<String, DataSource> slavePoolMap, Logger logger) { if (MASTER_POOL == null || DEFAULT_SLAVE_POOL == null) { if (masterPool == null) { throw new RuntimeException("master pool must not null"); } MASTER_POOL = masterPool; if (slavePoolMap != null && !slavePoolMap.isEmpty()) { DEFAULT_SLAVE_POOL = slavePoolMap.values().iterator().next(); POOL_MAP.putAll(slavePoolMap); } else { DEFAULT_SLAVE_POOL = masterPool; } LOGGER = logger; } } /** * Get the logger object to print log. * * @since 2.0 */ public static Logger getLogger() { return LOGGER; } /** * <p>Get slave datasource object by given pool name.</p> * <p>When pool name is {@code null} or not in {@link #POOL_MAP}, {@link #DEFAULT_SLAVE_POOL} will be returned.</p> * * @param poolName the pool name * @return slave pool datasource object * @since 1.0 */ private static DataSource getSlaveDataSource(String poolName) { return POOL_MAP.getOrDefault(poolName, DEFAULT_SLAVE_POOL); } /** * Close the given connection without commit. * * @param connection the connection to close * @throws SQLException exception when close failed * @since 1.0 */ private static void close(Connection connection) throws SQLException { if (connection != null) { connection.close(); connection = null; } } /** * Commit the connection and then close. * * @param connection the connection to close * @throws SQLException exception when close failed * @since 1.0 */ private static void commitAndClose(Connection connection) throws SQLException { if (connection != null) { try { connection.commit(); } finally { close(connection); } } } /** * <p>Get {@link ConnectionBean} object by the given slave pool name.</p> * <p>The write connection is a connection from master datasource.</p> * <p>The read connection is a connection from slave datasource which pool name is the given pool name.</p> * <p>When slave pool not found, a connection from default slave pool will be used as read connection.</p> * * @param slavePoolName slave pool name * @return an object of {@link ConnectionBean} * @throws SQLException exception when get connection failed * @since 1.0 */ public static ConnectionBean getConnectionBean(String slavePoolName) throws SQLException { Connection writeConnection = MASTER_POOL.getConnection(); writeConnection.setAutoCommit(false); return new ConnectionBean(writeConnection, getSlaveDataSource(slavePoolName).getConnection()); } /** * Close the write connection with commit and close the read connection without commit. * * @param connection the connection to close * @throws SQLException exception when close failed * @since 1.0 */ public static void closeConnectionBean(ConnectionBean connection) throws SQLException { if (connection != null) { commitAndClose(connection.getWriteConnection()); close(connection.getReadConnection()); } } /** * Roll back the write connection when exception occurred and close both connection without commit. * * @param connection the connection to roll back * @throws SQLException exception when roll back failed * @since 1.0 */ public static void rollbackConnectionBean(ConnectionBean connection) throws SQLException { if (connection != null && connection.getWriteConnection() != null) { try { connection.getWriteConnection().rollback(); } finally { close(connection.getWriteConnection()); close(connection.getReadConnection()); } } } /** * <p>Close the {@link ResultSet} object.</p> * <p>When {@code com.github.fastjdbc.common.BaseDao#executeSelectReturnResultSet(ConnectionBean, String, List)} called, * this method should be called to close {@link ResultSet} at last.</p> * * @param rs {@link ResultSet} object to close * @throws SQLException exception when close failed * @since 1.0 */ public static void close(ResultSet rs) throws SQLException { if (rs != null) { Statement stmt = rs.getStatement(); rs.close(); stmt.close(); rs = null; stmt = null; } } }
4eaacc887ca3954d6b2d621b30ad45eb71e8d560
a6e2cd9ea01bdc5cfe58acce25627786fdfe76e9
/src/main/java/com/alipay/api/domain/FileSignature.java
26ff4c475b9c19e7787db14a28257d1c0e7e00e0
[ "Apache-2.0" ]
permissive
cc-shifo/alipay-sdk-java-all
38b23cf946b73768981fdeee792e3dae568da48c
938d6850e63160e867d35317a4a00ed7ba078257
refs/heads/master
2022-12-22T14:06:26.961978
2020-09-23T04:00:10
2020-09-23T04:00:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,008
java
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 签约文件签章描述信息 * * @author auto create * @since 1.0, 2017-12-20 15:24:35 */ public class FileSignature extends AlipayObject { private static final long serialVersionUID = 2384165219121559412L; /** * 签约主体证件号,关联principal对象 */ @ApiField("cert_no") private String certNo; /** * 图章id/图章模板id */ @ApiField("seal_id") private String sealId; /** * 签章位置描述 */ @ApiField("seal_position") private SealPosition sealPosition; /** * 电子图章类型 1 : 图章模板自动合成 2 : 托管图章编号 */ @ApiField("seal_type") private Long sealType; /** * 签约原因描述,可展示在PDF签名区 */ @ApiField("sign_reason") private String signReason; /** * 电子签章类型 1:仅数字证书文档签名 2:仅图章 3:数字证书文档签名,加盖图章 */ @ApiField("signature_type") private Long signatureType; public String getCertNo() { return this.certNo; } public void setCertNo(String certNo) { this.certNo = certNo; } public String getSealId() { return this.sealId; } public void setSealId(String sealId) { this.sealId = sealId; } public SealPosition getSealPosition() { return this.sealPosition; } public void setSealPosition(SealPosition sealPosition) { this.sealPosition = sealPosition; } public Long getSealType() { return this.sealType; } public void setSealType(Long sealType) { this.sealType = sealType; } public String getSignReason() { return this.signReason; } public void setSignReason(String signReason) { this.signReason = signReason; } public Long getSignatureType() { return this.signatureType; } public void setSignatureType(Long signatureType) { this.signatureType = signatureType; } }
670f5dc9e8f59da43ffc57ce18e51c51253a92a6
0c99b4f3e4e5fd8dd701e768b6e47a6f3e95518d
/app/src/main/java/com/eclairios/CrossComps/AffiliteTeamManager/MembersScreenOfCoManagersActivity.java
e88b7bbcbdaa532460192a91c5048bd07a1704b1
[]
no_license
awaisali-hub/CrossCompApplication
543e12beb97a1a3199db4b4abb94225de0a065d8
3f1356e82745adbd3a77e5af693af77b6fd591bf
refs/heads/master
2023-04-14T22:09:00.868392
2021-04-14T09:50:08
2021-04-14T09:50:08
338,239,086
0
0
null
null
null
null
UTF-8
Java
false
false
477
java
package com.eclairios.CrossComps.AffiliteTeamManager; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import com.eclairios.CrossComps.R; public class MembersScreenOfCoManagersActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_members_screen_of_co_managers); getSupportActionBar().hide(); } }
eda456c068d51f487cb24fdc1d74ee29667bfe42
dfdf5aab6312d7ff06e7d241815c254f81a06299
/src/main/java/com/poo/flf/repositories/FilmeRepository.java
e8b9609162736d2398684b04e74eb147746f08e9
[]
no_license
diegobarrosflf/poo-projeto-spring
b8dae2d6fec34dede1132078ae8a757cb4dbeefe
b692789ee8bd9607aa4d43d64c232ec5698e2a24
refs/heads/master
2022-11-07T00:25:17.325805
2020-06-23T00:40:57
2020-06-23T00:40:57
272,571,303
0
0
null
null
null
null
UTF-8
Java
false
false
207
java
package com.poo.flf.repositories; import org.springframework.data.jpa.repository.JpaRepository; import com.poo.flf.domain.Filme; public interface FilmeRepository extends JpaRepository<Filme, Integer>{ }
321a32f93878b6d0b41ee7e25341100e38066d44
4376ac2bf8805d7b0846887155a0aa96440ba21f
/src-gen/ec/com/sidesoft/secondary/accounting/SSACCTJournalLine.java
c529ab4bb2b8c1b0d15ee48a0087f13ed8104790
[]
no_license
rarc88/innovativa
eebb82f4137a70210be5fdd94384c482f3065019
77ab7b4ebda8be9bd02066e5c40b34c854cc49c7
refs/heads/master
2022-08-22T10:58:22.619152
2020-05-22T21:43:22
2020-05-22T21:43:22
266,206,020
0
1
null
null
null
null
UTF-8
Java
false
false
17,571
java
/* ************************************************************************* * The contents of this file are subject to the Openbravo Public License * Version 1.1 (the "License"), being the Mozilla Public License * Version 1.1 with a permitted attribution clause; you may not use this * file except in compliance with the License. You may obtain a copy of * the License at http://www.openbravo.com/legal/license.html * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * The Original Code is Openbravo ERP. * The Initial Developer of the Original Code is Openbravo SLU * All portions are Copyright (C) 2008-2014 Openbravo SLU * All Rights Reserved. * Contributor(s): ______________________________________. ************************************************************************ */ package ec.com.sidesoft.secondary.accounting; import com.sidesoft.flopec.budget.data.SFBBudgetCertLine; import java.math.BigDecimal; import java.util.Date; import org.openbravo.base.structure.ActiveEnabled; import org.openbravo.base.structure.BaseOBObject; import org.openbravo.base.structure.ClientEnabled; import org.openbravo.base.structure.OrganizationEnabled; import org.openbravo.base.structure.Traceable; import org.openbravo.model.ad.access.User; import org.openbravo.model.ad.system.Client; import org.openbravo.model.common.businesspartner.BusinessPartner; import org.openbravo.model.common.currency.Currency; import org.openbravo.model.common.enterprise.Organization; import org.openbravo.model.common.plm.Product; import org.openbravo.model.common.uom.UOM; import org.openbravo.model.financialmgmt.accounting.Costcenter; import org.openbravo.model.financialmgmt.accounting.UserDimension1; import org.openbravo.model.financialmgmt.accounting.UserDimension2; import org.openbravo.model.financialmgmt.accounting.coa.ElementValue; import org.openbravo.model.financialmgmt.assetmgmt.Asset; import org.openbravo.model.financialmgmt.gl.GLItem; import org.openbravo.model.financialmgmt.payment.DebtPayment; import org.openbravo.model.financialmgmt.payment.FIN_FinancialAccount; import org.openbravo.model.financialmgmt.payment.FIN_Payment; import org.openbravo.model.financialmgmt.payment.FIN_PaymentMethod; import org.openbravo.model.financialmgmt.tax.TaxRate; import org.openbravo.model.financialmgmt.tax.Withholding; import org.openbravo.model.marketing.Campaign; import org.openbravo.model.materialmgmt.cost.ABCActivity; import org.openbravo.model.sales.SalesRegion; /** * Entity class for entity SSACCT_JournalLine (stored in table SSACCT_JournalLine). * * NOTE: This class should not be instantiated directly. To instantiate this * class the {@link org.openbravo.base.provider.OBProvider} should be used. */ public class SSACCTJournalLine extends BaseOBObject implements Traceable, ClientEnabled, OrganizationEnabled, ActiveEnabled { private static final long serialVersionUID = 1L; public static final String TABLE_NAME = "SSACCT_JournalLine"; public static final String ENTITY_NAME = "SSACCT_JournalLine"; public static final String PROPERTY_ID = "id"; public static final String PROPERTY_CLIENT = "client"; public static final String PROPERTY_ORGANIZATION = "organization"; public static final String PROPERTY_ACTIVE = "active"; public static final String PROPERTY_CREATIONDATE = "creationDate"; public static final String PROPERTY_CREATEDBY = "createdBy"; public static final String PROPERTY_UPDATED = "updated"; public static final String PROPERTY_UPDATEDBY = "updatedBy"; public static final String PROPERTY_SSACCTJOURNAL = "ssacctJournal"; public static final String PROPERTY_LINENO = "lineNo"; public static final String PROPERTY_GENERATED = "generated"; public static final String PROPERTY_DESCRIPTION = "description"; public static final String PROPERTY_FOREIGNCURRENCYDEBIT = "foreignCurrencyDebit"; public static final String PROPERTY_FOREIGNCURRENCYCREDIT = "foreignCurrencyCredit"; public static final String PROPERTY_CURRENCY = "currency"; public static final String PROPERTY_CURRENCYRATETYPE = "currencyRateType"; public static final String PROPERTY_RATE = "rate"; public static final String PROPERTY_ACCOUNTINGDATE = "accountingDate"; public static final String PROPERTY_DEBIT = "debit"; public static final String PROPERTY_CREDIT = "credit"; public static final String PROPERTY_UOM = "uOM"; public static final String PROPERTY_QUANTITY = "quantity"; public static final String PROPERTY_ACCOUNTINGCOMBINATION = "accountingCombination"; public static final String PROPERTY_PAYMENT = "payment"; public static final String PROPERTY_WITHHOLDING = "withholding"; public static final String PROPERTY_TAX = "tax"; public static final String PROPERTY_STDIMENSION = "stDimension"; public static final String PROPERTY_NDDIMENSION = "ndDimension"; public static final String PROPERTY_SALESCAMPAIGN = "salesCampaign"; public static final String PROPERTY_PROJECT = "project"; public static final String PROPERTY_ACTIVITY = "activity"; public static final String PROPERTY_SALESREGION = "salesRegion"; public static final String PROPERTY_PRODUCT = "product"; public static final String PROPERTY_BUSINESSPARTNER = "businessPartner"; public static final String PROPERTY_ASSET = "asset"; public static final String PROPERTY_COSTCENTER = "costCenter"; public static final String PROPERTY_RELATEDPAYMENT = "relatedPayment"; public static final String PROPERTY_FINANCIALACCOUNT = "financialAccount"; public static final String PROPERTY_FINPAYMENTMETHOD = "fINPaymentmethod"; public static final String PROPERTY_OPENITEMS = "openItems"; public static final String PROPERTY_GLITEM = "gLItem"; public static final String PROPERTY_PAYMENTDATE = "paymentDate"; public static final String PROPERTY_HASHCODE = "hashcode"; public static final String PROPERTY_SFBBUDGETCERTLINE = "sFBBudgetCertLine"; public static final String PROPERTY_AFFECTBUDGET = "affectbudget"; public static final String PROPERTY_ADDPAYMENT = "addpayment"; public static final String PROPERTY_GLITEMS = "gLItems"; public static final String PROPERTY_ISBUDGETED = "isbudgeted"; public static final String PROPERTY_AFFECTINCOMEBUDGET = "affectincomebudget"; public SSACCTJournalLine() { setDefaultValue(PROPERTY_ACTIVE, true); setDefaultValue(PROPERTY_GENERATED, false); setDefaultValue(PROPERTY_FOREIGNCURRENCYDEBIT, new BigDecimal(0)); setDefaultValue(PROPERTY_FOREIGNCURRENCYCREDIT, new BigDecimal(0)); setDefaultValue(PROPERTY_CURRENCYRATETYPE, "S"); setDefaultValue(PROPERTY_RATE, (long) 1); setDefaultValue(PROPERTY_DEBIT, new BigDecimal(0)); setDefaultValue(PROPERTY_CREDIT, new BigDecimal(0)); setDefaultValue(PROPERTY_QUANTITY, new BigDecimal(0)); setDefaultValue(PROPERTY_OPENITEMS, false); setDefaultValue(PROPERTY_AFFECTBUDGET, false); setDefaultValue(PROPERTY_ADDPAYMENT, true); setDefaultValue(PROPERTY_ISBUDGETED, false); setDefaultValue(PROPERTY_AFFECTINCOMEBUDGET, false); } @Override public String getEntityName() { return ENTITY_NAME; } public String getId() { return (String) get(PROPERTY_ID); } public void setId(String id) { set(PROPERTY_ID, id); } public Client getClient() { return (Client) get(PROPERTY_CLIENT); } public void setClient(Client client) { set(PROPERTY_CLIENT, client); } public Organization getOrganization() { return (Organization) get(PROPERTY_ORGANIZATION); } public void setOrganization(Organization organization) { set(PROPERTY_ORGANIZATION, organization); } public Boolean isActive() { return (Boolean) get(PROPERTY_ACTIVE); } public void setActive(Boolean active) { set(PROPERTY_ACTIVE, active); } public Date getCreationDate() { return (Date) get(PROPERTY_CREATIONDATE); } public void setCreationDate(Date creationDate) { set(PROPERTY_CREATIONDATE, creationDate); } public User getCreatedBy() { return (User) get(PROPERTY_CREATEDBY); } public void setCreatedBy(User createdBy) { set(PROPERTY_CREATEDBY, createdBy); } public Date getUpdated() { return (Date) get(PROPERTY_UPDATED); } public void setUpdated(Date updated) { set(PROPERTY_UPDATED, updated); } public User getUpdatedBy() { return (User) get(PROPERTY_UPDATEDBY); } public void setUpdatedBy(User updatedBy) { set(PROPERTY_UPDATEDBY, updatedBy); } public SSACCTJOURNAL getSsacctJournal() { return (SSACCTJOURNAL) get(PROPERTY_SSACCTJOURNAL); } public void setSsacctJournal(SSACCTJOURNAL ssacctJournal) { set(PROPERTY_SSACCTJOURNAL, ssacctJournal); } public Long getLineNo() { return (Long) get(PROPERTY_LINENO); } public void setLineNo(Long lineNo) { set(PROPERTY_LINENO, lineNo); } public Boolean isGenerated() { return (Boolean) get(PROPERTY_GENERATED); } public void setGenerated(Boolean generated) { set(PROPERTY_GENERATED, generated); } public String getDescription() { return (String) get(PROPERTY_DESCRIPTION); } public void setDescription(String description) { set(PROPERTY_DESCRIPTION, description); } public BigDecimal getForeignCurrencyDebit() { return (BigDecimal) get(PROPERTY_FOREIGNCURRENCYDEBIT); } public void setForeignCurrencyDebit(BigDecimal foreignCurrencyDebit) { set(PROPERTY_FOREIGNCURRENCYDEBIT, foreignCurrencyDebit); } public BigDecimal getForeignCurrencyCredit() { return (BigDecimal) get(PROPERTY_FOREIGNCURRENCYCREDIT); } public void setForeignCurrencyCredit(BigDecimal foreignCurrencyCredit) { set(PROPERTY_FOREIGNCURRENCYCREDIT, foreignCurrencyCredit); } public Currency getCurrency() { return (Currency) get(PROPERTY_CURRENCY); } public void setCurrency(Currency currency) { set(PROPERTY_CURRENCY, currency); } public String getCurrencyRateType() { return (String) get(PROPERTY_CURRENCYRATETYPE); } public void setCurrencyRateType(String currencyRateType) { set(PROPERTY_CURRENCYRATETYPE, currencyRateType); } public Long getRate() { return (Long) get(PROPERTY_RATE); } public void setRate(Long rate) { set(PROPERTY_RATE, rate); } public Date getAccountingDate() { return (Date) get(PROPERTY_ACCOUNTINGDATE); } public void setAccountingDate(Date accountingDate) { set(PROPERTY_ACCOUNTINGDATE, accountingDate); } public BigDecimal getDebit() { return (BigDecimal) get(PROPERTY_DEBIT); } public void setDebit(BigDecimal debit) { set(PROPERTY_DEBIT, debit); } public BigDecimal getCredit() { return (BigDecimal) get(PROPERTY_CREDIT); } public void setCredit(BigDecimal credit) { set(PROPERTY_CREDIT, credit); } public UOM getUOM() { return (UOM) get(PROPERTY_UOM); } public void setUOM(UOM uOM) { set(PROPERTY_UOM, uOM); } public BigDecimal getQuantity() { return (BigDecimal) get(PROPERTY_QUANTITY); } public void setQuantity(BigDecimal quantity) { set(PROPERTY_QUANTITY, quantity); } public ElementValue getAccountingCombination() { return (ElementValue) get(PROPERTY_ACCOUNTINGCOMBINATION); } public void setAccountingCombination(ElementValue accountingCombination) { set(PROPERTY_ACCOUNTINGCOMBINATION, accountingCombination); } public DebtPayment getPayment() { return (DebtPayment) get(PROPERTY_PAYMENT); } public void setPayment(DebtPayment payment) { set(PROPERTY_PAYMENT, payment); } public Withholding getWithholding() { return (Withholding) get(PROPERTY_WITHHOLDING); } public void setWithholding(Withholding withholding) { set(PROPERTY_WITHHOLDING, withholding); } public TaxRate getTax() { return (TaxRate) get(PROPERTY_TAX); } public void setTax(TaxRate tax) { set(PROPERTY_TAX, tax); } public UserDimension1 getStDimension() { return (UserDimension1) get(PROPERTY_STDIMENSION); } public void setStDimension(UserDimension1 stDimension) { set(PROPERTY_STDIMENSION, stDimension); } public UserDimension2 getNdDimension() { return (UserDimension2) get(PROPERTY_NDDIMENSION); } public void setNdDimension(UserDimension2 ndDimension) { set(PROPERTY_NDDIMENSION, ndDimension); } public Campaign getSalesCampaign() { return (Campaign) get(PROPERTY_SALESCAMPAIGN); } public void setSalesCampaign(Campaign salesCampaign) { set(PROPERTY_SALESCAMPAIGN, salesCampaign); } public Product getProject() { return (Product) get(PROPERTY_PROJECT); } public void setProject(Product project) { set(PROPERTY_PROJECT, project); } public ABCActivity getActivity() { return (ABCActivity) get(PROPERTY_ACTIVITY); } public void setActivity(ABCActivity activity) { set(PROPERTY_ACTIVITY, activity); } public SalesRegion getSalesRegion() { return (SalesRegion) get(PROPERTY_SALESREGION); } public void setSalesRegion(SalesRegion salesRegion) { set(PROPERTY_SALESREGION, salesRegion); } public Product getProduct() { return (Product) get(PROPERTY_PRODUCT); } public void setProduct(Product product) { set(PROPERTY_PRODUCT, product); } public BusinessPartner getBusinessPartner() { return (BusinessPartner) get(PROPERTY_BUSINESSPARTNER); } public void setBusinessPartner(BusinessPartner businessPartner) { set(PROPERTY_BUSINESSPARTNER, businessPartner); } public Asset getAsset() { return (Asset) get(PROPERTY_ASSET); } public void setAsset(Asset asset) { set(PROPERTY_ASSET, asset); } public Costcenter getCostCenter() { return (Costcenter) get(PROPERTY_COSTCENTER); } public void setCostCenter(Costcenter costCenter) { set(PROPERTY_COSTCENTER, costCenter); } public FIN_Payment getRelatedPayment() { return (FIN_Payment) get(PROPERTY_RELATEDPAYMENT); } public void setRelatedPayment(FIN_Payment relatedPayment) { set(PROPERTY_RELATEDPAYMENT, relatedPayment); } public FIN_FinancialAccount getFinancialAccount() { return (FIN_FinancialAccount) get(PROPERTY_FINANCIALACCOUNT); } public void setFinancialAccount(FIN_FinancialAccount financialAccount) { set(PROPERTY_FINANCIALACCOUNT, financialAccount); } public FIN_PaymentMethod getFINPaymentmethod() { return (FIN_PaymentMethod) get(PROPERTY_FINPAYMENTMETHOD); } public void setFINPaymentmethod(FIN_PaymentMethod fINPaymentmethod) { set(PROPERTY_FINPAYMENTMETHOD, fINPaymentmethod); } public Boolean isOpenItems() { return (Boolean) get(PROPERTY_OPENITEMS); } public void setOpenItems(Boolean openItems) { set(PROPERTY_OPENITEMS, openItems); } public GLItem getGLItem() { return (GLItem) get(PROPERTY_GLITEM); } public void setGLItem(GLItem gLItem) { set(PROPERTY_GLITEM, gLItem); } public Date getPaymentDate() { return (Date) get(PROPERTY_PAYMENTDATE); } public void setPaymentDate(Date paymentDate) { set(PROPERTY_PAYMENTDATE, paymentDate); } public String getHashcode() { return (String) get(PROPERTY_HASHCODE); } public void setHashcode(String hashcode) { set(PROPERTY_HASHCODE, hashcode); } public SFBBudgetCertLine getSFBBudgetCertLine() { return (SFBBudgetCertLine) get(PROPERTY_SFBBUDGETCERTLINE); } public void setSFBBudgetCertLine(SFBBudgetCertLine sFBBudgetCertLine) { set(PROPERTY_SFBBUDGETCERTLINE, sFBBudgetCertLine); } public Boolean isAffectbudget() { return (Boolean) get(PROPERTY_AFFECTBUDGET); } public void setAffectbudget(Boolean affectbudget) { set(PROPERTY_AFFECTBUDGET, affectbudget); } public Boolean isAddpayment() { return (Boolean) get(PROPERTY_ADDPAYMENT); } public void setAddpayment(Boolean addpayment) { set(PROPERTY_ADDPAYMENT, addpayment); } public GLItem getGLItems() { return (GLItem) get(PROPERTY_GLITEMS); } public void setGLItems(GLItem gLItems) { set(PROPERTY_GLITEMS, gLItems); } public Boolean isBudgeted() { return (Boolean) get(PROPERTY_ISBUDGETED); } public void setBudgeted(Boolean isbudgeted) { set(PROPERTY_ISBUDGETED, isbudgeted); } public Boolean isAffectincomebudget() { return (Boolean) get(PROPERTY_AFFECTINCOMEBUDGET); } public void setAffectincomebudget(Boolean affectincomebudget) { set(PROPERTY_AFFECTINCOMEBUDGET, affectincomebudget); } }
7b95a21916f02b038896b29cc5bf50cd1fe198b4
81a1aa5783c9db562448caf1808c5fb1e4280ea5
/Auxiliary/DragonAPIASMHandler.java
d2b784bd757db78db037c4360133edbb098a8406
[]
no_license
SirPersonJr/DragonAPI
98b2d3e61b29f2753a368960fd9b483bbb988f5f
ae90b4e70f7adc9695095f7e647cbdd66eb335e0
refs/heads/master
2021-01-17T15:53:31.229604
2016-05-17T04:23:50
2016-05-17T04:23:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,544
java
/******************************************************************************* * @author Reika Kalseki * * Copyright 2016 * * All rights reserved. * Distribution of the software in any form is only allowed with * explicit, prior permission from the owner. ******************************************************************************/ package Reika.DragonAPI.Auxiliary; import java.util.Map; import net.minecraft.launchwrapper.Launch; import Reika.DragonAPI.ASM.APIStripper; import Reika.DragonAPI.ASM.DependentMethodStripper; import Reika.DragonAPI.ASM.DragonAPIClassTransfomer; import Reika.DragonAPI.ASM.FMLItemBlockPatch; import Reika.DragonAPI.ASM.FluidNamePatch; import Reika.DragonAPI.ASM.InterfaceInjector; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; import cpw.mods.fml.relauncher.IFMLLoadingPlugin.SortingIndex; @SortingIndex(1001) @MCVersion("1.7.10") public class DragonAPIASMHandler implements IFMLLoadingPlugin { static { Launch.classLoader.addTransformerExclusion("Reika.DragonAPI.ASM"); Launch.classLoader.addTransformerExclusion("Reika.LegacyCraft.LegacyASMHandler"); Launch.classLoader.addTransformerExclusion("Reika.ChromatiCraft.Auxiliary.ChromaASMHandler"); Launch.classLoader.addTransformerExclusion("Reika.RotaryCraft.Auxiliary.RotaryASMHandler"); Launch.classLoader.addTransformerExclusion("Reika.RotaryCraft.Auxiliary.RotaryIntegrationManager"); Launch.classLoader.addTransformerExclusion("Reika.DragonAPI.Libraries.Java.ReikaASMHelper"); Launch.classLoader.addTransformerExclusion("Reika.DragonAPI.Libraries.Java.ReikaJVMParser"); Launch.classLoader.addTransformerExclusion("Reika.DragonAPI.Exception.ASMException"); Launch.classLoader.addTransformerExclusion("Reika.DragonAPI.ModInteract.BannedItemReader"); } @Override public String[] getASMTransformerClass() { return new String[]{ InterfaceInjector.class.getName(), //Must run before dependent method stripper APIStripper.class.getName(), DragonAPIClassTransfomer.class.getName(), FMLItemBlockPatch.class.getName(), FluidNamePatch.class.getName(), DependentMethodStripper.class.getName(), }; } @Override public String getModContainerClass() { return "Reika.DragonAPI.ASM.APIStripper$AnnotationDummyContainer"; } @Override public String getSetupClass() { return null; } @Override public void injectData(Map<String, Object> data) { } @Override public String getAccessTransformerClass() { return null; } }
49251bffc8e6457ed305c2bd9c3e506de97a38d1
85d7de9ece69480c9e37bbe3182056e447e000ae
/Notepad/src/models/Page.java
df695087944b1d9667dc8d77bdab443611803711
[]
no_license
DavidPavlov/ItTalents
2223917d2bc1b4fb775c54ad6c454ac8f863f996
bc2583e3bcd4e175f120effb082cb6e98111708c
refs/heads/master
2021-04-15T10:00:28.540523
2016-07-17T14:31:42
2016-07-17T14:31:42
63,176,210
0
0
null
null
null
null
UTF-8
Java
false
false
630
java
package models; public class Page { private String headline; private String text; public Page(String head) { this.headline = head; this.text = ""; } public void addText(String text){ if(text != null){ this.text += text; } } public void clearText(){ this.text = ""; } public String pagePreview(){ StringBuilder sb = new StringBuilder(); sb.append(String.format("%s\n", this.headline)); sb.append(this.text); return sb.toString(); } public boolean searchWord(String word){ return this.text.contains(word); } public boolean containsDigits(){ return this.text.matches("[0-9]"); } }
06bf11710a1eda7e3b55d734b2af9663c11fdcfd
842e2914f8f782d243887e53abf51f08c3e73020
/src/Lesson_3/ClassWork/CarParking.java
5d2ad83fdd2017c7915e0e019b4c40da98892ef5
[]
no_license
pandemonian/Work
f0ab865416e01ca78e561b39b2f63dfe6ac903d6
6f2ac21fedc42338dc0b42865c79cfa22d90926f
refs/heads/master
2020-07-02T17:08:13.811239
2017-01-23T17:20:26
2017-01-23T17:20:26
74,293,714
0
1
null
null
null
null
UTF-8
Java
false
false
151
java
package Lesson_3.ClassWork; /** * Created by Admin on 19.11.16. */ public class CarParking { static int arenda; Car[] array = new Car[4]; }
99f69b60a9c0a02957a3e5b4d470a10db6d888ce
67efe59dca2f958cbc8e80ca9fd739550843a5cd
/src/com/agenthun/schoolrecruit2016/ReverseSentenceMore.java
de354f996c035e06d851a8aeabd1c9fa4387952d
[]
no_license
agenthun/Array
871d8c2a6accfca42cd3b570194b96c4aca520f8
a3fbed3d78479c00e4ed7d9db2eb768da59492ca
refs/heads/master
2021-11-28T12:25:40.128325
2021-11-19T14:25:49
2021-11-19T14:25:49
39,020,822
2
1
null
null
null
null
UTF-8
Java
false
false
1,974
java
package com.agenthun.schoolrecruit2016; import java.util.Scanner; /** * Created by agenthun on 16/4/27. * 现在有一个字符串,你要对这个字符串进行 n 次操作,每次操作给出两个数字:(p, l) 表示当前字符串中从下标为 p 的字符开始的长度为 l 的一个子串。 * 你要将这个子串左右翻转后插在这个子串原来位置的正后方,求最后得到的字符串是什么。字符串的下标是从 0 开始的,你可以从样例中得到更多信息。 * 输入描述: * 每组测试用例仅包含一组数据,每组数据第一行为原字符串,长度不超过 10 ,仅包含大小写字符与数字。接下来会有一个数字 n 表示有 n 个操作,再接下来有 n 行, * 每行两个整数,表示每次操作的(p , l)。 * 保证输入的操作一定合法,最后得到的字符串长度不超过 1000。 * 输出描述: * 输出一个字符串代表最后得到的字符串。 * 输入例子: * ab * 2 * 0 2 * 1 3 输出例子: abbaabb * */ public class ReverseSentenceMore { public static void reverse(StringBuffer s, int index, int len) { StringBuffer temp = new StringBuffer(s.substring(index, index + len)); temp.reverse(); s.insert(index + len, temp.toString()); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String inputStr = scanner.nextLine(); int n = Integer.parseInt(scanner.nextLine()); int[] index = new int[n]; int[] len = new int[n]; StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(inputStr); for (int i = 0; i < n; i++) { String[] s = scanner.nextLine().split(" "); index[i] = Integer.parseInt(s[0]); len[i] = Integer.parseInt(s[1]); reverse(stringBuffer, index[i], len[i]); } System.out.println(stringBuffer.toString()); } }
64026f16030dd661a22d8b0010bfc2d62a005122
7e5acfd551c5e28b8b79ea47e1d40cc44873b5d0
/src/test/java/org/jsynthlib/device/viewcontroller/widgets/AbstractDocumentHandler.java
edd8323ae8f0c4bcbe70579f92ed6317941d3fef
[]
no_license
Xycl/JSynthLib
c1c69d043b8146a00e84bc1c7381d569392d4f46
a4a9e37b7fda8f495caf138728be5a6f78c4bc01
refs/heads/master
2021-01-15T13:34:55.882406
2014-12-29T22:15:18
2014-12-29T22:15:18
99,676,396
1
3
null
2021-01-07T12:38:12
2017-08-08T09:39:01
Java
UTF-8
Java
false
false
16,826
java
/* * Copyright 2014 Pascal Collberg * * This file is part of JSynthLib. * * JSynthLib is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or(at your option) any later version. * * JSynthLib 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 JSynthLib; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package org.jsynthlib.device.viewcontroller.widgets; import java.awt.Component; import java.awt.Container; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import org.apache.log4j.Logger; import org.fest.swing.exception.ComponentLookupException; import org.fest.swing.fixture.FrameFixture; import org.fest.swing.fixture.JPanelFixture; import org.fest.swing.fixture.JTabbedPaneFixture; import org.fest.swing.fixture.JTableFixture; import org.jsynthlib.core.ContainerDisplayer; import org.jsynthlib.core.GuiHandler; import org.jsynthlib.core.PatchEditorTest; import org.jsynthlib.core.PopupContainer; import org.jsynthlib.core.TitleFinder.FrameWrapper; import org.jsynthlib.driver.Xmldriver; import org.jsynthlib.driver.Xmleditor; import org.jsynthlib.driver.XmlenvelopeParam; import org.jsynthlib.driver.Xmlparam; import org.jsynthlib.driver.Xmlparams; import org.jsynthlib.driver.Xmlpatches; import org.jsynthlib.driver.Xmlstores; import org.jsynthlib.test.adapter.WidgetAdapter; import org.jsynthlib.test.adapter.WidgetAdapter.Type; import org.jsynthlib.utils.SingletonMidiDeviceProvider; import org.jsynthlib.utils.SingletonMidiDeviceProvider.MidiRecordSession; public abstract class AbstractDocumentHandler { protected final transient Logger log = Logger.getLogger(getClass()); protected final File outputFile; protected final FrameFixture testFrame; private final List<String> uniqueNames; protected GuiHandler guiHandler; protected final SingletonMidiDeviceProvider midiDeviceProvider; public AbstractDocumentHandler(File outputFile, FrameFixture testFrame) { this.testFrame = testFrame; this.outputFile = outputFile; uniqueNames = new ArrayList<String>(); guiHandler = new GuiHandler(testFrame); midiDeviceProvider = SingletonMidiDeviceProvider.getInstance(); } public abstract Xmldriver handleDriver(String driverName); public abstract void handleDocument(String manufacturer, String deviceName); public abstract Xmleditor handlePatchEditor(Xmldriver driver, boolean editable, String editorName, List<PopupContainer> popups); public void handleParam(Xmleditor editor, WidgetAdapter sysexWidget, FrameWrapper frame) { String uniqueName = sysexWidget.getUniqueName(frame); if (Type.ENVELOPE.equals(sysexWidget.getType())) { handleEnvelopeWidget((AbstractEnvelopeWidgetAdapter) sysexWidget, uniqueName, editor); return; } if (!sysexWidget.isShowing()) { handleWidgetNotVisible(uniqueName, editor); return; } Xmlparam param = handleParamInternal(editor, sysexWidget, uniqueName); int min = param.getMin(); int max = param.getMax(); if (Type.LABEL.equals(sysexWidget.getType())) { // Skip... return; } if (Type.CHECKBOX.equals(sysexWidget.getType())) { if (sysexWidget.isEnabled()) { try { Thread.sleep(100); } catch (InterruptedException e) { } handleCheckboxWidget(sysexWidget, param, min, max); } else { handleDisabledWidget(param); } } else if (Type.COMBOBOX.equals(sysexWidget.getType())) { if (sysexWidget.isEnabled()) { handleComboboxWidget(sysexWidget, param, min, max); } else { handleDisabledWidget(param); } } else if (Type.ID_COMBOBOX.equals(sysexWidget.getType())) { if (sysexWidget.isEnabled()) { handleUb99ComboboxWidget(sysexWidget, param, min, max); } else { handleDisabledWidget(param); } } else if (Type.KNOB.equals(sysexWidget.getType())) { if (sysexWidget.isEnabled()) { handleKnobWidget(sysexWidget, param, min, max); } else { handleDisabledWidget(param); } } else if (Type.PATCH_NAME.equals(sysexWidget.getType())) { if (sysexWidget.isEnabled()) { handlePatchNameWidget(sysexWidget, param); } else { handleDisabledWidget(param); } } else if (Type.SCROLLBAR.equals(sysexWidget.getType())) { handleScrollbarWidget(sysexWidget, param, min, max); } else if (Type.SPINNER.equals(sysexWidget.getType())) { if (sysexWidget.isEnabled()) { handleSpinnerWidget(sysexWidget, param, min, max); } else { handleDisabledWidget(param); } } else if (Type.TREE.equals(sysexWidget.getType())) { // TreeWidget widget = (TreeWidget) sysexWidget; // JTreeFixture fixture = // new JTreeFixture(testFrame.robot, widget.tree); if (sysexWidget.isEnabled()) { // handleTreeWidget(sysexWidget, param); } else { handleDisabledWidget(param); } } else if (Type.SCROLLBAR_LOOKUP.equals(sysexWidget.getType())) { if (sysexWidget.isEnabled()) { handleScrollbarLookupWidget(sysexWidget, param, min, max); } else { handleDisabledWidget(param); } } else if (Type.MULTI.equals(sysexWidget.getType())) { // JPanelFixture fixture = // new JPanelFixture(testFrame.robot, sysexWidget); // handleMultiWidget(sysexWidget, param); } else { log.warn("Could not handle widget " + sysexWidget.getType().name()); System.exit(0); } } protected abstract Xmlparam handleParamInternal(Xmleditor editor, WidgetAdapter sysexWidget, String uniqueName); // protected abstract void handleMultiWidget(WidgetAdapter sysexWidget, // Xmlparam param); protected abstract void handleWidgetNotVisible(String uniqueName, Xmleditor editor); protected abstract void handleEnvelopeWidget( AbstractEnvelopeWidgetAdapter sysexWidget, String uniqueName, Xmleditor editor); protected abstract void handleDisabledWidget(Xmlparam param); // protected abstract void handleTreeWidget(WidgetAdapter sysexWidget, // Xmlparam param); protected abstract void handleCheckboxWidget(WidgetAdapter sysexWidget, Xmlparam param, int min, int max); protected abstract void handleComboboxWidget(WidgetAdapter sysexWidget, Xmlparam param, int min, int max); protected abstract void handleUb99ComboboxWidget(WidgetAdapter sysexWidget, Xmlparam param, int min, int max); protected abstract void handleKnobWidget(WidgetAdapter sysexWidget, Xmlparam param, int min, int max); protected abstract void handlePatchNameWidget(WidgetAdapter sysexWidget, Xmlparam param); protected abstract void handleScrollbarWidget(WidgetAdapter sysexWidget, Xmlparam param, int min, int max); protected abstract void handleScrollbarLookupWidget( WidgetAdapter sysexWidget, Xmlparam param, int min, int max); protected abstract void handleSpinnerWidget(WidgetAdapter sysexWidget, Xmlparam param, int min, int max); public abstract void saveDocument() throws IOException; protected abstract Xmlpatches getXmlpatches(Xmleditor editor, String[][] contents); protected abstract void handlePatch(Xmlpatches xmlpatches, String name, String sysex, List<PopupContainer> popups, String[][] contents); protected int getBankIncrement(int length) { String testLevelStr = System.getProperty(PatchEditorTest.TEST_LEVEL); int testLevel = Integer.parseInt(testLevelStr); int retval = 0; switch (testLevel) { case PatchEditorTest.TESTLEVEL_LOW: retval = length / 2; case PatchEditorTest.TESTLEVEL_MEDIUM: retval = length / 4; case PatchEditorTest.TESTLEVEL_HIGH: default: retval = 1; } if (retval < 1) { retval = 1; } return retval; } public void handleBankEditor(Xmleditor editor, JTableFixture table) { String[][] contents = table.contents(); Xmlpatches xmlpatches = getXmlpatches(editor, contents); int rowIncr = getBankIncrement(contents.length); for (int i = 0; i < contents.length; i += rowIncr) { int colIncr = getBankIncrement(contents[i].length); for (int j = 0; j < contents[i].length; j += colIncr) { MidiRecordSession session = midiDeviceProvider.openSession(); // TODO:Workaround for Roland MT32 char c = 21; String name = table.target.getModel().getValueAt(i, j).toString() .trim().replace(c, ' '); List<PopupContainer> popups = guiHandler.sendPatch(table, j, i); String sysex = midiDeviceProvider.closeSession(session); handlePatch(xmlpatches, name, sysex, popups, contents); } } } String getUniqueName(FrameWrapper frame, SysexWidget sysexWidget) { JComponent parent = (JComponent) sysexWidget.getParent(); String containerName = null; if (parent == null) { try { log.info("Showing table"); containerName = ContainerDisplayer.showTableAndGetNameRecursive(frame, sysexWidget); } catch (ComponentLookupException e) { log.warn("Widget is not visible!"); } } else { log.info("Showing container"); containerName = ContainerDisplayer.showContainerAndGetNameRecursive(frame, sysexWidget); } String label = sysexWidget.getLabel(); if (label == null || label.isEmpty()) { if (sysexWidget instanceof EnvelopeWidget) { label = "Envelope"; } else if (sysexWidget.getParent() != null) { label = findNearestLabelRecursive(sysexWidget.getParent(), 0); } } if (label == null || label.isEmpty()) { log.warn("Label is not valid!"); } String uniqueName = containerName + label; int index = 1; while (uniqueNames.contains(uniqueName)) { log.warn("Editor has duplicate widgets! " + uniqueName); if (index == 1) { uniqueName = uniqueName + "-id" + index; } else { uniqueName = uniqueName.replace("-id" + (index - 1), "-id" + index); } index++; } uniqueNames.add(uniqueName); return uniqueName; } String findNearestLabelRecursive(Container parent, int index) { if (index >= 3) { log.warn("Could not find label!"); return null; } Component[] components = parent.getComponents(); for (Component component : components) { if (component instanceof JLabel) { String text = ((JLabel) component).getText(); if (text != null && !text.isEmpty()) { return text; } } } return findNearestLabelRecursive(parent.getParent(), index + 1); } protected interface IClickable { void click(); } protected IClickable getClickableParentRecursive(Container container) { if (container instanceof JFrame) { JFrame frame = (JFrame) container; final FrameFixture fixture = new FrameFixture(frame); return new IClickable() { @Override public void click() { fixture.click(); } }; } else if (container instanceof JTabbedPane) { JTabbedPane pane = (JTabbedPane) container; final JTabbedPaneFixture fixture = new JTabbedPaneFixture(testFrame.robot, pane); return new IClickable() { @Override public void click() { fixture.click(); } }; } else if (container instanceof JPanel) { JPanel pane = (JPanel) container; final JPanelFixture fixture = new JPanelFixture(testFrame.robot, pane); return new IClickable() { @Override public void click() { fixture.focus(); } }; } else { return getClickableParentRecursive(container.getParent()); } } @SuppressWarnings("unchecked") protected <T> T getField(String fieldName, Class<T> klass, Object object) throws IllegalAccessException, NoSuchFieldException { Field f = object.getClass().getDeclaredField(fieldName); f.setAccessible(true); return (T) f.get(object); } protected abstract Xmlstores getXmlstores(Xmldriver driver, Map<String, List<String>> bankMap); protected abstract void handleXmlstore(Xmlstores xmlstores, String bank, String patchNum, List<PopupContainer> popupList, String sysex); public void handleStore(Xmldriver driver, JTableFixture table, Map<String, List<String>> bankMap) { Iterator<Entry<String, List<String>>> iterator = bankMap.entrySet().iterator(); if (bankMap.isEmpty()) { log.info("No banks to handle..."); return; } Xmlstores xmlstores = getXmlstores(driver, bankMap); while (iterator.hasNext()) { Entry<String, List<String>> entry = iterator.next(); String bank = entry.getKey(); List<String> patchNumList = entry.getValue(); if (patchNumList.isEmpty()) { MidiRecordSession session = midiDeviceProvider.openSession(); List<PopupContainer> popupList = guiHandler.storePatch(table, bank, null); String sysex = midiDeviceProvider.closeSession(session); handleXmlstore(xmlstores, bank, null, popupList, sysex); } else { int incr = (patchNumList.size() / 4) + 1; for (int i = 0; i < patchNumList.size(); i += incr) { MidiRecordSession session = midiDeviceProvider.openSession(); String patchNum = patchNumList.get(i); List<PopupContainer> popupList = guiHandler.storePatch(table, bank, patchNum); String sysex = midiDeviceProvider.closeSession(session); handleXmlstore(xmlstores, bank, patchNum, popupList, sysex); } } } } protected XmlenvelopeParam getEnvelopeParamByUniqueName(Xmlparams params, String uniqueName) { XmlenvelopeParam[] envelopeParams = params.getXmlenvelopeParamArray(); for (XmlenvelopeParam xmlenvelopeParam : envelopeParams) { if (xmlenvelopeParam.getLabel() != null && xmlenvelopeParam.getLabel().equals(uniqueName)) { return xmlenvelopeParam; } } throw new IllegalArgumentException("Could not find envelope param " + uniqueName); } }
943b72941531c6224a7b4d8ae716e798db97d337
7596b13ad3a84feb67f05aeda486e8b9fc93f65f
/getAndroidAPI/src/java/lang/NoSuchMethodError.java
c8e691c3ca440c643f05dad81ba6ceb01a66196d
[]
no_license
WinterPan2017/Android-Malware-Detection
7aeacfa03ca1431e7f3ba3ec8902cfe2498fd3de
ff38c91dc6985112e958291867d87bfb41c32a0f
refs/heads/main
2023-02-08T00:02:28.775711
2020-12-20T06:58:01
2020-12-20T06:58:01
303,900,592
1
0
null
null
null
null
UTF-8
Java
false
false
589
java
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) // Source File Name: NoSuchMethodError.java package java.lang; // Referenced classes of package java.lang: // IncompatibleClassChangeError, RuntimeException, String public class NoSuchMethodError extends IncompatibleClassChangeError { public NoSuchMethodError() { throw new RuntimeException("Stub!"); } public NoSuchMethodError(String s) { throw new RuntimeException("Stub!"); } }
61ff5064057238e2021d2eb51a12b24d3259261d
4414095ac7bb09338759793a5c6c4ae03428a6a3
/src/main/java/lottery/exception/BaseException.java
c62f9990f618bd0283fa110ca487cb4b2423da9b
[]
no_license
zt1983811/silanis_lottery
73011a4cd27d785438842f3e8b8bc2e710a8420f
949c7228ce9061c8f35761adb83af083b91ff96a
refs/heads/master
2021-01-17T17:09:19.570228
2016-06-09T00:55:19
2016-06-09T00:55:19
60,475,140
0
0
null
null
null
null
UTF-8
Java
false
false
360
java
package lottery.exception; /** * BaseException * * @author Tong Zhou */ public class BaseException extends Exception { /** * */ private static final long serialVersionUID = 1L; /** * {@inheritDoc} * * @see Exception#BaseException(String) */ public BaseException(String msg) { super(msg); } }
bba4e766db9343f10e9d647922d65e54dcd0f28f
9bde7f61ccd4b00493744eb0aea2d2525e09b348
/support/cas-server-support-shell/src/test/java/org/apereo/cas/shell/commands/cipher/GenerateCryptoKeysCommandTests.java
d24230a1e70e46ca19908ade27eb853632b8c722
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-free-unknown" ]
permissive
rkorn86/cas
12c15c0ee021bbfab8c3cd042945e7af51071871
0aa46d0a89cd2a76775262ea09ee9e06646bb818
refs/heads/master
2023-06-07T23:11:08.708565
2023-06-04T10:45:46
2023-06-04T10:45:46
44,962,359
0
0
Apache-2.0
2023-05-17T01:17:22
2015-10-26T10:48:38
Java
UTF-8
Java
false
false
673
java
package org.apereo.cas.shell.commands.cipher; import org.apereo.cas.shell.commands.BaseCasShellCommandTests; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import static org.junit.jupiter.api.Assertions.*; /** * This is {@link GenerateCryptoKeysCommandTests}. * * @author Misagh Moayyed * @since 6.2.0 */ @EnableAutoConfiguration @Tag("SHELL") public class GenerateCryptoKeysCommandTests extends BaseCasShellCommandTests { @Test public void verifyOperation() { assertDoesNotThrow(() -> runShellCommand(() -> () -> "generate-key --key-size 512")); } }
95479b6a0f995d34285918f31497ecdaf9c45e9b
7534ad6ab0230965b9e52f2fa0e6582947521f1e
/fundamentos-oo/lab_03/project/src/teceira/lista/TeceiraLista.java
754fbdaa6fc22af67eb8e0aef50b22b7574d23db
[]
no_license
danielfnz/espwebmob-fullstack
95f4af6055adb057f21dfb72c73aac6298f7ff2c
c440eee52ffef426ac36aaeaec288e98ce5b88fb
refs/heads/master
2020-03-17T01:19:33.280849
2018-08-04T17:52:31
2018-08-04T17:52:31
133,148,051
0
0
null
null
null
null
UTF-8
Java
false
false
878
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 teceira.lista; /** * * @author Alunoinf_2 */ public class TeceiraLista { /** * @param args the command line arguments */ public static void main(String[] args) { List list = new List(5); list.adiciona(new Cidade(0, "Goiania", "GO", 78787, 5454)); list.adiciona(new Cidade(1, "Ceres", "GO", 55555, 121)); list.adiciona(new Cidade(2, "AP. Goiania", "GO", 78787872, 5555)); list.adiciona(new Cidade(3, "Mineiros", "GO", 9235, 452)); list.remove(2); list.getMaiorCidadeAcidentes(); list.getMenorCidadeAcidentes(); list.getMediaVeiculosPasseios(); list.getMediaAcidentesGO(); } }
803d4cf8926fc6198579594390452bc357f4102a
657880c54f8d2167c1f02afaac0f3e27a271eac6
/cafeinme/src/main/java/com/kh/cafeinme/bookmark/svc/BookmarkSVCImpl.java
99692b1cf2fb2c62e67c813115547ff4cc7ba090
[]
no_license
jeong-dong-hoon/cafeinme
b8b1a3d6d6b6621da6dc5dcb69d5c7f930565996
4214c6099ad915c6a8c455a9f4390af4bdb2b380
refs/heads/main
2023-05-03T21:00:09.379600
2021-05-27T06:07:46
2021-05-27T06:07:46
371,258,551
0
0
null
null
null
null
UTF-8
Java
false
false
732
java
package com.kh.cafeinme.bookmark.svc; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.kh.cafeinme.bookmark.dao.BookmarkDAO; import com.kh.cafeinme.mycafe.vo.CafeVO; @Service public class BookmarkSVCImpl implements BookmarkSVC{ @Autowired BookmarkDAO bd; @Override public int bookmark(int cafe_no, String member_id) { return bd.bookmark(cafe_no, member_id); } @Override public int delbookmark(int cafe_no, String member_id) { return bd.delbookmark(cafe_no, member_id); } @Override public List<CafeVO> mybookmark(String member_id) { return bd.mybookmark(member_id); } }
[ "user@user" ]
user@user
83dbe0c9342390232a684c4e029f55d618771d14
f12d7bddf1767fe6ca17238c1eedab2ece2c3b3b
/app/src/main/java/com/fangzuo/assist/Utils/SquareRelativeLayout.java
8645bbb87f64f9e3f9621acc87394c9fe7426d74
[]
no_license
huohehuo/ZL-NewPad
a7e6f9280688ef47cd973b8cba46c92a9ae4e303
3211dc589671d35a7c7f29126249f8821adcabff
refs/heads/master
2020-03-20T13:56:12.881550
2018-06-20T09:20:43
2018-06-20T09:20:43
137,470,698
1
0
null
null
null
null
UTF-8
Java
false
false
1,073
java
package com.fangzuo.assist.Utils; import android.content.Context; import android.util.AttributeSet; import android.widget.RelativeLayout; /** * Created by 王璐阳 on 2018/3/27. */ public class SquareRelativeLayout extends RelativeLayout { public SquareRelativeLayout(Context context) { super(context); } public SquareRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); } public SquareRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec)); int childWidthSize = getMeasuredWidth(); // 高度和宽度一样 heightMeasureSpec = widthMeasureSpec = MeasureSpec.makeMeasureSpec( childWidthSize, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }
2e8b89d45736f0ac30a35e983660d70529ba419f
d5cf3f481988e20c65ef48edfab86dcc776d30d9
/app/src/main/java/com/bankmanagement/r/bankmanagement/SqlData.java
c9b70c28ffd11993e2068663d4b7585a71de203e
[]
no_license
ali-phpcs/BankManagement
2ae6d4d35221b0d3c08e2b817ec3d05d446aa1d5
4a81924708775eb1439133303725197a7aaa2e0d
refs/heads/master
2021-01-20T07:30:04.899456
2017-05-08T23:43:53
2017-05-08T23:43:53
90,008,958
0
0
null
null
null
null
UTF-8
Java
false
false
1,485
java
package com.bankmanagement.r.bankmanagement; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class SqlData { MySQLite mySQLite; SQLiteDatabase sqliteDB; public SqlData(Context context) { mySQLite = new MySQLite(context); } public void openDB() { try { sqliteDB = mySQLite.getWritableDatabase(); } catch (Exception e) { } } public void closeDB() { sqliteDB.close(); } public void loginUser(String user_phone) { openDB(); ContentValues list = new ContentValues(); list.put(MySQLite.USER_PHONE, user_phone); sqliteDB.insert(MySQLite.USER_TABLE, null, list); closeDB(); } public boolean isLogin() { openDB(); Cursor cursor = sqliteDB.query(MySQLite.USER_TABLE, null, null, null, null, null, null); return cursor.getCount() > 0; } public void logOut() { openDB(); sqliteDB.delete(MySQLite.USER_TABLE, "", null); closeDB(); } public String getPhoneNumber() { openDB(); Cursor cursor = sqliteDB.query(MySQLite.USER_TABLE, null, null, null, null, null, null); cursor.moveToFirst(); String u = cursor.getString(cursor.getColumnIndex(MySQLite.USER_PHONE)); cursor.moveToNext(); cursor.close(); return u; } }
[ "ali12131415" ]
ali12131415
c1e2856f359759d46edd421b2918b51a1ec62a7f
cd447f0ad8aed25d20f406e1aae1b946c34579f4
/src/main/java/br/eti/emersondantas/coursesocialnetwork/api/discipline/services/CreateCommentServiceImpl.java
3ba1536b38608a0eb1bd786eee0cf6e8758b43f9
[]
no_license
EmersonDantas/LAB3-DSC
569500fa21be633038bde7b3a900fe162412670f
073cba64d52fef3a23eb9583eb2092dbe4adf763
refs/heads/master
2023-05-01T15:19:21.514575
2021-05-24T03:07:45
2021-05-24T03:07:45
367,496,372
0
0
null
null
null
null
UTF-8
Java
false
false
1,884
java
package br.eti.emersondantas.coursesocialnetwork.api.discipline.services; import br.eti.emersondantas.coursesocialnetwork.api.discipline.Comment; import br.eti.emersondantas.coursesocialnetwork.api.discipline.CommentRepository; import br.eti.emersondantas.coursesocialnetwork.api.discipline.Discipline; import br.eti.emersondantas.coursesocialnetwork.api.discipline.DisciplineRepository; import br.eti.emersondantas.coursesocialnetwork.api.discipline.dto.CommentDTO; import br.eti.emersondantas.coursesocialnetwork.api.discipline.exceptions.DisciplineNotFoundException; import br.eti.emersondantas.coursesocialnetwork.api.jwt.service.JWTService; import br.eti.emersondantas.coursesocialnetwork.api.user.User; import br.eti.emersondantas.coursesocialnetwork.api.user.UserRepository; import br.eti.emersondantas.coursesocialnetwork.api.user.exceptions.UserNotFoundException; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @RequiredArgsConstructor @Service public class CreateCommentServiceImpl implements CreateCommentService{ private final DisciplineRepository disciplineRepository; private final CommentRepository commentRepository; private final JWTService jwtService; private final UserRepository userRepository; @Override public Discipline create(CommentDTO comment, Long disciplineId, String authHeader) { User user = userRepository.findByEmail(this.jwtService.getSujeitoDoToken(authHeader)).orElseThrow(UserNotFoundException::new); Discipline discipline = this.disciplineRepository.findById(disciplineId).orElseThrow(DisciplineNotFoundException::new); this.commentRepository.save(Comment.builder() .comentario(comment.getComentario()) .disciplina(discipline) .usuario(user) .build()); return discipline; } }
b67ab24419b846fb1ec918ae093cb07ec5ef8448
644d4d8967640fd17b1cb4644e1f3d490f930180
/src/pool/Conllision.java
eeafc94418cc329edcbb12c6e7e9c361855579d9
[]
no_license
leuducanh/android8-ci-ducanhl
14b2f76082787a63764bece296af0cce71bcffb4
1828c1d21fd63025335dc6bc13160b590891289c
refs/heads/master
2021-01-19T17:27:02.157022
2017-03-21T11:45:42
2017-03-21T11:45:42
82,459,969
0
0
null
null
null
null
UTF-8
Java
false
false
1,174
java
package pool; import controllers.GameController; import models.GameModel; import java.util.Vector; /** * Created by l on 3/5/2017. */ public class Conllision { public static Vector<GameController> gameControllersCollision; public static void openPool(){ gameControllersCollision = new Vector<>(); } public void checkCollision(){ for(int i = 0;i < gameControllersCollision.size() - 1;i++){ for(int j = 0;j < gameControllersCollision.size();j++){ if(gameControllersCollision.get(i).getModel().checkContact(gameControllersCollision.get(j).getModel())){ gameControllersCollision.get(i).getModel().collisionHandler(gameControllersCollision.get(j).getModel()); gameControllersCollision.get(j).getModel().collisionHandler(gameControllersCollision.get(i).getModel()); } } } } public void delete(){ for(int i = 0;i < gameControllersCollision.size();i++){ if(!gameControllersCollision.get(i).getModel().isVisible()){ gameControllersCollision.removeElementAt(i); } } } }
021cd445a1cffa4b40edeb4c951dc50d26c66d0e
4d7d4b4085a7c9afc1b386024caf1a60e1bc8b1c
/lealone-test/src/test/java/org/lealone/test/jdbc/misc/RegionSplitTest.java
a8c981e7eb3743f00473a923aefaeef5aab09148
[ "Apache-2.0" ]
permissive
suicloud/Lealone
daa96a4bf09e30b47e4b1296cedf22009807a0ca
fbb5e6fe24101dd90dcf831743fa4c352788eea3
refs/heads/master
2020-12-25T19:38:37.250703
2014-12-14T01:13:55
2014-12-14T01:13:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,724
java
/* * Copyright 2011 The Apache Software Foundation * * 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.lealone.test.jdbc.misc; import java.util.Map; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.util.Bytes; import org.junit.Test; import org.lealone.hbase.util.HBaseUtils; import org.lealone.test.jdbc.TestBase; public class RegionSplitTest extends TestBase { @Test public void run() throws Exception { stmt.executeUpdate("DROP TABLE IF EXISTS RegionSplitTest"); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS RegionSplitTest (id int primary key, name varchar(500))"); int size = 50; for (int i = 1; i < size; i++) stmt.executeUpdate("INSERT INTO RegionSplitTest(id, name) VALUES(" + i + ", 'a1')"); String tableName = "RegionSplitTest".toUpperCase(); HBaseAdmin admin = HBaseUtils.getHBaseAdmin(); //admin.getConnection().clearRegionCache(); admin.split(Bytes.toBytes(tableName), Bytes.toBytes(10)); for (int i = 1; i < size; i++) stmt.executeUpdate("INSERT INTO RegionSplitTest(id, name) VALUES(" + i + ", 'a1')"); //admin.getConnection().clearRegionCache(); Thread.sleep(2000); admin.split(Bytes.toBytes(tableName), Bytes.toBytes(30)); sql = "select id, name from RegionSplitTest"; printResultSet(); for (int i = 1; i < size; i++) stmt.executeUpdate("INSERT INTO RegionSplitTest(id, name) VALUES(" + i + ", 'a1')"); //admin.getConnection().clearRegionCache(); Thread.sleep(2000); admin.split(Bytes.toBytes(tableName), Bytes.toBytes(40)); sql = "select id, name from RegionSplitTest"; printResultSet(); } void closeRegionWithEncodedRegionName(String tableName) throws Exception { printRegions(tableName); HBaseAdmin admin = HBaseUtils.getHBaseAdmin(); //admin.getConnection().clearRegionCache(); //admin.split(Bytes.toBytes(tableName), Bytes.toBytes(10)); HTable t = new HTable(HBaseConfiguration.create(), tableName.toUpperCase()); for (Map.Entry<HRegionInfo, ServerName> e : t.getRegionLocations().entrySet()) { HRegionInfo info = e.getKey(); System.out.println("info.getEncodedName()=" + info.getEncodedName()); ServerName server = e.getValue(); System.out.println("HRegionInfo = " + info.getRegionNameAsString()); System.out.println("ServerName = " + server); System.out.println(); //admin.closeRegion(server, info); admin.closeRegionWithEncodedRegionName(info.getEncodedName(), server.getServerName()); break; } t.close(); } }
f2f89b8a38f9ce771822205e8958dea3d56d5f6e
5dfd91cf3cdec263a015d01c07b8e7e5b3984e88
/src/main/java/com/thanglv/sprnonblocking/repository/MessageRepository.java
affa929223220fef3e69afba94f393b38e0d9e83
[]
no_license
vietthang197/sprnonblocking
178ea7c2a78234dd67654ae2cf421a6c5144c411
e8b6e372420cccb869da325ad1273e35ae3dc577
refs/heads/master
2020-05-04T08:02:36.886958
2019-04-02T09:04:49
2019-04-02T09:04:49
179,039,219
0
0
null
null
null
null
UTF-8
Java
false
false
330
java
package com.thanglv.sprnonblocking.repository; import com.thanglv.sprnonblocking.entity.Message; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; public interface MessageRepository extends JpaRepository<Message, Integer> { List<Message> findAllByRoomIdOrderByDateComment(Integer roomId); }
288d3bd1bbca22f0433262baffff73a27d46c310
f3c80a33fb02b8931bc5e05e44bca9f70ea5f077
/upskill_Java1_LPJ_grupo1-main/Sprint/Projeto/src/main/java/com/company/ui/AdicionarTarefaUI.java
6527cd8031780842a2d2b96f192a4fe5f6e90169
[]
no_license
helfer1991/T4J-Platform-UpSkill
ae4728fa3ca37964e8083e2d2d3bafde4c894043
2c439b6196ff6d1eae0f0877a4caba60b89f728b
refs/heads/main
2023-04-04T19:10:25.676176
2021-04-12T20:20:14
2021-04-12T20:20:14
357,322,435
1
0
null
null
null
null
UTF-8
Java
false
false
7,890
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 com.company.ui; import com.company.controller.RegistarTarefaController; import static com.company.ui.App.TITULO_APLICACAO; import java.net.URL; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.ComboBox; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; /** * FXML Controller class * * @author joaor */ public class AdicionarTarefaUI implements Initializable { private TabTarefasUI tabTarefasUI; @FXML private TextField txtNovaTarefaRef; @FXML private TextField txtNovaTarefaDesign; @FXML private TextField txtNovaTarefaDuracao; @FXML private TextField txtNovaTarefaCusto; @FXML private TextArea txtNovaTarefaDescInformal; @FXML private TextArea txtNovaTarefaDescTecnica; @FXML private ComboBox<String> cmbNovaTarefaCatTarefa; private RegistarTarefaController tarCtrl; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { } @FXML private void actionAddNovaTarefa(ActionEvent event) { try { tarCtrl.novaTarefa(txtNovaTarefaRef.getText().trim(), txtNovaTarefaDesign.getText().trim(), txtNovaTarefaDescInformal.getText().trim(), txtNovaTarefaDescTecnica.getText().trim(), Integer.parseInt(txtNovaTarefaDuracao.getText().trim()), Double.parseDouble(txtNovaTarefaCusto.getText().trim()), tarCtrl.getCategoriaTarefa(cmbNovaTarefaCatTarefa.getValue().split(" ")[0]), tarCtrl.getColaborador()); showAACreationSuccess(); tabTarefasUI.updateList(); encerrarNovaTarefaUI(event); } catch (Exception ex) { showIncorrectInformation(ex); } } void updateCatTarCMB() throws Exception { tarCtrl = new RegistarTarefaController(); ObservableList obList = FXCollections.observableList(tarCtrl.getListaCatTarefaIdDesc()); this.cmbNovaTarefaCatTarefa.getItems().clear(); this.cmbNovaTarefaCatTarefa.setItems(obList); } public void showAACreationSuccess() { Alert alerta = AlertaUI.criarAlerta(Alert.AlertType.INFORMATION, App.TITULO_APLICACAO, "Sucesso", "Tarefa Adicionada com Sucesso"); if (alerta.showAndWait().get() == ButtonType.OK) { alerta.close(); } } public void showIncorrectInformation(Exception e) { Alert alert = AlertaUI.criarAlerta(Alert.AlertType.INFORMATION, App.TITULO_APLICACAO, "Erro ao Adicionar Tarefa.", e.getMessage()); if (alert.showAndWait().get() == ButtonType.OK) { alert.close(); } } void associarParentUI(TabTarefasUI tabTarefasUI, RegistarTarefaController tarCtrl) { this.tabTarefasUI = tabTarefasUI; this.tarCtrl = tarCtrl; } @FXML private void actionCancel(ActionEvent event) { if (txtNovaTarefaRef.getText().isEmpty() && txtNovaTarefaDesign.getText().isEmpty() && txtNovaTarefaDuracao.getText().isEmpty() && txtNovaTarefaCusto.getText().isEmpty() && txtNovaTarefaDescInformal.getText().isEmpty() && txtNovaTarefaDescTecnica.getText().isEmpty()) { encerrarNovaTarefaUI(event); } else { Alert alerta = AlertaUI.criarAlerta(Alert.AlertType.CONFIRMATION, TITULO_APLICACAO, "Ira Perder os dados inseridos.", "Deseja mesmo encerrar o Registo?"); if (alerta.showAndWait().get() == ButtonType.CANCEL) { event.consume(); } else { encerrarNovaTarefaUI(event); } } } private void encerrarNovaTarefaUI(ActionEvent event) { this.txtNovaTarefaRef.clear(); this.txtNovaTarefaDesign.clear(); this.txtNovaTarefaDuracao.clear(); this.txtNovaTarefaCusto.clear(); this.txtNovaTarefaDescInformal.clear(); this.txtNovaTarefaDescTecnica.clear(); this.cmbNovaTarefaCatTarefa.getSelectionModel().clearSelection(); this.cmbNovaTarefaCatTarefa.setValue(null); ((Node) event.getSource()).getScene().getWindow().hide(); } @FXML private void txtNovaTarefaRefMaxSize(KeyEvent event) { } @FXML private void txtNovaTarefaDesignacaoMaxSize(KeyEvent event) { if (!(event.getCode() == KeyCode.BACK_SPACE || event.getCode() == KeyCode.DELETE || event.getCode() == KeyCode.ESCAPE)) { if (txtNovaTarefaDescInformal.getText().length() > 49) { Alert alerta = AlertaUI.criarAlerta(Alert.AlertType.INFORMATION, TITULO_APLICACAO, "Maximo Caracteres", "Maximo Carateres de Descrição Informal é 50 caracteres"); if (alerta.showAndWait().get() == ButtonType.OK) { event.consume(); } } } } @FXML private void txtNovaTarefaDuracaoInfMaxSize(KeyEvent event) { if (!(event.getCode() == KeyCode.BACK_SPACE || event.getCode() == KeyCode.DELETE || event.getCode() == KeyCode.ESCAPE)) { if (!event.getCode().isDigitKey()) { Alert alerta = AlertaUI.criarAlerta(Alert.AlertType.INFORMATION, TITULO_APLICACAO, "Caracter Invalido", "Duração tem de ser Numerico (0-9)"); if (alerta.showAndWait().get() == ButtonType.OK) { event.consume(); } } } } @FXML private void txtNovaTarefaCustoMaxSize(KeyEvent event) { if (!(event.getCode() == KeyCode.BACK_SPACE || event.getCode() == KeyCode.DELETE || event.getCode() == KeyCode.ESCAPE || event.getCode() == KeyCode.PERIOD)) { if (!event.getCode().isDigitKey()) { Alert alerta = AlertaUI.criarAlerta(Alert.AlertType.INFORMATION, TITULO_APLICACAO, "Caracter Invalido", "Custo tem de ser Numerico (0-9)"); if (alerta.showAndWait().get() == ButtonType.OK) { event.consume(); } } } } @FXML private void txtNovaTarefaDescInfMaxSize(KeyEvent event) { if (!(event.getCode() == KeyCode.BACK_SPACE || event.getCode() == KeyCode.DELETE || event.getCode() == KeyCode.ESCAPE)) { if (txtNovaTarefaDescInformal.getText().length() > 49) { Alert alerta = AlertaUI.criarAlerta(Alert.AlertType.INFORMATION, TITULO_APLICACAO, "Maximo Caracteres", "Maximo Carateres de Descrição Informal é 50 caracteres"); if (alerta.showAndWait().get() == ButtonType.OK) { event.consume(); } } } } @FXML private void txtNovaTarefaDescTecMaxSize(KeyEvent event) { if (!(event.getCode() == KeyCode.BACK_SPACE || event.getCode() == KeyCode.DELETE || event.getCode() == KeyCode.ESCAPE)) { if (txtNovaTarefaDescTecnica.getText().length() > 199) { Alert alerta = AlertaUI.criarAlerta(Alert.AlertType.INFORMATION, TITULO_APLICACAO, "Maximo Caracteres", "Maximo Carateres de Descrição Tecnica é 199 caracteres"); if (alerta.showAndWait().get() == ButtonType.OK) { event.consume(); } } } } }
e2af0640a69df54848d4847d50491d4f01a0ee12
8239921dcb66886300f5d25ef5c36bf3abc46aa9
/ajs/src/ajs/server/Factory.java
c0311ec5d9fda897e202f447d23ff9122fb8c03f
[]
no_license
JuliaKazsmerova/KOPR_AJS
fa25e05f284ea735a89a79f1df64601498a20b5c
9c46331bacd43e3f15e99b64f461a09e75599cd4
refs/heads/master
2021-04-29T13:17:15.329907
2018-02-17T21:12:20
2018-02-17T21:12:20
121,744,065
0
0
null
null
null
null
UTF-8
Java
false
false
851
java
package ajs.server; import org.springframework.jdbc.core.JdbcTemplate; import com.mysql.cj.jdbc.MysqlDataSource; public enum Factory { INSTANCE; String url = "jdbc:mysql://localhost:3306/kopr?useUnicode=true&useJDBCCompliantTimezoneShift=true&serverTimezone=UTC"; String username = "java"; String password = "password"; private StudentMysqlDao studentMysqlDao = null; private Factory() { JdbcTemplate jdbcTemplate = connection(); studentMysqlDao = new StudentMysqlDao(jdbcTemplate); } public JdbcTemplate connection() { MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUser(username); dataSource.setPassword(password); dataSource.setURL(url); return new JdbcTemplate(dataSource); } public StudentMysqlDao getStudentMysqlDao() { return studentMysqlDao; } }
[ "July@Julka" ]
July@Julka
feb612681a0fe526c04be8c161458e1363ade65a
d0479ca0831bf1ca1d2f5f3c75a81245a0835ac7
/core-modules/core-module-impex/src/main/java/org/yes/cart/bulkimport/xml/internal/QuantityTypeType.java
78897f6315da065f2125b4f5de866f76b767e257
[ "Apache-2.0" ]
permissive
inspire-software/yes-cart
20a8e035116e0fb0a9d63da7362799fb530fab72
803b7c302f718803e5b841f93899942dd28a4ea0
refs/heads/master
2023-08-31T18:09:26.780049
2023-08-26T12:07:25
2023-08-26T12:07:25
39,092,083
131
92
Apache-2.0
2022-12-16T05:46:38
2015-07-14T18:10:24
Java
UTF-8
Java
false
false
1,264
java
package org.yes.cart.bulkimport.xml.internal; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for quantityTypeType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="quantityTypeType"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="stock"/> * &lt;enumeration value="reserved"/> * &lt;enumeration value="ats"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "quantityTypeType") @XmlEnum public enum QuantityTypeType { @XmlEnumValue("stock") STOCK("stock"), @XmlEnumValue("reserved") RESERVED("reserved"), @XmlEnumValue("ats") ATS("ats"); private final String value; QuantityTypeType(String v) { value = v; } public String value() { return value; } public static QuantityTypeType fromValue(String v) { for (QuantityTypeType c: QuantityTypeType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
431e6479c198493f208e0a07d07eb53913abbbc2
b982f703a7428d27e7c3f3df1996fbf6809c9da8
/export_parent/export_cargo_service/src/main/java/com/itheima/service/cargo/impl/ContractServiceImpl.java
c5a8c77bc9bfb3a32e2eb248a916e4d160b6c16b
[]
no_license
CRX1120785929/itheima
0417db5080f6c98354debe0080612be6af019bab
8cc4d8674d74de7df409cd8367e693f8eed52ba2
refs/heads/master
2023-01-24T06:04:29.905216
2019-07-02T12:19:47
2019-07-02T12:19:47
189,370,824
0
0
null
2023-01-02T22:12:39
2019-05-30T07:55:09
JavaScript
UTF-8
Java
false
false
1,966
java
package com.itheima.service.cargo.impl; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.itheima.commons.utils.UtilFuns; import com.itheima.dao.cargo.ContractDao; import com.itheima.domain.cargo.Contract; import com.itheima.domain.cargo.ContractExample; import com.itheima.service.cargo.ContractService; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; import java.util.List; /** * @author 黑马程序员 * @Company http://www.itheima.com */ @Service public class ContractServiceImpl implements ContractService { @Autowired private ContractDao contractDao; @Override public Contract findById(String id) { return contractDao.selectByPrimaryKey(id); } @Override public void save(Contract contract) { //1.设置购销合同的id contract.setId(UtilFuns.generateId()); //2.设置合同的总金额为0 contract.setTotalAmount(0d); //3.设置货物数和附件数为0 contract.setProNum(0); contract.setExtNum(0); //4.设置合同的状态为草稿:0草稿 1已上报 2已报运 contract.setState(0); //5.设置创建时间 contract.setCreateTime(new Date()); //6.保存 contractDao.insertSelective(contract); } @Override public void update(Contract contract) { contractDao.updateByPrimaryKeySelective(contract); } @Override public void delete(String id) { contractDao.deleteByPrimaryKey(id); } @Override public PageInfo findAll(ContractExample example, int page, int size) { //1.设置分页条件 PageHelper.startPage(page,size); //2.查询所有 List<Contract> contractList = contractDao.selectByExample(example); //3.返回分页对象 return new PageInfo(contractList); } }
d8a66fcac5b2f14af821cba704f6104039f83667
d718694c904a96b8d88e364ad535e34c58164889
/FlightsService/src/main/java/com/sep6/flights/model/flight/FlightDestination.java
a3e7c99a583f082db373dffe8af672413b4526bf
[]
no_license
Michaela97/SEP6
a455158904bdeb707914bfd6972ca9089f5d1212
08eb862bf79cd0f6b189190b27fd617863b6cb8d
refs/heads/master
2022-09-29T18:27:42.529936
2020-06-03T16:15:05
2020-06-03T16:15:05
262,758,180
0
0
null
2020-05-31T09:04:09
2020-05-10T10:03:24
HTML
UTF-8
Java
false
false
757
java
package com.sep6.flights.model.flight; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.NamedQuery; import javax.persistence.Entity; import javax.persistence.Id; @Entity @AllArgsConstructor @NoArgsConstructor @Data @NamedQuery(name = "FlightDestination.getNoOfFlightsByDestination", query = "select new com.sep6.flights.model.flight.FlightDestination( f.dest, count(f.id) as countOfFlights) " + "from Flight as f " + "where f.origin = :origin " + "group by f.dest " + "order by countOfFlights DESC") public class FlightDestination { @Id private String destination; private long countOfFlights; }
6a54026984d53136e5cbca9942bbcf197cd79f0d
a8f3457fb4d1f12f3706f6f3fda73befc66ddecf
/src/test/java/com/lance/test/dubbo/ICalculatorServiceTest.java
d986e8c5451904e6324c1d7cf4cf92220e20b9fa
[]
no_license
LanceHuang/test
ff636a45342119a132640db6a016e2b4b79a3ca5
5cf2cf95e736d06d2540cf2635a823cae23e32d6
refs/heads/master
2022-10-19T21:17:40.781477
2022-05-16T08:02:28
2022-05-16T08:02:28
101,545,043
0
1
null
2022-10-12T20:09:55
2017-08-27T10:26:47
Java
UTF-8
Java
false
false
601
java
package com.lance.test.dubbo; import com.alibaba.dubbo.config.annotation.Reference; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @ContextConfiguration("classpath:dubbo-demo-consumer.xml") public class ICalculatorServiceTest { @Reference private ICalculatorService calculatorService; @Test public void execute() { System.out.println(calculatorService.execute(6, 102)); } }
fdf6564b3fca893d5a0fdaad66bbbb4c00faa7fe
4dff6f1349cab3273261b53091dfa8ebf3bbfd0b
/AndroidQuickStartProject/app/src/main/java/com/devilwwj/pull/internal/IndicatorLayout.java
41a4db193992596cbb0026a85962948a05912287
[ "Apache-2.0" ]
permissive
devilWwj/AndroidQuickStartProject
bd552397b6dc508b8c9a818310b01c59ac5970fa
519c744362a6195542698f22bbab8cd48c5a10bb
refs/heads/master
2021-01-10T12:01:10.355860
2016-02-17T14:28:41
2016-02-17T14:28:41
49,260,104
3
0
null
null
null
null
UTF-8
Java
false
false
4,729
java
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * 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.devilwwj.pull.internal; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.view.View; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import com.devilwwj.app.R; import com.devilwwj.pull.PullToRefreshBase; @SuppressLint("ViewConstructor") public class IndicatorLayout extends FrameLayout implements AnimationListener { static final int DEFAULT_ROTATION_ANIMATION_DURATION = 150; private Animation mInAnim, mOutAnim; private ImageView mArrowImageView; private final Animation mRotateAnimation, mResetRotateAnimation; public IndicatorLayout(Context context, PullToRefreshBase.Mode mode) { super(context); mArrowImageView = new ImageView(context); Drawable arrowD = getResources().getDrawable(R.drawable.indicator_arrow); mArrowImageView.setImageDrawable(arrowD); final int padding = getResources().getDimensionPixelSize(R.dimen.indicator_internal_padding); mArrowImageView.setPadding(padding, padding, padding, padding); addView(mArrowImageView); int inAnimResId, outAnimResId; switch (mode) { case PULL_FROM_END: inAnimResId = R.anim.slide_in_from_bottom; outAnimResId = R.anim.slide_out_to_bottom; setBackgroundResource(R.drawable.indicator_bg_bottom); // Rotate Arrow so it's pointing the correct way mArrowImageView.setScaleType(ScaleType.MATRIX); Matrix matrix = new Matrix(); matrix.setRotate(180f, arrowD.getIntrinsicWidth() / 2f, arrowD.getIntrinsicHeight() / 2f); mArrowImageView.setImageMatrix(matrix); break; default: case PULL_FROM_START: inAnimResId = R.anim.slide_in_from_top; outAnimResId = R.anim.slide_out_to_top; setBackgroundResource(R.drawable.indicator_bg_top); break; } mInAnim = AnimationUtils.loadAnimation(context, inAnimResId); mInAnim.setAnimationListener(this); mOutAnim = AnimationUtils.loadAnimation(context, outAnimResId); mOutAnim.setAnimationListener(this); final Interpolator interpolator = new LinearInterpolator(); mRotateAnimation = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); mRotateAnimation.setInterpolator(interpolator); mRotateAnimation.setDuration(DEFAULT_ROTATION_ANIMATION_DURATION); mRotateAnimation.setFillAfter(true); mResetRotateAnimation = new RotateAnimation(-180, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); mResetRotateAnimation.setInterpolator(interpolator); mResetRotateAnimation.setDuration(DEFAULT_ROTATION_ANIMATION_DURATION); mResetRotateAnimation.setFillAfter(true); } public final boolean isVisible() { Animation currentAnim = getAnimation(); if (null != currentAnim) { return mInAnim == currentAnim; } return getVisibility() == View.VISIBLE; } public void hide() { startAnimation(mOutAnim); } public void show() { mArrowImageView.clearAnimation(); startAnimation(mInAnim); } @Override public void onAnimationEnd(Animation animation) { if (animation == mOutAnim) { mArrowImageView.clearAnimation(); setVisibility(View.GONE); } else if (animation == mInAnim) { setVisibility(View.VISIBLE); } clearAnimation(); } @Override public void onAnimationRepeat(Animation animation) { // NO-OP } @Override public void onAnimationStart(Animation animation) { setVisibility(View.VISIBLE); } public void releaseToRefresh() { mArrowImageView.startAnimation(mRotateAnimation); } public void pullToRefresh() { mArrowImageView.startAnimation(mResetRotateAnimation); } }
687fc2a219f8a6fcd7c4f02071f5727bda7aeeeb
996ad6ec9251e020c0b95370c5712c152efc73c4
/src/main/java/com/tuncays/issuemanagement/service/UserService.java
5f981af9a3a021412f0c30873bf93af614d319fd
[]
no_license
titanotank/issue-management
dc2f3e5dac066951e5df6b6cc2beeff67f72f7f1
40d78dfb9821324fa34d0eb02544e7a2ae632f4a
refs/heads/master
2020-12-10T23:59:56.909338
2020-01-27T16:48:29
2020-01-27T16:48:29
233,746,719
0
0
null
null
null
null
UTF-8
Java
false
false
423
java
package com.tuncays.issuemanagement.service; import com.tuncays.issuemanagement.entity.Project; import com.tuncays.issuemanagement.entity.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; public interface UserService { User save(User user); User getById(Long id); Page<User> getAllPageable(Pageable pageable); User getUserName(String username); }
893ea83332a73f744b70dc5dc8dec4c6110af7c7
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/17/17_c6e345856837e11986ae2a82cd1b6611804b05ca/FSNamesystem/17_c6e345856837e11986ae2a82cd1b6611804b05ca_FSNamesystem_s.java
b062bd1d3ea16743c4bad6a128341806d64f224f
[]
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
149,355
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.hadoop.dfs; import org.apache.commons.logging.*; import org.apache.hadoop.io.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.util.*; import org.apache.hadoop.mapred.StatusHttpServer; import org.apache.hadoop.net.NetworkTopology; import org.apache.hadoop.net.NodeBase; import org.apache.hadoop.fs.Path; import org.apache.hadoop.ipc.Server; import java.io.*; import java.util.*; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /*************************************************** * FSNamesystem does the actual bookkeeping work for the * DataNode. * * It tracks several important tables. * * 1) valid fsname --> blocklist (kept on disk, logged) * 2) Set of all valid blocks (inverted #1) * 3) block --> machinelist (kept in memory, rebuilt dynamically from reports) * 4) machine --> blocklist (inverted #2) * 5) LRU cache of updated-heartbeat machines ***************************************************/ class FSNamesystem implements FSConstants { public static final Log LOG = LogFactory.getLog("org.apache.hadoop.fs.FSNamesystem"); // // Stores the correct file name hierarchy // FSDirectory dir; // // Stores the block-->datanode(s) map. Updated only in response // to client-sent information. // Mapping: Block -> TreeSet<DatanodeDescriptor> // Map<Block, List<DatanodeDescriptor>> blocksMap = new HashMap<Block, List<DatanodeDescriptor>>(); /** * Stores the datanode -> block map. * <p> * Done by storing a set of {@link DatanodeDescriptor} objects, sorted by * storage id. In order to keep the storage map consistent it tracks * all storages ever registered with the namenode. * A descriptor corresponding to a specific storage id can be * <ul> * <li>added to the map if it is a new storage id;</li> * <li>updated with a new datanode started as a replacement for the old one * with the same storage id; and </li> * <li>removed if and only if an existing datanode is restarted to serve a * different storage id.</li> * </ul> <br> * The list of the {@link DatanodeDescriptor}s in the map is checkpointed * in the namespace image file. Only the {@link DatanodeInfo} part is * persistent, the list of blocks is restored from the datanode block * reports. * <p> * Mapping: StorageID -> DatanodeDescriptor */ Map<String, DatanodeDescriptor> datanodeMap = new TreeMap<String, DatanodeDescriptor>(); // // Keeps a Collection for every named machine containing // blocks that have recently been invalidated and are thought to live // on the machine in question. // Mapping: StorageID -> ArrayList<Block> // private Map<String, Collection<Block>> recentInvalidateSets = new TreeMap<String, Collection<Block>>(); // // Keeps a TreeSet for every named node. Each treeset contains // a list of the blocks that are "extra" at that location. We'll // eventually remove these extras. // Mapping: StorageID -> TreeSet<Block> // private Map<String, Collection<Block>> excessReplicateMap = new TreeMap<String, Collection<Block>>(); // // Keeps track of files that are being created, plus the // blocks that make them up. // Mapping: fileName -> FileUnderConstruction // Map<UTF8, FileUnderConstruction> pendingCreates = new TreeMap<UTF8, FileUnderConstruction>(); // // Keeps track of the blocks that are part of those pending creates // Set of: Block // Collection<Block> pendingCreateBlocks = new TreeSet<Block>(); // // Stats on overall usage // long totalCapacity = 0, totalRemaining = 0; // total number of connections per live datanode int totalLoad = 0; // // For the HTTP browsing interface // StatusHttpServer infoServer; int infoPort; String infoBindAddress; Date startTime; // Random r = new Random(); /** * Stores a set of DatanodeDescriptor objects. * This is a subset of {@link #datanodeMap}, containing nodes that are * considered alive. * The {@link HeartbeatMonitor} periodically checks for outdated entries, * and removes them from the list. */ ArrayList<DatanodeDescriptor> heartbeats = new ArrayList<DatanodeDescriptor>(); // // Store set of Blocks that need to be replicated 1 or more times. // We also store pending replication-orders. // Set of: Block // private UnderReplicatedBlocks neededReplications = new UnderReplicatedBlocks(); private PendingReplicationBlocks pendingReplications; // // Used for handling lock-leases // Mapping: leaseHolder -> Lease // private Map<UTF8, Lease> leases = new TreeMap<UTF8, Lease>(); // Set of: Lease private SortedSet<Lease> sortedLeases = new TreeSet<Lease>(); // // Threaded object that checks to see if we have been // getting heartbeats from all clients. // Daemon hbthread = null; // HeartbeatMonitor thread Daemon lmthread = null; // LeaseMonitor thread Daemon smmthread = null; // SafeModeMonitor thread Daemon replthread = null; // Replication thread boolean fsRunning = true; long systemStart = 0; // The maximum number of replicates we should allow for a single block private int maxReplication; // How many outgoing replication streams a given node should have at one time private int maxReplicationStreams; // MIN_REPLICATION is how many copies we need in place or else we disallow the write private int minReplication; // Default replication private int defaultReplication; // heartbeatRecheckInterval is how often namenode checks for expired datanodes private long heartbeatRecheckInterval; // heartbeatExpireInterval is how long namenode waits for datanode to report // heartbeat private long heartbeatExpireInterval; //replicationRecheckInterval is how often namenode checks for new replication work private long replicationRecheckInterval; static int replIndex = 0; // last datanode used for replication work static int REPL_WORK_PER_ITERATION = 32; // max percent datanodes per iteration public static FSNamesystem fsNamesystemObject; private String localMachine; private int port; private SafeModeInfo safeMode; // safe mode information // datanode networktoplogy NetworkTopology clusterMap = new NetworkTopology(); // for block replicas placement ReplicationTargetChooser replicator; private HostsFileReader hostsReader; private Daemon dnthread = null; /** * dirs is a list oif directories where the filesystem directory state * is stored */ public FSNamesystem(File[] dirs, String hostname, int port, NameNode nn, Configuration conf) throws IOException { fsNamesystemObject = this; this.replicator = new ReplicationTargetChooser( conf.getBoolean("dfs.replication.considerLoad", true)); this.defaultReplication = conf.getInt("dfs.replication", 3); this.maxReplication = conf.getInt("dfs.replication.max", 512); this.minReplication = conf.getInt("dfs.replication.min", 1); if( minReplication <= 0 ) throw new IOException( "Unexpected configuration parameters: dfs.replication.min = " + minReplication + " must be greater than 0" ); if( maxReplication >= (int)Short.MAX_VALUE ) throw new IOException( "Unexpected configuration parameters: dfs.replication.max = " + maxReplication + " must be less than " + (Short.MAX_VALUE) ); if( maxReplication < minReplication ) throw new IOException( "Unexpected configuration parameters: dfs.replication.min = " + minReplication + " must be less than dfs.replication.max = " + maxReplication ); this.maxReplicationStreams = conf.getInt("dfs.max-repl-streams", 2); long heartbeatInterval = conf.getLong("dfs.heartbeat.interval", 3) * 1000; this.heartbeatRecheckInterval = 5 * 60 * 1000; // 5 minutes this.heartbeatExpireInterval = 2 * heartbeatRecheckInterval + 10 * heartbeatInterval; this.replicationRecheckInterval = 3 * 1000; // 3 second this.localMachine = hostname; this.port = port; this.dir = new FSDirectory(dirs); this.dir.loadFSImage( conf ); this.safeMode = new SafeModeInfo( conf ); setBlockTotal(); pendingReplications = new PendingReplicationBlocks(LOG); this.hbthread = new Daemon(new HeartbeatMonitor()); this.lmthread = new Daemon(new LeaseMonitor()); this.replthread = new Daemon(new ReplicationMonitor()); hbthread.start(); lmthread.start(); replthread.start(); this.systemStart = now(); this.startTime = new Date(systemStart); this.hostsReader = new HostsFileReader(conf.get("dfs.hosts",""), conf.get("dfs.hosts.exclude","")); this.dnthread = new Daemon(new DecommissionedMonitor()); dnthread.start(); this.infoPort = conf.getInt("dfs.info.port", 50070); this.infoBindAddress = conf.get("dfs.info.bindAddress", "0.0.0.0"); this.infoServer = new StatusHttpServer("dfs",infoBindAddress, infoPort, false); this.infoServer.setAttribute("name.system", this); this.infoServer.setAttribute("name.node", nn); this.infoServer.setAttribute("name.conf", conf); this.infoServer.addServlet("fsck", "/fsck", FsckServlet.class); this.infoServer.addServlet("getimage", "/getimage", GetImageServlet.class); this.infoServer.start(); } /** * dirs is a list of directories where the filesystem directory state * is stored */ FSNamesystem(FSImage fsImage) throws IOException { fsNamesystemObject = this; this.dir = new FSDirectory(fsImage); } /** Return the FSNamesystem object * */ public static FSNamesystem getFSNamesystem() { return fsNamesystemObject; } /** Close down this filesystem manager. * Causes heartbeat and lease daemons to stop; waits briefly for * them to finish, but a short timeout returns control back to caller. */ public void close() { synchronized (this) { fsRunning = false; } try { pendingReplications.stop(); infoServer.stop(); hbthread.join(3000); replthread.join(3000); dnthread.join(3000); } catch (InterruptedException ie) { } finally { // using finally to ensure we also wait for lease daemon try { lmthread.join(3000); } catch (InterruptedException ie) { } finally { try { dir.close(); } catch (IOException ex) { // do nothing } } } } /* get replication factor of a block */ private int getReplication( Block block ) { FSDirectory.INode fileINode = dir.getFileByBlock(block); if( fileINode == null ) { // block does not belong to any file return 0; } else { return fileINode.getReplication(); } } /* Class for keeping track of under replication blocks * Blocks have replication priority, with priority 0 indicating the highest * Blocks have only one replicas has the highest */ private class UnderReplicatedBlocks { private static final int LEVEL = 3; TreeSet<Block>[] priorityQueues = new TreeSet[LEVEL]; /* constructor */ UnderReplicatedBlocks() { for(int i=0; i<LEVEL; i++) { priorityQueues[i] = new TreeSet<Block>(); } } /* Return the total number of under replication blocks */ synchronized int size() { int size = 0; for( int i=0; i<LEVEL; i++ ) { size += priorityQueues[i].size(); } return size; } /* Check if a block is in the neededReplication queue */ synchronized boolean contains(Block block) { for(TreeSet<Block> set:priorityQueues) { if(set.contains(block)) return true; } return false; } /* Return the priority of a block * @param block a under replication block * @param curReplicas current number of replicas of the block * @param expectedReplicas expected number of replicas of the block */ private int getPriority(Block block, int curReplicas, int expectedReplicas) { if (curReplicas<=0 || curReplicas>=expectedReplicas) { return LEVEL; // no need to replicate } else if(curReplicas==1) { return 0; // highest priority } else if(curReplicas*3<expectedReplicas) { return 1; } else { return 2; } } /* add a block to a under replication queue according to its priority * @param block a under replication block * @param curReplicas current number of replicas of the block * @param expectedReplicas expected number of replicas of the block */ synchronized boolean add( Block block, int curReplicas, int expectedReplicas) { if(expectedReplicas <= curReplicas) { return false; } int priLevel = getPriority(block, curReplicas, expectedReplicas); if( priorityQueues[priLevel].add(block) ) { NameNode.stateChangeLog.debug( "BLOCK* NameSystem.UnderReplicationBlock.add:" + block.getBlockName() + " has only "+curReplicas + " replicas and need " + expectedReplicas + " replicas so is added to neededReplications" + " at priority level " + priLevel ); return true; } return false; } /* add a block to a under replication queue */ synchronized boolean add(Block block) { int curReplicas = countContainingNodes(blocksMap.get(block)); int expectedReplicas = getReplication(block); return add(block, curReplicas, expectedReplicas); } /* remove a block from a under replication queue */ synchronized boolean remove(Block block, int oldReplicas, int oldExpectedReplicas) { int priLevel = getPriority(block, oldReplicas, oldExpectedReplicas); return remove(block, priLevel); } /* remove a block from a under replication queue given a priority*/ private boolean remove(Block block, int priLevel ) { if( priLevel >= 0 && priLevel < LEVEL && priorityQueues[priLevel].remove(block) ) { NameNode.stateChangeLog.debug( "BLOCK* NameSystem.UnderReplicationBlock.remove: " + "Removing block " + block.getBlockName() + " from priority queue "+ priLevel ); return true; } else { for(int i=0; i<LEVEL; i++) { if( i!=priLevel && priorityQueues[i].remove(block) ) { NameNode.stateChangeLog.debug( "BLOCK* NameSystem.UnderReplicationBlock.remove: " + "Removing block " + block.getBlockName() + " from priority queue "+ i ); return true; } } } return false; } /* remove a block from a under replication queue */ synchronized boolean remove(Block block) { int curReplicas = countContainingNodes(blocksMap.get(block)); int expectedReplicas = getReplication(block); return remove(block, curReplicas, expectedReplicas); } /* update the priority level of a block */ synchronized void update(Block block, int curReplicasDelta, int expectedReplicasDelta) { int curReplicas = countContainingNodes(blocksMap.get(block)); int curExpectedReplicas = getReplication(block); int oldReplicas = curReplicas-curReplicasDelta; int oldExpectedReplicas = curExpectedReplicas-expectedReplicasDelta; int curPri = getPriority(block, curReplicas, curExpectedReplicas); int oldPri = getPriority(block, oldReplicas, oldExpectedReplicas); NameNode.stateChangeLog.debug("UnderReplicationBlocks.update " + block + " curReplicas " + curReplicas + " curExpectedReplicas " + curExpectedReplicas + " oldReplicas " + oldReplicas + " oldExpectedReplicas " + oldExpectedReplicas + " curPri " + curPri + " oldPri " + oldPri); if( oldPri != LEVEL && oldPri != curPri ) { remove(block, oldPri); } if( curPri != LEVEL && oldPri != curPri && priorityQueues[curPri].add(block)) { NameNode.stateChangeLog.debug( "BLOCK* NameSystem.UnderReplicationBlock.update:" + block.getBlockName() + " has only "+curReplicas + " replicas and need " + curExpectedReplicas + " replicas so is added to neededReplications" + " at priority level " + curPri ); } } /* return a iterator of all the under replication blocks */ synchronized Iterator<Block> iterator() { return new Iterator<Block>() { int level; Iterator<Block>[] iterator = new Iterator[LEVEL]; { level=0; for(int i=0; i<LEVEL; i++) { iterator[i] = priorityQueues[i].iterator(); } } private void update() { while( level< LEVEL-1 && !iterator[level].hasNext() ) { level++; } } public Block next() { update(); return iterator[level].next(); } public boolean hasNext() { update(); return iterator[level].hasNext(); } public void remove() { iterator[level].remove(); } }; } } ///////////////////////////////////////////////////////// // // These methods are called by HadoopFS clients // ///////////////////////////////////////////////////////// /** * The client wants to open the given filename. Return a * list of (block,machineArray) pairs. The sequence of unique blocks * in the list indicates all the blocks that make up the filename. * * The client should choose one of the machines from the machineArray * at random. */ public Object[] open(String clientMachine, UTF8 src) { Object results[] = null; Block blocks[] = dir.getFile(src); if (blocks != null) { results = new Object[2]; DatanodeDescriptor machineSets[][] = new DatanodeDescriptor[blocks.length][]; for (int i = 0; i < blocks.length; i++) { Collection<DatanodeDescriptor> containingNodes = blocksMap.get(blocks[i]); if (containingNodes == null) { machineSets[i] = new DatanodeDescriptor[0]; } else { machineSets[i] = new DatanodeDescriptor[containingNodes.size()]; ArrayList<DatanodeDescriptor> containingNodesList = new ArrayList<DatanodeDescriptor>(containingNodes.size()); containingNodesList.addAll(containingNodes); machineSets[i] = replicator.sortByDistance( getDatanodeByHost(clientMachine), containingNodesList); } } results[0] = blocks; results[1] = machineSets; } return results; } /** * Set replication for an existing file. * * The NameNode sets new replication and schedules either replication of * under-replicated data blocks or removal of the eccessive block copies * if the blocks are over-replicated. * * @see ClientProtocol#setReplication(String, short) * @param src file name * @param replication new replication * @return true if successful; * false if file does not exist or is a directory * @author shv */ public synchronized boolean setReplication(String src, short replication ) throws IOException { if( isInSafeMode() ) throw new SafeModeException( "Cannot set replication for " + src, safeMode ); verifyReplication(src, replication, null ); Vector<Integer> oldReplication = new Vector<Integer>(); Block[] fileBlocks; fileBlocks = dir.setReplication( src, replication, oldReplication ); if( fileBlocks == null ) // file not found or is a directory return false; int oldRepl = oldReplication.elementAt(0).intValue(); if( oldRepl == replication ) // the same replication return true; // update needReplication priority queues LOG.info("Increasing replication for file " + src + ". New replication is " + replication ); for( int idx = 0; idx < fileBlocks.length; idx++ ) neededReplications.update( fileBlocks[idx], 0, replication-oldRepl ); if( oldRepl > replication ) { // old replication > the new one; need to remove copies LOG.info("Reducing replication for file " + src + ". New replication is " + replication ); for( int idx = 0; idx < fileBlocks.length; idx++ ) proccessOverReplicatedBlock( fileBlocks[idx], replication ); } return true; } public long getBlockSize(String filename) throws IOException { return dir.getBlockSize(filename); } /** * Check whether the replication parameter is within the range * determined by system configuration. */ private void verifyReplication( String src, short replication, UTF8 clientName ) throws IOException { String text = "file " + src + ((clientName != null) ? " on client " + clientName : "") + ".\n" + "Requested replication " + replication; if( replication > maxReplication ) throw new IOException( text + " exceeds maximum " + maxReplication ); if( replication < minReplication ) throw new IOException( text + " is less than the required minimum " + minReplication ); } /** * The client would like to create a new block for the indicated * filename. Return an array that consists of the block, plus a set * of machines. The first on this list should be where the client * writes data. Subsequent items in the list must be provided in * the connection to the first datanode. * @return Return an array that consists of the block, plus a set * of machines * @throws IOException if the filename is invalid * {@link FSDirectory#isValidToCreate(UTF8)}. */ public synchronized Object[] startFile( UTF8 src, UTF8 holder, UTF8 clientMachine, boolean overwrite, short replication, long blockSize ) throws IOException { NameNode.stateChangeLog.debug("DIR* NameSystem.startFile: file " +src+" for "+holder+" at "+clientMachine); if( isInSafeMode() ) throw new SafeModeException( "Cannot create file" + src, safeMode ); if (!isValidName(src.toString())) { throw new IOException("Invalid file name: " + src); } try { FileUnderConstruction pendingFile = pendingCreates.get(src); if (pendingFile != null) { // // If the file exists in pendingCreate, then it must be in our // leases. Find the appropriate lease record. // Lease lease = leases.get(holder); // // We found the lease for this file. And surprisingly the original // holder is trying to recreate this file. This should never occur. // if (lease != null) { throw new AlreadyBeingCreatedException( "failed to create file " + src + " for " + holder + " on client " + clientMachine + " because current leaseholder is trying to recreate file."); } // // Find the original holder. // UTF8 oldholder = pendingFile.getClientName(); lease = leases.get(oldholder); if (lease == null) { throw new AlreadyBeingCreatedException( "failed to create file " + src + " for " + holder + " on client " + clientMachine + " because pendingCreates is non-null but no leases found."); } // // If the original holder has not renewed in the last SOFTLIMIT // period, then reclaim all resources and allow this request // to proceed. Otherwise, prevent this request from creating file. // if (lease.expiredSoftLimit()) { lease.releaseLocks(); leases.remove(lease.holder); LOG.info("Removing lease " + lease + " "); if (!sortedLeases.remove(lease)) { LOG.error("Unknown failure trying to remove " + lease + " from lease set."); } } else { throw new AlreadyBeingCreatedException( "failed to create file " + src + " for " + holder + " on client " + clientMachine + " because pendingCreates is non-null."); } } try { verifyReplication(src.toString(), replication, clientMachine ); } catch( IOException e) { throw new IOException( "failed to create "+e.getMessage()); } if (!dir.isValidToCreate(src)) { if (overwrite) { delete(src); } else { throw new IOException("failed to create file " + src +" on client " + clientMachine +" either because the filename is invalid or the file exists"); } } // Get the array of replication targets DatanodeDescriptor targets[] = replicator.chooseTarget(replication, getDatanodeByHost(clientMachine.toString()), null, blockSize); if (targets.length < this.minReplication) { throw new IOException("failed to create file "+src +" on client " + clientMachine +" because target-length is " + targets.length +", below MIN_REPLICATION (" + minReplication+ ")"); } // Reserve space for this pending file pendingCreates.put(src, new FileUnderConstruction(replication, blockSize, holder, clientMachine)); NameNode.stateChangeLog.debug( "DIR* NameSystem.startFile: " +"add "+src+" to pendingCreates for "+holder ); synchronized (leases) { Lease lease = leases.get(holder); if (lease == null) { lease = new Lease(holder); leases.put(holder, lease); sortedLeases.add(lease); } else { sortedLeases.remove(lease); lease.renew(); sortedLeases.add(lease); } lease.startedCreate(src); } // Create next block Object results[] = new Object[2]; results[0] = allocateBlock(src); results[1] = targets; return results; } catch (IOException ie) { NameNode.stateChangeLog.warn("DIR* NameSystem.startFile: " +ie.getMessage()); throw ie; } } /** * The client would like to obtain an additional block for the indicated * filename (which is being written-to). Return an array that consists * of the block, plus a set of machines. The first on this list should * be where the client writes data. Subsequent items in the list must * be provided in the connection to the first datanode. * * Make sure the previous blocks have been reported by datanodes and * are replicated. Will return an empty 2-elt array if we want the * client to "try again later". */ public synchronized Object[] getAdditionalBlock(UTF8 src, UTF8 clientName ) throws IOException { NameNode.stateChangeLog.debug("BLOCK* NameSystem.getAdditionalBlock: file " +src+" for "+clientName); if( isInSafeMode() ) throw new SafeModeException( "Cannot add block to " + src, safeMode ); FileUnderConstruction pendingFile = pendingCreates.get(src); // make sure that we still have the lease on this file if (pendingFile == null) { throw new LeaseExpiredException("No lease on " + src); } if (!pendingFile.getClientName().equals(clientName)) { throw new LeaseExpiredException("Lease mismatch on " + src + " owned by " + pendingFile.getClientName() + " and appended by " + clientName); } if (dir.getFile(src) != null) { throw new IOException("File " + src + " created during write"); } // // If we fail this, bad things happen! // if (!checkFileProgress(src)) { throw new NotReplicatedYetException("Not replicated yet"); } // Get the array of replication targets String clientHost = pendingFile.getClientMachine().toString(); DatanodeDescriptor targets[] = replicator.chooseTarget( (int)(pendingFile.getReplication()), getDatanodeByHost(clientHost), null, pendingFile.getBlockSize()); if (targets.length < this.minReplication) { throw new IOException("File " + src + " could only be replicated to " + targets.length + " nodes, instead of " + minReplication); } // Create next block return new Object[]{allocateBlock(src), targets}; } /** * The client would like to let go of the given block */ public synchronized boolean abandonBlock(Block b, UTF8 src) { // // Remove the block from the pending creates list // NameNode.stateChangeLog.debug("BLOCK* NameSystem.abandonBlock: " +b.getBlockName()+"of file "+src ); FileUnderConstruction pendingFile = pendingCreates.get(src); if (pendingFile != null) { Collection<Block> pendingVector = pendingFile.getBlocks(); for (Iterator<Block> it = pendingVector.iterator(); it.hasNext(); ) { Block cur = it.next(); if (cur.compareTo(b) == 0) { pendingCreateBlocks.remove(cur); it.remove(); NameNode.stateChangeLog.debug( "BLOCK* NameSystem.abandonBlock: " +b.getBlockName() +" is removed from pendingCreateBlock and pendingCreates"); return true; } } } return false; } /** * Abandon the entire file in progress */ public synchronized void abandonFileInProgress(UTF8 src, UTF8 holder ) throws IOException { NameNode.stateChangeLog.debug("DIR* NameSystem.abandonFileInProgress:" + src ); synchronized (leases) { // find the lease Lease lease = leases.get(holder); if (lease != null) { // remove the file from the lease if (lease.completedCreate(src)) { // if we found the file in the lease, remove it from pendingCreates internalReleaseCreate(src, holder); } else { LOG.info("Attempt by " + holder.toString() + " to release someone else's create lock on " + src.toString()); } } else { LOG.info("Attempt to release a lock from an unknown lease holder " + holder.toString() + " for " + src.toString()); } } } /** * Finalize the created file and make it world-accessible. The * FSNamesystem will already know the blocks that make up the file. * Before we return, we make sure that all the file's blocks have * been reported by datanodes and are replicated correctly. */ public synchronized int completeFile( UTF8 src, UTF8 holder) throws IOException { NameNode.stateChangeLog.debug("DIR* NameSystem.completeFile: " + src + " for " + holder ); if( isInSafeMode() ) throw new SafeModeException( "Cannot complete file " + src, safeMode ); if (dir.getFile(src) != null || pendingCreates.get(src) == null) { NameNode.stateChangeLog.warn( "DIR* NameSystem.completeFile: " + "failed to complete " + src + " because dir.getFile()==" + dir.getFile(src) + " and " + pendingCreates.get(src)); return OPERATION_FAILED; } else if (! checkFileProgress(src)) { return STILL_WAITING; } FileUnderConstruction pendingFile = pendingCreates.get(src); Collection<Block> blocks = pendingFile.getBlocks(); int nrBlocks = blocks.size(); Block pendingBlocks[] = blocks.toArray(new Block[nrBlocks]); // // We have the pending blocks, but they won't have // length info in them (as they were allocated before // data-write took place). Find the block stored in // node descriptor. // for (int i = 0; i < nrBlocks; i++) { Block b = pendingBlocks[i]; List<DatanodeDescriptor> containingNodes = blocksMap.get(b); Block storedBlock = containingNodes.get(0).getBlock(b); if ( storedBlock != null ) { pendingBlocks[i] = storedBlock; } } // // Now we can add the (name,blocks) tuple to the filesystem // if ( ! dir.addFile(src, pendingBlocks, pendingFile.getReplication())) { return OPERATION_FAILED; } // The file is no longer pending pendingCreates.remove(src); NameNode.stateChangeLog.debug( "DIR* NameSystem.completeFile: " + src + " is removed from pendingCreates"); for (int i = 0; i < nrBlocks; i++) { pendingCreateBlocks.remove(pendingBlocks[i]); } synchronized (leases) { Lease lease = leases.get(holder); if (lease != null) { lease.completedCreate(src); if (! lease.hasLocks()) { leases.remove(holder); sortedLeases.remove(lease); } } } // // REMIND - mjc - this should be done only after we wait a few secs. // The namenode isn't giving datanodes enough time to report the // replicated blocks that are automatically done as part of a client // write. // // Now that the file is real, we need to be sure to replicate // the blocks. int numExpectedReplicas = pendingFile.getReplication(); for (int i = 0; i < nrBlocks; i++) { Collection<DatanodeDescriptor> containingNodes = blocksMap.get(pendingBlocks[i]); // filter out containingNodes that are marked for decommission. int numCurrentReplica = countContainingNodes(containingNodes); if (numCurrentReplica < numExpectedReplicas) { neededReplications.add( pendingBlocks[i], numCurrentReplica, numExpectedReplicas); } } return COMPLETE_SUCCESS; } static Random randBlockId = new Random(); /** * Allocate a block at the given pending filename */ synchronized Block allocateBlock(UTF8 src) { Block b = null; do { b = new Block(FSNamesystem.randBlockId.nextLong(), 0); } while (dir.isValidBlock(b)); FileUnderConstruction v = pendingCreates.get(src); v.getBlocks().add(b); pendingCreateBlocks.add(b); NameNode.stateChangeLog.debug("BLOCK* NameSystem.allocateBlock: " +src+ ". "+b.getBlockName()+ " is created and added to pendingCreates and pendingCreateBlocks" ); return b; } /** * Check that the indicated file's blocks are present and * replicated. If not, return false. */ synchronized boolean checkFileProgress(UTF8 src) { FileUnderConstruction v = pendingCreates.get(src); for (Iterator<Block> it = v.getBlocks().iterator(); it.hasNext(); ) { Block b = it.next(); Collection<DatanodeDescriptor> containingNodes = blocksMap.get(b); if (containingNodes == null || containingNodes.size() < this.minReplication) { return false; } } return true; } /** * Adds block to list of blocks which will be invalidated on * specified datanode. */ private void addToInvalidates(Block b, DatanodeInfo n) { Collection<Block> invalidateSet = recentInvalidateSets.get(n.getStorageID()); if (invalidateSet == null) { invalidateSet = new ArrayList<Block>(); recentInvalidateSets.put(n.getStorageID(), invalidateSet); } invalidateSet.add(b); } /** * Invalidates the given block on the given datanode. */ public synchronized void invalidateBlock(Block blk, DatanodeInfo dn) throws IOException { NameNode.stateChangeLog.info("DIR* NameSystem.invalidateBlock: " + blk.getBlockName() + " on " + dn.getName()); if (isInSafeMode()) { throw new SafeModeException("Cannot invalidate block " + blk.getBlockName(), safeMode); } Collection<DatanodeDescriptor> containingNodes = blocksMap.get(blk); // Check how many copies we have of the block. If we have at least one // copy on a live node, then we can delete it. if (containingNodes != null ) { if ((countContainingNodes(containingNodes) > 1) || ((countContainingNodes(containingNodes) == 1) && (dn.isDecommissionInProgress() || dn.isDecommissioned()))) { addToInvalidates(blk, dn); removeStoredBlock(blk, getDatanode(dn)); NameNode.stateChangeLog.info("BLOCK* NameSystem.invalidateBlocks: " + blk.getBlockName() + " on " + dn.getName() + " listed for deletion."); } else { NameNode.stateChangeLog.info("BLOCK* NameSystem.invalidateBlocks: " + blk.getBlockName() + " on " + dn.getName() + " is the only copy and was not deleted."); } } } //////////////////////////////////////////////////////////////// // Here's how to handle block-copy failure during client write: // -- As usual, the client's write should result in a streaming // backup write to a k-machine sequence. // -- If one of the backup machines fails, no worries. Fail silently. // -- Before client is allowed to close and finalize file, make sure // that the blocks are backed up. Namenode may have to issue specific backup // commands to make up for earlier datanode failures. Once all copies // are made, edit namespace and return to client. //////////////////////////////////////////////////////////////// /** * Change the indicated filename. */ public synchronized boolean renameTo(UTF8 src, UTF8 dst) throws IOException { NameNode.stateChangeLog.debug("DIR* NameSystem.renameTo: " + src + " to " + dst ); if( isInSafeMode() ) throw new SafeModeException( "Cannot rename " + src, safeMode ); if (!isValidName(dst.toString())) { throw new IOException("Invalid name: " + dst); } return dir.renameTo(src, dst); } /** * Remove the indicated filename from the namespace. This may * invalidate some blocks that make up the file. */ public synchronized boolean delete(UTF8 src) throws IOException { NameNode.stateChangeLog.debug("DIR* NameSystem.delete: " + src ); if( isInSafeMode() ) throw new SafeModeException( "Cannot delete " + src, safeMode ); Block deletedBlocks[] = dir.delete(src); if (deletedBlocks != null) { for (int i = 0; i < deletedBlocks.length; i++) { Block b = deletedBlocks[i]; Collection<DatanodeDescriptor> containingNodes = blocksMap.get(b); if (containingNodes != null) { for (Iterator<DatanodeDescriptor> it = containingNodes.iterator(); it.hasNext(); ) { DatanodeDescriptor node = it.next(); addToInvalidates(b, node); NameNode.stateChangeLog.debug("BLOCK* NameSystem.delete: " + b.getBlockName() + " is added to invalidSet of " + node.getName() ); } } } } return (deletedBlocks != null); } /** * Return whether the given filename exists */ public boolean exists(UTF8 src) { if (dir.getFile(src) != null || dir.isDir(src)) { return true; } else { return false; } } /** * Whether the given name is a directory */ public boolean isDir(UTF8 src) { return dir.isDir(src); } /** * Whether the pathname is valid. Currently prohibits relative paths, * and names which contain a ":" or "/" */ static boolean isValidName(String src) { // Path must be absolute. if (!src.startsWith(Path.SEPARATOR)) { return false; } // Check for ".." "." ":" "/" StringTokenizer tokens = new StringTokenizer(src, Path.SEPARATOR); while( tokens.hasMoreTokens()) { String element = tokens.nextToken(); if (element.equals("..") || element.equals(".") || (element.indexOf(":") >= 0) || (element.indexOf("/") >= 0)) { return false; } } return true; } /** * Create all the necessary directories */ public synchronized boolean mkdirs( String src ) throws IOException { boolean success; NameNode.stateChangeLog.debug("DIR* NameSystem.mkdirs: " + src ); if( isInSafeMode() ) throw new SafeModeException( "Cannot create directory " + src, safeMode ); if (!isValidName(src)) { throw new IOException("Invalid directory name: " + src); } success = dir.mkdirs(src); if (!success) { throw new IOException("Invalid directory name: " + src); } return success; } /** * Figure out a few hosts that are likely to contain the * block(s) referred to by the given (filename, start, len) tuple. */ public String[][] getDatanodeHints(String src, long start, long len) { if (start < 0 || len < 0) { return new String[0][]; } int startBlock = -1; int endBlock = -1; Block blocks[] = dir.getFile( new UTF8( src )); if (blocks == null) { // no blocks return new String[0][]; } // // First, figure out where the range falls in // the blocklist. // long startpos = start; long endpos = start + len; for (int i = 0; i < blocks.length; i++) { if (startpos >= 0) { startpos -= blocks[i].getNumBytes(); if (startpos <= 0) { startBlock = i; } } if (endpos >= 0) { endpos -= blocks[i].getNumBytes(); if (endpos <= 0) { endBlock = i; break; } } } // // Next, create an array of hosts where each block can // be found // if (startBlock < 0 || endBlock < 0) { return new String[0][]; } else { String hosts[][] = new String[(endBlock - startBlock) + 1][]; for (int i = startBlock; i <= endBlock; i++) { Collection<DatanodeDescriptor> containingNodes = blocksMap.get(blocks[i]); Collection<String> v = new ArrayList<String>(); if (containingNodes != null) { for (Iterator<DatanodeDescriptor> it =containingNodes.iterator(); it.hasNext();) { v.add( it.next().getHostName() ); } } hosts[i-startBlock] = v.toArray(new String[v.size()]); } return hosts; } } /************************************************************ * A Lease governs all the locks held by a single client. * For each client there's a corresponding lease, whose * timestamp is updated when the client periodically * checks in. If the client dies and allows its lease to * expire, all the corresponding locks can be released. *************************************************************/ class Lease implements Comparable<Lease> { public UTF8 holder; public long lastUpdate; private Collection<UTF8> locks = new TreeSet<UTF8>(); private Collection<UTF8> creates = new TreeSet<UTF8>(); public Lease(UTF8 holder) { this.holder = holder; renew(); } public void renew() { this.lastUpdate = now(); } /** * Returns true if the Hard Limit Timer has expired */ public boolean expiredHardLimit() { if (now() - lastUpdate > LEASE_HARDLIMIT_PERIOD) { return true; } return false; } /** * Returns true if the Soft Limit Timer has expired */ public boolean expiredSoftLimit() { if (now() - lastUpdate > LEASE_SOFTLIMIT_PERIOD) { return true; } return false; } public void obtained(UTF8 src) { locks.add(src); } public void released(UTF8 src) { locks.remove(src); } public void startedCreate(UTF8 src) { creates.add(src); } public boolean completedCreate(UTF8 src) { return creates.remove(src); } public boolean hasLocks() { return (locks.size() + creates.size()) > 0; } public void releaseLocks() { for (Iterator<UTF8> it = locks.iterator(); it.hasNext(); ) internalReleaseLock(it.next(), holder); locks.clear(); for (Iterator<UTF8> it = creates.iterator(); it.hasNext(); ) internalReleaseCreate(it.next(), holder); creates.clear(); } /** */ public String toString() { return "[Lease. Holder: " + holder.toString() + ", heldlocks: " + locks.size() + ", pendingcreates: " + creates.size() + "]"; } /** */ public int compareTo(Lease o) { Lease l1 = this; Lease l2 = o; long lu1 = l1.lastUpdate; long lu2 = l2.lastUpdate; if (lu1 < lu2) { return -1; } else if (lu1 > lu2) { return 1; } else { return l1.holder.compareTo(l2.holder); } } } /****************************************************** * LeaseMonitor checks for leases that have expired, * and disposes of them. ******************************************************/ class LeaseMonitor implements Runnable { public void run() { while (fsRunning) { synchronized (FSNamesystem.this) { synchronized (leases) { Lease top; while ((sortedLeases.size() > 0) && ((top = sortedLeases.first()) != null)) { if (top.expiredHardLimit()) { top.releaseLocks(); leases.remove(top.holder); LOG.info("Removing lease " + top + ", leases remaining: " + sortedLeases.size()); if (!sortedLeases.remove(top)) { LOG.info("Unknown failure trying to remove " + top + " from lease set."); } } else { break; } } } } try { Thread.sleep(2000); } catch (InterruptedException ie) { } } } } /** * Get a lock (perhaps exclusive) on the given file */ /** @deprecated */ @Deprecated public synchronized int obtainLock( UTF8 src, UTF8 holder, boolean exclusive) throws IOException { if( isInSafeMode() ) throw new SafeModeException( "Cannot lock file " + src, safeMode ); int result = dir.obtainLock(src, holder, exclusive); if (result == COMPLETE_SUCCESS) { synchronized (leases) { Lease lease = leases.get(holder); if (lease == null) { lease = new Lease(holder); leases.put(holder, lease); sortedLeases.add(lease); } else { sortedLeases.remove(lease); lease.renew(); sortedLeases.add(lease); } lease.obtained(src); } } return result; } /** * Release the lock on the given file */ /** @deprecated */ @Deprecated public synchronized int releaseLock(UTF8 src, UTF8 holder) { int result = internalReleaseLock(src, holder); if (result == COMPLETE_SUCCESS) { synchronized (leases) { Lease lease = leases.get(holder); if (lease != null) { lease.released(src); if (! lease.hasLocks()) { leases.remove(holder); sortedLeases.remove(lease); } } } } return result; } private int internalReleaseLock(UTF8 src, UTF8 holder) { return dir.releaseLock(src, holder); } /** * Release a pending file creation lock. * @param src The filename * @param holder The datanode that was creating the file */ private void internalReleaseCreate(UTF8 src, UTF8 holder) { FileUnderConstruction v = pendingCreates.remove(src); if (v != null) { NameNode.stateChangeLog.debug( "DIR* NameSystem.internalReleaseCreate: " + src + " is removed from pendingCreates for " + holder + " (failure)"); for (Iterator<Block> it2 = v.getBlocks().iterator(); it2.hasNext(); ) { Block b = it2.next(); pendingCreateBlocks.remove(b); } } else { NameNode.stateChangeLog.warn("DIR* NameSystem.internalReleaseCreate: " + "attempt to release a create lock on "+ src.toString() + " that was not in pedingCreates"); } } /** * Renew the lease(s) held by the given client */ public void renewLease(UTF8 holder) throws IOException { synchronized (leases) { if( isInSafeMode() ) throw new SafeModeException( "Cannot renew lease for " + holder, safeMode ); Lease lease = leases.get(holder); if (lease != null) { sortedLeases.remove(lease); lease.renew(); sortedLeases.add(lease); } } } /** * Get a listing of all files at 'src'. The Object[] array * exists so we can return file attributes (soon to be implemented) */ public DFSFileInfo[] getListing(UTF8 src) { return dir.getListing(src); } ///////////////////////////////////////////////////////// // // These methods are called by datanodes // ///////////////////////////////////////////////////////// /** * Register Datanode. * <p> * The purpose of registration is to identify whether the new datanode * serves a new data storage, and will report new data block copies, * which the namenode was not aware of; or the datanode is a replacement * node for the data storage that was previously served by a different * or the same (in terms of host:port) datanode. * The data storages are distinguished by their storageIDs. When a new * data storage is reported the namenode issues a new unique storageID. * <p> * Finally, the namenode returns its namespaceID as the registrationID * for the datanodes. * namespaceID is a persistent attribute of the name space. * The registrationID is checked every time the datanode is communicating * with the namenode. * Datanodes with inappropriate registrationID are rejected. * If the namenode stops, and then restarts it can restore its * namespaceID and will continue serving the datanodes that has previously * registered with the namenode without restarting the whole cluster. * * @see DataNode#register() * @author Konstantin Shvachko */ public synchronized void registerDatanode( DatanodeRegistration nodeReg, String networkLocation ) throws IOException { if (!verifyNodeRegistration(nodeReg)) { throw new DisallowedDatanodeException( nodeReg ); } String dnAddress = Server.getRemoteAddress(); if ( dnAddress == null ) { //Mostly not called inside an RPC. throw new IOException( "Could not find remote address for " + "registration from " + nodeReg.getName() ); } String hostName = nodeReg.getHost(); // update the datanode's name with ip:port DatanodeID dnReg = new DatanodeID( dnAddress + ":" + nodeReg.getPort(), nodeReg.getStorageID(), nodeReg.getInfoPort() ); nodeReg.updateRegInfo( dnReg ); NameNode.stateChangeLog.info( "BLOCK* NameSystem.registerDatanode: " + "node registration from " + nodeReg.getName() + " storage " + nodeReg.getStorageID() ); nodeReg.registrationID = getRegistrationID(); DatanodeDescriptor nodeS = datanodeMap.get(nodeReg.getStorageID()); DatanodeDescriptor nodeN = getDatanodeByName( nodeReg.getName() ); if( nodeN != null && nodeN != nodeS ) { NameNode.LOG.info( "BLOCK* NameSystem.registerDatanode: " + "node from name: " + nodeN.getName() ); // nodeN previously served a different data storage, // which is not served by anybody anymore. removeDatanode( nodeN ); // physically remove node from datanodeMap wipeDatanode( nodeN ); // and log removal getEditLog().logRemoveDatanode( nodeN ); nodeN = null; } if ( nodeS != null ) { if( nodeN == nodeS ) { // The same datanode has been just restarted to serve the same data // storage. We do not need to remove old data blocks, the delta will // be calculated on the next block report from the datanode NameNode.stateChangeLog.debug("BLOCK* NameSystem.registerDatanode: " + "node restarted." ); } else { // nodeS is found // The registering datanode is a replacement node for the existing // data storage, which from now on will be served by a new node. NameNode.stateChangeLog.debug( "BLOCK* NameSystem.registerDatanode: " + "node " + nodeS.getName() + " is replaced by " + nodeReg.getName() + "." ); } getEditLog().logRemoveDatanode( nodeS ); // update cluster map clusterMap.remove( nodeS ); nodeS.updateRegInfo( nodeReg ); nodeS.setNetworkLocation( networkLocation ); clusterMap.add( nodeS ); nodeS.setHostName( hostName ); getEditLog().logAddDatanode( nodeS ); // also treat the registration message as a heartbeat synchronized( heartbeats ) { heartbeats.add( nodeS ); //update its timestamp nodeS.updateHeartbeat( 0L, 0L, 0); nodeS.isAlive = true; } return; } // this is a new datanode serving a new data storage if( nodeReg.getStorageID().equals("") ) { // this data storage has never been registered // it is either empty or was created by pre-storageID version of DFS nodeReg.storageID = newStorageID(); NameNode.stateChangeLog.debug( "BLOCK* NameSystem.registerDatanode: " + "new storageID " + nodeReg.getStorageID() + " assigned." ); } // register new datanode DatanodeDescriptor nodeDescr = new DatanodeDescriptor( nodeReg, networkLocation, hostName ); unprotectedAddDatanode( nodeDescr ); clusterMap.add(nodeDescr); getEditLog().logAddDatanode( nodeDescr ); // also treat the registration message as a heartbeat synchronized( heartbeats ) { heartbeats.add( nodeDescr ); nodeDescr.isAlive = true; // no need to update its timestamp // because its is done when the descriptor is created } return; } /** * Get registrationID for datanodes based on the namespaceID. * * @see #registerDatanode(DatanodeRegistration) * @see FSImage#newNamespaceID() * @return registration ID */ public String getRegistrationID() { return "NS" + Integer.toString( dir.namespaceID ); } /** * Generate new storage ID. * * @return unique storage ID * * Note: that collisions are still possible if somebody will try * to bring in a data storage from a different cluster. */ private String newStorageID() { String newID = null; while( newID == null ) { newID = "DS" + Integer.toString( r.nextInt() ); if( datanodeMap.get( newID ) != null ) newID = null; } return newID; } private boolean isDatanodeDead(DatanodeDescriptor node) { return (node.getLastUpdate() < (System.currentTimeMillis() - heartbeatExpireInterval)); } void setDatanodeDead(DatanodeID nodeID) throws IOException { DatanodeDescriptor node = getDatanode(nodeID); node.setLastUpdate(0); } /** * The given node has reported in. This method should: * 1) Record the heartbeat, so the datanode isn't timed out * 2) Adjust usage stats for future block allocation * * If a substantial amount of time passed since the last datanode * heartbeat then request an immediate block report. * * @return true if block report is required or false otherwise. * @throws IOException */ public boolean gotHeartbeat( DatanodeID nodeID, long capacity, long remaining, int xceiverCount, int xmitsInProgress, Object[] xferResults, Object deleteList[] ) throws IOException { synchronized (heartbeats) { synchronized (datanodeMap) { DatanodeDescriptor nodeinfo; try { nodeinfo = getDatanode( nodeID ); if (nodeinfo == null ) { return true; } } catch(UnregisteredDatanodeException e) { return true; } // Check if this datanode should actually be shutdown instead. if (shouldNodeShutdown(nodeinfo)) { setDatanodeDead(nodeinfo); throw new DisallowedDatanodeException(nodeinfo); } if( !nodeinfo.isAlive ) { return true; } else { updateStats(nodeinfo, false); nodeinfo.updateHeartbeat(capacity, remaining, xceiverCount); updateStats(nodeinfo, true); // // Extract pending replication work or block invalidation // work from the datanode descriptor // nodeinfo.getReplicationSets(this.maxReplicationStreams - xmitsInProgress, xferResults); if (xferResults[0] == null) { nodeinfo.getInvalidateBlocks(FSConstants.BLOCK_INVALIDATE_CHUNK, deleteList); } return false; } } } } private void updateStats(DatanodeDescriptor node, boolean isAdded) { // // The statistics are protected by the heartbeat lock // assert(Thread.holdsLock(heartbeats)); if (isAdded) { totalCapacity += node.getCapacity(); totalRemaining += node.getRemaining(); totalLoad += node.getXceiverCount(); } else { totalCapacity -= node.getCapacity(); totalRemaining -= node.getRemaining(); totalLoad -= node.getXceiverCount(); } } /** * Periodically calls heartbeatCheck(). */ class HeartbeatMonitor implements Runnable { /** */ public void run() { while (fsRunning) { heartbeatCheck(); try { Thread.sleep(heartbeatRecheckInterval); } catch (InterruptedException ie) { } } } } /** * Periodically calls computeReplicationWork(). */ class ReplicationMonitor implements Runnable { public void run() { while (fsRunning) { try { computeDatanodeWork(); processPendingReplications(); Thread.sleep(replicationRecheckInterval); } catch (InterruptedException ie) { } catch (IOException ie) { LOG.warn("ReplicationMonitor thread received exception. " + ie); } } } } /** * Look at a few datanodes and compute any replication work that * can be scheduled on them. The datanode will be infomed of this * work at the next heartbeat. */ void computeDatanodeWork() throws IOException { int numiter = 0; int foundwork = 0; int hsize = 0; while (true) { DatanodeDescriptor node = null; // // pick the datanode that was the last one in the // previous invocation of this method. // synchronized (heartbeats) { hsize = heartbeats.size(); if (numiter++ >= hsize) { break; } if (replIndex >= hsize) { replIndex = 0; } node = heartbeats.get(replIndex); replIndex++; } // // Is there replication work to be computed for this datanode? // int precomputed = node.getNumberOfBlocksToBeReplicated(); int needed = this.maxReplicationStreams - precomputed; boolean doReplication = false; boolean doInvalidation = false; if (needed > 0) { // // Compute replication work and store work into the datanode // Object replsets[] = pendingTransfers(node, needed); if (replsets != null) { doReplication = true; addBlocksToBeReplicated(node, (Block[])replsets[0], (DatanodeDescriptor[][])replsets[1]); } } if (!doReplication) { // // Determine if block deletion is pending for this datanode // Block blocklist[] = blocksToInvalidate(node); if (blocklist != null) { doInvalidation = true; addBlocksToBeInvalidated(node, blocklist); } } if (doReplication || doInvalidation) { // // If we have already computed work for a predefined // number of datanodes in this iteration, then relax // if (foundwork > ((hsize * REPL_WORK_PER_ITERATION)/100)) { break; } foundwork++; } else { // // See if the decommissioned node has finished moving all // its datablocks to another replica. This is a loose // heuristic to determine when a decommission is really over. // checkDecommissionState(node); } } } /** * If there were any replication requests that timed out, reap them * and put them back into the neededReplication queue */ void processPendingReplications() { Block[] timedOutItems = pendingReplications.getTimedOutBlocks(); if (timedOutItems != null) { synchronized (this) { for (int i = 0; i < timedOutItems.length; i++) { neededReplications.add(timedOutItems[i]); } } } } /** * Add more replication work for this datanode. */ synchronized void addBlocksToBeReplicated(DatanodeDescriptor node, Block[] blocklist, DatanodeDescriptor[][] targets) throws IOException { // // Find the datanode with the FSNamesystem lock held. // DatanodeDescriptor n = getDatanode(node); if (n != null) { n.addBlocksToBeReplicated(blocklist, targets); } } /** * Add more block invalidation work for this datanode. */ synchronized void addBlocksToBeInvalidated(DatanodeDescriptor node, Block[] blocklist) throws IOException { // // Find the datanode with the FSNamesystem lock held. // DatanodeDescriptor n = getDatanode(node); if (n != null) { n.addBlocksToBeInvalidated(blocklist); } } /** * remove a datanode descriptor * @param nodeID datanode ID * @author hairong */ synchronized public void removeDatanode( DatanodeID nodeID ) throws IOException { DatanodeDescriptor nodeInfo = getDatanode( nodeID ); if (nodeInfo != null) { removeDatanode( nodeInfo ); } else { NameNode.stateChangeLog.warn("BLOCK* NameSystem.removeDatanode: " + nodeInfo.getName() + " does not exist"); } } /** * remove a datanode descriptor * @param nodeInfo datanode descriptor * @author hairong */ private void removeDatanode( DatanodeDescriptor nodeInfo ) { if (nodeInfo.isAlive) { updateStats(nodeInfo, false); heartbeats.remove(nodeInfo); nodeInfo.isAlive = false; } for (Iterator<Block> it = nodeInfo.getBlockIterator(); it.hasNext(); ) { removeStoredBlock(it.next(), nodeInfo); } unprotectedRemoveDatanode(nodeInfo); clusterMap.remove(nodeInfo); } void unprotectedRemoveDatanode( DatanodeDescriptor nodeDescr ) { // datanodeMap.remove(nodeDescr.getStorageID()); // deaddatanodeMap.put(nodeDescr.getName(), nodeDescr); nodeDescr.resetBlocks(); NameNode.stateChangeLog.debug( "BLOCK* NameSystem.unprotectedRemoveDatanode: " + nodeDescr.getName() + " is out of service now."); } void unprotectedAddDatanode( DatanodeDescriptor nodeDescr ) { datanodeMap.put( nodeDescr.getStorageID(), nodeDescr ); NameNode.stateChangeLog.debug( "BLOCK* NameSystem.unprotectedAddDatanode: " + "node " + nodeDescr.getName() + " is added to datanodeMap." ); } /** * Physically remove node from datanodeMap. * * @param nodeID node */ void wipeDatanode( DatanodeID nodeID ) { String key = nodeID.getStorageID(); datanodeMap.remove(key); NameNode.stateChangeLog.debug( "BLOCK* NameSystem.wipeDatanode: " + nodeID.getName() + " storage " + nodeID.getStorageID() + " is removed from datanodeMap."); } private FSEditLog getEditLog() { return dir.fsImage.getEditLog(); } /** * Check if there are any expired heartbeats, and if so, * whether any blocks have to be re-replicated. * While removing dead datanodes, make sure that only one datanode is marked * dead at a time within the synchronized section. Otherwise, a cascading * effect causes more datanodes to be declared dead. */ void heartbeatCheck() { boolean allAlive = false; while (!allAlive) { boolean foundDead = false; DatanodeID nodeID = null; // locate the first dead node. synchronized(heartbeats) { for (Iterator<DatanodeDescriptor> it = heartbeats.iterator(); it.hasNext();) { DatanodeDescriptor nodeInfo = it.next(); if (isDatanodeDead(nodeInfo)) { foundDead = true; nodeID = nodeInfo; break; } } } // acquire the fsnamesystem lock, and then remove the dead node. if (foundDead) { synchronized (this) { synchronized(heartbeats) { synchronized (datanodeMap) { DatanodeDescriptor nodeInfo = null; try { nodeInfo = getDatanode(nodeID); } catch (IOException e) { nodeInfo = null; } if (nodeInfo != null && isDatanodeDead(nodeInfo)) { NameNode.stateChangeLog.info("BLOCK* NameSystem.heartbeatCheck: " + "lost heartbeat from " + nodeInfo.getName()); removeDatanode(nodeInfo); } } } } } allAlive = ! foundDead; } } /** * The given node is reporting all its blocks. Use this info to * update the (machine-->blocklist) and (block-->machinelist) tables. */ public synchronized Block[] processReport(DatanodeID nodeID, Block newReport[] ) throws IOException { NameNode.stateChangeLog.debug("BLOCK* NameSystem.processReport: " +"from "+nodeID.getName()+" "+newReport.length+" blocks" ); DatanodeDescriptor node = getDatanode( nodeID ); // Check if this datanode should actually be shutdown instead. if (shouldNodeShutdown(node)) { setDatanodeDead(node); throw new DisallowedDatanodeException(node); } // // Modify the (block-->datanode) map, according to the difference // between the old and new block report. // int newPos = 0; Iterator<Block> iter = node.getBlockIterator(); Block oldblk = iter.hasNext() ? iter.next() : null; Block newblk = (newReport != null && newReport.length > 0) ? newReport[0] : null; // common case is that most of the blocks from the datanode // matches blocks in datanode descriptor. Collection<Block> toRemove = new LinkedList<Block>(); Collection<Block> toAdd = new LinkedList<Block>(); while (oldblk != null || newblk != null) { int cmp = (oldblk == null) ? 1 : ((newblk == null) ? -1 : oldblk.compareTo(newblk)); if (cmp == 0) { // Do nothing, blocks are the same newPos++; oldblk = iter.hasNext() ? iter.next() : null; newblk = (newPos < newReport.length) ? newReport[newPos] : null; } else if (cmp < 0) { // The old report has a block the new one does not toRemove.add(oldblk); oldblk = iter.hasNext() ? iter.next() : null; } else { // The new report has a block the old one does not toAdd.add(newblk); newPos++; newblk = (newPos < newReport.length) ? newReport[newPos] : null; } } for ( Iterator<Block> i = toRemove.iterator(); i.hasNext(); ) { Block b = i.next(); removeStoredBlock( b, node ); node.removeBlock( b ); } for ( Iterator<Block> i = toAdd.iterator(); i.hasNext(); ) { Block b = i.next(); node.addBlock( addStoredBlock(b, node) ); } // // We've now completely updated the node's block report profile. // We now go through all its blocks and find which ones are invalid, // no longer pending, or over-replicated. // // (Note it's not enough to just invalidate blocks at lease expiry // time; datanodes can go down before the client's lease on // the failed file expires and miss the "expire" event.) // // This function considers every block on a datanode, and thus // should only be invoked infrequently. // Collection<Block> obsolete = new ArrayList<Block>(); for (Iterator<Block> it = node.getBlockIterator(); it.hasNext(); ) { Block b = it.next(); // // A block report can only send BLOCK_INVALIDATE_CHUNK number of // blocks to be deleted. If there are more blocks to be deleted, // they are added to recentInvalidateSets and will be sent out // thorugh succeeding heartbeat responses. // if (! dir.isValidBlock(b) && ! pendingCreateBlocks.contains(b)) { if (obsolete.size() > FSConstants.BLOCK_INVALIDATE_CHUNK) { addToInvalidates(b, node); } else { obsolete.add(b); } NameNode.stateChangeLog.debug("BLOCK* NameSystem.processReport: " +"ask "+nodeID.getName()+" to delete "+b.getBlockName() ); } } return (Block[]) obsolete.toArray(new Block[obsolete.size()]); } /** * Modify (block-->datanode) map. Remove block from set of * needed replications if this takes care of the problem. * @return the block that is stored in blockMap. */ synchronized Block addStoredBlock(Block block, DatanodeDescriptor node) { List<DatanodeDescriptor> containingNodes = blocksMap.get(block); if (containingNodes == null) { //Create an arraylist with the current replication factor FSDirectory.INode inode = dir.getFileByBlock(block); int replication = (inode != null) ? inode.getReplication() : defaultReplication; containingNodes = new ArrayList<DatanodeDescriptor>(replication); blocksMap.put(block, containingNodes); } else { Block storedBlock = containingNodes.get(0).getBlock(block); // update stored block's length. if ( storedBlock != null ) { if ( block.getNumBytes() > 0 ) { storedBlock.setNumBytes( block.getNumBytes() ); } block = storedBlock; } } int curReplicaDelta = 0; if (! containingNodes.contains(node)) { containingNodes.add(node); curReplicaDelta = 1; // // Hairong: I would prefer to set the level of next logrecord // to be debug. // But at startup time, because too many new blocks come in // they simply take up all the space in the log file // So I set the level to be trace // NameNode.stateChangeLog.trace("BLOCK* NameSystem.addStoredBlock: " +"blockMap updated: "+node.getName()+" is added to "+block.getBlockName() ); } else { NameNode.stateChangeLog.warn("BLOCK* NameSystem.addStoredBlock: " + "Redundant addStoredBlock request received for " + block.getBlockName() + " on " + node.getName()); } FSDirectory.INode fileINode = dir.getFileByBlock(block); if( fileINode == null ) // block does not belong to any file return block; // filter out containingNodes that are marked for decommission. int numCurrentReplica = countContainingNodes(containingNodes) + pendingReplications.getNumReplicas(block); // check whether safe replication is reached for the block // only if it is a part of a files incrementSafeBlockCount( numCurrentReplica ); // handle underReplication/overReplication short fileReplication = fileINode.getReplication(); if (numCurrentReplica >= fileReplication) { neededReplications.remove(block); } else { neededReplications.update(block, curReplicaDelta, 0); } proccessOverReplicatedBlock( block, fileReplication ); return block; } /** * Find how many of the containing nodes are "extra", if any. * If there are any extras, call chooseExcessReplicates() to * mark them in the excessReplicateMap. */ private void proccessOverReplicatedBlock( Block block, short replication ) { Collection<DatanodeDescriptor> containingNodes = blocksMap.get(block); if( containingNodes == null ) return; Collection<DatanodeDescriptor> nonExcess = new ArrayList<DatanodeDescriptor>(); for (Iterator<DatanodeDescriptor> it = containingNodes.iterator(); it.hasNext(); ) { DatanodeDescriptor cur = it.next(); Collection<Block> excessBlocks = excessReplicateMap.get(cur.getStorageID()); if (excessBlocks == null || ! excessBlocks.contains(block)) { if (!cur.isDecommissionInProgress() && !cur.isDecommissioned()) { nonExcess.add(cur); } } } chooseExcessReplicates(nonExcess, block, replication); } /** * We want "replication" replicates for the block, but we now have too many. * In this method, copy enough nodes from 'srcNodes' into 'dstNodes' such that: * * srcNodes.size() - dstNodes.size() == replication * * We pick node with least free space * In the future, we might enforce some kind of policy * (like making sure replicates are spread across racks). */ void chooseExcessReplicates(Collection<DatanodeDescriptor> nonExcess, Block b, short replication) { while (nonExcess.size() - replication > 0) { DatanodeInfo cur = null; long minSpace = Long.MAX_VALUE; for (Iterator<DatanodeDescriptor> iter = nonExcess.iterator(); iter.hasNext();) { DatanodeInfo node = iter.next(); long free = node.getRemaining(); if(minSpace > free) { minSpace = free; cur = node; } } nonExcess.remove(cur); Collection<Block> excessBlocks = excessReplicateMap.get(cur.getStorageID()); if (excessBlocks == null) { excessBlocks = new TreeSet<Block>(); excessReplicateMap.put(cur.getStorageID(), excessBlocks); } excessBlocks.add(b); NameNode.stateChangeLog.debug("BLOCK* NameSystem.chooseExcessReplicates: " +"("+cur.getName()+", "+b.getBlockName()+") is added to excessReplicateMap" ); // // The 'excessblocks' tracks blocks until we get confirmation // that the datanode has deleted them; the only way we remove them // is when we get a "removeBlock" message. // // The 'invalidate' list is used to inform the datanode the block // should be deleted. Items are removed from the invalidate list // upon giving instructions to the namenode. // Collection<Block> invalidateSet = recentInvalidateSets.get(cur.getStorageID()); if (invalidateSet == null) { invalidateSet = new ArrayList<Block>(); recentInvalidateSets.put(cur.getStorageID(), invalidateSet); } invalidateSet.add(b); NameNode.stateChangeLog.debug("BLOCK* NameSystem.chooseExcessReplicates: " +"("+cur.getName()+", "+b.getBlockName()+") is added to recentInvalidateSets" ); } } /** * Modify (block-->datanode) map. Possibly generate * replication tasks, if the removed block is still valid. */ synchronized void removeStoredBlock(Block block, DatanodeDescriptor node) { NameNode.stateChangeLog.debug("BLOCK* NameSystem.removeStoredBlock: " +block.getBlockName() + " from "+node.getName() ); Collection<DatanodeDescriptor> containingNodes = blocksMap.get(block); if (containingNodes == null || ! containingNodes.contains(node)) { NameNode.stateChangeLog.debug("BLOCK* NameSystem.removeStoredBlock: " +block.getBlockName()+" has already been removed from node "+node ); return; } containingNodes.remove(node); // filter out containingNodes that are marked for decommission. int numCurrentReplica = countContainingNodes(containingNodes); decrementSafeBlockCount( numCurrentReplica ); if( containingNodes.isEmpty() ) blocksMap.remove(block); // // It's possible that the block was removed because of a datanode // failure. If the block is still valid, check if replication is // necessary. In that case, put block on a possibly-will- // be-replicated list. // FSDirectory.INode fileINode = dir.getFileByBlock(block); if( fileINode != null ) { neededReplications.update(block, -1, 0); } // // We've removed a block from a node, so it's definitely no longer // in "excess" there. // Collection<Block> excessBlocks = excessReplicateMap.get(node.getStorageID()); if (excessBlocks != null) { excessBlocks.remove(block); NameNode.stateChangeLog.debug("BLOCK* NameSystem.removeStoredBlock: " +block.getBlockName()+" is removed from excessBlocks" ); if (excessBlocks.size() == 0) { excessReplicateMap.remove(node.getStorageID()); } } } /** * The given node is reporting that it received a certain block. */ public synchronized void blockReceived( DatanodeID nodeID, Block block ) throws IOException { DatanodeDescriptor node = getDatanode( nodeID ); if (node == null) { NameNode.stateChangeLog.warn("BLOCK* NameSystem.blockReceived: " + block.getBlockName() + " is received from an unrecorded node " + nodeID.getName() ); throw new IllegalArgumentException( "Unexpected exception. Got blockReceived message from node " + block.getBlockName() + ", but there is no info for it"); } NameNode.stateChangeLog.debug("BLOCK* NameSystem.blockReceived: " +block.getBlockName()+" is received from " + nodeID.getName() ); // Check if this datanode should actually be shutdown instead. if (shouldNodeShutdown(node)) { setDatanodeDead(node); throw new DisallowedDatanodeException(node); } // // Modify the blocks->datanode map and node's map. // node.addBlock( addStoredBlock(block, node) ); pendingReplications.remove(block); } /** * Total raw bytes. */ public long totalCapacity() { synchronized (heartbeats) { return totalCapacity; } } /** * Total non-used raw bytes. */ public long totalRemaining() { synchronized (heartbeats) { return totalRemaining; } } /** * Total number of connections. */ public int totalLoad() { synchronized (heartbeats) { return totalLoad; } } public synchronized DatanodeInfo[] datanodeReport() { DatanodeInfo results[] = null; synchronized (datanodeMap) { results = new DatanodeInfo[datanodeMap.size()]; int i = 0; for(Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator(); it.hasNext(); ) results[i++] = new DatanodeInfo( it.next() ); } return results; } /** */ public synchronized void DFSNodesStatus( ArrayList<DatanodeDescriptor> live, ArrayList<DatanodeDescriptor> dead ) { synchronized (datanodeMap) { for(Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator(); it.hasNext(); ) { DatanodeDescriptor node = it.next(); if( isDatanodeDead(node)) dead.add( node ); else live.add( node ); } } } /** * Start decommissioning the specified datanode. */ private void startDecommission (DatanodeDescriptor node) throws IOException { if (!node.isDecommissionInProgress() && !node.isDecommissioned()) { LOG.info("Start Decommissioning node " + node.name); node.startDecommission(); // // all the blocks that reside on this node have to be // replicated. Block decommissionBlocks[] = node.getBlocks(); for (int j = 0; j < decommissionBlocks.length; j++) { neededReplications.update(decommissionBlocks[j], -1, 0); } } } /** * Stop decommissioning the specified datanodes. */ public void stopDecommission (DatanodeDescriptor node) throws IOException { LOG.info("Stop Decommissioning node " + node.name); node.stopDecommission(); } /** * Return true if all specified nodes are decommissioned. * Otherwise return false. */ public synchronized boolean checkDecommissioned (String[] nodes) throws IOException { String badnodes = ""; boolean isError = false; synchronized (datanodeMap) { for (int i = 0; i < nodes.length; i++) { boolean found = false; for (Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator(); it.hasNext(); ) { DatanodeDescriptor node = it.next(); // // If this is a node that we are interested in, check its admin state. // if (node.getName().equals(nodes[i]) || node.getHost().equals(nodes[i])) { found = true; boolean isDecommissioned = checkDecommissionStateInternal(node); if (!isDecommissioned) { return false; } } } if (!found) { badnodes += nodes[i] + " "; isError = true; } } } if (isError) { throw new IOException("Nodes " + badnodes + " not found"); } return true; } /** */ public DatanodeInfo getDataNodeInfo(String name) { return datanodeMap.get(name); } /** */ public String getDFSNameNodeMachine() { return localMachine; } /** */ public int getDFSNameNodePort() { return port; } /** */ public Date getStartTime() { return startTime; } ///////////////////////////////////////////////////////// // // These methods are called by the Namenode system, to see // if there is any work for a given datanode. // ///////////////////////////////////////////////////////// /** * Check if there are any recently-deleted blocks a datanode should remove. */ public synchronized Block[] blocksToInvalidate( DatanodeID nodeID ) { // Ask datanodes to perform block delete // only if safe mode is off. if( isInSafeMode() ) return null; Collection<Block> invalidateSet = recentInvalidateSets.remove( nodeID.getStorageID() ); if (invalidateSet == null) { return null; } Iterator<Block> it = null; int sendNum = invalidateSet.size(); int origSize = sendNum; ArrayList sendBlock = new ArrayList(sendNum); // // calculate the number of blocks that we send in one message // if (sendNum > FSConstants.BLOCK_INVALIDATE_CHUNK) { sendNum = FSConstants.BLOCK_INVALIDATE_CHUNK; } // // Copy the first chunk into sendBlock // for (it = invalidateSet.iterator(); sendNum > 0; sendNum--) { assert(it.hasNext()); sendBlock.add(it.next()); it.remove(); } // // If we could not send everything in this message, reinsert this item // into the collection. // if (it.hasNext()) { assert(origSize > FSConstants.BLOCK_INVALIDATE_CHUNK); recentInvalidateSets.put(nodeID.getStorageID(), invalidateSet); } if (NameNode.stateChangeLog.isInfoEnabled()) { StringBuffer blockList = new StringBuffer(); for (int i = 0; i < sendBlock.size(); i++) { blockList.append(' '); Block block = (Block) sendBlock.get(i); blockList.append(block.getBlockName()); } NameNode.stateChangeLog.debug("BLOCK* NameSystem.blockToInvalidate: " +"ask "+nodeID.getName()+" to delete " + blockList ); } return (Block[]) sendBlock.toArray(new Block[sendBlock.size()]); } /* * Counts the number of nodes in the given list. Skips over nodes * that are marked for decommission. */ private int countContainingNodes(Collection<DatanodeDescriptor> nodelist) { if( nodelist == null ) return 0; int count = 0; for (Iterator<DatanodeDescriptor> it = nodelist.iterator(); it.hasNext(); ) { DatanodeDescriptor node = it.next(); if (!node.isDecommissionInProgress() && !node.isDecommissioned()) { count++; } } return count; } /* * Filter nodes that are marked for decommison in the given list. * Return a list of non-decommissioned nodes */ private List<DatanodeDescriptor> filterDecommissionedNodes( Collection<DatanodeDescriptor> nodelist) { List<DatanodeDescriptor> nonCommissionedNodeList = new ArrayList<DatanodeDescriptor>(); for (Iterator<DatanodeDescriptor> it = nodelist.iterator(); it.hasNext(); ) { DatanodeDescriptor node = it.next(); if (!node.isDecommissionInProgress() && !node.isDecommissioned()) { nonCommissionedNodeList.add(node); } } return nonCommissionedNodeList; } /* * Return true if there are any blocks on this node that have not * yet reached their replication factor. Otherwise returns false. */ private boolean isReplicationInProgress(DatanodeDescriptor srcNode) { Block decommissionBlocks[] = srcNode.getBlocks(); for (int i = 0; i < decommissionBlocks.length; i++) { Block block = decommissionBlocks[i]; FSDirectory.INode fileINode = dir.getFileByBlock(block); if (fileINode == null) { continue; } Collection<DatanodeDescriptor> containingNodes = blocksMap.get(block); List<DatanodeDescriptor> nodes = filterDecommissionedNodes(containingNodes); int numCurrentReplica = nodes.size(); if (fileINode.getReplication() > numCurrentReplica) { return true; } } return false; } /** * Change, if appropriate, the admin state of a datanode to * decommission completed. Return true if decommission is complete. */ private boolean checkDecommissionStateInternal(DatanodeDescriptor node) { // // Check to see if there are all blocks in this decommisioned // node has reached their target replication factor. // if (node.isDecommissionInProgress()) { if (!isReplicationInProgress(node)) { node.setDecommissioned(); LOG.info("Decommission complete for node " + node.name); } } if (node.isDecommissioned()) { return true; } return false; } /** * Change, if appropriate, the admin state of a datanode to * decommission completed. */ public synchronized void checkDecommissionState(DatanodeID nodeReg) { DatanodeDescriptor node = datanodeMap.get(nodeReg.getStorageID()); if (node == null) { return; } checkDecommissionStateInternal(node); } /** * Return with a list of Block/DataNodeInfo sets, indicating * where various Blocks should be copied, ASAP. * * The Array that we return consists of two objects: * The 1st elt is an array of Blocks. * The 2nd elt is a 2D array of DatanodeDescriptor objs, identifying the * target sequence for the Block at the appropriate index. * */ public synchronized Object[] pendingTransfers(DatanodeID srcNode, int needed) { // Ask datanodes to perform block replication // only if safe mode is off. if( isInSafeMode() ) return null; synchronized (neededReplications) { Object results[] = null; if (neededReplications.size() > 0) { // // Go through all blocks that need replications. See if any // are present at the current node. If so, ask the node to // replicate them. // List<Block> replicateBlocks = new ArrayList<Block>(); List<Integer> numCurrentReplicas = new ArrayList<Integer>(); List<DatanodeDescriptor[]> replicateTargetSets; replicateTargetSets = new ArrayList<DatanodeDescriptor[]>(); for (Iterator<Block> it = neededReplications.iterator(); it.hasNext();) { if (needed <= 0) { break; } Block block = it.next(); long blockSize = block.getNumBytes(); FSDirectory.INode fileINode = dir.getFileByBlock(block); if (fileINode == null) { // block does not belong to any file it.remove(); } else { Collection<DatanodeDescriptor> containingNodes = blocksMap.get(block); Collection<Block> excessBlocks = excessReplicateMap.get( srcNode.getStorageID() ); // srcNode must contain the block, and the block must // not be scheduled for removal on that node if (containingNodes != null && containingNodes.contains(srcNode) && (excessBlocks == null || ! excessBlocks.contains(block))) { // filter out containingNodes that are marked for decommission. List<DatanodeDescriptor> nodes = filterDecommissionedNodes(containingNodes); int numCurrentReplica = nodes.size() + pendingReplications.getNumReplicas(block); if (numCurrentReplica >= fileINode.getReplication()) { it.remove(); } else { DatanodeDescriptor targets[] = replicator.chooseTarget( Math.min( fileINode.getReplication() - numCurrentReplica, needed), datanodeMap.get(srcNode.getStorageID()), nodes, null, blockSize); if (targets.length > 0) { // Build items to return replicateBlocks.add(block); numCurrentReplicas.add(new Integer(numCurrentReplica)); replicateTargetSets.add(targets); needed -= targets.length; } } } } } // // Move the block-replication into a "pending" state. // The reason we use 'pending' is so we can retry // replications that fail after an appropriate amount of time. // (REMIND - mjc - this timer is not yet implemented.) // if (replicateBlocks.size() > 0) { int i = 0; for (Iterator<Block> it = replicateBlocks.iterator(); it.hasNext(); i++) { Block block = it.next(); DatanodeDescriptor targets[] = (DatanodeDescriptor[]) replicateTargetSets.get(i); int numCurrentReplica = numCurrentReplicas.get(i).intValue(); int numExpectedReplica = dir.getFileByBlock( block).getReplication(); if (numCurrentReplica + targets.length >= numExpectedReplica) { neededReplications.remove( block, numCurrentReplica, numExpectedReplica); pendingReplications.add(block, targets.length); NameNode.stateChangeLog.debug( "BLOCK* NameSystem.pendingTransfer: " + block.getBlockName() + " is removed from neededReplications to pendingReplications"); } if (NameNode.stateChangeLog.isInfoEnabled()) { StringBuffer targetList = new StringBuffer("datanode(s)"); for (int k = 0; k < targets.length; k++) { targetList.append(' '); targetList.append(targets[k].getName()); } NameNode.stateChangeLog.info( "BLOCK* NameSystem.pendingTransfer: " + "ask " + srcNode.getName() + " to replicate " + block.getBlockName() + " to " + targetList); NameNode.stateChangeLog.debug( "BLOCK* neededReplications = " + neededReplications.size() + " pendingReplications = " + pendingReplications.size() ); } } // // Build returned objects from above lists // DatanodeDescriptor targetMatrix[][] = new DatanodeDescriptor[replicateTargetSets.size()][]; for (i = 0; i < targetMatrix.length; i++) { targetMatrix[i] = replicateTargetSets.get(i); } results = new Object[2]; results[0] = replicateBlocks.toArray(new Block[replicateBlocks.size()]); results[1] = targetMatrix; } } return results; } } /** The class is responsible for choosing the desired number of targets * for placing block replicas. * The replica placement strategy is that if the writer is on a datanode, * the 1st replica is placed on the local machine, * otherwise a random datanode. The 2nd replica is placed on a datanode * that is on a different rack. The 3rd replica is placed on a datanode * which is on the same rack as the first replca. * @author hairong * */ class ReplicationTargetChooser { final boolean considerLoad; ReplicationTargetChooser( boolean considerLoad ) { this.considerLoad = considerLoad; } private class NotEnoughReplicasException extends Exception { NotEnoughReplicasException( String msg ) { super( msg ); } } /** * choose <i>numOfReplicas</i> data nodes for <i>writer</i> to replicate * a block with size <i>blocksize</i> * If not, return as many as we can. * * @param numOfReplicas: number of replicas wanted. * @param writer: the writer's machine, null if not in the cluster. * @param excludedNodes: datanodesthat should not be considered targets. * @param blocksize: size of the data to be written. * @return array of DatanodeDescriptor instances chosen as targets * and sorted as a pipeline. */ DatanodeDescriptor[] chooseTarget(int numOfReplicas, DatanodeDescriptor writer, List<DatanodeDescriptor> excludedNodes, long blocksize ) { if( excludedNodes == null) { excludedNodes = new ArrayList<DatanodeDescriptor>(); } return chooseTarget(numOfReplicas, writer, new ArrayList<DatanodeDescriptor>(), excludedNodes, blocksize); } /** * choose <i>numOfReplicas</i> data nodes for <i>writer</i> * to re-replicate a block with size <i>blocksize</i> * If not, return as many as we can. * * @param numOfReplicas: additional number of replicas wanted. * @param writer: the writer's machine, null if not in the cluster. * @param choosenNodes: datanodes that have been choosen as targets. * @param excludedNodes: datanodesthat should not be considered targets. * @param blocksize: size of the data to be written. * @return array of DatanodeDescriptor instances chosen as target * and sorted as a pipeline. */ DatanodeDescriptor[] chooseTarget(int numOfReplicas, DatanodeDescriptor writer, List<DatanodeDescriptor> choosenNodes, List<DatanodeDescriptor> excludedNodes, long blocksize ) { if( numOfReplicas == 0 ) return new DatanodeDescriptor[0]; if( excludedNodes == null) { excludedNodes = new ArrayList<DatanodeDescriptor>(); } int clusterSize = clusterMap.getNumOfLeaves(); int totalNumOfReplicas = choosenNodes.size()+numOfReplicas; if( totalNumOfReplicas > clusterSize) { numOfReplicas -= (totalNumOfReplicas-clusterSize); totalNumOfReplicas = clusterSize; } int maxNodesPerRack = (totalNumOfReplicas-1)/clusterMap.getNumOfRacks()+2; List<DatanodeDescriptor> results = new ArrayList<DatanodeDescriptor>(choosenNodes); excludedNodes.addAll(choosenNodes); if(!clusterMap.contains(writer)) writer=null; DatanodeDescriptor localNode = chooseTarget(numOfReplicas, writer, excludedNodes, blocksize, maxNodesPerRack, results ); results.removeAll(choosenNodes); // sorting nodes to form a pipeline return getPipeline((writer==null)?localNode:writer, results); } /* choose <i>numOfReplicas</i> from all data nodes */ private DatanodeDescriptor chooseTarget(int numOfReplicas, DatanodeDescriptor writer, List<DatanodeDescriptor> excludedNodes, long blocksize, int maxNodesPerRack, List<DatanodeDescriptor> results) { if( numOfReplicas == 0 || clusterMap.getNumOfLeaves()==0 ) { return writer; } int numOfResults = results.size(); if(writer == null && (numOfResults==1 || numOfResults==2) ) { writer = results.get(0); } try { switch( numOfResults ) { case 0: writer = chooseLocalNode(writer, excludedNodes, blocksize, maxNodesPerRack, results); if(--numOfReplicas == 0) break; case 1: chooseRemoteRack(1, writer, excludedNodes, blocksize, maxNodesPerRack, results); if(--numOfReplicas == 0) break; case 2: if(clusterMap.isOnSameRack(results.get(0), results.get(1))) { chooseRemoteRack(1, writer, excludedNodes, blocksize, maxNodesPerRack, results); } else { chooseLocalRack(writer, excludedNodes, blocksize, maxNodesPerRack, results); } if(--numOfReplicas == 0) break; default: chooseRandom(numOfReplicas, NodeBase.ROOT, excludedNodes, blocksize, maxNodesPerRack, results); } } catch (NotEnoughReplicasException e) { LOG.warn("Not able to place enough replicas, still in need of " + numOfReplicas ); } return writer; } /* choose <i>localMachine</i> as the target. * if <i>localMachine</i> is not availabe, * choose a node on the same rack * @return the choosen node */ private DatanodeDescriptor chooseLocalNode( DatanodeDescriptor localMachine, List<DatanodeDescriptor> excludedNodes, long blocksize, int maxNodesPerRack, List<DatanodeDescriptor> results) throws NotEnoughReplicasException { // if no local machine, randomly choose one node if(localMachine == null) return chooseRandom(NodeBase.ROOT, excludedNodes, blocksize, maxNodesPerRack, results); // otherwise try local machine first if(!excludedNodes.contains(localMachine)) { excludedNodes.add(localMachine); if( isGoodTarget(localMachine, blocksize, maxNodesPerRack, false, results)) { results.add(localMachine); return localMachine; } } // try a node on local rack return chooseLocalRack(localMachine, excludedNodes, blocksize, maxNodesPerRack, results); } /* choose one node from the rack that <i>localMachine</i> is on. * if no such node is availabe, choose one node from the rack where * a second replica is on. * if still no such node is available, choose a random node * in the cluster. * @return the choosen node */ private DatanodeDescriptor chooseLocalRack( DatanodeDescriptor localMachine, List<DatanodeDescriptor> excludedNodes, long blocksize, int maxNodesPerRack, List<DatanodeDescriptor> results) throws NotEnoughReplicasException { // no local machine, so choose a random machine if( localMachine == null ) { return chooseRandom(NodeBase.ROOT, excludedNodes, blocksize, maxNodesPerRack, results ); } // choose one from the local rack try { return chooseRandom( localMachine.getNetworkLocation(), excludedNodes, blocksize, maxNodesPerRack, results); } catch (NotEnoughReplicasException e1) { // find the second replica DatanodeDescriptor newLocal=null; for(Iterator<DatanodeDescriptor> iter=results.iterator(); iter.hasNext();) { DatanodeDescriptor nextNode = iter.next(); if(nextNode != localMachine) { newLocal = nextNode; break; } } if( newLocal != null ) { try { return chooseRandom( newLocal.getNetworkLocation(), excludedNodes, blocksize, maxNodesPerRack, results); } catch( NotEnoughReplicasException e2 ) { //otherwise randomly choose one from the network return chooseRandom(NodeBase.ROOT, excludedNodes, blocksize, maxNodesPerRack, results); } } else { //otherwise randomly choose one from the network return chooseRandom(NodeBase.ROOT, excludedNodes, blocksize, maxNodesPerRack, results); } } } /* choose <i>numOfReplicas</i> nodes from the racks * that <i>localMachine</i> is NOT on. * if not enough nodes are availabe, choose the remaining ones * from the local rack */ private void chooseRemoteRack( int numOfReplicas, DatanodeDescriptor localMachine, List<DatanodeDescriptor> excludedNodes, long blocksize, int maxReplicasPerRack, List<DatanodeDescriptor> results) throws NotEnoughReplicasException { int oldNumOfReplicas = results.size(); // randomly choose one node from remote racks try { chooseRandom( numOfReplicas, "~"+localMachine.getNetworkLocation(), excludedNodes, blocksize, maxReplicasPerRack, results ); } catch (NotEnoughReplicasException e) { chooseRandom( numOfReplicas-(results.size()-oldNumOfReplicas), localMachine.getNetworkLocation(), excludedNodes, blocksize, maxReplicasPerRack, results); } } /* Randomly choose one target from <i>nodes</i>. * @return the choosen node */ private DatanodeDescriptor chooseRandom( String nodes, List<DatanodeDescriptor> excludedNodes, long blocksize, int maxNodesPerRack, List<DatanodeDescriptor> results) throws NotEnoughReplicasException { DatanodeDescriptor result; do { DatanodeDescriptor[] selectedNodes = chooseRandom(1, nodes, excludedNodes); if(selectedNodes.length == 0 ) { throw new NotEnoughReplicasException( "Not able to place enough replicas" ); } result = (DatanodeDescriptor)(selectedNodes[0]); } while( !isGoodTarget( result, blocksize, maxNodesPerRack, results)); results.add(result); return result; } /* Randomly choose <i>numOfReplicas</i> targets from <i>nodes</i>. */ private void chooseRandom(int numOfReplicas, String nodes, List<DatanodeDescriptor> excludedNodes, long blocksize, int maxNodesPerRack, List<DatanodeDescriptor> results) throws NotEnoughReplicasException { boolean toContinue = true; do { DatanodeDescriptor[] selectedNodes = chooseRandom(numOfReplicas, nodes, excludedNodes); if(selectedNodes.length < numOfReplicas) { toContinue = false; } for(int i=0; i<selectedNodes.length; i++) { DatanodeDescriptor result = (DatanodeDescriptor)(selectedNodes[i]); if( isGoodTarget( result, blocksize, maxNodesPerRack, results)) { numOfReplicas--; results.add(result); } } // end of for } while (numOfReplicas>0 && toContinue ); if(numOfReplicas>0) { throw new NotEnoughReplicasException( "Not able to place enough replicas"); } } /* Randomly choose <i>numOfNodes</i> nodes from <i>scope</i>. * @return the choosen nodes */ private DatanodeDescriptor[] chooseRandom(int numOfReplicas, String nodes, List<DatanodeDescriptor> excludedNodes) { List<DatanodeDescriptor> results = new ArrayList<DatanodeDescriptor>(); int numOfAvailableNodes = clusterMap.countNumOfAvailableNodes(nodes, excludedNodes); numOfReplicas = (numOfAvailableNodes<numOfReplicas)? numOfAvailableNodes:numOfReplicas; while( numOfReplicas > 0 ) { DatanodeDescriptor choosenNode = clusterMap.chooseRandom(nodes); if(!excludedNodes.contains(choosenNode)) { results.add( choosenNode ); excludedNodes.add(choosenNode); numOfReplicas--; } } return (DatanodeDescriptor[])results.toArray( new DatanodeDescriptor[results.size()]); } /* judge if a node is a good target. * return true if <i>node</i> has enough space, * does not have too much load, and the rack does not have too many nodes */ private boolean isGoodTarget( DatanodeDescriptor node, long blockSize, int maxTargetPerLoc, List<DatanodeDescriptor> results) { return isGoodTarget(node, blockSize, maxTargetPerLoc, this.considerLoad, results); } private boolean isGoodTarget( DatanodeDescriptor node, long blockSize, int maxTargetPerLoc, boolean considerLoad, List<DatanodeDescriptor> results) { // check if the node is (being) decommissed if(node.isDecommissionInProgress() || node.isDecommissioned()) { LOG.debug("Node "+node.getPath()+ " is not chosen because the node is (being) decommissioned"); return false; } // check the remaining capacity of the target machine if(blockSize* FSConstants.MIN_BLOCKS_FOR_WRITE>node.getRemaining() ) { LOG.debug("Node "+node.getPath()+ " is not chosen because the node does not have enough space"); return false; } // check the communication traffic of the target machine if(considerLoad) { double avgLoad = 0; int size = clusterMap.getNumOfLeaves(); if( size != 0 ) { avgLoad = (double)totalLoad()/size; } if(node.getXceiverCount() > (2.0 * avgLoad)) { LOG.debug("Node "+node.getPath()+ " is not chosen because the node is too busy"); return false; } } // check if the target rack has chosen too many nodes String rackname = node.getNetworkLocation(); int counter=1; for( Iterator<DatanodeDescriptor> iter = results.iterator(); iter.hasNext(); ) { DatanodeDescriptor result = iter.next(); if(rackname.equals(result.getNetworkLocation())) { counter++; } } if(counter>maxTargetPerLoc) { LOG.debug("Node "+node.getPath()+ " is not chosen because the rack has too many chosen nodes"); return false; } return true; } /* Return a pipeline of nodes. * The pipeline is formed finding a shortest path that * starts from the writer and tranverses all <i>nodes</i> * This is basically a traveling salesman problem. */ private DatanodeDescriptor[] getPipeline( DatanodeDescriptor writer, List<DatanodeDescriptor> nodes ) { int numOfNodes = nodes.size(); DatanodeDescriptor[] results = new DatanodeDescriptor[numOfNodes]; if( numOfNodes==0 ) return results; synchronized( clusterMap ) { int index=0; if(writer == null || !clusterMap.contains(writer)) { writer = nodes.get(0); } for( ;index<numOfNodes; index++ ) { DatanodeDescriptor shortestNode = null; int shortestDistance = Integer.MAX_VALUE; int shortestIndex = index; for( int i=index; i<numOfNodes; i++ ) { DatanodeDescriptor currentNode = nodes.get(i); int currentDistance = clusterMap.getDistance( writer, currentNode ); if(shortestDistance>currentDistance ) { shortestDistance = currentDistance; shortestNode = currentNode; shortestIndex = i; } } //switch position index & shortestIndex if( index != shortestIndex ) { nodes.set(shortestIndex, nodes.get(index)); nodes.set(index, shortestNode); } writer = shortestNode; } } return nodes.toArray( results ); } /** Return datanodes that sorted by their distances to <i>reader</i> */ DatanodeDescriptor[] sortByDistance( final DatanodeDescriptor reader, List<DatanodeDescriptor> nodes ) { synchronized(clusterMap) { if(reader != null && clusterMap.contains(reader)) { java.util.Collections.sort(nodes, new Comparator<DatanodeDescriptor>() { public int compare(DatanodeDescriptor n1, DatanodeDescriptor n2) { return clusterMap.getDistance(reader, n1) -clusterMap.getDistance(reader, n2); } }); } } return (DatanodeDescriptor[])nodes.toArray( new DatanodeDescriptor[nodes.size()]); } } //end of Replicator // Keeps track of which datanodes are allowed to connect to the namenode. private boolean inHostsList(DatanodeID node) { Set<String> hostsList = hostsReader.getHosts(); return (hostsList.isEmpty() || hostsList.contains(node.getName()) || hostsList.contains(node.getHost()) || ((node instanceof DatanodeInfo) && hostsList.contains(((DatanodeInfo)node).getHostName()))); } private boolean inExcludedHostsList(DatanodeID node) { Set<String> excludeList = hostsReader.getExcludedHosts(); return (excludeList.contains(node.getName()) || excludeList.contains(node.getHost()) || ((node instanceof DatanodeInfo) && excludeList.contains(((DatanodeInfo)node).getHostName()))); } /** * Rereads the files to update the hosts and exclude lists. It * checks if any of the hosts have changed states: * 1. Added to hosts --> no further work needed here. * 2. Removed from hosts --> mark AdminState as decommissioned. * 3. Added to exclude --> start decommission. * 4. Removed from exclude --> stop decommission. */ void refreshNodes() throws IOException { hostsReader.refresh(); synchronized (this) { for (Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator(); it.hasNext(); ) { DatanodeDescriptor node = it.next(); // Check if not include. if (!inHostsList(node)) { node.setDecommissioned(); // case 2. } else { if (inExcludedHostsList(node)) { if (!node.isDecommissionInProgress() && !node.isDecommissioned()) { startDecommission(node); // case 3. } } else { if (node.isDecommissionInProgress() || node.isDecommissioned()) { stopDecommission(node); // case 4. } } } } } } /** * Checks if the node is not on the hosts list. If it is not, then * it will be ignored. If the node is in the hosts list, but is also * on the exclude list, then it will be decommissioned. * Returns FALSE if node is rejected for registration. * Returns TRUE if node is registered (including when it is on the * exclude list and is being decommissioned). */ public synchronized boolean verifyNodeRegistration(DatanodeRegistration nodeReg) throws IOException { if (!inHostsList(nodeReg)) { return false; } if (inExcludedHostsList(nodeReg)) { DatanodeDescriptor node = getDatanode(nodeReg); if (!checkDecommissionStateInternal(node)) { startDecommission(node); } } return true; } /** * Checks if the Admin state bit is DECOMMISSIONED. If so, then * we should shut it down. * * Returns true if the node should be shutdown. */ private boolean shouldNodeShutdown(DatanodeDescriptor node) { return (node.isDecommissioned()); } /** * Check if any of the nodes being decommissioned has finished * moving all its datablocks to another replica. This is a loose * heuristic to determine when a decommission is really over. */ public synchronized void decommissionedDatanodeCheck() { for (Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator(); it.hasNext(); ) { DatanodeDescriptor node = it.next(); checkDecommissionStateInternal(node); } } /** * Periodically calls decommissionedDatanodeCheck(). */ class DecommissionedMonitor implements Runnable { public void run() { while (fsRunning) { try { decommissionedDatanodeCheck(); } catch (Exception e) { FSNamesystem.LOG.info(StringUtils.stringifyException(e)); } try { Thread.sleep(1000 * 60 * 5); } catch (InterruptedException ie) { } } } } /** * Information about the file while it is being written to. * Note that at that time the file is not visible to the outside. * * This class contains a <code>Collection</code> of {@link Block}s that has * been written into the file so far, and file replication. * * @author shv */ private class FileUnderConstruction { private short blockReplication; // file replication private long blockSize; private Collection<Block> blocks; private UTF8 clientName; // lease holder private UTF8 clientMachine; FileUnderConstruction(short replication, long blockSize, UTF8 clientName, UTF8 clientMachine) throws IOException { this.blockReplication = replication; this.blockSize = blockSize; this.blocks = new ArrayList<Block>(); this.clientName = clientName; this.clientMachine = clientMachine; } public short getReplication() { return this.blockReplication; } public long getBlockSize() { return blockSize; } public Collection<Block> getBlocks() { return blocks; } public UTF8 getClientName() { return clientName; } public UTF8 getClientMachine() { return clientMachine; } } /** * Get data node by storage ID. * * @param nodeID * @return DatanodeDescriptor or null if the node is not found. * @throws IOException */ public DatanodeDescriptor getDatanode( DatanodeID nodeID ) throws IOException { UnregisteredDatanodeException e = null; DatanodeDescriptor node = datanodeMap.get(nodeID.getStorageID()); if (node == null) return null; if (!node.getName().equals(nodeID.getName())) { e = new UnregisteredDatanodeException( nodeID, node ); NameNode.stateChangeLog.fatal("BLOCK* NameSystem.getDatanode: " + e.getLocalizedMessage() ); throw e; } return node; } /** * Find data node by its name. * * This method is called when the node is registering. * Not performance critical. * Otherwise an additional tree-like structure will be required. * * @param name * @return DatanodeDescriptor if found or null otherwise * @throws IOException */ public DatanodeDescriptor getDatanodeByName( String name ) throws IOException { for (Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator(); it.hasNext(); ) { DatanodeDescriptor node = it.next(); if( node.getName().equals(name) ) return node; } return null; } /* Find data node by its host name. */ private DatanodeDescriptor getDatanodeByHost( String name ) { for (Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator(); it.hasNext(); ) { DatanodeDescriptor node = it.next(); if( node.getHost().equals(name) ) return node; } return null; } /** Stop at and return the datanode at index (used for content browsing)*/ private DatanodeInfo getDatanodeByIndex( int index ) { int i = 0; for (Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator(); it.hasNext(); ) { DatanodeInfo node = it.next(); if( i == index ) return node; i++; } return null; } public String randomDataNode() { int size = datanodeMap.size(); int index = 0; if (size != 0) { index = r.nextInt(size); DatanodeInfo d = getDatanodeByIndex(index); if (d != null) { return d.getHost() + ":" + d.getInfoPort(); } } return null; } public int getNameNodeInfoPort() { return infoPort; } /** * SafeModeInfo contains information related to the safe mode. * <p> * An instance of {@link SafeModeInfo} is created when the name node * enters safe mode. * <p> * During name node startup {@link SafeModeInfo} counts the number of * <em>safe blocks</em>, those that have at least the minimal number of * replicas, and calculates the ratio of safe blocks to the total number * of blocks in the system, which is the size of * {@link FSDirectory#activeBlocks}. When the ratio reaches the * {@link #threshold} it starts the {@link SafeModeMonitor} daemon in order * to monitor whether the safe mode extension is passed. Then it leaves safe * mode and destroys itself. * <p> * If safe mode is turned on manually then the number of safe blocks is * not tracked because the name node is not intended to leave safe mode * automatically in the case. * * @see ClientProtocol#setSafeMode(FSConstants.SafeModeAction) * @see SafeModeMonitor * @author Konstantin Shvachko */ class SafeModeInfo { // configuration fields /** Safe mode threshold condition %.*/ private double threshold; /** Safe mode extension after the threshold. */ private int extension; /** Min replication required by safe mode. */ private int safeReplication; // internal fields /** Time when threshold was reached. * * <br>-1 safe mode is off * <br> 0 safe mode is on, but threshold is not reached yet */ private long reached = -1; /** Total number of blocks. */ int blockTotal; /** Number of safe blocks. */ private int blockSafe; /** * Creates SafeModeInfo when the name node enters * automatic safe mode at startup. * * @param conf configuration */ SafeModeInfo( Configuration conf ) { this.threshold = conf.getFloat( "dfs.safemode.threshold.pct", 0.95f ); this.extension = conf.getInt( "dfs.safemode.extension", 0 ); this.safeReplication = conf.getInt( "dfs.replication.min", 1 ); this.blockTotal = 0; this.blockSafe = 0; } /** * Creates SafeModeInfo when safe mode is entered manually. * * The {@link #threshold} is set to 1.5 so that it could never be reached. * {@link #blockTotal} is set to -1 to indicate that safe mode is manual. * * @see SafeModeInfo */ private SafeModeInfo() { this.threshold = 1.5f; // this threshold can never be riched this.extension = 0; this.safeReplication = Short.MAX_VALUE + 1; // more than maxReplication this.blockTotal = -1; this.blockSafe = -1; this.reached = -1; enter(); } /** * Check if safe mode is on. * @return true if in safe mode */ synchronized boolean isOn() { try { isConsistent(); // SHV this is an assert } catch( IOException e ) { System.err.print( StringUtils.stringifyException( e )); } return this.reached >= 0; } /** * Enter safe mode. */ void enter() { if( reached != 0 ) NameNode.stateChangeLog.info( "STATE* SafeModeInfo.enter: " + "Safe mode is ON.\n" + getTurnOffTip() ); this.reached = 0; } /** * Leave safe mode. */ synchronized void leave() { if( reached >= 0 ) NameNode.stateChangeLog.info( "STATE* SafeModeInfo.leave: " + "Safe mode is OFF." ); reached = -1; safeMode = null; NameNode.stateChangeLog.info("STATE* Network topology has " +clusterMap.getNumOfRacks()+" racks and " +clusterMap.getNumOfLeaves()+ " datanodes"); NameNode.stateChangeLog.info("STATE* UnderReplicatedBlocks has " +neededReplications.size()+" blocks" ); } /** * Safe mode can be turned off iff * the threshold is reached and * the extension time have passed. * @return true if can leave or false otherwise. */ synchronized boolean canLeave() { if( reached == 0 ) return false; if( now() - reached < extension ) return false; return ! needEnter(); } /** * There is no need to enter safe mode * if DFS is empty or {@link #threshold} == 0 */ boolean needEnter() { return getSafeBlockRatio() < threshold; } /** * Ratio of the number of safe blocks to the total number of blocks * to be compared with the threshold. */ private float getSafeBlockRatio() { return ( blockTotal == 0 ? 1 : (float)blockSafe/blockTotal ); } /** * Check and trigger safe mode if needed. */ private void checkMode() { if( needEnter() ) { enter(); return; } // the threshold is reached if( ! isOn() || // safe mode is off extension <= 0 || threshold <= 0 ) { // don't need to wait this.leave(); // just leave safe mode return; } if( reached > 0 ) // threshold has already been reached before return; // start monitor reached = now(); smmthread = new Daemon(new SafeModeMonitor()); smmthread.start(); } /** * Set total number of blocks. */ synchronized void setBlockTotal( int total) { this.blockTotal = total; checkMode(); } /** * Increment number of safe blocks if current block has * reached minimal replication. * @param replication current replication */ synchronized void incrementSafeBlockCount( short replication ) { if( (int)replication == safeReplication ) this.blockSafe++; checkMode(); } /** * Decrement number of safe blocks if current block has * fallen below minimal replication. * @param replication current replication */ synchronized void decrementSafeBlockCount( short replication ) { if( replication == safeReplication-1 ) this.blockSafe--; checkMode(); } /** * Check if safe mode was entered manually or at startup. */ boolean isManual() { return blockTotal == -1; } /** * A tip on how safe mode is to be turned off: manually or automatically. */ String getTurnOffTip() { return ( isManual() ? "Use \"hadoop dfs -safemode leave\" to turn safe mode off." : "Safe mode will be turned off automatically." ); } /** * Returns printable state of the class. */ public String toString() { String resText = "Current safe block ratio = " + getSafeBlockRatio() + ". Target threshold = " + threshold + ". Minimal replication = " + safeReplication + "."; if( reached > 0 ) resText += " Threshold was reached " + new Date(reached) + "."; return resText; } /** * Checks consistency of the class state. */ void isConsistent() throws IOException { if( blockTotal == -1 && blockSafe == -1 ) { return; // manual safe mode } int activeBlocks = dir.activeBlocks.size(); if( blockTotal != activeBlocks ) throw new IOException( "blockTotal " + blockTotal + " does not match all blocks count. " + "activeBlocks = " + activeBlocks + ". safeBlocks = " + blockSafe + " safeMode is: " + ((safeMode == null) ? "null" : safeMode.toString()) ); if( blockSafe < 0 || blockSafe > blockTotal ) throw new IOException( "blockSafe " + blockSafe + " is out of range [0," + blockTotal + "]. " + "activeBlocks = " + activeBlocks + " safeMode is: " + ((safeMode == null) ? "null" : safeMode.toString()) ); } } /** * Periodically check whether it is time to leave safe mode. * This thread starts when the threshold level is reached. * * @author Konstantin Shvachko */ class SafeModeMonitor implements Runnable { /** interval in msec for checking safe mode: {@value} */ private static final long recheckInterval = 1000; /** */ public void run() { while( ! safeMode.canLeave() ) { try { Thread.sleep(recheckInterval); } catch (InterruptedException ie) { } } // leave safe mode an stop the monitor safeMode.leave(); smmthread = null; } } /** * Current system time. * @return current time in msec. */ static long now() { return System.currentTimeMillis(); } /** * Check whether the name node is in safe mode. * @return true if safe mode is ON, false otherwise */ boolean isInSafeMode() { if( safeMode == null ) return false; return safeMode.isOn(); } /** * Increment number of blocks that reached minimal replication. * @param replication current replication */ void incrementSafeBlockCount( int replication ) { if( safeMode == null ) return; safeMode.incrementSafeBlockCount( (short)replication ); } /** * Decrement number of blocks that reached minimal replication. * @param replication current replication */ void decrementSafeBlockCount( int replication ) { if( safeMode == null ) return; safeMode.decrementSafeBlockCount( (short)replication ); } /** * Set the total number of blocks in the system. */ void setBlockTotal() { if( safeMode == null ) return; safeMode.setBlockTotal( dir.activeBlocks.size() ); } /** * Enter safe mode manually. * @throws IOException */ synchronized void enterSafeMode() throws IOException { if( isInSafeMode() ) { NameNode.stateChangeLog.info( "STATE* FSNamesystem.enterSafeMode: " + "Safe mode is already ON."); return; } safeMode = new SafeModeInfo(); } /** * Leave safe mode. * @throws IOException */ synchronized void leaveSafeMode() throws IOException { if( ! isInSafeMode() ) { NameNode.stateChangeLog.info( "STATE* FSNamesystem.leaveSafeMode: " + "Safe mode is already OFF."); return; } safeMode.leave(); } String getSafeModeTip() { if( ! isInSafeMode() ) return ""; return safeMode.getTurnOffTip(); } long getEditLogSize() throws IOException { return getEditLog().getEditLogSize(); } synchronized void rollEditLog() throws IOException { if (isInSafeMode()) { throw new SafeModeException("Checkpoint not created", safeMode); } LOG.info("Roll Edit Log"); getEditLog().rollEditLog(); } synchronized void rollFSImage() throws IOException { LOG.info("Roll FSImage"); if (isInSafeMode()) { throw new SafeModeException("Checkpoint not created", safeMode); } dir.fsImage.rollFSImage(); } File getFsImageName() throws IOException { return dir.fsImage.getFsImageName(); } File[] getFsImageNameCheckpoint() throws IOException { return dir.fsImage.getFsImageNameCheckpoint(); } File getFsEditName() throws IOException { return getEditLog().getFsEditName(); } /** * This class is used in Namesystem's jetty to do fsck on namenode * @author Milind Bhandarkar */ public static class FsckServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { Map<String,String[]> pmap = request.getParameterMap(); try { ServletContext context = getServletContext(); NameNode nn = (NameNode) context.getAttribute("name.node"); Configuration conf = (Configuration) context.getAttribute("name.conf"); NamenodeFsck fscker = new NamenodeFsck(conf, nn, pmap, response); fscker.fsck(); } catch (IOException ie) { StringUtils.stringifyException(ie); LOG.warn(ie); String errMsg = "Fsck on path " + pmap.get("path") + " failed."; response.sendError(HttpServletResponse.SC_GONE, errMsg); throw ie; } } } /** * This class is used in Namesystem's jetty to retrieve a file. * Typically used by the Secondary NameNode to retrieve image and * edit file for periodic checkpointing. * @author Dhruba Borthakur */ public static class GetImageServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { Map<String,String[]> pmap = request.getParameterMap(); try { ServletContext context = getServletContext(); NameNode nn = (NameNode) context.getAttribute("name.node"); Configuration conf = (Configuration) context.getAttribute("name.conf"); TransferFsImage ff = new TransferFsImage(pmap, request, response); if (ff.getImage()) { // send fsImage to Secondary TransferFsImage.getFileServer(response.getOutputStream(), nn.getFsImageName()); } else if (ff.getEdit()) { // send old edits to Secondary TransferFsImage.getFileServer(response.getOutputStream(), nn.getFsEditName()); } else if (ff.putImage()) { // issue a HTTP get request to download the new fsimage TransferFsImage.getFileClient(ff.getInfoServer(), "getimage=1", nn.getFsImageNameCheckpoint()); } } catch (IOException ie) { StringUtils.stringifyException(ie); LOG.warn(ie); String errMsg = "GetImage failed."; response.sendError(HttpServletResponse.SC_GONE, errMsg); throw ie; } } } }
8df0116be5a1ba858d2e9e43e24b1f7e4c655bc0
e58a8e0fb0cfc7b9a05f43e38f1d01a4d8d8cf1f
/DungeonDiver2/lib/net/worldwizard/support/map/InvalidMapException.java
c158f5dd5f2b1b583c4ef34fbb03b5b7c93d77ac
[ "Unlicense" ]
permissive
retropipes/older-java-games
777574e222f30a1dffe7936ed08c8bfeb23a21ba
786b0c165d800c49ab9977a34ec17286797c4589
refs/heads/master
2023-04-12T14:28:25.525259
2021-05-15T13:03:54
2021-05-15T13:03:54
235,693,016
0
0
null
null
null
null
UTF-8
Java
false
false
494
java
/* DungeonDiverII: A Map-Solving Game Copyright (C) 2008-2010 Eric Ahnell Any questions should be directed to the author via email at: [email protected] */ package net.worldwizard.support.map; public class InvalidMapException extends Exception { // Serialization private static final long serialVersionUID = 999L; // Constructors public InvalidMapException() { super(); } public InvalidMapException(final String msg) { super(msg); } }
d0b4fce834615bc1e340fe066418456cea34f6fc
1d12507e208ab3a249e8ad4e9dfc93a7535fef96
/AuthenticationService/src/main/java/org/lu/AuthenticationApplication.java
6773aa1395aa66a689c057fbe2826efe11c20e48
[]
no_license
popwar/Jwt-Auth
913ef57c21c1b2ed3dbe89a7f05f9f787aca79b3
6d63fb47f3c6fd69660d7f56d4b1bfc4a2da77af
refs/heads/master
2021-01-19T03:49:07.832373
2018-04-22T22:58:53
2018-04-22T22:58:53
84,415,981
0
0
null
2018-04-22T22:57:37
2017-03-09T08:15:22
Java
UTF-8
Java
false
false
2,779
java
package org.lu; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Date; import java.util.Map; import java.util.Optional; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; //@EnableDiscoveryClient @SpringBootApplication public class AuthenticationApplication { public static void main(String[] args) { SpringApplication.run(AuthenticationApplication.class, args); } } @Controller class AuthenticationController extends WebMvcConfigurerAdapter { @Autowired private TokenUtils tokenUtils; @RequestMapping(value = "/home", method = RequestMethod.GET) @ResponseBody public String home() { return "home"; } @RequestMapping(value = "/validateToken", method = RequestMethod.POST) @ResponseBody public ReturnTokenResponse authenticateToken(@RequestBody TokenRequest token) { Optional<ReturnTokenResponse> a = tokenUtils.validateToken(token.getToken(), "tomcat"); ReturnTokenResponse response = a.get(); return response; } @RequestMapping(value = "/toLogin", method = RequestMethod.GET) public String gotoLogin(@RequestParam("forwardURL") String forwardURL, Map<String, Object> model) // forwardURL { model.put("time", new Date()); model.put("forwardURL", forwardURL); return "login"; } @RequestMapping(value = "/login", method = RequestMethod.POST) @ResponseBody public Response login(@RequestBody LoginRequest loginRequest, HttpServletResponse httpServletResponse) throws UnsupportedEncodingException { // skip verify user and get role from repository String username = loginRequest.getUsername(); String role = "user"; String token = tokenUtils.generateToken(username, role); Response response = new Response(URLDecoder.decode(loginRequest.getUrl(), "UTF-8"), token); return response; } private class Response { final private String url; final private String token; public Response(String url, String token) { super(); this.url = url; this.token = token; } public String getUrl() { return url; } public String getToken() { return token; } } }
c3554fc27ffa5b69d7c3c64b1ef7b1cd837c2c71
327d615dbf9e4dd902193b5cd7684dfd789a76b1
/base_source_from_JADX/sources/com/google/android/gms/ads_identifier/C2230R.java
3e30f89579462674b1f935384c5995ad5d3ccc48
[]
no_license
dnosauro/singcie
e53ce4c124cfb311e0ffafd55b58c840d462e96f
34d09c2e2b3497dd452246b76646b3571a18a100
refs/heads/main
2023-01-13T23:17:49.094499
2020-11-20T10:46:19
2020-11-20T10:46:19
314,513,307
0
0
null
null
null
null
UTF-8
Java
false
false
167
java
package com.google.android.gms.ads_identifier; /* renamed from: com.google.android.gms.ads_identifier.R */ public final class C2230R { private C2230R() { } }
890bee17271e594743fd26401041dc98989f6079
80403ec5838e300c53fcb96aeb84d409bdce1c0c
/server/modules/ms2/src/org/labkey/ms2/RunListCache.java
df16124ba6a04bf92cd6aa117d0042aa000d3d5a
[]
no_license
scchess/LabKey
7e073656ea494026b0020ad7f9d9179f03d87b41
ce5f7a903c78c0d480002f738bccdbef97d6aeb9
refs/heads/master
2021-09-17T10:49:48.147439
2018-03-22T13:01:41
2018-03-22T13:01:41
126,447,224
0
1
null
null
null
null
UTF-8
Java
false
false
5,113
java
/* * Copyright (c) 2008-2017 LabKey Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.labkey.ms2; import org.labkey.api.view.ViewContext; import org.labkey.api.data.DataRegionSelection; import org.labkey.api.exp.api.ExpRun; import org.labkey.api.exp.api.ExperimentService; import org.labkey.api.exp.api.ExpExperiment; import javax.servlet.ServletException; import java.util.*; /** * User: jeckels * Date: Jan 23, 2008 */ public class RunListCache { private static final String NO_RUNS_MESSAGE = "Run list is empty. Please reselect the runs."; public static List<MS2Run> getCachedRuns(int index, boolean requireSameType, ViewContext ctx) throws RunListException { ExpExperiment group = ExperimentService.get().getExpExperiment(index); if (group == null || !group.getContainer().equals(ctx.getContainer())) { throw new RunListException(NO_RUNS_MESSAGE); } List<MS2Run> ms2Runs = new ArrayList<>(); for (ExpRun expRun : group.getRuns()) { ms2Runs.add(MS2Manager.getRunByExperimentRunLSID(expRun.getLSID())); } MS2Manager.validateRuns(ms2Runs, requireSameType, ctx.getUser()); return ms2Runs; } // We store just the list of run IDs, not the runs themselves. Even though we're // just storing the list, we do all error & security checks upfront to alert the user early. public static int cacheSelectedRuns(boolean requireSameType, MS2Controller.RunListForm form, ViewContext ctx) throws ServletException, RunListException { String selectionKey = ctx.getRequest().getParameter(DataRegionSelection.DATA_REGION_SELECTION_KEY); if (selectionKey == null) { throw new RunListException(NO_RUNS_MESSAGE); } Set<String> stringIds = DataRegionSelection.getSelected(ctx, selectionKey, true, true); if (stringIds.isEmpty()) { throw new RunListException(NO_RUNS_MESSAGE); } List<String> parseErrors = new ArrayList<>(); List<ExpRun> expRuns = new ArrayList<>(); List<MS2Run> ms2Runs = new ArrayList<>(); for (String stringId : stringIds) { try { int id = Integer.parseInt(stringId); if (form.isExperimentRunIds()) { ExpRun expRun = ExperimentService.get().getExpRun(id); if (expRun != null) { expRuns.add(expRun); MS2Run ms2Run = MS2Manager.getRunByExperimentRunLSID(expRun.getLSID()); if (ms2Run == null) { parseErrors.add("Could not find MS2 run for run LSID: " + expRun.getLSID()); } } else { parseErrors.add("Could not find experiment run with RowId " + id); } } else { MS2Run ms2Run = MS2Manager.getRun(id); if (ms2Run == null) { parseErrors.add("Could not find MS2 run with id " + id); } else { ms2Runs.add(ms2Run); ExpRun expRun = ExperimentService.get().getExpRun(ms2Run.getExperimentRunLSID()); if (expRun == null) { parseErrors.add("Could not find experiment run with LSID " + ms2Run.getExperimentRunLSID()); } else { expRuns.add(expRun); } } } } catch (NumberFormatException e) { parseErrors.add("Run " + stringId + ": Number format error"); } } if (!parseErrors.isEmpty()) { throw new RunListException(parseErrors); } MS2Manager.validateRuns(ms2Runs, requireSameType, ctx.getUser()); ExpExperiment group = ExperimentService.get().createHiddenRunGroup(ctx.getContainer(), ctx.getUser(), expRuns.toArray(new ExpRun[expRuns.size()])); return group.getRowId(); } }
1d5627cffafa9cfcc8a9f97c61396c0f3090d8ef
a6d2c85d1ee03c9ee56c8309a63a5d92498cf64b
/app/src/main/java/com/swyftpartner/driver/utils/TaxifyUtils.java
8ef247f810b3d8efef8b244850163b759d9a1df7
[]
no_license
asgeorgia/swyftdrive_driver_android
233a048a8b42e63218533ac32ab1e322be9f0a2c
2e2316de5154ccc4a84a4d22817500436b940b65
refs/heads/master
2021-01-25T13:40:58.779926
2018-02-09T13:18:20
2018-02-09T13:18:20
123,602,327
0
0
null
null
null
null
UTF-8
Java
false
false
1,121
java
package com.swyftpartner.driver.utils; import android.app.Activity; import android.content.Context; import android.util.DisplayMetrics; import java.text.SimpleDateFormat; public class TaxifyUtils { public static String toDateTimeFormat(long dateTime) { return new SimpleDateFormat("MMMM dd HH:mm").format(Long.valueOf(dateTime)); } public static String toDateFormat(long dateTime) { return new SimpleDateFormat("dd.MM.yyyy").format(Long.valueOf(dateTime)); } private static DisplayMetrics getDisplayMetrics(Context context) { DisplayMetrics displayMetrics = new DisplayMetrics(); ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); return displayMetrics; } public static int getScreenHeight(Context context) { return getDisplayMetrics(context).heightPixels; } public static int getScreenWidth(Context context) { return getDisplayMetrics(context).widthPixels; } public static float getScreenDensity(Context context) { return getDisplayMetrics(context).density; } }
eb7c5e2f6b5ad426374c5573339ca66abb3ca7de
404a189c16767191ffb172572d36eca7db5571fb
/hibernate/build/java/gov/georgia/dhr/dfcs/sacwis/db/Ncands.java
4b952ba5e07b4a488ec5f71ae617a81179d3dda0
[]
no_license
tayduivn/training
648a8e9e91194156fb4ffb631749e6d4bf2d0590
95078fb2c7e21bf2bba31e2bbd5e404ac428da2f
refs/heads/master
2021-06-13T16:20:41.293097
2017-05-08T21:37:59
2017-05-08T21:37:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
38,698
java
package gov.georgia.dhr.dfcs.sacwis.db; // Generated Apr 23, 2012 11:16:12 AM by Hibernate Tools 3.2.0.b9 import java.util.Date; /** * Ncands generated by hbm2java */ public class Ncands implements java.io.Serializable { private NcandsId id; private Date dtLastUpdate; private String staterr; private String rptid; private String chid; private String rptcnty; private String rptdt; private String invstdt; private String rptsrc; private String rptdisp; private String rptdisdt; private String notifs; private String chage; private String childBdate; private String childSex; private String childRaceAmerind; private String childRaceAsian; private String childRaceBlack; private String childRaceHawaiiPac; private String childRaceWhite; private String childRaceUnable; private String childIsp; private String childCnty; private String childLvng; private String childMil; private String childPrior; private String childMal1; private String childMaldisp1; private String childMal2; private String childMaldisp2; private String childMal3; private String childMaldisp3; private String childMal4; private String childMaldisp4; private String childMalDeath; private String cdalc; private String cddrug; private String cdrtrd; private String cdemotnl; private String cdvisual; private String cdlearn; private String cdphys; private String cdbehav; private String cdmedicl; private String fcalc; private String fcdrug; private String fcrtrd; private String fcemotnl; private String fcvisual; private String fclearn; private String fcphys; private String fcmedicl; private String fcviol; private String fchouse; private String fcmoney; private String fcpublic; private String postserv; private String servdate; private String famsup; private String fampres; private String fostercr; private String rmvdate; private String juvpet; private String petdate; private String cochrep; private String adopt; private String casemanag; private String counsel; private String daycare; private String educatn; private String employ; private String famplan; private String health; private String homebase; private String housing; private String transliv; private String inforef; private String legal; private String menthlth; private String pregpar; private String respite; private String ssdisabl; private String ssdelinq; private String subabuse; private String transprt; private String othersv; private String wrkrid; private String suprvid; private String perId1; private String perRel1; private String perPrnt1; private String perCr1; private String perAge1; private String perSex1; private String perRaceIndian1; private String perRaceAsian1; private String perRaceBlack1; private String perRaceHawaiiPac1; private String perRaceWhite1; private String perRaceUnable1; private String perHisp1; private String perMil1; private String perPrior1; private String perMal11; private String perMal21; private String perMal31; private String perMal41; private String perId2; private String perRel2; private String perPrnt2; private String perCr2; private String perAge2; private String perSex2; private String perRaceIndian2; private String perRaceAsian2; private String perRaceBlack2; private String perRaceHawaiiPac2; private String perRaceWhite2; private String perRaceUnable2; private String perHisp2; private String perMil2; private String perPrior2; private String perMal12; private String perMal22; private String perMal32; private String perMal42; private String perId3; private String perRel3; private String perPrnt3; private String perCr3; private String perAge3; private String perSex3; private String perRaceIndian3; private String perRaceAsian3; private String perRaceBlack3; private String perRaceHawaiiPac3; private String perRaceWhite3; private String perRaceUnable3; private String perHisp3; private String perMil3; private String perPrior3; private String perMal13; private String perMal23; private String perMal33; private String perMal43; private String afcarsId; private String incidentDate; private String caseManager; private String supervisor; public Ncands() { } public Ncands(NcandsId id) { this.id = id; } public Ncands(NcandsId id, String staterr, String rptid, String chid, String rptcnty, String rptdt, String invstdt, String rptsrc, String rptdisp, String rptdisdt, String notifs, String chage, String childBdate, String childSex, String childRaceAmerind, String childRaceAsian, String childRaceBlack, String childRaceHawaiiPac, String childRaceWhite, String childRaceUnable, String childIsp, String childCnty, String childLvng, String childMil, String childPrior, String childMal1, String childMaldisp1, String childMal2, String childMaldisp2, String childMal3, String childMaldisp3, String childMal4, String childMaldisp4, String childMalDeath, String cdalc, String cddrug, String cdrtrd, String cdemotnl, String cdvisual, String cdlearn, String cdphys, String cdbehav, String cdmedicl, String fcalc, String fcdrug, String fcrtrd, String fcemotnl, String fcvisual, String fclearn, String fcphys, String fcmedicl, String fcviol, String fchouse, String fcmoney, String fcpublic, String postserv, String servdate, String famsup, String fampres, String fostercr, String rmvdate, String juvpet, String petdate, String cochrep, String adopt, String casemanag, String counsel, String daycare, String educatn, String employ, String famplan, String health, String homebase, String housing, String transliv, String inforef, String legal, String menthlth, String pregpar, String respite, String ssdisabl, String ssdelinq, String subabuse, String transprt, String othersv, String wrkrid, String suprvid, String perId1, String perRel1, String perPrnt1, String perCr1, String perAge1, String perSex1, String perRaceIndian1, String perRaceAsian1, String perRaceBlack1, String perRaceHawaiiPac1, String perRaceWhite1, String perRaceUnable1, String perHisp1, String perMil1, String perPrior1, String perMal11, String perMal21, String perMal31, String perMal41, String perId2, String perRel2, String perPrnt2, String perCr2, String perAge2, String perSex2, String perRaceIndian2, String perRaceAsian2, String perRaceBlack2, String perRaceHawaiiPac2, String perRaceWhite2, String perRaceUnable2, String perHisp2, String perMil2, String perPrior2, String perMal12, String perMal22, String perMal32, String perMal42, String perId3, String perRel3, String perPrnt3, String perCr3, String perAge3, String perSex3, String perRaceIndian3, String perRaceAsian3, String perRaceBlack3, String perRaceHawaiiPac3, String perRaceWhite3, String perRaceUnable3, String perHisp3, String perMil3, String perPrior3, String perMal13, String perMal23, String perMal33, String perMal43, String afcarsId, String incidentDate, String caseManager, String supervisor) { this.id = id; this.staterr = staterr; this.rptid = rptid; this.chid = chid; this.rptcnty = rptcnty; this.rptdt = rptdt; this.invstdt = invstdt; this.rptsrc = rptsrc; this.rptdisp = rptdisp; this.rptdisdt = rptdisdt; this.notifs = notifs; this.chage = chage; this.childBdate = childBdate; this.childSex = childSex; this.childRaceAmerind = childRaceAmerind; this.childRaceAsian = childRaceAsian; this.childRaceBlack = childRaceBlack; this.childRaceHawaiiPac = childRaceHawaiiPac; this.childRaceWhite = childRaceWhite; this.childRaceUnable = childRaceUnable; this.childIsp = childIsp; this.childCnty = childCnty; this.childLvng = childLvng; this.childMil = childMil; this.childPrior = childPrior; this.childMal1 = childMal1; this.childMaldisp1 = childMaldisp1; this.childMal2 = childMal2; this.childMaldisp2 = childMaldisp2; this.childMal3 = childMal3; this.childMaldisp3 = childMaldisp3; this.childMal4 = childMal4; this.childMaldisp4 = childMaldisp4; this.childMalDeath = childMalDeath; this.cdalc = cdalc; this.cddrug = cddrug; this.cdrtrd = cdrtrd; this.cdemotnl = cdemotnl; this.cdvisual = cdvisual; this.cdlearn = cdlearn; this.cdphys = cdphys; this.cdbehav = cdbehav; this.cdmedicl = cdmedicl; this.fcalc = fcalc; this.fcdrug = fcdrug; this.fcrtrd = fcrtrd; this.fcemotnl = fcemotnl; this.fcvisual = fcvisual; this.fclearn = fclearn; this.fcphys = fcphys; this.fcmedicl = fcmedicl; this.fcviol = fcviol; this.fchouse = fchouse; this.fcmoney = fcmoney; this.fcpublic = fcpublic; this.postserv = postserv; this.servdate = servdate; this.famsup = famsup; this.fampres = fampres; this.fostercr = fostercr; this.rmvdate = rmvdate; this.juvpet = juvpet; this.petdate = petdate; this.cochrep = cochrep; this.adopt = adopt; this.casemanag = casemanag; this.counsel = counsel; this.daycare = daycare; this.educatn = educatn; this.employ = employ; this.famplan = famplan; this.health = health; this.homebase = homebase; this.housing = housing; this.transliv = transliv; this.inforef = inforef; this.legal = legal; this.menthlth = menthlth; this.pregpar = pregpar; this.respite = respite; this.ssdisabl = ssdisabl; this.ssdelinq = ssdelinq; this.subabuse = subabuse; this.transprt = transprt; this.othersv = othersv; this.wrkrid = wrkrid; this.suprvid = suprvid; this.perId1 = perId1; this.perRel1 = perRel1; this.perPrnt1 = perPrnt1; this.perCr1 = perCr1; this.perAge1 = perAge1; this.perSex1 = perSex1; this.perRaceIndian1 = perRaceIndian1; this.perRaceAsian1 = perRaceAsian1; this.perRaceBlack1 = perRaceBlack1; this.perRaceHawaiiPac1 = perRaceHawaiiPac1; this.perRaceWhite1 = perRaceWhite1; this.perRaceUnable1 = perRaceUnable1; this.perHisp1 = perHisp1; this.perMil1 = perMil1; this.perPrior1 = perPrior1; this.perMal11 = perMal11; this.perMal21 = perMal21; this.perMal31 = perMal31; this.perMal41 = perMal41; this.perId2 = perId2; this.perRel2 = perRel2; this.perPrnt2 = perPrnt2; this.perCr2 = perCr2; this.perAge2 = perAge2; this.perSex2 = perSex2; this.perRaceIndian2 = perRaceIndian2; this.perRaceAsian2 = perRaceAsian2; this.perRaceBlack2 = perRaceBlack2; this.perRaceHawaiiPac2 = perRaceHawaiiPac2; this.perRaceWhite2 = perRaceWhite2; this.perRaceUnable2 = perRaceUnable2; this.perHisp2 = perHisp2; this.perMil2 = perMil2; this.perPrior2 = perPrior2; this.perMal12 = perMal12; this.perMal22 = perMal22; this.perMal32 = perMal32; this.perMal42 = perMal42; this.perId3 = perId3; this.perRel3 = perRel3; this.perPrnt3 = perPrnt3; this.perCr3 = perCr3; this.perAge3 = perAge3; this.perSex3 = perSex3; this.perRaceIndian3 = perRaceIndian3; this.perRaceAsian3 = perRaceAsian3; this.perRaceBlack3 = perRaceBlack3; this.perRaceHawaiiPac3 = perRaceHawaiiPac3; this.perRaceWhite3 = perRaceWhite3; this.perRaceUnable3 = perRaceUnable3; this.perHisp3 = perHisp3; this.perMil3 = perMil3; this.perPrior3 = perPrior3; this.perMal13 = perMal13; this.perMal23 = perMal23; this.perMal33 = perMal33; this.perMal43 = perMal43; this.afcarsId = afcarsId; this.incidentDate = incidentDate; this.caseManager = caseManager; this.supervisor = supervisor; } public NcandsId getId() { return this.id; } public void setId(NcandsId id) { this.id = id; } public Date getDtLastUpdate() { return this.dtLastUpdate; } public void setDtLastUpdate(Date dtLastUpdate) { this.dtLastUpdate = dtLastUpdate; } public String getStaterr() { return this.staterr; } public void setStaterr(String staterr) { this.staterr = staterr; } public String getRptid() { return this.rptid; } public void setRptid(String rptid) { this.rptid = rptid; } public String getChid() { return this.chid; } public void setChid(String chid) { this.chid = chid; } public String getRptcnty() { return this.rptcnty; } public void setRptcnty(String rptcnty) { this.rptcnty = rptcnty; } public String getRptdt() { return this.rptdt; } public void setRptdt(String rptdt) { this.rptdt = rptdt; } public String getInvstdt() { return this.invstdt; } public void setInvstdt(String invstdt) { this.invstdt = invstdt; } public String getRptsrc() { return this.rptsrc; } public void setRptsrc(String rptsrc) { this.rptsrc = rptsrc; } public String getRptdisp() { return this.rptdisp; } public void setRptdisp(String rptdisp) { this.rptdisp = rptdisp; } public String getRptdisdt() { return this.rptdisdt; } public void setRptdisdt(String rptdisdt) { this.rptdisdt = rptdisdt; } public String getNotifs() { return this.notifs; } public void setNotifs(String notifs) { this.notifs = notifs; } public String getChage() { return this.chage; } public void setChage(String chage) { this.chage = chage; } public String getChildBdate() { return this.childBdate; } public void setChildBdate(String childBdate) { this.childBdate = childBdate; } public String getChildSex() { return this.childSex; } public void setChildSex(String childSex) { this.childSex = childSex; } public String getChildRaceAmerind() { return this.childRaceAmerind; } public void setChildRaceAmerind(String childRaceAmerind) { this.childRaceAmerind = childRaceAmerind; } public String getChildRaceAsian() { return this.childRaceAsian; } public void setChildRaceAsian(String childRaceAsian) { this.childRaceAsian = childRaceAsian; } public String getChildRaceBlack() { return this.childRaceBlack; } public void setChildRaceBlack(String childRaceBlack) { this.childRaceBlack = childRaceBlack; } public String getChildRaceHawaiiPac() { return this.childRaceHawaiiPac; } public void setChildRaceHawaiiPac(String childRaceHawaiiPac) { this.childRaceHawaiiPac = childRaceHawaiiPac; } public String getChildRaceWhite() { return this.childRaceWhite; } public void setChildRaceWhite(String childRaceWhite) { this.childRaceWhite = childRaceWhite; } public String getChildRaceUnable() { return this.childRaceUnable; } public void setChildRaceUnable(String childRaceUnable) { this.childRaceUnable = childRaceUnable; } public String getChildIsp() { return this.childIsp; } public void setChildIsp(String childIsp) { this.childIsp = childIsp; } public String getChildCnty() { return this.childCnty; } public void setChildCnty(String childCnty) { this.childCnty = childCnty; } public String getChildLvng() { return this.childLvng; } public void setChildLvng(String childLvng) { this.childLvng = childLvng; } public String getChildMil() { return this.childMil; } public void setChildMil(String childMil) { this.childMil = childMil; } public String getChildPrior() { return this.childPrior; } public void setChildPrior(String childPrior) { this.childPrior = childPrior; } public String getChildMal1() { return this.childMal1; } public void setChildMal1(String childMal1) { this.childMal1 = childMal1; } public String getChildMaldisp1() { return this.childMaldisp1; } public void setChildMaldisp1(String childMaldisp1) { this.childMaldisp1 = childMaldisp1; } public String getChildMal2() { return this.childMal2; } public void setChildMal2(String childMal2) { this.childMal2 = childMal2; } public String getChildMaldisp2() { return this.childMaldisp2; } public void setChildMaldisp2(String childMaldisp2) { this.childMaldisp2 = childMaldisp2; } public String getChildMal3() { return this.childMal3; } public void setChildMal3(String childMal3) { this.childMal3 = childMal3; } public String getChildMaldisp3() { return this.childMaldisp3; } public void setChildMaldisp3(String childMaldisp3) { this.childMaldisp3 = childMaldisp3; } public String getChildMal4() { return this.childMal4; } public void setChildMal4(String childMal4) { this.childMal4 = childMal4; } public String getChildMaldisp4() { return this.childMaldisp4; } public void setChildMaldisp4(String childMaldisp4) { this.childMaldisp4 = childMaldisp4; } public String getChildMalDeath() { return this.childMalDeath; } public void setChildMalDeath(String childMalDeath) { this.childMalDeath = childMalDeath; } public String getCdalc() { return this.cdalc; } public void setCdalc(String cdalc) { this.cdalc = cdalc; } public String getCddrug() { return this.cddrug; } public void setCddrug(String cddrug) { this.cddrug = cddrug; } public String getCdrtrd() { return this.cdrtrd; } public void setCdrtrd(String cdrtrd) { this.cdrtrd = cdrtrd; } public String getCdemotnl() { return this.cdemotnl; } public void setCdemotnl(String cdemotnl) { this.cdemotnl = cdemotnl; } public String getCdvisual() { return this.cdvisual; } public void setCdvisual(String cdvisual) { this.cdvisual = cdvisual; } public String getCdlearn() { return this.cdlearn; } public void setCdlearn(String cdlearn) { this.cdlearn = cdlearn; } public String getCdphys() { return this.cdphys; } public void setCdphys(String cdphys) { this.cdphys = cdphys; } public String getCdbehav() { return this.cdbehav; } public void setCdbehav(String cdbehav) { this.cdbehav = cdbehav; } public String getCdmedicl() { return this.cdmedicl; } public void setCdmedicl(String cdmedicl) { this.cdmedicl = cdmedicl; } public String getFcalc() { return this.fcalc; } public void setFcalc(String fcalc) { this.fcalc = fcalc; } public String getFcdrug() { return this.fcdrug; } public void setFcdrug(String fcdrug) { this.fcdrug = fcdrug; } public String getFcrtrd() { return this.fcrtrd; } public void setFcrtrd(String fcrtrd) { this.fcrtrd = fcrtrd; } public String getFcemotnl() { return this.fcemotnl; } public void setFcemotnl(String fcemotnl) { this.fcemotnl = fcemotnl; } public String getFcvisual() { return this.fcvisual; } public void setFcvisual(String fcvisual) { this.fcvisual = fcvisual; } public String getFclearn() { return this.fclearn; } public void setFclearn(String fclearn) { this.fclearn = fclearn; } public String getFcphys() { return this.fcphys; } public void setFcphys(String fcphys) { this.fcphys = fcphys; } public String getFcmedicl() { return this.fcmedicl; } public void setFcmedicl(String fcmedicl) { this.fcmedicl = fcmedicl; } public String getFcviol() { return this.fcviol; } public void setFcviol(String fcviol) { this.fcviol = fcviol; } public String getFchouse() { return this.fchouse; } public void setFchouse(String fchouse) { this.fchouse = fchouse; } public String getFcmoney() { return this.fcmoney; } public void setFcmoney(String fcmoney) { this.fcmoney = fcmoney; } public String getFcpublic() { return this.fcpublic; } public void setFcpublic(String fcpublic) { this.fcpublic = fcpublic; } public String getPostserv() { return this.postserv; } public void setPostserv(String postserv) { this.postserv = postserv; } public String getServdate() { return this.servdate; } public void setServdate(String servdate) { this.servdate = servdate; } public String getFamsup() { return this.famsup; } public void setFamsup(String famsup) { this.famsup = famsup; } public String getFampres() { return this.fampres; } public void setFampres(String fampres) { this.fampres = fampres; } public String getFostercr() { return this.fostercr; } public void setFostercr(String fostercr) { this.fostercr = fostercr; } public String getRmvdate() { return this.rmvdate; } public void setRmvdate(String rmvdate) { this.rmvdate = rmvdate; } public String getJuvpet() { return this.juvpet; } public void setJuvpet(String juvpet) { this.juvpet = juvpet; } public String getPetdate() { return this.petdate; } public void setPetdate(String petdate) { this.petdate = petdate; } public String getCochrep() { return this.cochrep; } public void setCochrep(String cochrep) { this.cochrep = cochrep; } public String getAdopt() { return this.adopt; } public void setAdopt(String adopt) { this.adopt = adopt; } public String getCasemanag() { return this.casemanag; } public void setCasemanag(String casemanag) { this.casemanag = casemanag; } public String getCounsel() { return this.counsel; } public void setCounsel(String counsel) { this.counsel = counsel; } public String getDaycare() { return this.daycare; } public void setDaycare(String daycare) { this.daycare = daycare; } public String getEducatn() { return this.educatn; } public void setEducatn(String educatn) { this.educatn = educatn; } public String getEmploy() { return this.employ; } public void setEmploy(String employ) { this.employ = employ; } public String getFamplan() { return this.famplan; } public void setFamplan(String famplan) { this.famplan = famplan; } public String getHealth() { return this.health; } public void setHealth(String health) { this.health = health; } public String getHomebase() { return this.homebase; } public void setHomebase(String homebase) { this.homebase = homebase; } public String getHousing() { return this.housing; } public void setHousing(String housing) { this.housing = housing; } public String getTransliv() { return this.transliv; } public void setTransliv(String transliv) { this.transliv = transliv; } public String getInforef() { return this.inforef; } public void setInforef(String inforef) { this.inforef = inforef; } public String getLegal() { return this.legal; } public void setLegal(String legal) { this.legal = legal; } public String getMenthlth() { return this.menthlth; } public void setMenthlth(String menthlth) { this.menthlth = menthlth; } public String getPregpar() { return this.pregpar; } public void setPregpar(String pregpar) { this.pregpar = pregpar; } public String getRespite() { return this.respite; } public void setRespite(String respite) { this.respite = respite; } public String getSsdisabl() { return this.ssdisabl; } public void setSsdisabl(String ssdisabl) { this.ssdisabl = ssdisabl; } public String getSsdelinq() { return this.ssdelinq; } public void setSsdelinq(String ssdelinq) { this.ssdelinq = ssdelinq; } public String getSubabuse() { return this.subabuse; } public void setSubabuse(String subabuse) { this.subabuse = subabuse; } public String getTransprt() { return this.transprt; } public void setTransprt(String transprt) { this.transprt = transprt; } public String getOthersv() { return this.othersv; } public void setOthersv(String othersv) { this.othersv = othersv; } public String getWrkrid() { return this.wrkrid; } public void setWrkrid(String wrkrid) { this.wrkrid = wrkrid; } public String getSuprvid() { return this.suprvid; } public void setSuprvid(String suprvid) { this.suprvid = suprvid; } public String getPerId1() { return this.perId1; } public void setPerId1(String perId1) { this.perId1 = perId1; } public String getPerRel1() { return this.perRel1; } public void setPerRel1(String perRel1) { this.perRel1 = perRel1; } public String getPerPrnt1() { return this.perPrnt1; } public void setPerPrnt1(String perPrnt1) { this.perPrnt1 = perPrnt1; } public String getPerCr1() { return this.perCr1; } public void setPerCr1(String perCr1) { this.perCr1 = perCr1; } public String getPerAge1() { return this.perAge1; } public void setPerAge1(String perAge1) { this.perAge1 = perAge1; } public String getPerSex1() { return this.perSex1; } public void setPerSex1(String perSex1) { this.perSex1 = perSex1; } public String getPerRaceIndian1() { return this.perRaceIndian1; } public void setPerRaceIndian1(String perRaceIndian1) { this.perRaceIndian1 = perRaceIndian1; } public String getPerRaceAsian1() { return this.perRaceAsian1; } public void setPerRaceAsian1(String perRaceAsian1) { this.perRaceAsian1 = perRaceAsian1; } public String getPerRaceBlack1() { return this.perRaceBlack1; } public void setPerRaceBlack1(String perRaceBlack1) { this.perRaceBlack1 = perRaceBlack1; } public String getPerRaceHawaiiPac1() { return this.perRaceHawaiiPac1; } public void setPerRaceHawaiiPac1(String perRaceHawaiiPac1) { this.perRaceHawaiiPac1 = perRaceHawaiiPac1; } public String getPerRaceWhite1() { return this.perRaceWhite1; } public void setPerRaceWhite1(String perRaceWhite1) { this.perRaceWhite1 = perRaceWhite1; } public String getPerRaceUnable1() { return this.perRaceUnable1; } public void setPerRaceUnable1(String perRaceUnable1) { this.perRaceUnable1 = perRaceUnable1; } public String getPerHisp1() { return this.perHisp1; } public void setPerHisp1(String perHisp1) { this.perHisp1 = perHisp1; } public String getPerMil1() { return this.perMil1; } public void setPerMil1(String perMil1) { this.perMil1 = perMil1; } public String getPerPrior1() { return this.perPrior1; } public void setPerPrior1(String perPrior1) { this.perPrior1 = perPrior1; } public String getPerMal11() { return this.perMal11; } public void setPerMal11(String perMal11) { this.perMal11 = perMal11; } public String getPerMal21() { return this.perMal21; } public void setPerMal21(String perMal21) { this.perMal21 = perMal21; } public String getPerMal31() { return this.perMal31; } public void setPerMal31(String perMal31) { this.perMal31 = perMal31; } public String getPerMal41() { return this.perMal41; } public void setPerMal41(String perMal41) { this.perMal41 = perMal41; } public String getPerId2() { return this.perId2; } public void setPerId2(String perId2) { this.perId2 = perId2; } public String getPerRel2() { return this.perRel2; } public void setPerRel2(String perRel2) { this.perRel2 = perRel2; } public String getPerPrnt2() { return this.perPrnt2; } public void setPerPrnt2(String perPrnt2) { this.perPrnt2 = perPrnt2; } public String getPerCr2() { return this.perCr2; } public void setPerCr2(String perCr2) { this.perCr2 = perCr2; } public String getPerAge2() { return this.perAge2; } public void setPerAge2(String perAge2) { this.perAge2 = perAge2; } public String getPerSex2() { return this.perSex2; } public void setPerSex2(String perSex2) { this.perSex2 = perSex2; } public String getPerRaceIndian2() { return this.perRaceIndian2; } public void setPerRaceIndian2(String perRaceIndian2) { this.perRaceIndian2 = perRaceIndian2; } public String getPerRaceAsian2() { return this.perRaceAsian2; } public void setPerRaceAsian2(String perRaceAsian2) { this.perRaceAsian2 = perRaceAsian2; } public String getPerRaceBlack2() { return this.perRaceBlack2; } public void setPerRaceBlack2(String perRaceBlack2) { this.perRaceBlack2 = perRaceBlack2; } public String getPerRaceHawaiiPac2() { return this.perRaceHawaiiPac2; } public void setPerRaceHawaiiPac2(String perRaceHawaiiPac2) { this.perRaceHawaiiPac2 = perRaceHawaiiPac2; } public String getPerRaceWhite2() { return this.perRaceWhite2; } public void setPerRaceWhite2(String perRaceWhite2) { this.perRaceWhite2 = perRaceWhite2; } public String getPerRaceUnable2() { return this.perRaceUnable2; } public void setPerRaceUnable2(String perRaceUnable2) { this.perRaceUnable2 = perRaceUnable2; } public String getPerHisp2() { return this.perHisp2; } public void setPerHisp2(String perHisp2) { this.perHisp2 = perHisp2; } public String getPerMil2() { return this.perMil2; } public void setPerMil2(String perMil2) { this.perMil2 = perMil2; } public String getPerPrior2() { return this.perPrior2; } public void setPerPrior2(String perPrior2) { this.perPrior2 = perPrior2; } public String getPerMal12() { return this.perMal12; } public void setPerMal12(String perMal12) { this.perMal12 = perMal12; } public String getPerMal22() { return this.perMal22; } public void setPerMal22(String perMal22) { this.perMal22 = perMal22; } public String getPerMal32() { return this.perMal32; } public void setPerMal32(String perMal32) { this.perMal32 = perMal32; } public String getPerMal42() { return this.perMal42; } public void setPerMal42(String perMal42) { this.perMal42 = perMal42; } public String getPerId3() { return this.perId3; } public void setPerId3(String perId3) { this.perId3 = perId3; } public String getPerRel3() { return this.perRel3; } public void setPerRel3(String perRel3) { this.perRel3 = perRel3; } public String getPerPrnt3() { return this.perPrnt3; } public void setPerPrnt3(String perPrnt3) { this.perPrnt3 = perPrnt3; } public String getPerCr3() { return this.perCr3; } public void setPerCr3(String perCr3) { this.perCr3 = perCr3; } public String getPerAge3() { return this.perAge3; } public void setPerAge3(String perAge3) { this.perAge3 = perAge3; } public String getPerSex3() { return this.perSex3; } public void setPerSex3(String perSex3) { this.perSex3 = perSex3; } public String getPerRaceIndian3() { return this.perRaceIndian3; } public void setPerRaceIndian3(String perRaceIndian3) { this.perRaceIndian3 = perRaceIndian3; } public String getPerRaceAsian3() { return this.perRaceAsian3; } public void setPerRaceAsian3(String perRaceAsian3) { this.perRaceAsian3 = perRaceAsian3; } public String getPerRaceBlack3() { return this.perRaceBlack3; } public void setPerRaceBlack3(String perRaceBlack3) { this.perRaceBlack3 = perRaceBlack3; } public String getPerRaceHawaiiPac3() { return this.perRaceHawaiiPac3; } public void setPerRaceHawaiiPac3(String perRaceHawaiiPac3) { this.perRaceHawaiiPac3 = perRaceHawaiiPac3; } public String getPerRaceWhite3() { return this.perRaceWhite3; } public void setPerRaceWhite3(String perRaceWhite3) { this.perRaceWhite3 = perRaceWhite3; } public String getPerRaceUnable3() { return this.perRaceUnable3; } public void setPerRaceUnable3(String perRaceUnable3) { this.perRaceUnable3 = perRaceUnable3; } public String getPerHisp3() { return this.perHisp3; } public void setPerHisp3(String perHisp3) { this.perHisp3 = perHisp3; } public String getPerMil3() { return this.perMil3; } public void setPerMil3(String perMil3) { this.perMil3 = perMil3; } public String getPerPrior3() { return this.perPrior3; } public void setPerPrior3(String perPrior3) { this.perPrior3 = perPrior3; } public String getPerMal13() { return this.perMal13; } public void setPerMal13(String perMal13) { this.perMal13 = perMal13; } public String getPerMal23() { return this.perMal23; } public void setPerMal23(String perMal23) { this.perMal23 = perMal23; } public String getPerMal33() { return this.perMal33; } public void setPerMal33(String perMal33) { this.perMal33 = perMal33; } public String getPerMal43() { return this.perMal43; } public void setPerMal43(String perMal43) { this.perMal43 = perMal43; } public String getAfcarsId() { return this.afcarsId; } public void setAfcarsId(String afcarsId) { this.afcarsId = afcarsId; } public String getIncidentDate() { return this.incidentDate; } public void setIncidentDate(String incidentDate) { this.incidentDate = incidentDate; } public String getCaseManager() { return this.caseManager; } public void setCaseManager(String caseManager) { this.caseManager = caseManager; } public String getSupervisor() { return this.supervisor; } public void setSupervisor(String supervisor) { this.supervisor = supervisor; } }
4e8587682a05b658e7e6ec1e4f4c62feb064d241
28b2d13a903b52fab6292919302b33d791de154f
/Java_OOP/Lab/lab 6/lab_a_6_2/src/lab_a_6_2/Lab_a_6.java
c4678df40118e6a8f254be467e10bd28c5797b1a
[]
no_license
Charvik2020/Collage-Work
f3480e2d3a54d7b0aab06e61e3de0d636aa2b5ee
fedbd558ed6800064c68beef9394befcd37d9f5f
refs/heads/master
2021-06-19T09:48:35.654132
2017-06-21T07:25:33
2017-06-21T07:25:33
66,243,315
1
0
null
null
null
null
UTF-8
Java
false
false
3,857
java
package lab_a_6_2; import java.util.Scanner; class Media { private String title; private int YearOfPublication; private int price; public Media() //defult constructor { title=null; YearOfPublication=0; price=0; } public Media(String t,int yop,int p) //parameter constructor { title=t; YearOfPublication=yop; price=p; } void Display_C() //display function of CD of media detail { System.out.println("\n_______IET-AU________"+"\nTITLE:"+title+"\nYEAR OF PUBLICATION:"+YearOfPublication+"\nPRICE OF CD:"+price+" RS"); } void Display_B() //display function of BOOK { System.out.println("\n_______IET-AU________"+"\nTITLE:"+title+"\nYEAR OF PUBLICATION:"+YearOfPublication+"\nPRICE OF BOOK:"+price+" RS"); } } class Cd extends Media //child class of Media { private float SizeMB; private float PlayTym; public Cd(String t,int yop,int p,float sMB,float pTym) //parameter constructor of child class with parent class member variable { super(t,yop,p); //super keyword for member of parent class with private data type SizeMB=sMB; PlayTym=pTym; } void Display_Cd() //display function for CD { System.out.println("CD SIZE:="+SizeMB+" MB"+"\nCD PLAY TIME:"+PlayTym+" MINUTES"+"\n_______END___________"); } } class Book extends Media { private String Author; private int total_Page; public Book(String t,int yop,int p,String Atr,int tP) //parameter constructor of Book class with parent class member variable { super(t,yop,p); //super keyword for member of parent class with private data type Author=Atr; total_Page= tP; } void Display_Book() //display function of BOOK { System.out.println("AUTHOR NAME:"+Author+"\nTOTAL PAGES:"+total_Page+"\n_______END___________"); } } public class Lab_a_6 { public static void main(String[] args) { int n,y=0,z=0; String x=null; Scanner sc=new Scanner(System.in); do{ System.out.println("\n1) ENTER MEDIA DETAIL \n2) ENTER CD DETAIL \n3) ENTER BOOK DETAIL \n0) EXIT"); System.out.println("ENTER YOUR CHOICE :"); n=sc.nextInt(); switch(n) { case 1: System.out.println("ENTER TITLE :"); x=sc.next(); System.out.println("ENTER YEAR OF PUBLICATION :"); y=sc.nextInt(); System.out.println("ENTER PRICE : "); z=sc.nextInt(); break; case 2: System.out.println("ENTER SIZE OF CD(IN MB): "); int sCD=0; sCD=sc.nextInt(); System.out.println("ENTER PLAY TIME(IN MINUTE): "); int pTym=0; pTym=sc.nextInt(); Cd m=new Cd(x, y, z, sCD, pTym); m.Display_C(); m.Display_Cd();break; case 3: System.out.println("ENTER AUTHOR NAME: "); String Atr=null; Atr=sc.next(); System.out.println("ENTER TOTAL PAGE: "); int tP=0; tP=sc.nextInt(); Book b=new Book(x, y, z, Atr, tP); b.Display_B(); b.Display_Book();break; } }while(n!=0); } }
c1d013739bf4570bb3795cc52ee87bfc88dedfd4
b8bd0161d72c4ca1eca465dde3f2d898ca9f5f39
/src/com/itedu365/best4631/BeforeFather.java
569aca8502dfc49322e1347301a723dd2b4b6bc9
[]
no_license
cakin24/TheBestCodeAndArchitectOptimize
2a3f07242ada411c0533c1587f88f90cf84fca1f
bdc671f410df0a46d89d20f468e4b08ce8f0703a
refs/heads/master
2020-09-15T20:43:05.916235
2019-11-23T07:58:38
2019-11-23T07:58:38
223,552,748
1
0
null
null
null
null
UTF-8
Java
false
false
539
java
/* * 本书配套视频教程网址(架构师系列培训): * www.365itedu.com * 365IT学院,让学习变得更简单! */ package com.itedu365.best4631; /** * * 【Java代码与架构之完美优化——实战经典】 * * 46、避免有深度耦合的类关系 * * 重构15 —— 移动方法(具有父子关系) * * @author 颜廷吉 */ public class BeforeFather { // 玩玩具方法 public void playToy(String person) { System.out.println(person + " 正在玩玩具。"); } }
ac10ffb00c31a370be94852645c32fa9f421a6d3
f9f5f95239b890a545c1111ba3f244240232c3df
/hypervisor/sirius/dijkstra/teste/Vertex.java
d03f3163364e49f030b816ea35b032d329e6661a
[]
no_license
maxalaluna/Sirius
cf34bc9e5936f9514bd7a045d6a9cadd00a66169
c41a0cb0676266a74a97745bb0968112ec52dac2
refs/heads/master
2020-04-03T16:52:13.585423
2018-11-09T12:12:37
2018-11-09T12:12:37
155,422,518
1
0
null
null
null
null
UTF-8
Java
false
false
987
java
package net.floodlightcontroller.sirius.dijkstra.teste; public class Vertex { final private String id; final private String name; public Vertex(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Vertex other = (Vertex) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return name; } }
875171199747a9be0c924e0b55e1eeee6ae0b0a6
083c0189c683e9fc063fbe83b9b1ebd9f738c069
/eQueue/eQueue-ejb/src/java/util/exceptions/TransactionNotFoundException.java
bc61ac75b8930058752e8b12eded623230f8df20
[]
no_license
jianyiee96/eQueue
af749b160ee5b28bc930d0b9f88e10ab88d14547
efaac10d1346990c248bc1a15e472407e0e0b0b5
refs/heads/master
2022-12-10T03:05:28.844883
2020-05-04T15:29:14
2020-05-04T15:29:14
237,906,471
0
1
null
null
null
null
UTF-8
Java
false
false
222
java
package util.exceptions; public class TransactionNotFoundException extends Exception { public TransactionNotFoundException() { } public TransactionNotFoundException(String msg) { super(msg); } }
b5b9c23f796e9f0776df84b7f0712fa693afb0a0
8d2271c5182ba20a4243d2ab5183c9e1566af09f
/src/filters/LoginFilter.java
2d2cbebe76bb987de0d4fea36cd31fe1b9a60fe4
[]
no_license
tomoya-ueno/daily_report_system
7f55b077b14deadad570eb8ee4960405278f3aaa
bc06cf0ffea9e7fb7707249db281b9b707af2858
refs/heads/main
2023-02-19T01:05:42.157332
2021-01-21T08:11:13
2021-01-21T08:11:13
331,306,859
0
0
null
null
null
null
UTF-8
Java
false
false
2,127
java
package filters; 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.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import models.Employee; /** * Servlet Filter implementation class LoginFilter */ @WebFilter("/*") public class LoginFilter implements Filter { /** * Default constructor. */ public LoginFilter() { } /** * @see Filter#destroy() */ public void destroy() { } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String context_path = ((HttpServletRequest)request).getContextPath(); String servlet_path = ((HttpServletRequest)request).getServletPath(); if(!servlet_path.matches("/css.*")) { HttpSession session = ((HttpServletRequest)request).getSession(); Employee e = (Employee)session.getAttribute("login_employee"); if(!servlet_path.equals("/login")) { if(e == null) { ((HttpServletResponse)response).sendRedirect(context_path + "/login"); return; } if(servlet_path.matches("/employees.*") && e.getAdmin_flag() == 0) { ((HttpServletResponse)response).sendRedirect(context_path + "/"); return; } if(e != null) { ((HttpServletResponse)response).sendRedirect(context_path + "/"); return; } } } chain.doFilter(request, response); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { } }
21f7df4e8c491e148a073de40b005536d794c1ca
a10b3d857344dfdc55ef220af829eecd5b049ee7
/src/main/java/edu/usm/service/EncounterTypeService.java
a130c1f1febb3584e298e825408c8c3b5c1acc0d
[]
no_license
project-bayard/Bayard
bf8107e392d8dfa842e29413cac41c2b0bddff42
f0ce7b17b28f770af7ac4425e5192ef690c7dd46
refs/heads/master
2021-01-24T23:35:12.847957
2019-04-23T20:06:54
2019-04-23T20:06:54
44,610,326
4
2
null
2016-05-28T22:37:41
2015-10-20T14:04:18
Java
UTF-8
Java
false
false
1,105
java
package edu.usm.service; import edu.usm.domain.EncounterType; import org.springframework.security.access.prepost.PreAuthorize; import java.util.Set; /** * Created by scottkimball on 8/17/15. */ public interface EncounterTypeService { @PreAuthorize(value = "hasAnyRole('ROLE_USER','ROLE_DEVELOPMENT','ROLE_ELEVATED','ROLE_SUPERUSER')") EncounterType findById(String id); @PreAuthorize(value = "hasAnyRole('ROLE_USER','ROLE_DEVELOPMENT','ROLE_ELEVATED','ROLE_SUPERUSER')") EncounterType findByName (String name); @PreAuthorize(value = "hasAnyRole('ROLE_ELEVATED','ROLE_SUPERUSER')") String create(EncounterType encounterType); @PreAuthorize(value = "hasAnyRole('ROLE_ELEVATED','ROLE_SUPERUSER')") void delete(EncounterType encounterType); @PreAuthorize(value = "hasAnyRole('ROLE_SUPERUSER')") void deleteAll(); @PreAuthorize(value = "hasAnyRole('ROLE_USER','ROLE_DEVELOPMENT','ROLE_ELEVATED','ROLE_SUPERUSER')") Set<EncounterType> findAll(); @PreAuthorize(value = "hasAnyRole('ROLE_ELEVATED','ROLE_SUPERUSER')") void delete(String id); }
fcd56ee6f7ec8e71801d0e92ceac4fc4b0562c2d
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/Alluxio--alluxio/135ff42817aaf21ab49e72f6dad122d70e0a2df5/after/MasterInfo.java
8839a0e062c3a5067b9aeb4ed1575f436069a202
[]
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
79,576
java
package tachyon.master; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectWriter; import com.google.common.base.Optional; import com.google.common.collect.Lists; import tachyon.Constants; import tachyon.HeartbeatExecutor; import tachyon.HeartbeatThread; import tachyon.Pair; import tachyon.PrefixList; import tachyon.TachyonURI; import tachyon.UnderFileSystem; import tachyon.UnderFileSystem.SpaceType; import tachyon.conf.CommonConf; import tachyon.conf.MasterConf; import tachyon.thrift.BlockInfoException; import tachyon.thrift.ClientBlockInfo; import tachyon.thrift.ClientDependencyInfo; import tachyon.thrift.ClientFileInfo; import tachyon.thrift.ClientRawTableInfo; import tachyon.thrift.ClientWorkerInfo; import tachyon.thrift.Command; import tachyon.thrift.CommandType; import tachyon.thrift.DependencyDoesNotExistException; import tachyon.thrift.FileAlreadyExistException; import tachyon.thrift.FileDoesNotExistException; import tachyon.thrift.InvalidPathException; import tachyon.thrift.NetAddress; import tachyon.thrift.SuspectedFileSizeException; import tachyon.thrift.TableColumnException; import tachyon.thrift.TableDoesNotExistException; import tachyon.thrift.TachyonException; import tachyon.util.CommonUtils; /** * A global view of filesystem in master. */ public class MasterInfo extends ImageWriter { /** * Master info periodical status check. */ public class MasterInfoHeartbeatExecutor implements HeartbeatExecutor { @Override public void heartbeat() { LOG.debug("System status checking."); Set<Long> lostWorkers = new HashSet<Long>(); synchronized (mWorkers) { for (Entry<Long, MasterWorkerInfo> worker : mWorkers.entrySet()) { if (CommonUtils.getCurrentMs() - worker.getValue().getLastUpdatedTimeMs() > mMasterConf.WORKER_TIMEOUT_MS) { LOG.error("The worker " + worker.getValue() + " got timed out!"); mLostWorkers.add(worker.getValue()); lostWorkers.add(worker.getKey()); } } for (long workerId : lostWorkers) { MasterWorkerInfo workerInfo = mWorkers.get(workerId); mWorkerAddressToId.remove(workerInfo.getAddress()); mWorkers.remove(workerId); } } boolean hadFailedWorker = false; while (mLostWorkers.size() != 0) { hadFailedWorker = true; MasterWorkerInfo worker = mLostWorkers.poll(); // TODO these two locks are not efficient. Since node failure is rare, this is fine for now. synchronized (ROOT_LOCK) { synchronized (mFileIdToDependency) { try { for (long blockId : worker.getBlocks()) { int fileId = BlockInfo.computeInodeId(blockId); InodeFile tFile = (InodeFile) mFileIdToInodes.get(fileId); if (tFile != null) { int blockIndex = BlockInfo.computeBlockIndex(blockId); tFile.removeLocation(blockIndex, worker.getId()); if (!tFile.hasCheckpointed() && tFile.getBlockLocations(blockIndex).size() == 0) { LOG.info("Block " + blockId + " got lost from worker " + worker.getId() + " ."); int depId = tFile.getDependencyId(); if (depId == -1) { LOG.error("Permanent Data loss: " + tFile); } else { mLostFiles.add(tFile.getId()); Dependency dep = mFileIdToDependency.get(depId); dep.addLostFile(tFile.getId()); LOG.info("File " + tFile.getId() + " got lost from worker " + worker.getId() + " . Trying to recompute it using dependency " + dep.mId); if (!getPath(tFile).getPath().startsWith(mMasterConf.TEMPORARY_FOLDER)) { mMustRecomputedDpendencies.add(depId); } } } else { LOG.info("Block " + blockId + " only lost an in memory copy from worker " + worker.getId()); } } } } catch (BlockInfoException e) { LOG.error(e.getMessage(), e); } } } } if (hadFailedWorker) { LOG.warn("Restarting failed workers."); try { java.lang.Runtime.getRuntime().exec( CommonConf.get().TACHYON_HOME + "/bin/tachyon-start.sh restart_workers"); } catch (IOException e) { LOG.error(e.getMessage()); } } } } public class RecomputationScheduler implements Runnable { @Override public void run() { while (true) { boolean hasLostFiles = false; boolean launched = false; List<String> cmds = new ArrayList<String>(); synchronized (ROOT_LOCK) { synchronized (mFileIdToDependency) { if (!mMustRecomputedDpendencies.isEmpty()) { List<Integer> recomputeList = new ArrayList<Integer>(); Queue<Integer> checkQueue = new LinkedList<Integer>(); checkQueue.addAll(mMustRecomputedDpendencies); while (!checkQueue.isEmpty()) { int depId = checkQueue.poll(); Dependency dep = mFileIdToDependency.get(depId); boolean canLaunch = true; for (int k = 0; k < dep.mParentFiles.size(); k ++) { int fildId = dep.mParentFiles.get(k); if (mLostFiles.contains(fildId)) { canLaunch = false; InodeFile iFile = (InodeFile) mFileIdToInodes.get(fildId); if (!mBeingRecomputedFiles.contains(fildId)) { int tDepId = iFile.getDependencyId(); if (tDepId != -1 && !mMustRecomputedDpendencies.contains(tDepId)) { mMustRecomputedDpendencies.add(tDepId); checkQueue.add(tDepId); } } } } if (canLaunch) { recomputeList.add(depId); } } hasLostFiles = !mMustRecomputedDpendencies.isEmpty(); launched = (recomputeList.size() > 0); for (int k = 0; k < recomputeList.size(); k ++) { mMustRecomputedDpendencies.remove(recomputeList.get(k)); Dependency dep = mFileIdToDependency.get(recomputeList.get(k)); mBeingRecomputedFiles.addAll(dep.getLostFiles()); cmds.add(dep.getCommand()); } } } } for (String cmd : cmds) { String filePath = CommonConf.get().TACHYON_HOME + "/logs/rerun-" + mRerunCounter.incrementAndGet(); new Thread(new RecomputeCommand(cmd, filePath)).start(); } if (!launched) { if (hasLostFiles) { LOG.info("HasLostFiles, but no job can be launched."); } CommonUtils.sleepMs(LOG, Constants.SECOND_MS); } } } } public static final String COL = "COL_"; private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE); private final InetSocketAddress mMasterAddress; private final long mStartTimeNSPrefix; private final long mStartTimeMs; private final MasterConf mMasterConf; private final Counters mCheckpointInfo = new Counters(0, 0, 0); private final AtomicInteger mInodeCounter = new AtomicInteger(0); private final AtomicInteger mDependencyCounter = new AtomicInteger(0); private final AtomicInteger mRerunCounter = new AtomicInteger(0); private final AtomicInteger mUserCounter = new AtomicInteger(0); private final AtomicInteger mWorkerCounter = new AtomicInteger(0); // Root Inode's id must be 1. private InodeFolder mRoot; private final Object ROOT_LOCK = new Object(); // A map from file ID's to Inodes. All operations on it are currently synchronized on ROOT_LOCK. private final Map<Integer, Inode> mFileIdToInodes = new HashMap<Integer, Inode>(); private final Map<Integer, Dependency> mFileIdToDependency = new HashMap<Integer, Dependency>(); private final RawTables mRawTables = new RawTables(); // TODO add initialization part for master failover or restart. All operations on these members // are synchronized on mFileIdToDependency. private final Set<Integer> mUncheckpointedDependencies = new HashSet<Integer>(); private final Set<Integer> mPriorityDependencies = new HashSet<Integer>(); private final Set<Integer> mLostFiles = new HashSet<Integer>(); private final Set<Integer> mBeingRecomputedFiles = new HashSet<Integer>(); private final Set<Integer> mMustRecomputedDpendencies = new HashSet<Integer>(); private final Map<Long, MasterWorkerInfo> mWorkers = new HashMap<Long, MasterWorkerInfo>(); private final Map<NetAddress, Long> mWorkerAddressToId = new HashMap<NetAddress, Long>(); private final BlockingQueue<MasterWorkerInfo> mLostWorkers = new ArrayBlockingQueue<MasterWorkerInfo>(32); // TODO Check the logic related to this two lists. private final PrefixList mWhitelist; // Synchronized set containing all InodeFile ids that are currently pinned. private final Set<Integer> mPinnedInodeFileIds; private final Journal mJournal; private HeartbeatThread mHeartbeatThread; private Thread mRecomputeThread; public MasterInfo(InetSocketAddress address, Journal journal) throws IOException { mMasterConf = MasterConf.get(); mRoot = new InodeFolder("", mInodeCounter.incrementAndGet(), -1, System.currentTimeMillis()); mFileIdToInodes.put(mRoot.getId(), mRoot); mMasterAddress = address; mStartTimeMs = System.currentTimeMillis(); // TODO This name need to be changed. mStartTimeNSPrefix = mStartTimeMs - (mStartTimeMs % 1000000); mJournal = journal; mWhitelist = new PrefixList(mMasterConf.WHITELIST); mPinnedInodeFileIds = Collections.synchronizedSet(new HashSet<Integer>()); mJournal.loadImage(this); } /** * Add a checkpoint to a file, inner method. * * @param workerId The worker which submitted the request. -1 if the request is not from a worker. * @param fileId The file to add the checkpoint. * @param length The length of the checkpoint. * @param checkpointPath The path of the checkpoint. * @param opTimeMs The time of the operation, in milliseconds * @return the Pair of success and needLog * @throws FileNotFoundException * @throws SuspectedFileSizeException * @throws BlockInfoException */ Pair<Boolean, Boolean> _addCheckpoint(long workerId, int fileId, long length, String checkpointPath, long opTimeMs) throws FileNotFoundException, SuspectedFileSizeException, BlockInfoException { LOG.info(CommonUtils.parametersToString(workerId, fileId, length, checkpointPath)); if (workerId != -1) { MasterWorkerInfo tWorkerInfo = getWorkerInfo(workerId); tWorkerInfo.updateLastUpdatedTimeMs(); } synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(fileId); if (inode == null) { throw new FileNotFoundException("File " + fileId + " does not exist."); } if (inode.isDirectory()) { throw new FileNotFoundException("File " + fileId + " is a folder."); } InodeFile tFile = (InodeFile) inode; boolean needLog = false; if (tFile.isComplete()) { if (tFile.getLength() != length) { throw new SuspectedFileSizeException(fileId + ". Original Size: " + tFile.getLength() + ". New Size: " + length); } } else { tFile.setLength(length); needLog = true; } if (!tFile.hasCheckpointed()) { tFile.setUfsPath(checkpointPath); needLog = true; synchronized (mFileIdToDependency) { int depId = tFile.getDependencyId(); if (depId != -1) { Dependency dep = mFileIdToDependency.get(depId); dep.childCheckpointed(tFile.getId()); if (dep.hasCheckpointed()) { mUncheckpointedDependencies.remove(dep.mId); mPriorityDependencies.remove(dep.mId); } } } } addFile(fileId, tFile.getDependencyId()); tFile.setComplete(); if (needLog) { tFile.setLastModificationTimeMs(opTimeMs); } return new Pair<Boolean, Boolean>(true, needLog); } } /** * Completes the checkpointing of a file, inner method. * * @param fileId The id of the file * @param opTimeMs The time of the complete file operation, in milliseconds * @throws FileDoesNotExistException */ void _completeFile(int fileId, long opTimeMs) throws FileDoesNotExistException { synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(fileId); if (inode == null) { throw new FileDoesNotExistException("File " + fileId + " does not exit."); } if (!inode.isFile()) { throw new FileDoesNotExistException("File " + fileId + " is not a file."); } addFile(fileId, ((InodeFile) inode).getDependencyId()); ((InodeFile) inode).setComplete(); inode.setLastModificationTimeMs(opTimeMs); } } int _createDependency(List<Integer> parentsIds, List<Integer> childrenIds, String commandPrefix, List<ByteBuffer> data, String comment, String framework, String frameworkVersion, DependencyType dependencyType, int dependencyId, long creationTimeMs) throws InvalidPathException, FileDoesNotExistException { Dependency dep = null; synchronized (ROOT_LOCK) { Set<Integer> parentDependencyIds = new HashSet<Integer>(); for (int k = 0; k < parentsIds.size(); k ++) { int parentId = parentsIds.get(k); Inode inode = mFileIdToInodes.get(parentId); if (inode.isFile()) { LOG.info("PARENT DEPENDENCY ID IS " + ((InodeFile) inode).getDependencyId() + " " + (inode)); if (((InodeFile) inode).getDependencyId() != -1) { parentDependencyIds.add(((InodeFile) inode).getDependencyId()); } } else { throw new InvalidPathException("Parent " + parentId + " is not a file."); } } dep = new Dependency(dependencyId, parentsIds, childrenIds, commandPrefix, data, comment, framework, frameworkVersion, dependencyType, parentDependencyIds, creationTimeMs); List<Inode> childrenInodes = new ArrayList<Inode>(); for (int k = 0; k < childrenIds.size(); k ++) { InodeFile inode = (InodeFile) mFileIdToInodes.get(childrenIds.get(k)); inode.setDependencyId(dep.mId); inode.setLastModificationTimeMs(creationTimeMs); childrenInodes.add(inode); if (inode.hasCheckpointed()) { dep.childCheckpointed(inode.getId()); } } } synchronized (mFileIdToDependency) { mFileIdToDependency.put(dep.mId, dep); if (!dep.hasCheckpointed()) { mUncheckpointedDependencies.add(dep.mId); } for (int parentDependencyId : dep.mParentDependencies) { mFileIdToDependency.get(parentDependencyId).addChildrenDependency(dep.mId); } } mJournal.getEditLog().createDependency(parentsIds, childrenIds, commandPrefix, data, comment, framework, frameworkVersion, dependencyType, dependencyId, creationTimeMs); mJournal.getEditLog().flush(); LOG.info("Dependency created: " + dep); return dep.mId; } // TODO Make this API better. /** * Internal API. * * @param recursive If recursive is true and the filesystem tree is not filled in all the way to * path yet, it fills in the missing components. * @param path The path to create * @param directory If true, creates an InodeFolder instead of an Inode * @param blockSizeByte If it's a file, the block size for the Inode * @param creationTimeMs The time the file was created * @return the id of the inode created at the given path * @throws FileAlreadyExistException * @throws InvalidPathException * @throws BlockInfoException * @throws TachyonException */ int _createFile(boolean recursive, TachyonURI path, boolean directory, long blockSizeByte, long creationTimeMs) throws FileAlreadyExistException, InvalidPathException, BlockInfoException, TachyonException { if (path.isRoot()) { LOG.info("FileAlreadyExistException: " + path); throw new FileAlreadyExistException(path.toString()); } if (!directory && blockSizeByte < 1) { throw new BlockInfoException("Invalid block size " + blockSizeByte); } LOG.debug("createFile {}", CommonUtils.parametersToString(path)); String[] pathNames = CommonUtils.getPathComponents(path.getPath()); String name = path.getName(); String[] parentPath = new String[pathNames.length - 1]; System.arraycopy(pathNames, 0, parentPath, 0, parentPath.length); synchronized (ROOT_LOCK) { Pair<Inode, Integer> inodeTraversal = traverseToInode(parentPath); // pathIndex is the index into pathNames where we start filling in the path from the inode. int pathIndex = parentPath.length; if (!traversalSucceeded(inodeTraversal)) { // Then the path component at errorInd k doesn't exist. If it's not recursive, we throw an // exception here. Otherwise we add the remaining path components to the list of components // to create. if (!recursive) { final String msg = "File " + path + " creation failed. Component " + inodeTraversal.getSecond() + "(" + parentPath[inodeTraversal.getSecond()] + ") does not exist"; LOG.info("InvalidPathException: " + msg); throw new InvalidPathException(msg); } else { // We will start filling in the path from inodeTraversal.getSecond() pathIndex = inodeTraversal.getSecond(); } } if (!inodeTraversal.getFirst().isDirectory()) { throw new InvalidPathException("Could not traverse to parent folder of path " + path + ". Component " + pathNames[pathIndex - 1] + " is not a directory."); } InodeFolder currentInodeFolder = (InodeFolder) inodeTraversal.getFirst(); // Fill in the directories that were missing. for (int k = pathIndex; k < parentPath.length; k ++) { Inode dir = new InodeFolder(pathNames[k], mInodeCounter.incrementAndGet(), currentInodeFolder.getId(), creationTimeMs); dir.setPinned(currentInodeFolder.isPinned()); currentInodeFolder.addChild(dir); currentInodeFolder.setLastModificationTimeMs(creationTimeMs); mFileIdToInodes.put(dir.getId(), dir); currentInodeFolder = (InodeFolder) dir; } // Create the final path component. First we need to make sure that there isn't already a file // here with that name. If there is an existing file that is a directory and we're creating a // directory, we just return the existing directory's id. Inode ret = currentInodeFolder.getChild(name); if (ret != null) { if (ret.isDirectory() && directory) { return ret.getId(); } LOG.info("FileAlreadyExistException: " + path); throw new FileAlreadyExistException(path.toString()); } if (directory) { ret = new InodeFolder(name, mInodeCounter.incrementAndGet(), currentInodeFolder.getId(), creationTimeMs); ret.setPinned(currentInodeFolder.isPinned()); } else { ret = new InodeFile(name, mInodeCounter.incrementAndGet(), currentInodeFolder.getId(), blockSizeByte, creationTimeMs); ret.setPinned(currentInodeFolder.isPinned()); if (ret.isPinned()) { mPinnedInodeFileIds.add(ret.getId()); } if (mWhitelist.inList(path.getPath())) { ((InodeFile) ret).setCache(true); } } mFileIdToInodes.put(ret.getId(), ret); currentInodeFolder.addChild(ret); currentInodeFolder.setLastModificationTimeMs(creationTimeMs); LOG.debug("createFile: File Created: {} parent: ", ret, currentInodeFolder); return ret.getId(); } } void _createRawTable(int tableId, int columns, ByteBuffer metadata) throws TachyonException { synchronized (mRawTables) { if (!mRawTables.addRawTable(tableId, columns, metadata)) { throw new TachyonException("Failed to create raw table."); } mJournal.getEditLog().createRawTable(tableId, columns, metadata); } } /** * Inner delete function. Return true if the file does not exist in the first place. * * @param fileId The inode to delete * @param recursive True if the file and it's subdirectories should be deleted * @param opTimeMs The time of the delete operation, in milliseconds * @return true if the deletion succeeded and false otherwise. * @throws TachyonException */ boolean _delete(int fileId, boolean recursive, long opTimeMs) throws TachyonException { synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(fileId); if (inode == null) { return true; } if (inode.isDirectory() && !recursive && ((InodeFolder) inode).getNumberOfChildren() > 0) { // inode is nonempty, and we don't want to delete a nonempty directory unless recursive is // true return false; } if (inode.getId() == mRoot.getId()) { // The root cannot be deleted. return false; } List<Inode> delInodes = new ArrayList<Inode>(); delInodes.add(inode); if (inode.isDirectory()) { delInodes.addAll(getInodeChildrenRecursive((InodeFolder) inode)); } // We go through each inode, removing it from it's parent set and from mDelInodes. If it's a // file, we deal with the checkpoints and blocks as well. for (int i = delInodes.size() - 1; i >= 0; i --) { Inode delInode = delInodes.get(i); if (delInode.isFile()) { String checkpointPath = ((InodeFile) delInode).getUfsPath(); if (!checkpointPath.equals("")) { UnderFileSystem ufs = UnderFileSystem.get(checkpointPath); try { if (!ufs.exists(checkpointPath)) { LOG.warn("File does not exist the underfs: " + checkpointPath); } else if (!ufs.delete(checkpointPath, true)) { return false; } } catch (IOException e) { throw new TachyonException(e.getMessage()); } } List<Pair<Long, Long>> blockIdWorkerIdList = ((InodeFile) delInode).getBlockIdWorkerIdPairs(); synchronized (mWorkers) { for (Pair<Long, Long> blockIdWorkerId : blockIdWorkerIdList) { MasterWorkerInfo workerInfo = mWorkers.get(blockIdWorkerId.getSecond()); if (workerInfo != null) { workerInfo.updateToRemovedBlock(true, blockIdWorkerId.getFirst()); } } } mPinnedInodeFileIds.remove(delInode.getId()); } InodeFolder parent = (InodeFolder) mFileIdToInodes.get(delInode.getParentId()); parent.removeChild(delInode); parent.setLastModificationTimeMs(opTimeMs); if (mRawTables.exist(delInode.getId()) && !mRawTables.delete(delInode.getId())) { return false; } mFileIdToInodes.remove(delInode.getId()); delInode.reverseId(); } return true; } } /** * Get the raw table info associated with the given id. * * @param path The path of the table * @param inode The inode at the path * @return the table info * @throws TableDoesNotExistException */ public ClientRawTableInfo _getClientRawTableInfo(TachyonURI path, Inode inode) throws TableDoesNotExistException { LOG.info("getClientRawTableInfo(" + path + ")"); if (!mRawTables.exist(inode.getId())) { throw new TableDoesNotExistException("Table " + inode.getId() + " does not exist."); } ClientRawTableInfo ret = new ClientRawTableInfo(); ret.id = inode.getId(); ret.name = inode.getName(); ret.path = path.getPath(); ret.columns = mRawTables.getColumns(ret.id); ret.metadata = mRawTables.getMetadata(ret.id); return ret; } /** * Get the names of the sub-directories at the given path. * * @param inode The inode to list * @param path The path of the given inode * @param recursive If true, recursively add the paths of the sub-directories * @return the list of paths * @throws InvalidPathException * @throws FileDoesNotExistException */ private List<TachyonURI> _ls(Inode inode, TachyonURI path, boolean recursive) throws InvalidPathException, FileDoesNotExistException { synchronized (ROOT_LOCK) { List<TachyonURI> ret = new ArrayList<TachyonURI>(); ret.add(path); if (inode.isDirectory()) { for (Inode child : ((InodeFolder) inode).getChildren()) { TachyonURI childUri = path.join(child.getName()); if (recursive) { ret.addAll(_ls(child, childUri, recursive)); } else { ret.add(childUri); } } } return ret; } } /** * Inner method of recomputePinnedFiles. Also directly called by EditLog. * * @param inode The inode to start traversal from * @param setPinState An optional parameter indicating whether we should also set the "pinned" * flag on each inode we traverse. If absent, the "isPinned" flag is unchanged. * @param opTimeMs The time of set pinned, in milliseconds */ void _recomputePinnedFiles(Inode inode, Optional<Boolean> setPinState, long opTimeMs) { if (setPinState.isPresent()) { inode.setPinned(setPinState.get()); inode.setLastModificationTimeMs(opTimeMs); } if (inode.isFile()) { if (inode.isPinned()) { mPinnedInodeFileIds.add(inode.getId()); } else { mPinnedInodeFileIds.remove(inode.getId()); } } else if (inode.isDirectory()) { for (Inode child : ((InodeFolder) inode).getChildren()) { _recomputePinnedFiles(child, setPinState, opTimeMs); } } } /** * Rename a file to the given path, inner method. * * @param fileId The id of the file to rename * @param dstPath The new uri of the file * @param opTimeMs The time of the rename operation, in milliseconds * @return true if the rename succeeded, false otherwise * @throws FileDoesNotExistException If the id doesn't point to an inode * @throws InvalidPathException if the source path is a prefix of the destination */ public boolean _rename(int fileId, TachyonURI dstPath, long opTimeMs) throws FileDoesNotExistException, InvalidPathException { synchronized (ROOT_LOCK) { TachyonURI srcPath = getPath(fileId); if (srcPath.equals(dstPath)) { return true; } if (srcPath.isRoot() || dstPath.isRoot()) { return false; } String[] srcComponents = CommonUtils.getPathComponents(srcPath.getPath()); String[] dstComponents = CommonUtils.getPathComponents(dstPath.getPath()); // We can't rename a path to one of its subpaths, so we check for that, by making sure // srcComponents isn't a prefix of dstComponents. if (srcComponents.length < dstComponents.length) { boolean isPrefix = true; for (int prefixInd = 0; prefixInd < srcComponents.length; prefixInd ++) { if (!srcComponents[prefixInd].equals(dstComponents[prefixInd])) { isPrefix = false; break; } } if (isPrefix) { throw new InvalidPathException("Failed to rename: " + srcPath + " is a prefix of " + dstPath); } } TachyonURI srcParent = srcPath.getParent(); TachyonURI dstParent = dstPath.getParent(); // We traverse down to the source and destinations' parent paths Inode srcParentInode = getInode(srcParent); if (srcParentInode == null || !srcParentInode.isDirectory()) { return false; } Inode dstParentInode = getInode(dstParent); if (dstParentInode == null || !dstParentInode.isDirectory()) { return false; } // We make sure that the source path exists and the destination path doesn't Inode srcInode = ((InodeFolder) srcParentInode).getChild(srcComponents[srcComponents.length - 1]); if (srcInode == null) { return false; } if (((InodeFolder) dstParentInode).getChild(dstComponents[dstComponents.length - 1]) != null) { return false; } // Now we remove srcInode from it's parent and insert it into dstPath's parent ((InodeFolder) srcParentInode).removeChild(srcInode); srcParentInode.setLastModificationTimeMs(opTimeMs); srcInode.setParentId(dstParentInode.getId()); srcInode.setName(dstComponents[dstComponents.length - 1]); ((InodeFolder) dstParentInode).addChild(srcInode); dstParentInode.setLastModificationTimeMs(opTimeMs); return true; } } void _setPinned(int fileId, boolean pinned, long opTimeMs) throws FileDoesNotExistException { LOG.info("setPinned(" + fileId + ", " + pinned + ")"); synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(fileId); if (inode == null) { throw new FileDoesNotExistException("Failed to find inode" + fileId); } _recomputePinnedFiles(inode, Optional.of(pinned), opTimeMs); } } private void addBlock(InodeFile tFile, BlockInfo blockInfo, long opTimeMs) throws BlockInfoException { tFile.addBlock(blockInfo); tFile.setLastModificationTimeMs(opTimeMs); mJournal.getEditLog().addBlock(tFile.getId(), blockInfo.mBlockIndex, blockInfo.mLength, opTimeMs); mJournal.getEditLog().flush(); } /** * Add a checkpoint to a file. * * @param workerId The worker which submitted the request. -1 if the request is not from a worker. * @param fileId The file to add the checkpoint. * @param length The length of the checkpoint. * @param checkpointPath The path of the checkpoint. * @return true if the checkpoint is added successfully, false if not. * @throws FileNotFoundException * @throws SuspectedFileSizeException * @throws BlockInfoException */ public boolean addCheckpoint(long workerId, int fileId, long length, String checkpointPath) throws FileNotFoundException, SuspectedFileSizeException, BlockInfoException { long opTimeMs = System.currentTimeMillis(); synchronized (ROOT_LOCK) { Pair<Boolean, Boolean> ret = _addCheckpoint(workerId, fileId, length, checkpointPath, opTimeMs); if (ret.getSecond()) { mJournal.getEditLog().addCheckpoint(fileId, length, checkpointPath, opTimeMs); mJournal.getEditLog().flush(); } return ret.getFirst(); } } /** * Removes a checkpointed file from the set of lost or being-recomputed files if it's there * * @param fileId The file to examine */ private void addFile(int fileId, int dependencyId) { synchronized (mFileIdToDependency) { if (mLostFiles.contains(fileId)) { mLostFiles.remove(fileId); } if (mBeingRecomputedFiles.contains(fileId)) { mBeingRecomputedFiles.remove(fileId); } } } /** * While loading an image, addToInodeMap will map the various ids to their inodes. * * @param inode The inode to add * @param map The map to add the inodes to */ private void addToInodeMap(Inode inode, Map<Integer, Inode> map) { map.put(inode.getId(), inode); if (inode.isDirectory()) { InodeFolder inodeFolder = (InodeFolder) inode; for (Inode child : inodeFolder.getChildren()) { addToInodeMap(child, map); } } } /** * A worker cache a block in its memory. * * @param workerId * @param workerUsedBytes * @param blockId * @param length * @return the dependency id of the file if it has not been checkpointed. -1 means the file either * does not have dependency or has already been checkpointed. * @throws FileDoesNotExistException * @throws SuspectedFileSizeException * @throws BlockInfoException */ public int cacheBlock(long workerId, long workerUsedBytes, long blockId, long length) throws FileDoesNotExistException, SuspectedFileSizeException, BlockInfoException { LOG.debug("Cache block: {}", CommonUtils.parametersToString(workerId, workerUsedBytes, blockId, length)); MasterWorkerInfo tWorkerInfo = getWorkerInfo(workerId); tWorkerInfo.updateBlock(true, blockId); tWorkerInfo.updateUsedBytes(workerUsedBytes); tWorkerInfo.updateLastUpdatedTimeMs(); int fileId = BlockInfo.computeInodeId(blockId); int blockIndex = BlockInfo.computeBlockIndex(blockId); synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(fileId); if (inode == null) { throw new FileDoesNotExistException("File " + fileId + " does not exist."); } if (inode.isDirectory()) { throw new FileDoesNotExistException("File " + fileId + " is a folder."); } InodeFile tFile = (InodeFile) inode; if (tFile.getNumberOfBlocks() <= blockIndex) { addBlock(tFile, new BlockInfo(tFile, blockIndex, length), System.currentTimeMillis()); } tFile.addLocation(blockIndex, workerId, tWorkerInfo.mWorkerAddress); if (tFile.hasCheckpointed()) { return -1; } else { return tFile.getDependencyId(); } } } /** * Completes the checkpointing of a file. * * @param fileId The id of the file * @throws FileDoesNotExistException */ public void completeFile(int fileId) throws FileDoesNotExistException { long opTimeMs = System.currentTimeMillis(); synchronized (ROOT_LOCK) { _completeFile(fileId, opTimeMs); mJournal.getEditLog().completeFile(fileId, opTimeMs); mJournal.getEditLog().flush(); } } public int createDependency(List<TachyonURI> parents, List<TachyonURI> children, String commandPrefix, List<ByteBuffer> data, String comment, String framework, String frameworkVersion, DependencyType dependencyType) throws InvalidPathException, FileDoesNotExistException { synchronized (ROOT_LOCK) { LOG.info("ParentList: " + CommonUtils.listToString(parents)); List<Integer> parentsIdList = getFilesIds(parents); List<Integer> childrenIdList = getFilesIds(children); int depId = mDependencyCounter.incrementAndGet(); long creationTimeMs = System.currentTimeMillis(); int ret = _createDependency(parentsIdList, childrenIdList, commandPrefix, data, comment, framework, frameworkVersion, dependencyType, depId, creationTimeMs); return ret; } } /** * Create a file. // TODO Make this API better. * * @throws FileAlreadyExistException * @throws InvalidPathException * @throws BlockInfoException * @throws TachyonException */ public int createFile(boolean recursive, TachyonURI path, boolean directory, long blockSizeByte) throws FileAlreadyExistException, InvalidPathException, BlockInfoException, TachyonException { long creationTimeMs = System.currentTimeMillis(); synchronized (ROOT_LOCK) { int ret = _createFile(recursive, path, directory, blockSizeByte, creationTimeMs); mJournal.getEditLog().createFile(recursive, path, directory, blockSizeByte, creationTimeMs); mJournal.getEditLog().flush(); return ret; } } public int createFile(TachyonURI path, long blockSizeByte) throws FileAlreadyExistException, InvalidPathException, BlockInfoException, TachyonException { return createFile(true, path, false, blockSizeByte); } public int createFile(TachyonURI path, long blockSizeByte, boolean recursive) throws FileAlreadyExistException, InvalidPathException, BlockInfoException, TachyonException { return createFile(recursive, path, false, blockSizeByte); } /** * Creates a new block for the given file. * * @param fileId The id of the file * @return the block id. * @throws FileDoesNotExistException */ public long createNewBlock(int fileId) throws FileDoesNotExistException { synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(fileId); if (inode == null) { throw new FileDoesNotExistException("File " + fileId + " does not exit."); } if (!inode.isFile()) { throw new FileDoesNotExistException("File " + fileId + " is not a file."); } return ((InodeFile) inode).getNewBlockId(); } } /** * Creates a raw table. * * @param path The path to place the table at * @param columns The number of columns in the table * @param metadata Additional metadata about the table * @return the file id of the table * @throws FileAlreadyExistException * @throws InvalidPathException * @throws TableColumnException * @throws TachyonException */ public int createRawTable(TachyonURI path, int columns, ByteBuffer metadata) throws FileAlreadyExistException, InvalidPathException, TableColumnException, TachyonException { LOG.info("createRawTable" + CommonUtils.parametersToString(path, columns)); if (columns <= 0 || columns >= CommonConf.get().MAX_COLUMNS) { throw new TableColumnException("Column " + columns + " should between 0 to " + CommonConf.get().MAX_COLUMNS); } int id; try { id = createFile(true, path, true, 0); _createRawTable(id, columns, metadata); } catch (BlockInfoException e) { throw new FileAlreadyExistException(e.getMessage()); } for (int k = 0; k < columns; k ++) { mkdirs(path.join(COL + k), true); } return id; } /** * Delete a file based on the file's ID. * * @param fileId the file to be deleted. * @param recursive whether delete the file recursively or not. * @return succeed or not * @throws TachyonException */ public boolean delete(int fileId, boolean recursive) throws TachyonException { long opTimeMs = System.currentTimeMillis(); synchronized (ROOT_LOCK) { boolean ret = _delete(fileId, recursive, opTimeMs); mJournal.getEditLog().delete(fileId, recursive, opTimeMs); mJournal.getEditLog().flush(); return ret; } } /** * Delete files based on the path. * * @param path The file to be deleted. * @param recursive whether delete the file recursively or not. * @return succeed or not * @throws TachyonException */ public boolean delete(TachyonURI path, boolean recursive) throws TachyonException { LOG.info("delete(" + path + ")"); synchronized (ROOT_LOCK) { Inode inode = null; try { inode = getInode(path); } catch (InvalidPathException e) { return false; } if (inode == null) { return true; } return delete(inode.getId(), recursive); } } public long getBlockIdBasedOnOffset(int fileId, long offset) throws FileDoesNotExistException { synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(fileId); if (inode == null) { throw new FileDoesNotExistException("FileId " + fileId + " does not exist."); } if (!inode.isFile()) { throw new FileDoesNotExistException(fileId + " is not a file."); } return ((InodeFile) inode).getBlockIdBasedOnOffset(offset); } } /** * Get the list of blocks of an InodeFile determined by path. * * @param path The file. * @return The list of the blocks of the file. * @throws InvalidPathException * @throws FileDoesNotExistException */ public List<BlockInfo> getBlockList(TachyonURI path) throws InvalidPathException, FileDoesNotExistException { Inode inode = getInode(path); if (inode == null) { throw new FileDoesNotExistException(path + " does not exist."); } if (!inode.isFile()) { throw new FileDoesNotExistException(path + " is not a file."); } InodeFile inodeFile = (InodeFile) inode; return inodeFile.getBlockList(); } /** * Get the capacity of the whole system. * * @return the system's capacity in bytes. */ public long getCapacityBytes() { long ret = 0; synchronized (mWorkers) { for (MasterWorkerInfo worker : mWorkers.values()) { ret += worker.getCapacityBytes(); } } return ret; } /** * Get the block info associated with the given id. * * @param blockId The id of the block return * @return the block info * @throws FileDoesNotExistException * @throws IOException * @throws BlockInfoException */ public ClientBlockInfo getClientBlockInfo(long blockId) throws FileDoesNotExistException, IOException, BlockInfoException { int fileId = BlockInfo.computeInodeId(blockId); synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(fileId); if (inode == null || inode.isDirectory()) { throw new FileDoesNotExistException("FileId " + fileId + " does not exist."); } ClientBlockInfo ret = ((InodeFile) inode).getClientBlockInfo(BlockInfo.computeBlockIndex(blockId)); LOG.debug("getClientBlockInfo: {} : {}", blockId, ret); return ret; } } /** * Get the dependency info associated with the given id. * * @param dependencyId The id of the dependency * @return the dependency info * @throws DependencyDoesNotExistException */ public ClientDependencyInfo getClientDependencyInfo(int dependencyId) throws DependencyDoesNotExistException { Dependency dep = null; synchronized (mFileIdToDependency) { dep = mFileIdToDependency.get(dependencyId); if (dep == null) { throw new DependencyDoesNotExistException("No dependency with id " + dependencyId); } } return dep.generateClientDependencyInfo(); } /** * Get the file info associated with the given id. * * @param fid The id of the file * @return the file info * @throws FileDoesNotExistException * @throws InvalidPathException */ public ClientFileInfo getClientFileInfo(int fid) throws InvalidPathException { synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(fid); if (inode == null) { ClientFileInfo info = new ClientFileInfo(); info.id = -1; return info; } return inode.generateClientFileInfo(getPath(inode).getPath()); } } /** * Get the file info for the file at the given path * * @param path The path of the file * @return the file info * @throws FileDoesNotExistException * @throws InvalidPathException */ public ClientFileInfo getClientFileInfo(TachyonURI path) throws InvalidPathException { synchronized (ROOT_LOCK) { Inode inode = getInode(path); if (inode == null) { ClientFileInfo info = new ClientFileInfo(); info.id = -1; return info; } return inode.generateClientFileInfo(path.getPath()); } } /** * Get the raw table info associated with the given id. * * @param id The id of the table * @return the table info * @throws TableDoesNotExistException */ public ClientRawTableInfo getClientRawTableInfo(int id) throws TableDoesNotExistException { synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(id); if (inode == null || !inode.isDirectory()) { throw new TableDoesNotExistException("Table " + id + " does not exist."); } return _getClientRawTableInfo(getPath(inode), inode); } } /** * Get the raw table info for the table at the given path * * @param path The path of the table * @return the table info * @throws TableDoesNotExistException * @throws InvalidPathException */ public ClientRawTableInfo getClientRawTableInfo(TachyonURI path) throws TableDoesNotExistException, InvalidPathException { synchronized (ROOT_LOCK) { Inode inode = getInode(path); if (inode == null) { throw new TableDoesNotExistException("Table " + path + " does not exist."); } return _getClientRawTableInfo(path, inode); } } /** * Get the file id of the file. * * @param path The path of the file * @return The file id of the file. -1 if the file does not exist. * @throws InvalidPathException */ public int getFileId(TachyonURI path) throws InvalidPathException { Inode inode = getInode(path); int ret = -1; if (inode != null) { ret = inode.getId(); } LOG.debug("getFileId({}): {}", path, ret); return ret; } /** * Get the block infos of a file with the given id. Throws an exception if the id names a * directory. * * @param fileId The id of the file to look up * @return the block infos of the file * @throws FileDoesNotExistException * @throws IOException */ public List<ClientBlockInfo> getFileBlocks(int fileId) throws FileDoesNotExistException, IOException { synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(fileId); if (inode == null || inode.isDirectory()) { throw new FileDoesNotExistException("FileId " + fileId + " does not exist."); } List<ClientBlockInfo> ret = ((InodeFile) inode).getClientBlockInfos(); LOG.debug("getFileLocations: {} {}", fileId, ret); return ret; } } /** * Get the block infos of a file with the given path. Throws an exception if the path names a * directory. * * @param path The path of the file to look up * @return the block infos of the file * @throws FileDoesNotExistException * @throws InvalidPathException * @throws IOException */ public List<ClientBlockInfo> getFileBlocks(TachyonURI path) throws FileDoesNotExistException, InvalidPathException, IOException { LOG.info("getFileLocations: " + path); synchronized (ROOT_LOCK) { Inode inode = getInode(path); if (inode == null) { throw new FileDoesNotExistException(path.toString()); } return getFileBlocks(inode.getId()); } } /** * Get the file id's of the given paths. It recursively scans directories for the file id's inside * of them. * * @param pathList The list of paths to look at * @return the file id's of the files. * @throws InvalidPathException * @throws FileDoesNotExistException */ private List<Integer> getFilesIds(List<TachyonURI> pathList) throws InvalidPathException, FileDoesNotExistException { List<Integer> ret = new ArrayList<Integer>(pathList.size()); for (int k = 0; k < pathList.size(); k ++) { ret.addAll(listFiles(pathList.get(k), true)); } return ret; } /** * If the <code>uri</code> is a directory, return all the direct entries in it. If the * <code>uri</code> is a file, return its ClientFileInfo. * * @param uri the target directory/file uri * @return A list of ClientFileInfo * @throws FileDoesNotExistException * @throws InvalidPathException */ public List<ClientFileInfo> getFilesInfo(TachyonURI uri) throws FileDoesNotExistException, InvalidPathException { List<ClientFileInfo> ret = new ArrayList<ClientFileInfo>(); Inode inode = getInode(uri); if (inode == null) { throw new FileDoesNotExistException(uri.toString()); } if (inode.isDirectory()) { for (Inode child : ((InodeFolder) inode).getChildren()) { ret.add(child.generateClientFileInfo(CommonUtils.concat(uri, child.getName()))); } } else { ret.add(inode.generateClientFileInfo(uri.getPath())); } return ret; } /** * Get absolute paths of all in memory files. * * @return absolute paths of all in memory files. */ public List<TachyonURI> getInMemoryFiles() { List<TachyonURI> ret = new ArrayList<TachyonURI>(); LOG.info("getInMemoryFiles()"); Queue<Pair<InodeFolder, TachyonURI>> nodesQueue = new LinkedList<Pair<InodeFolder, TachyonURI>>(); synchronized (ROOT_LOCK) { // TODO: Verify we want to use absolute path. nodesQueue.add( new Pair<InodeFolder, TachyonURI>(mRoot, new TachyonURI(TachyonURI.SEPARATOR))); while (!nodesQueue.isEmpty()) { Pair<InodeFolder, TachyonURI> tPair = nodesQueue.poll(); InodeFolder tFolder = tPair.getFirst(); TachyonURI curUri = tPair.getSecond(); Set<Inode> children = tFolder.getChildren(); for (Inode tInode : children) { TachyonURI newUri = curUri.join(tInode.getName()); if (tInode.isDirectory()) { nodesQueue.add(new Pair<InodeFolder, TachyonURI>((InodeFolder) tInode, newUri)); } else if (((InodeFile) tInode).isFullyInMemory()) { ret.add(newUri); } } } } return ret; } /** * Same as {@link #getInode(String[] pathNames)} except that it takes a path string. */ private Inode getInode(TachyonURI path) throws InvalidPathException { return getInode(CommonUtils.getPathComponents(path.getPath())); } /** * Get the inode of the file at the given path. * * @param pathNames The path components of the path to search for * @return the inode of the file at the given path, or null if the file does not exist * @throws InvalidPathException */ private Inode getInode(String[] pathNames) throws InvalidPathException { Pair<Inode, Integer> inodeTraversal = traverseToInode(pathNames); if (!traversalSucceeded(inodeTraversal)) { return null; } return inodeTraversal.getFirst(); } /** * Returns a list of the given folder's children, recursively scanning subdirectories. It adds the * parent of a node before adding its children. * * @param inodeFolder The folder to start looking at * @return a list of the children inodes. */ private List<Inode> getInodeChildrenRecursive(InodeFolder inodeFolder) { synchronized (ROOT_LOCK) { List<Inode> ret = new ArrayList<Inode>(); for (Inode i : inodeFolder.getChildren()) { ret.add(i); if (i.isDirectory()) { ret.addAll(getInodeChildrenRecursive((InodeFolder) i)); } } return ret; } } /** * Get Journal instance for MasterInfo for Unit test only * * @return Journal instance */ public Journal getJournal() { return mJournal; } /** * Get the master address. * * @return the master address */ public InetSocketAddress getMasterAddress() { return mMasterAddress; } /** * Get a new user id * * @return a new user id */ public long getNewUserId() { return mUserCounter.incrementAndGet(); } /** * Get the number of files at a given uri. * * @param uri The uri to look at * @return The number of files at the uri. Returns 1 if the uri specifies a file. If it's a * directory, returns the number of items in the directory. * @throws InvalidPathException * @throws FileDoesNotExistException */ public int getNumberOfFiles(TachyonURI uri) throws InvalidPathException, FileDoesNotExistException { Inode inode = getInode(uri); if (inode == null) { throw new FileDoesNotExistException(uri.toString()); } if (inode.isFile()) { return 1; } return ((InodeFolder) inode).getNumberOfChildren(); } /** * Get the uri specified by a given inode. * * @param inode The inode * @return the uri of the inode */ private TachyonURI getPath(Inode inode) { synchronized (ROOT_LOCK) { if (inode.getId() == 1) { return new TachyonURI(TachyonURI.SEPARATOR); } if (inode.getParentId() == 1) { return new TachyonURI(TachyonURI.SEPARATOR + inode.getName()); } return getPath(mFileIdToInodes.get(inode.getParentId())).join(inode.getName()); } } /** * Get the path of a file with the given id * * @param fileId The id of the file to look up * @return the path of the file * @throws FileDoesNotExistException raise if the file does not exist. */ public TachyonURI getPath(int fileId) throws FileDoesNotExistException { synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(fileId); if (inode == null) { throw new FileDoesNotExistException("FileId " + fileId + " does not exist"); } return getPath(inode); } } /** * Get a list of the pin id's. * * @return a list of pin id's */ public List<Integer> getPinIdList() { synchronized (mPinnedInodeFileIds) { return Lists.newArrayList(mPinnedInodeFileIds); } } /** * Creates a list of high priority dependencies, which don't yet have checkpoints. * * @return the list of dependency ids */ public List<Integer> getPriorityDependencyList() { synchronized (mFileIdToDependency) { int earliestDepId = -1; if (mPriorityDependencies.isEmpty()) { long earliest = Long.MAX_VALUE; for (int depId : mUncheckpointedDependencies) { Dependency dep = mFileIdToDependency.get(depId); if (!dep.hasChildrenDependency()) { mPriorityDependencies.add(dep.mId); } if (dep.mCreationTimeMs < earliest) { earliest = dep.mCreationTimeMs; earliestDepId = dep.mId; } } if (!mPriorityDependencies.isEmpty()) { LOG.info("New computed priority dependency list " + mPriorityDependencies); } } if (mPriorityDependencies.isEmpty() && earliestDepId != -1) { mPriorityDependencies.add(earliestDepId); LOG.info("Priority dependency list by earliest creation time: " + mPriorityDependencies); } List<Integer> ret = new ArrayList<Integer>(mPriorityDependencies.size()); ret.addAll(mPriorityDependencies); return ret; } } /** * Get the id of the table at the given uri. * * @param uri The uri of the table * @return the id of the table * @throws InvalidPathException * @throws TableDoesNotExistException */ public int getRawTableId(TachyonURI uri) throws InvalidPathException, TableDoesNotExistException { Inode inode = getInode(uri); if (inode == null) { throw new TableDoesNotExistException(uri.toString()); } if (inode.isDirectory()) { int id = inode.getId(); if (mRawTables.exist(id)) { return id; } } return -1; } /** * Get the master start time in milliseconds. * * @return the master start time in milliseconds */ public long getStarttimeMs() { return mStartTimeMs; } /** * Get the capacity of the under file system. * * @return the capacity in bytes * @throws IOException */ public long getUnderFsCapacityBytes() throws IOException { UnderFileSystem ufs = UnderFileSystem.get(CommonConf.get().UNDERFS_DATA_FOLDER); return ufs.getSpace(CommonConf.get().UNDERFS_DATA_FOLDER, SpaceType.SPACE_TOTAL); } /** * Get the amount of free space in the under file system. * * @return the free space in bytes * @throws IOException */ public long getUnderFsFreeBytes() throws IOException { UnderFileSystem ufs = UnderFileSystem.get(CommonConf.get().UNDERFS_DATA_FOLDER); return ufs.getSpace(CommonConf.get().UNDERFS_DATA_FOLDER, SpaceType.SPACE_FREE); } /** * Get the amount of space used in the under file system. * * @return the space used in bytes * @throws IOException */ public long getUnderFsUsedBytes() throws IOException { UnderFileSystem ufs = UnderFileSystem.get(CommonConf.get().UNDERFS_DATA_FOLDER); return ufs.getSpace(CommonConf.get().UNDERFS_DATA_FOLDER, SpaceType.SPACE_USED); } /** * Get the amount of space used by the workers. * * @return the amount of space used in bytes */ public long getUsedBytes() { long ret = 0; synchronized (mWorkers) { for (MasterWorkerInfo worker : mWorkers.values()) { ret += worker.getUsedBytes(); } } return ret; } /** * Get the white list. * * @return the white list */ public List<String> getWhiteList() { return mWhitelist.getList(); } /** * Get the address of a worker. * * @param random If true, select a random worker * @param host If <code>random</code> is false, select a worker on this host * @return the address of the selected worker, or null if no address could be found */ public NetAddress getWorker(boolean random, String host) throws UnknownHostException { synchronized (mWorkers) { if (mWorkerAddressToId.isEmpty()) { return null; } if (random) { int index = new Random(mWorkerAddressToId.size()).nextInt(mWorkerAddressToId.size()); for (NetAddress address : mWorkerAddressToId.keySet()) { if (index == 0) { LOG.debug("getRandomWorker: {}", address); return address; } index --; } for (NetAddress address : mWorkerAddressToId.keySet()) { LOG.debug("getRandomWorker: {}", address); return address; } } else { for (NetAddress address : mWorkerAddressToId.keySet()) { InetAddress inetAddress = InetAddress.getByName(address.getMHost()); if (inetAddress.getHostName().equals(host) || inetAddress.getHostAddress().equals(host) || inetAddress.getCanonicalHostName().equals(host)) { LOG.debug("getLocalWorker: {}" + address); return address; } } } } LOG.info("getLocalWorker: no local worker on " + host); return null; } /** * Get the number of workers. * * @return the number of workers */ public int getWorkerCount() { synchronized (mWorkers) { return mWorkers.size(); } } /** * Get info about a worker. * * @param workerId The id of the worker to look at * @return the info about the worker */ private MasterWorkerInfo getWorkerInfo(long workerId) { MasterWorkerInfo ret = null; synchronized (mWorkers) { ret = mWorkers.get(workerId); if (ret == null) { LOG.error("No worker: " + workerId); } } return ret; } /** * Get info about all the workers. * * @return a list of worker infos */ public List<ClientWorkerInfo> getWorkersInfo() { List<ClientWorkerInfo> ret = new ArrayList<ClientWorkerInfo>(); synchronized (mWorkers) { for (MasterWorkerInfo worker : mWorkers.values()) { ret.add(worker.generateClientWorkerInfo()); } } return ret; } /** * Get info about the lost workers * * @return a list of worker info */ public List<ClientWorkerInfo> getLostWorkersInfo() { List<ClientWorkerInfo> ret = new ArrayList<ClientWorkerInfo>(); for (MasterWorkerInfo worker : mLostWorkers) { ret.add(worker.generateClientWorkerInfo()); } return ret; } public void init() throws IOException { mCheckpointInfo.updateEditTransactionCounter(mJournal.loadEditLog(this)); mJournal.createImage(this); mJournal.createEditLog(mCheckpointInfo.getEditTransactionCounter()); mHeartbeatThread = new HeartbeatThread("Master Heartbeat", new MasterInfoHeartbeatExecutor(), mMasterConf.HEARTBEAT_INTERVAL_MS); mHeartbeatThread.start(); mRecomputeThread = new Thread(new RecomputationScheduler()); mRecomputeThread.start(); } /** * Get the id of the file at the given uri. If recursive, it scans the subdirectories as well. * * @param uri The uri to start looking at * @param recursive If true, recursively scan the subdirectories at the given uri as well * @return the list of the inode id's at the uri * @throws InvalidPathException * @throws FileDoesNotExistException */ public List<Integer> listFiles(TachyonURI uri, boolean recursive) throws InvalidPathException, FileDoesNotExistException { List<Integer> ret = new ArrayList<Integer>(); synchronized (ROOT_LOCK) { Inode inode = getInode(uri); if (inode == null) { throw new FileDoesNotExistException(uri.toString()); } if (inode.isFile()) { ret.add(inode.getId()); } else if (recursive) { Queue<Inode> queue = new LinkedList<Inode>(); queue.addAll(((InodeFolder) inode).getChildren()); while (!queue.isEmpty()) { Inode qinode = queue.poll(); if (qinode.isDirectory()) { queue.addAll(((InodeFolder) qinode).getChildren()); } else { ret.add(qinode.getId()); } } } else { for (Inode child : ((InodeFolder) inode).getChildren()) { ret.add(child.getId()); } } } return ret; } /** * Load the image from <code>parser</code>, which is created based on the <code>path</code>. * Assume this blocks the whole MasterInfo. * * @param parser the JsonParser to load the image * @param uri the file to load the image * @throws IOException */ public void loadImage(JsonParser parser, TachyonURI uri) throws IOException { while (true) { ImageElement ele; try { ele = parser.readValueAs(ImageElement.class); LOG.debug("Read Element: {}", ele); } catch (IOException e) { // Unfortunately brittle, but Jackson rethrows EOF with this message. if (e.getMessage().contains("end-of-input")) { break; } else { throw e; } } switch (ele.type) { case Version: { if (ele.getInt("version") != Constants.JOURNAL_VERSION) { throw new IOException("Image " + uri + " has journal version " + ele.getInt("version") + " . The system has verion " + Constants.JOURNAL_VERSION); } break; } case Checkpoint: { mInodeCounter.set(ele.getInt("inodeCounter")); mCheckpointInfo.updateEditTransactionCounter(ele.getLong("editTransactionCounter")); mCheckpointInfo.updateDependencyCounter(ele.getInt("dependencyCounter")); break; } case Dependency: { Dependency dep = Dependency.loadImage(ele); mFileIdToDependency.put(dep.mId, dep); if (!dep.hasCheckpointed()) { mUncheckpointedDependencies.add(dep.mId); } for (int parentDependencyId : dep.mParentDependencies) { mFileIdToDependency.get(parentDependencyId).addChildrenDependency(dep.mId); } break; } case InodeFile: { // This element should not be loaded here. It should be loaded by InodeFolder. throw new IOException("Invalid element type " + ele); } case InodeFolder: { Inode inode = InodeFolder.loadImage(parser, ele); addToInodeMap(inode, mFileIdToInodes); recomputePinnedFiles(inode, Optional.<Boolean>absent()); if (inode.getId() != 1) { throw new IOException("Invalid element type " + ele); } mRoot = (InodeFolder) inode; break; } case RawTable: { mRawTables.loadImage(ele); break; } default: throw new IOException("Invalid element type " + ele); } } } /** * Get the names of the sub-directories at the given path. * * @param path The path to look at * @param recursive If true, recursively add the paths of the sub-directories * @return the list of paths * @throws InvalidPathException * @throws FileDoesNotExistException */ public List<TachyonURI> ls(TachyonURI path, boolean recursive) throws InvalidPathException, FileDoesNotExistException { synchronized (ROOT_LOCK) { Inode inode = getInode(path); if (inode == null) { throw new FileDoesNotExistException(path.toString()); } return _ls(inode, path, recursive); } } /** * Create a directory at the given path. * * @param path The path to create a directory at * @return true if and only if the directory was created; false otherwise * @throws FileAlreadyExistException * @throws InvalidPathException * @throws TachyonException */ public boolean mkdirs(TachyonURI path, boolean recursive) throws FileAlreadyExistException, InvalidPathException, TachyonException { try { return createFile(recursive, path, true, 0) > 0; } catch (BlockInfoException e) { throw new FileAlreadyExistException(e.getMessage()); } } /** * Called by edit log only. * * @param fileId * @param blockIndex * @param blockLength * @param opTimeMs * @throws FileDoesNotExistException * @throws BlockInfoException */ void opAddBlock(int fileId, int blockIndex, long blockLength, long opTimeMs) throws FileDoesNotExistException, BlockInfoException { synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(fileId); if (inode == null) { throw new FileDoesNotExistException("File " + fileId + " does not exist."); } if (inode.isDirectory()) { throw new FileDoesNotExistException("File " + fileId + " is a folder."); } addBlock((InodeFile) inode, new BlockInfo((InodeFile) inode, blockIndex, blockLength), opTimeMs); } } /** * Recomputes mFileIdPinList at the given Inode, recursively recomputing for children. Optionally * will set the "pinned" flag as we go. * * @param inode The inode to start traversal from * @param setPinState An optional parameter indicating whether we should also set the "pinned" * flag on each inode we traverse. If absent, the "isPinned" flag is unchanged. */ private void recomputePinnedFiles(Inode inode, Optional<Boolean> setPinState) { long opTimeMs = System.currentTimeMillis(); _recomputePinnedFiles(inode, setPinState, opTimeMs); } /** * Register a worker at the given address, setting it up and associating it with a given list of * blocks. * * @param workerNetAddress The address of the worker to register * @param totalBytes The capacity of the worker in bytes * @param usedBytes The number of bytes already used in the worker * @param currentBlockIds The id's of the blocks held by the worker * @return the new id of the registered worker * @throws BlockInfoException */ public long registerWorker(NetAddress workerNetAddress, long totalBytes, long usedBytes, List<Long> currentBlockIds) throws BlockInfoException { long id = 0; NetAddress workerAddress = new NetAddress(workerNetAddress); LOG.info("registerWorker(): WorkerNetAddress: " + workerAddress); synchronized (mWorkers) { if (mWorkerAddressToId.containsKey(workerAddress)) { id = mWorkerAddressToId.get(workerAddress); mWorkerAddressToId.remove(workerAddress); LOG.warn("The worker " + workerAddress + " already exists as id " + id + "."); } if (id != 0 && mWorkers.containsKey(id)) { MasterWorkerInfo tWorkerInfo = mWorkers.get(id); mWorkers.remove(id); mLostWorkers.add(tWorkerInfo); LOG.warn("The worker with id " + id + " has been removed."); } id = mStartTimeNSPrefix + mWorkerCounter.incrementAndGet(); MasterWorkerInfo tWorkerInfo = new MasterWorkerInfo(id, workerAddress, totalBytes); tWorkerInfo.updateUsedBytes(usedBytes); tWorkerInfo.updateBlocks(true, currentBlockIds); tWorkerInfo.updateLastUpdatedTimeMs(); mWorkers.put(id, tWorkerInfo); mWorkerAddressToId.put(workerAddress, id); LOG.info("registerWorker(): " + tWorkerInfo); } synchronized (ROOT_LOCK) { for (long blockId : currentBlockIds) { int fileId = BlockInfo.computeInodeId(blockId); int blockIndex = BlockInfo.computeBlockIndex(blockId); Inode inode = mFileIdToInodes.get(fileId); if (inode != null && inode.isFile()) { ((InodeFile) inode).addLocation(blockIndex, id, workerAddress); } else { LOG.warn("registerWorker failed to add fileId " + fileId + " blockIndex " + blockIndex); } } } return id; } /** * Rename a file to the given path. * * @param fileId The id of the file to rename * @param dstPath The new path of the file * @return true if the rename succeeded, false otherwise * @throws FileDoesNotExistException * @throws InvalidPathException */ public boolean rename(int fileId, TachyonURI dstPath) throws FileDoesNotExistException, InvalidPathException { long opTimeMs = System.currentTimeMillis(); synchronized (ROOT_LOCK) { boolean ret = _rename(fileId, dstPath, opTimeMs); mJournal.getEditLog().rename(fileId, dstPath, opTimeMs); mJournal.getEditLog().flush(); return ret; } } /** * Rename a file to the given path. * * @param srcPath The path of the file to rename * @param dstPath The new path of the file * @return true if the rename succeeded, false otherwise * @throws FileDoesNotExistException * @throws InvalidPathException */ public boolean rename(TachyonURI srcPath, TachyonURI dstPath) throws FileDoesNotExistException, InvalidPathException { synchronized (ROOT_LOCK) { Inode inode = getInode(srcPath); if (inode == null) { throw new FileDoesNotExistException("Failed to rename: " + srcPath + " does not exist"); } return rename(inode.getId(), dstPath); } } /** * Logs a lost file and sets it to be recovered. * * @param fileId The id of the file to be recovered */ public void reportLostFile(int fileId) { synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(fileId); if (inode == null) { LOG.warn("Tachyon does not have file " + fileId); } else if (inode.isDirectory()) { LOG.warn("Reported file is a directory " + inode); } else { InodeFile iFile = (InodeFile) inode; int depId = iFile.getDependencyId(); synchronized (mFileIdToDependency) { mLostFiles.add(fileId); if (depId == -1) { LOG.error("There is no dependency info for " + iFile + " . No recovery on that"); } else { LOG.info("Reported file loss. Tachyon will recompute it: " + iFile.toString()); Dependency dep = mFileIdToDependency.get(depId); dep.addLostFile(fileId); mMustRecomputedDpendencies.add(depId); } } } } } /** * Request that the files for the given dependency be recomputed. * * @param depId The dependency whose files are to be recomputed */ public void requestFilesInDependency(int depId) { synchronized (mFileIdToDependency) { if (mFileIdToDependency.containsKey(depId)) { Dependency dep = mFileIdToDependency.get(depId); LOG.info("Request files in dependency " + dep); if (dep.hasLostFile()) { mMustRecomputedDpendencies.add(depId); } } else { LOG.error("There is no dependency with id " + depId); } } } /** Sets the isPinned flag on the given inode and all of its children. */ public void setPinned(int fileId, boolean pinned) throws FileDoesNotExistException { long opTimeMs = System.currentTimeMillis(); synchronized (ROOT_LOCK) { _setPinned(fileId, pinned, opTimeMs); mJournal.getEditLog().setPinned(fileId, pinned, opTimeMs); mJournal.getEditLog().flush(); } } /** * Stops the heartbeat thread. */ public void stop() { mHeartbeatThread.shutdown(); } /** * Returns whether the traversal was successful or not. * * @return true if the traversal was successful, or false otherwise. */ private boolean traversalSucceeded(Pair<Inode, Integer> inodeTraversal) { return inodeTraversal.getSecond() == -1; } /** * Traverse to the inode at the given path. * * @param pathNames The path to search for, broken into components * @return the inode of the file at the given path. If it was not able to traverse down the entire * path, it will set the second field to the first path component it didn't find. It never * returns null. * @throws InvalidPathException */ private Pair<Inode, Integer> traverseToInode(String[] pathNames) throws InvalidPathException { synchronized (ROOT_LOCK) { if (pathNames == null || pathNames.length == 0) { throw new InvalidPathException("passed-in pathNames is null or empty"); } if (pathNames.length == 1) { if (pathNames[0].equals("")) { return new Pair<Inode, Integer>(mRoot, -1); } else { final String msg = "File name starts with " + pathNames[0]; LOG.info("InvalidPathException: " + msg); throw new InvalidPathException(msg); } } Pair<Inode, Integer> ret = new Pair<Inode, Integer>(mRoot, -1); for (int k = 1; k < pathNames.length; k ++) { Inode next = ((InodeFolder) ret.getFirst()).getChild(pathNames[k]); if (next == null) { // The user might want to create the nonexistent directories, so we leave ret.getFirst() // as the last Inode taken. We set nonexistentInd to k, to indicate that the kth path // component was the first one that couldn't be found. ret.setSecond(k); break; } ret.setFirst(next); if (!ret.getFirst().isDirectory()) { // The inode can't have any children. If this is the last path component, we're good. // Otherwise, we can't traverse further, so we clean up and throw an exception. if (k == pathNames.length - 1) { break; } else { final String msg = "Traversal failed. Component " + k + "(" + ret.getFirst().getName() + ") is a file"; LOG.info("InvalidPathException: " + msg); throw new InvalidPathException(msg); } } } return ret; } } /** * Update the metadata of a table. * * @param tableId The id of the table to update * @param metadata The new metadata to update the table with * @throws TableDoesNotExistException * @throws TachyonException */ public void updateRawTableMetadata(int tableId, ByteBuffer metadata) throws TableDoesNotExistException, TachyonException { synchronized (ROOT_LOCK) { Inode inode = mFileIdToInodes.get(tableId); if (inode == null || !inode.isDirectory() || !mRawTables.exist(tableId)) { throw new TableDoesNotExistException("Table " + tableId + " does not exist."); } mRawTables.updateMetadata(tableId, metadata); mJournal.getEditLog().updateRawTableMetadata(tableId, metadata); mJournal.getEditLog().flush(); } } /** * The heartbeat of the worker. It updates the information of the worker and removes the given * block id's. * * @param workerId The id of the worker to deal with * @param usedBytes The number of bytes used in the worker * @param removedBlockIds The id's of the blocks that have been removed * @return a command specifying an action to take * @throws BlockInfoException */ public Command workerHeartbeat(long workerId, long usedBytes, List<Long> removedBlockIds) throws BlockInfoException { LOG.debug("WorkerId: {}", workerId); synchronized (ROOT_LOCK) { synchronized (mWorkers) { MasterWorkerInfo tWorkerInfo = mWorkers.get(workerId); if (tWorkerInfo == null) { LOG.info("worker_heartbeat(): Does not contain worker with ID " + workerId + " . Send command to let it re-register."); return new Command(CommandType.Register, new ArrayList<Long>()); } tWorkerInfo.updateUsedBytes(usedBytes); tWorkerInfo.updateBlocks(false, removedBlockIds); tWorkerInfo.updateToRemovedBlocks(false, removedBlockIds); tWorkerInfo.updateLastUpdatedTimeMs(); for (long blockId : removedBlockIds) { int fileId = BlockInfo.computeInodeId(blockId); int blockIndex = BlockInfo.computeBlockIndex(blockId); Inode inode = mFileIdToInodes.get(fileId); if (inode == null) { LOG.error("File " + fileId + " does not exist"); } else if (inode.isFile()) { ((InodeFile) inode).removeLocation(blockIndex, workerId); LOG.debug("File {} with block {} was evicted from worker {} ", fileId, blockIndex, workerId); } } List<Long> toRemovedBlocks = tWorkerInfo.getToRemovedBlocks(); if (toRemovedBlocks.size() != 0) { return new Command(CommandType.Free, toRemovedBlocks); } } } return new Command(CommandType.Nothing, new ArrayList<Long>()); } /** * Create an image of the dependencies and filesystem tree. * * @param objWriter The used object writer * @param dos The target data output stream * @throws IOException */ @Override public void writeImage(ObjectWriter objWriter, DataOutputStream dos) throws IOException { ImageElement ele = new ImageElement(ImageElementType.Version).withParameter("version", Constants.JOURNAL_VERSION); writeElement(objWriter, dos, ele); synchronized (ROOT_LOCK) { synchronized (mFileIdToDependency) { for (Dependency dep : mFileIdToDependency.values()) { dep.writeImage(objWriter, dos); } } mRoot.writeImage(objWriter, dos); mRawTables.writeImage(objWriter, dos); ele = new ImageElement(ImageElementType.Checkpoint) .withParameter("inodeCounter", mInodeCounter.get()) .withParameter("editTransactionCounter", mCheckpointInfo.getEditTransactionCounter()) .withParameter("dependencyCounter", mCheckpointInfo.getDependencyCounter()); writeElement(objWriter, dos, ele); } } }
c01f761e771e482f177b75eb1c9cf7d348feb5eb
4c5aaad3a83b3da0d252e2b9175ba4797f8aba67
/JSONServer/build/Server/appzillon-frameworks/src/main/java/com/iexceed/appzillon/impl/ConversationalUIRulesBeanImpl.java
b84e15bfa38d898f3b18057fcd863421a5e3af31
[]
no_license
lokesh-raju/RestCall
9643e7dcc52161eb7321667fb063704a138298f9
feb501edf324570e35fe3914de02de79aee0b21a
refs/heads/master
2020-03-18T03:32:34.197882
2018-05-21T09:46:46
2018-05-21T09:46:46
134,245,580
0
0
null
null
null
null
UTF-8
Java
false
false
376
java
package com.iexceed.appzillon.impl; import com.iexceed.appzillon.iface.IConversationalUI; import com.iexceed.appzillon.json.JSONObject; import com.iexceed.appzillon.message.Message; public class ConversationalUIRulesBeanImpl implements IConversationalUI{ @Override public JSONObject processDlgId(Message pMessage, JSONObject pRequestJson) { return pRequestJson; } }
6bb0aa55f762b4620982327c0472036f8d0ca88c
af60766a8cfaef939afb81102a7be4fdbe45d7a1
/src/ejemplo/herencia/Triangulo.java
77721e78a3835e30509fdb0aaf37ec6443f0b508
[]
no_license
ProyectosSoftwareUNIBE/poo
201b2501c322e8e7c770dac4b4db019d6431e2ba
01fcfed407ae20e427ea93c6c17b21b4c2f16fd9
refs/heads/master
2023-05-05T09:34:32.000641
2021-05-22T16:47:26
2021-05-22T16:47:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
559
java
package ejemplo.herencia; public class Triangulo implements FiguraInterface { private double base, altura; public Triangulo(double base, double altura) { super(); this.base = base; this.altura = altura; } public Triangulo() { super(); } public double getBase() { return base; } public void setBase(double base) { this.base = base; } public double getAltura() { return altura; } public void setAltura(double altura) { this.altura = altura; } @Override public double area() { return (base * altura) / 2; } }
9efa887720d857e1fe47431650b8053ea1797950
032c9b4d30244ca5c4a4af0ad80179d210ba3cd8
/tao/database/subsystem/Order.java
1609c5d50edb0b8ac91d3c15670061b0965258e1
[]
no_license
alexey-komarov/vector
b7ce86a1cb7b272fe4b475a6251c3686ff322f99
770528548f44005d689d94176f91e0f4c49941ec
refs/heads/master
2020-04-08T07:32:26.962794
2013-06-09T15:34:01
2013-06-09T15:34:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
547
java
/* Vector 2009, Alexey Komarov <[email protected]> */ package tao.database.subsystem; import tao.database.TaoDatabase; import java.util.Properties; import java.util.Enumeration; import java.sql.ResultSet; public class Order extends TaoDatabase { public Integer getNextNumber() throws Exception { ResultSet rs = getNewResultSet("SELECT Number + 1 FROM orders ORDER BY ID_Order DESC LIMIT 0,1"); rs.first(); try { return ((Long)rs.getObject(1)).intValue(); } catch (Exception e) { return 1; } } }
9433cf79de0a9a1d7bdc34818cb2649be8689dde
0562cecc4dfbf5ea09480a52b69ad187443f69d4
/src/main/java/edu/cmu/cs/stage3/alice/scenegraph/ComponentArray.java
8e36f7547d5d64eb3d410d5f70cfc565c9d25666
[ "BSD-2-Clause" ]
permissive
vorburger/Alice
9f12b91200b53c12ee562aad88be4964c9911aa6
af10b6edea7ecbf35bcba08d0853562fbe4a1837
refs/heads/master
2021-01-18T07:37:28.007447
2013-12-12T13:48:17
2013-12-12T13:48:17
3,757,745
1
2
null
null
null
null
UTF-8
Java
false
false
1,502
java
/* * Copyright (c) 1999-2003, Carnegie Mellon University. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Products derived from the software may not be called "Alice", * nor may "Alice" appear in their name, without prior written * permission of Carnegie Mellon University. * * 4. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes software developed by Carnegie Mellon University" */ package edu.cmu.cs.stage3.alice.scenegraph; /** * @author Dennis Cosgrove */ public class ComponentArray extends VertexGeometry { public static final Property COMPONENT_PROPERTY = new Property( ComponentArray.class, "COMPONENT" ); private Component m_component = null; public Component getComponent() { return m_component; } public void setComponent( Component component ) { if( m_component != component ) { m_component = component; onPropertyChange( COMPONENT_PROPERTY ); } } }
1dcac3daf536076cfcf893fc12626fa7afc6d2c1
d1a6d1e511df6db8d8dd0912526e3875c7e1797d
/genny_JavaWithoutLambdas/applicationModule/src/test/java/applicationModulepackageJava0/Foo644Test.java
bc0a0928c7c5ad3755ea6524690d11dd5d6bcc80
[]
no_license
NikitaKozlov/generated-project-for-desugaring
0bc1443ab3ddc84cd289331c726761585766aea7
81506b3711004185070ca4bb9a93482b70011d36
refs/heads/master
2020-03-20T00:35:06.996525
2018-06-12T09:30:37
2018-06-12T09:30:37
137,049,317
0
0
null
null
null
null
UTF-8
Java
false
false
481
java
package applicationModulepackageJava0; import org.junit.Test; public class Foo644Test { @Test public void testFoo0() { new Foo644().foo0(); } @Test public void testFoo1() { new Foo644().foo1(); } @Test public void testFoo2() { new Foo644().foo2(); } @Test public void testFoo3() { new Foo644().foo3(); } @Test public void testFoo4() { new Foo644().foo4(); } @Test public void testFoo5() { new Foo644().foo5(); } }
b7644d426bb1f16ea445f4500dc50f18436b3abc
7c3838598b39d4ae847ac529b810cae0891ea2c1
/src/main/java/main/Main.java
38fedd07f670f77ea77472f04f498ec7fe5130d4
[]
no_license
therealSvenson/MQTTClient
1948fb82453b18437caad34f6f00f0e838bc4562
f1a65a8fc722e5f3dd225d15bef2f5c9225edba3
refs/heads/main
2023-06-01T17:30:10.798104
2021-06-16T17:56:14
2021-06-16T17:56:14
377,168,397
0
0
null
null
null
null
UTF-8
Java
false
false
301
java
package main; public class Main { Main main; private Main() { main = new Main(); } public Main getInstance() { return this.main; } public static void main(String[] args) { Gui gui= new Gui(); MqttConnect connection = new MqttConnect(); connection.start(); } }
8b7a7bcbd67f775fc202ef3aa1763afe9dd17557
8a2213db9b2086178f05696a5f67e69ea514bcb2
/src/test/java/com/tsguild/flooringmasteryproject/dao/TaxDaoImplTest.java
bb14f4102c7472c74f5ccddabf1378063fb2c50c
[]
no_license
WJimmyCook/flooring-console
4164be57bc5700cea35eb16b7caf8ff9e60de5dc
3336851ab3ce9913470c58efa57c5d2ec08fae88
refs/heads/master
2020-07-04T02:16:10.525415
2016-12-21T01:06:56
2016-12-21T01:06:56
74,218,940
0
0
null
null
null
null
UTF-8
Java
false
false
2,777
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 com.tsguild.flooringmasteryproject.dao; import java.io.FileNotFoundException; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Jimmy Cook */ public class TaxDaoImplTest { TaxDaoImpl testObj; public TaxDaoImplTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() throws FileNotFoundException { testObj = new TaxDaoImpl("taxesTESTDATA.txt"); testObj.loadFromFile(); } @After public void tearDown() { } /** * Test of getTax method, of class TaxDaoImpl. */ @Test public void testGetTaxAL() { double expResult = 4; double result = testObj.getTax("AL"); assertEquals(expResult, result, 0.01); } @Test public void testGetTaxCA() { double expResult = 7.5; double result = testObj.getTax("CA"); assertEquals(expResult, result, 0.01); } @Test public void testGetTaxWrong() { double expResult = 9; double result = testObj.getTax("OH"); Assert.assertNotEquals(expResult, result, 0.01); } /** * Test of containsState method, of class TaxDaoImpl. */ @Test public void testContainsState() { boolean expResult = true; boolean result = testObj.containsState("AL"); assertEquals(expResult, result); } @Test public void testContainsStateB() { boolean expResult = true; boolean result = testObj.containsState("OH"); assertEquals(expResult, result); } @Test public void testContainsStateEmpty() { boolean expResult = false; boolean result = testObj.containsState(""); assertEquals(expResult, result); } @Test public void testContainsStateLetters() { boolean expResult = false; boolean result = testObj.containsState("AJKDL"); assertEquals(expResult, result); } @Test public void testContainsStateSpecialChars() { boolean expResult = false; boolean result = testObj.containsState("@$"); assertEquals(expResult, result); } @Test public void testContainsStateSpaces() { boolean expResult = false; boolean result = testObj.containsState(" AL "); assertEquals(expResult, result); } }
45eceed41e18f6f131f0039c5be41399a4625412
45bd54e36678386e42a732b0bfc55d11c04540ff
/appliAndroid/dancemashing/controller/MainActivity.java
bb022e746c53ba8a7f4231641eaeb32b24b53770
[]
no_license
Najet282/fil_rouge
20edbfaf80e662232a816735e1fa2d2d1491ccb2
ad7e50306b360650691bdb91114ac100293276f9
refs/heads/master
2023-08-01T05:36:37.048028
2021-09-24T13:07:55
2021-09-24T13:07:55
356,295,099
0
0
null
null
null
null
UTF-8
Java
false
false
2,307
java
package com.example.dancemashing.controller; import android.content.Intent; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import com.example.dancemashing.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { /************************* ATTRIBUTS ****************************/ private ActivityMainBinding binding; /***************** PAGE D ACCUEIL DE L ACTIVITE *****************/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); } /***************** REDIRECTIONS CLIC SUR BOUTON ******************/ public void onBtConnexionClic(View view) { Intent intent = new Intent(this, ConnexionActivity.class); startActivity(intent); } public void onIvLogoDMClic(View view) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } public void onIvLogoJDClic(View view) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } public void onTvTitleVideosClic(View view) { Intent intent = new Intent(this, VideoActivity.class); startActivity(intent); } public void onIvVideo1Clic(View view) { } public void onIvVideo2Clic(View view) { } public void onIvVideo3Clic(View view) { } public void onBtMashClic(View view) { } public void onTvTitleChoreClic(View view) { } public void onIvChoreClic(View view) { } public void onBtPosterVideoClic(View view) { Intent intent = new Intent(this, EnvoiVideo.class); startActivity(intent); } public void onTvTitleTopClic(View view) { Intent intent = new Intent(this, TopActivity.class); startActivity(intent); } public void onIvTop1Clic(View view) { } public void onIvTop2Clic(View view) { } public void onIvTop3Clic(View view) { } public void onTvTitleLastClic(View view) { } public void onIvLast1Clic(View view) { } public void onIvLast2Clic(View view) { } }
794ab6c2dda645c317d55252b22f8392397a148a
db8779f7a5bf0a4cb23fcd580fab1e3547fc0034
/src/main/java/com/example/dbflute/jsr310/bsentity/BsMember.java
64bd2c60d1047c2e66ecebe05f6549efaae27138
[]
no_license
taktos/dbflute-jsr310-example
c3ca049a435649191a18922e0c5e81dfd608704c
a7ef5805d999e46f55fd150c8ab1512256ef4c6c
refs/heads/master
2016-09-06T16:29:43.622252
2014-04-06T07:10:28
2014-04-06T07:11:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
34,330
java
package com.example.dbflute.jsr310.bsentity; import java.io.Serializable; import java.util.List; import java.util.ArrayList; import java.util.Set; import org.seasar.dbflute.dbmeta.DBMeta; import org.seasar.dbflute.Entity; import com.example.dbflute.jsr310.allcommon.DBMetaInstanceHandler; import com.example.dbflute.jsr310.exentity.*; /** * The entity of MEMBER as TABLE. <br /> * 会員: 会員のプロフィールやアカウントなどの基本情報を保持する。<br /> * 基本的に物理削除はなく、退会したらステータスが退会会員になる。<br /> * ライフサイクルやカテゴリの違う会員情報は、one-to-oneなどの関連テーブルにて。 * <pre> * [primary-key] * MEMBER_ID * * [column] * MEMBER_ID, MEMBER_NAME, MEMBER_ACCOUNT, MEMBER_STATUS_CODE, FORMALIZED_DATETIME, BIRTHDATE, REGISTER_DATETIME, REGISTER_USER, UPDATE_DATETIME, UPDATE_USER, VERSION_NO * * [sequence] * * * [identity] * MEMBER_ID * * [version-no] * VERSION_NO * * [foreign table] * MEMBER_STATUS, MEMBER_SECURITY(AsOne), MEMBER_SERVICE(AsOne), MEMBER_WITHDRAWAL(AsOne) * * [referrer table] * MEMBER_ADDRESS, MEMBER_FOLLOWING, MEMBER_LOGIN, PURCHASE, MEMBER_SECURITY, MEMBER_SERVICE, MEMBER_WITHDRAWAL * * [foreign property] * memberStatus, memberSecurityAsOne, memberServiceAsOne, memberWithdrawalAsOne * * [referrer property] * memberAddressList, memberFollowingByMyMemberIdList, memberFollowingByYourMemberIdList, memberLoginList, purchaseList * * [get/set template] * /= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * Integer memberId = entity.getMemberId(); * String memberName = entity.getMemberName(); * String memberAccount = entity.getMemberAccount(); * String memberStatusCode = entity.getMemberStatusCode(); * java.time.LocalDateTime formalizedDatetime = entity.getFormalizedDatetime(); * java.time.LocalDate birthdate = entity.getBirthdate(); * java.time.LocalDateTime registerDatetime = entity.getRegisterDatetime(); * String registerUser = entity.getRegisterUser(); * java.time.LocalDateTime updateDatetime = entity.getUpdateDatetime(); * String updateUser = entity.getUpdateUser(); * Long versionNo = entity.getVersionNo(); * entity.setMemberId(memberId); * entity.setMemberName(memberName); * entity.setMemberAccount(memberAccount); * entity.setMemberStatusCode(memberStatusCode); * entity.setFormalizedDatetime(formalizedDatetime); * entity.setBirthdate(birthdate); * entity.setRegisterDatetime(registerDatetime); * entity.setRegisterUser(registerUser); * entity.setUpdateDatetime(updateDatetime); * entity.setUpdateUser(updateUser); * entity.setVersionNo(versionNo); * = = = = = = = = = =/ * </pre> * @author DBFlute(AutoGenerator) */ public abstract class BsMember implements Entity, Serializable, Cloneable { // =================================================================================== // Definition // ========== /** Serial version UID. (Default) */ private static final long serialVersionUID = 1L; // =================================================================================== // Attribute // ========= // ----------------------------------------------------- // Column // ------ /** MEMBER_ID: {PK, ID, NotNull, INTEGER(10)} */ protected Integer _memberId; /** MEMBER_NAME: {IX, NotNull, VARCHAR(200)} */ protected String _memberName; /** MEMBER_ACCOUNT: {UQ, NotNull, VARCHAR(50)} */ protected String _memberAccount; /** MEMBER_STATUS_CODE: {IX, NotNull, CHAR(3), FK to MEMBER_STATUS} */ protected String _memberStatusCode; /** FORMALIZED_DATETIME: {IX, TIMESTAMP(23, 10)} */ protected java.time.LocalDateTime _formalizedDatetime; /** BIRTHDATE: {DATE(8)} */ protected java.time.LocalDate _birthdate; /** REGISTER_DATETIME: {NotNull, TIMESTAMP(23, 10)} */ protected java.time.LocalDateTime _registerDatetime; /** REGISTER_USER: {NotNull, VARCHAR(200)} */ protected String _registerUser; /** UPDATE_DATETIME: {NotNull, TIMESTAMP(23, 10)} */ protected java.time.LocalDateTime _updateDatetime; /** UPDATE_USER: {NotNull, VARCHAR(200)} */ protected String _updateUser; /** VERSION_NO: {NotNull, BIGINT(19)} */ protected Long _versionNo; // ----------------------------------------------------- // Internal // -------- /** The modified properties for this entity. (NotNull) */ protected final EntityModifiedProperties __modifiedProperties = newModifiedProperties(); /** Is the entity created by DBFlute select process? */ protected boolean __createdBySelect; // =================================================================================== // Table Name // ========== /** * {@inheritDoc} */ public String getTableDbName() { return "MEMBER"; } /** * {@inheritDoc} */ public String getTablePropertyName() { // according to Java Beans rule return "member"; } // =================================================================================== // DBMeta // ====== /** * {@inheritDoc} */ public DBMeta getDBMeta() { return DBMetaInstanceHandler.findDBMeta(getTableDbName()); } // =================================================================================== // Primary Key // =========== /** * {@inheritDoc} */ public boolean hasPrimaryKeyValue() { if (getMemberId() == null) { return false; } return true; } // =================================================================================== // Foreign Property // ================ /** MEMBER_STATUS by my MEMBER_STATUS_CODE, named 'memberStatus'. */ protected MemberStatus _memberStatus; /** * MEMBER_STATUS by my MEMBER_STATUS_CODE, named 'memberStatus'. * @return The entity of foreign property 'memberStatus'. (NullAllowed: when e.g. null FK column, no setupSelect) */ public MemberStatus getMemberStatus() { return _memberStatus; } /** * MEMBER_STATUS by my MEMBER_STATUS_CODE, named 'memberStatus'. * @param memberStatus The entity of foreign property 'memberStatus'. (NullAllowed) */ public void setMemberStatus(MemberStatus memberStatus) { _memberStatus = memberStatus; } /** MEMBER_SECURITY by MEMBER_ID, named 'memberSecurityAsOne'. */ protected MemberSecurity _memberSecurityAsOne; /** * MEMBER_SECURITY by MEMBER_ID, named 'memberSecurityAsOne'. * @return the entity of foreign property(referrer-as-one) 'memberSecurityAsOne'. (NullAllowed: when e.g. no data, no setupSelect) */ public MemberSecurity getMemberSecurityAsOne() { return _memberSecurityAsOne; } /** * MEMBER_SECURITY by MEMBER_ID, named 'memberSecurityAsOne'. * @param memberSecurityAsOne The entity of foreign property(referrer-as-one) 'memberSecurityAsOne'. (NullAllowed) */ public void setMemberSecurityAsOne(MemberSecurity memberSecurityAsOne) { _memberSecurityAsOne = memberSecurityAsOne; } /** MEMBER_SERVICE by MEMBER_ID, named 'memberServiceAsOne'. */ protected MemberService _memberServiceAsOne; /** * MEMBER_SERVICE by MEMBER_ID, named 'memberServiceAsOne'. * @return the entity of foreign property(referrer-as-one) 'memberServiceAsOne'. (NullAllowed: when e.g. no data, no setupSelect) */ public MemberService getMemberServiceAsOne() { return _memberServiceAsOne; } /** * MEMBER_SERVICE by MEMBER_ID, named 'memberServiceAsOne'. * @param memberServiceAsOne The entity of foreign property(referrer-as-one) 'memberServiceAsOne'. (NullAllowed) */ public void setMemberServiceAsOne(MemberService memberServiceAsOne) { _memberServiceAsOne = memberServiceAsOne; } /** MEMBER_WITHDRAWAL by MEMBER_ID, named 'memberWithdrawalAsOne'. */ protected MemberWithdrawal _memberWithdrawalAsOne; /** * MEMBER_WITHDRAWAL by MEMBER_ID, named 'memberWithdrawalAsOne'. * @return the entity of foreign property(referrer-as-one) 'memberWithdrawalAsOne'. (NullAllowed: when e.g. no data, no setupSelect) */ public MemberWithdrawal getMemberWithdrawalAsOne() { return _memberWithdrawalAsOne; } /** * MEMBER_WITHDRAWAL by MEMBER_ID, named 'memberWithdrawalAsOne'. * @param memberWithdrawalAsOne The entity of foreign property(referrer-as-one) 'memberWithdrawalAsOne'. (NullAllowed) */ public void setMemberWithdrawalAsOne(MemberWithdrawal memberWithdrawalAsOne) { _memberWithdrawalAsOne = memberWithdrawalAsOne; } // =================================================================================== // Referrer Property // ================= /** MEMBER_ADDRESS by MEMBER_ID, named 'memberAddressList'. */ protected List<MemberAddress> _memberAddressList; /** * MEMBER_ADDRESS by MEMBER_ID, named 'memberAddressList'. * @return The entity list of referrer property 'memberAddressList'. (NotNull: even if no loading, returns empty list) */ public List<MemberAddress> getMemberAddressList() { if (_memberAddressList == null) { _memberAddressList = newReferrerList(); } return _memberAddressList; } /** * MEMBER_ADDRESS by MEMBER_ID, named 'memberAddressList'. * @param memberAddressList The entity list of referrer property 'memberAddressList'. (NullAllowed) */ public void setMemberAddressList(List<MemberAddress> memberAddressList) { _memberAddressList = memberAddressList; } /** MEMBER_FOLLOWING by MY_MEMBER_ID, named 'memberFollowingByMyMemberIdList'. */ protected List<MemberFollowing> _memberFollowingByMyMemberIdList; /** * MEMBER_FOLLOWING by MY_MEMBER_ID, named 'memberFollowingByMyMemberIdList'. * @return The entity list of referrer property 'memberFollowingByMyMemberIdList'. (NotNull: even if no loading, returns empty list) */ public List<MemberFollowing> getMemberFollowingByMyMemberIdList() { if (_memberFollowingByMyMemberIdList == null) { _memberFollowingByMyMemberIdList = newReferrerList(); } return _memberFollowingByMyMemberIdList; } /** * MEMBER_FOLLOWING by MY_MEMBER_ID, named 'memberFollowingByMyMemberIdList'. * @param memberFollowingByMyMemberIdList The entity list of referrer property 'memberFollowingByMyMemberIdList'. (NullAllowed) */ public void setMemberFollowingByMyMemberIdList(List<MemberFollowing> memberFollowingByMyMemberIdList) { _memberFollowingByMyMemberIdList = memberFollowingByMyMemberIdList; } /** MEMBER_FOLLOWING by YOUR_MEMBER_ID, named 'memberFollowingByYourMemberIdList'. */ protected List<MemberFollowing> _memberFollowingByYourMemberIdList; /** * MEMBER_FOLLOWING by YOUR_MEMBER_ID, named 'memberFollowingByYourMemberIdList'. * @return The entity list of referrer property 'memberFollowingByYourMemberIdList'. (NotNull: even if no loading, returns empty list) */ public List<MemberFollowing> getMemberFollowingByYourMemberIdList() { if (_memberFollowingByYourMemberIdList == null) { _memberFollowingByYourMemberIdList = newReferrerList(); } return _memberFollowingByYourMemberIdList; } /** * MEMBER_FOLLOWING by YOUR_MEMBER_ID, named 'memberFollowingByYourMemberIdList'. * @param memberFollowingByYourMemberIdList The entity list of referrer property 'memberFollowingByYourMemberIdList'. (NullAllowed) */ public void setMemberFollowingByYourMemberIdList(List<MemberFollowing> memberFollowingByYourMemberIdList) { _memberFollowingByYourMemberIdList = memberFollowingByYourMemberIdList; } /** MEMBER_LOGIN by MEMBER_ID, named 'memberLoginList'. */ protected List<MemberLogin> _memberLoginList; /** * MEMBER_LOGIN by MEMBER_ID, named 'memberLoginList'. * @return The entity list of referrer property 'memberLoginList'. (NotNull: even if no loading, returns empty list) */ public List<MemberLogin> getMemberLoginList() { if (_memberLoginList == null) { _memberLoginList = newReferrerList(); } return _memberLoginList; } /** * MEMBER_LOGIN by MEMBER_ID, named 'memberLoginList'. * @param memberLoginList The entity list of referrer property 'memberLoginList'. (NullAllowed) */ public void setMemberLoginList(List<MemberLogin> memberLoginList) { _memberLoginList = memberLoginList; } /** PURCHASE by MEMBER_ID, named 'purchaseList'. */ protected List<Purchase> _purchaseList; /** * PURCHASE by MEMBER_ID, named 'purchaseList'. * @return The entity list of referrer property 'purchaseList'. (NotNull: even if no loading, returns empty list) */ public List<Purchase> getPurchaseList() { if (_purchaseList == null) { _purchaseList = newReferrerList(); } return _purchaseList; } /** * PURCHASE by MEMBER_ID, named 'purchaseList'. * @param purchaseList The entity list of referrer property 'purchaseList'. (NullAllowed) */ public void setPurchaseList(List<Purchase> purchaseList) { _purchaseList = purchaseList; } protected <ELEMENT> List<ELEMENT> newReferrerList() { return new ArrayList<ELEMENT>(); } // =================================================================================== // Modified Properties // =================== /** * {@inheritDoc} */ public Set<String> modifiedProperties() { return __modifiedProperties.getPropertyNames(); } /** * {@inheritDoc} */ public void clearModifiedInfo() { __modifiedProperties.clear(); } /** * {@inheritDoc} */ public boolean hasModification() { return !__modifiedProperties.isEmpty(); } protected EntityModifiedProperties newModifiedProperties() { return new EntityModifiedProperties(); } // =================================================================================== // Birthplace Mark // =============== /** * {@inheritDoc} */ public void markAsSelect() { __createdBySelect = true; } /** * {@inheritDoc} */ public boolean createdBySelect() { return __createdBySelect; } // =================================================================================== // Basic Override // ============== /** * Determine the object is equal with this. <br /> * If primary-keys or columns of the other are same as this one, returns true. * @param other The other entity. (NullAllowed: if null, returns false fixedly) * @return Comparing result. */ public boolean equals(Object other) { if (other == null || !(other instanceof BsMember)) { return false; } BsMember otherEntity = (BsMember)other; if (!xSV(getMemberId(), otherEntity.getMemberId())) { return false; } return true; } protected boolean xSV(Object value1, Object value2) { // isSameValue() return InternalUtil.isSameValue(value1, value2); } /** * Calculate the hash-code from primary-keys or columns. * @return The hash-code from primary-key or columns. */ public int hashCode() { int result = 17; result = xCH(result, getTableDbName()); result = xCH(result, getMemberId()); return result; } protected int xCH(int result, Object value) { // calculateHashcode() return InternalUtil.calculateHashcode(result, value); } /** * {@inheritDoc} */ public int instanceHash() { return super.hashCode(); } /** * Convert to display string of entity's data. (no relation data) * @return The display string of all columns and relation existences. (NotNull) */ public String toString() { return buildDisplayString(InternalUtil.toClassTitle(this), true, true); } /** * {@inheritDoc} */ public String toStringWithRelation() { StringBuilder sb = new StringBuilder(); sb.append(toString()); String l = "\n "; if (_memberStatus != null) { sb.append(l).append(xbRDS(_memberStatus, "memberStatus")); } if (_memberSecurityAsOne != null) { sb.append(l).append(xbRDS(_memberSecurityAsOne, "memberSecurityAsOne")); } if (_memberServiceAsOne != null) { sb.append(l).append(xbRDS(_memberServiceAsOne, "memberServiceAsOne")); } if (_memberWithdrawalAsOne != null) { sb.append(l).append(xbRDS(_memberWithdrawalAsOne, "memberWithdrawalAsOne")); } if (_memberAddressList != null) { for (Entity e : _memberAddressList) { if (e != null) { sb.append(l).append(xbRDS(e, "memberAddressList")); } } } if (_memberFollowingByMyMemberIdList != null) { for (Entity e : _memberFollowingByMyMemberIdList) { if (e != null) { sb.append(l).append(xbRDS(e, "memberFollowingByMyMemberIdList")); } } } if (_memberFollowingByYourMemberIdList != null) { for (Entity e : _memberFollowingByYourMemberIdList) { if (e != null) { sb.append(l).append(xbRDS(e, "memberFollowingByYourMemberIdList")); } } } if (_memberLoginList != null) { for (Entity e : _memberLoginList) { if (e != null) { sb.append(l).append(xbRDS(e, "memberLoginList")); } } } if (_purchaseList != null) { for (Entity e : _purchaseList) { if (e != null) { sb.append(l).append(xbRDS(e, "purchaseList")); } } } return sb.toString(); } protected String xbRDS(Entity e, String name) { // buildRelationDisplayString() return e.buildDisplayString(name, true, true); } /** * {@inheritDoc} */ public String buildDisplayString(String name, boolean column, boolean relation) { StringBuilder sb = new StringBuilder(); if (name != null) { sb.append(name).append(column || relation ? ":" : ""); } if (column) { sb.append(buildColumnString()); } if (relation) { sb.append(buildRelationString()); } sb.append("@").append(Integer.toHexString(hashCode())); return sb.toString(); } protected String buildColumnString() { StringBuilder sb = new StringBuilder(); String delimiter = ", "; sb.append(delimiter).append(getMemberId()); sb.append(delimiter).append(getMemberName()); sb.append(delimiter).append(getMemberAccount()); sb.append(delimiter).append(getMemberStatusCode()); sb.append(delimiter).append(getFormalizedDatetime()); sb.append(delimiter).append(getBirthdate()); sb.append(delimiter).append(getRegisterDatetime()); sb.append(delimiter).append(getRegisterUser()); sb.append(delimiter).append(getUpdateDatetime()); sb.append(delimiter).append(getUpdateUser()); sb.append(delimiter).append(getVersionNo()); if (sb.length() > delimiter.length()) { sb.delete(0, delimiter.length()); } sb.insert(0, "{").append("}"); return sb.toString(); } protected String buildRelationString() { StringBuilder sb = new StringBuilder(); String c = ","; if (_memberStatus != null) { sb.append(c).append("memberStatus"); } if (_memberSecurityAsOne != null) { sb.append(c).append("memberSecurityAsOne"); } if (_memberServiceAsOne != null) { sb.append(c).append("memberServiceAsOne"); } if (_memberWithdrawalAsOne != null) { sb.append(c).append("memberWithdrawalAsOne"); } if (_memberAddressList != null && !_memberAddressList.isEmpty()) { sb.append(c).append("memberAddressList"); } if (_memberFollowingByMyMemberIdList != null && !_memberFollowingByMyMemberIdList.isEmpty()) { sb.append(c).append("memberFollowingByMyMemberIdList"); } if (_memberFollowingByYourMemberIdList != null && !_memberFollowingByYourMemberIdList.isEmpty()) { sb.append(c).append("memberFollowingByYourMemberIdList"); } if (_memberLoginList != null && !_memberLoginList.isEmpty()) { sb.append(c).append("memberLoginList"); } if (_purchaseList != null && !_purchaseList.isEmpty()) { sb.append(c).append("purchaseList"); } if (sb.length() > c.length()) { sb.delete(0, c.length()).insert(0, "(").append(")"); } return sb.toString(); } /** * Clone entity instance using super.clone(). (shallow copy) * @return The cloned instance of this entity. (NotNull) */ public Member clone() { try { return (Member)super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Failed to clone the entity: " + toString(), e); } } // =================================================================================== // Accessor // ======== /** * [get] MEMBER_ID: {PK, ID, NotNull, INTEGER(10)} <br /> * 会員ID: 連番として自動採番される。会員IDだけに限らず採番方法はDBMS次第。 * @return The value of the column 'MEMBER_ID'. (basically NotNull if selected: for the constraint) */ public Integer getMemberId() { return _memberId; } /** * [set] MEMBER_ID: {PK, ID, NotNull, INTEGER(10)} <br /> * 会員ID: 連番として自動採番される。会員IDだけに限らず採番方法はDBMS次第。 * @param memberId The value of the column 'MEMBER_ID'. (basically NotNull if update: for the constraint) */ public void setMemberId(Integer memberId) { __modifiedProperties.addPropertyName("memberId"); this._memberId = memberId; } /** * [get] MEMBER_NAME: {IX, NotNull, VARCHAR(200)} <br /> * 会員名称: 会員のフルネームの名称。<br /> * 苗字と名前を分けて管理することが多いが、ここでは単純にひとまとめ。 * @return The value of the column 'MEMBER_NAME'. (basically NotNull if selected: for the constraint) */ public String getMemberName() { return _memberName; } /** * [set] MEMBER_NAME: {IX, NotNull, VARCHAR(200)} <br /> * 会員名称: 会員のフルネームの名称。<br /> * 苗字と名前を分けて管理することが多いが、ここでは単純にひとまとめ。 * @param memberName The value of the column 'MEMBER_NAME'. (basically NotNull if update: for the constraint) */ public void setMemberName(String memberName) { __modifiedProperties.addPropertyName("memberName"); this._memberName = memberName; } /** * [get] MEMBER_ACCOUNT: {UQ, NotNull, VARCHAR(50)} <br /> * 会員アカウント: ログインIDとして利用する。<br /> * 昨今メールアドレスをログインIDとすることが多いので、あまり見かけないかも!? * @return The value of the column 'MEMBER_ACCOUNT'. (basically NotNull if selected: for the constraint) */ public String getMemberAccount() { return _memberAccount; } /** * [set] MEMBER_ACCOUNT: {UQ, NotNull, VARCHAR(50)} <br /> * 会員アカウント: ログインIDとして利用する。<br /> * 昨今メールアドレスをログインIDとすることが多いので、あまり見かけないかも!? * @param memberAccount The value of the column 'MEMBER_ACCOUNT'. (basically NotNull if update: for the constraint) */ public void setMemberAccount(String memberAccount) { __modifiedProperties.addPropertyName("memberAccount"); this._memberAccount = memberAccount; } /** * [get] MEMBER_STATUS_CODE: {IX, NotNull, CHAR(3), FK to MEMBER_STATUS} <br /> * 会員ステータスコード: 会員ステータスを参照するコード。<br /> * ステータスが変わるたびに、このカラムが更新される。 * @return The value of the column 'MEMBER_STATUS_CODE'. (basically NotNull if selected: for the constraint) */ public String getMemberStatusCode() { return _memberStatusCode; } /** * [set] MEMBER_STATUS_CODE: {IX, NotNull, CHAR(3), FK to MEMBER_STATUS} <br /> * 会員ステータスコード: 会員ステータスを参照するコード。<br /> * ステータスが変わるたびに、このカラムが更新される。 * @param memberStatusCode The value of the column 'MEMBER_STATUS_CODE'. (basically NotNull if update: for the constraint) */ public void setMemberStatusCode(String memberStatusCode) { __modifiedProperties.addPropertyName("memberStatusCode"); this._memberStatusCode = memberStatusCode; } /** * [get] FORMALIZED_DATETIME: {IX, TIMESTAMP(23, 10)} <br /> * 正式会員日時: 会員が正式に確定した(正式会員になった)日時。<br /> * 一度確定したらもう二度と更新されないはずだ! * @return The value of the column 'FORMALIZED_DATETIME'. (NullAllowed even if selected: for no constraint) */ public java.time.LocalDateTime getFormalizedDatetime() { return _formalizedDatetime; } /** * [set] FORMALIZED_DATETIME: {IX, TIMESTAMP(23, 10)} <br /> * 正式会員日時: 会員が正式に確定した(正式会員になった)日時。<br /> * 一度確定したらもう二度と更新されないはずだ! * @param formalizedDatetime The value of the column 'FORMALIZED_DATETIME'. (NullAllowed: null update allowed for no constraint) */ public void setFormalizedDatetime(java.time.LocalDateTime formalizedDatetime) { __modifiedProperties.addPropertyName("formalizedDatetime"); this._formalizedDatetime = formalizedDatetime; } /** * [get] BIRTHDATE: {DATE(8)} <br /> * 生年月日: 必須項目ではないので、このデータがない会員もいる。 * @return The value of the column 'BIRTHDATE'. (NullAllowed even if selected: for no constraint) */ public java.time.LocalDate getBirthdate() { return _birthdate; } /** * [set] BIRTHDATE: {DATE(8)} <br /> * 生年月日: 必須項目ではないので、このデータがない会員もいる。 * @param birthdate The value of the column 'BIRTHDATE'. (NullAllowed: null update allowed for no constraint) */ public void setBirthdate(java.time.LocalDate birthdate) { __modifiedProperties.addPropertyName("birthdate"); this._birthdate = birthdate; } /** * [get] REGISTER_DATETIME: {NotNull, TIMESTAMP(23, 10)} <br /> * 登録日時: レコードが登録された日時。<br /> * 会員が登録された日時とほぼ等しいが、そういった業務的な役割を兼務させるのはあまり推奨されない。といいつつ、このテーブルには会員登録日時がない...<br /> * 仕様はどのテーブルでも同じなので、共通カラムの説明はこのテーブルでしか書かない。 * @return The value of the column 'REGISTER_DATETIME'. (basically NotNull if selected: for the constraint) */ public java.time.LocalDateTime getRegisterDatetime() { return _registerDatetime; } /** * [set] REGISTER_DATETIME: {NotNull, TIMESTAMP(23, 10)} <br /> * 登録日時: レコードが登録された日時。<br /> * 会員が登録された日時とほぼ等しいが、そういった業務的な役割を兼務させるのはあまり推奨されない。といいつつ、このテーブルには会員登録日時がない...<br /> * 仕様はどのテーブルでも同じなので、共通カラムの説明はこのテーブルでしか書かない。 * @param registerDatetime The value of the column 'REGISTER_DATETIME'. (basically NotNull if update: for the constraint) */ public void setRegisterDatetime(java.time.LocalDateTime registerDatetime) { __modifiedProperties.addPropertyName("registerDatetime"); this._registerDatetime = registerDatetime; } /** * [get] REGISTER_USER: {NotNull, VARCHAR(200)} <br /> * 登録ユーザ: レコードを登録したユーザ。<br /> * 会員テーブルであれば当然、会員自身であるはずだが、他のテーブルの場合では管理画面から運用者による登録など考えられるので、しっかり保持しておく。 * @return The value of the column 'REGISTER_USER'. (basically NotNull if selected: for the constraint) */ public String getRegisterUser() { return _registerUser; } /** * [set] REGISTER_USER: {NotNull, VARCHAR(200)} <br /> * 登録ユーザ: レコードを登録したユーザ。<br /> * 会員テーブルであれば当然、会員自身であるはずだが、他のテーブルの場合では管理画面から運用者による登録など考えられるので、しっかり保持しておく。 * @param registerUser The value of the column 'REGISTER_USER'. (basically NotNull if update: for the constraint) */ public void setRegisterUser(String registerUser) { __modifiedProperties.addPropertyName("registerUser"); this._registerUser = registerUser; } /** * [get] UPDATE_DATETIME: {NotNull, TIMESTAMP(23, 10)} <br /> * 更新日時: レコードが(最後に)更新された日時。<br /> * 業務的な利用はあまり推奨されないと別項目で説明したが、このカラムはソートの要素としてよく利用される。 * @return The value of the column 'UPDATE_DATETIME'. (basically NotNull if selected: for the constraint) */ public java.time.LocalDateTime getUpdateDatetime() { return _updateDatetime; } /** * [set] UPDATE_DATETIME: {NotNull, TIMESTAMP(23, 10)} <br /> * 更新日時: レコードが(最後に)更新された日時。<br /> * 業務的な利用はあまり推奨されないと別項目で説明したが、このカラムはソートの要素としてよく利用される。 * @param updateDatetime The value of the column 'UPDATE_DATETIME'. (basically NotNull if update: for the constraint) */ public void setUpdateDatetime(java.time.LocalDateTime updateDatetime) { __modifiedProperties.addPropertyName("updateDatetime"); this._updateDatetime = updateDatetime; } /** * [get] UPDATE_USER: {NotNull, VARCHAR(200)} <br /> * 更新ユーザ: レコードを更新したユーザ。<br /> * システムは誰が何をしたのかちゃんと覚えているのさ。 * @return The value of the column 'UPDATE_USER'. (basically NotNull if selected: for the constraint) */ public String getUpdateUser() { return _updateUser; } /** * [set] UPDATE_USER: {NotNull, VARCHAR(200)} <br /> * 更新ユーザ: レコードを更新したユーザ。<br /> * システムは誰が何をしたのかちゃんと覚えているのさ。 * @param updateUser The value of the column 'UPDATE_USER'. (basically NotNull if update: for the constraint) */ public void setUpdateUser(String updateUser) { __modifiedProperties.addPropertyName("updateUser"); this._updateUser = updateUser; } /** * [get] VERSION_NO: {NotNull, BIGINT(19)} <br /> * バージョンNO: データのバージョンを示すナンバー。<br /> * 更新回数と等しく、主に排他制御のために利用される。 * @return The value of the column 'VERSION_NO'. (basically NotNull if selected: for the constraint) */ public Long getVersionNo() { return _versionNo; } /** * [set] VERSION_NO: {NotNull, BIGINT(19)} <br /> * バージョンNO: データのバージョンを示すナンバー。<br /> * 更新回数と等しく、主に排他制御のために利用される。 * @param versionNo The value of the column 'VERSION_NO'. (basically NotNull if update: for the constraint) */ public void setVersionNo(Long versionNo) { __modifiedProperties.addPropertyName("versionNo"); this._versionNo = versionNo; } }
cd0ded81ad7550c96c94ed7e4b8caf1e5575c255
acb69175bbdcd4497483df25ed6b32ccbfc1288b
/src/main/java/cn/pluto/po/IndexExample.java
8fad7541910fc66fdd1539bae9c3b82171e5af0f
[]
no_license
qianyu12138/Pluto
1bd24492bc800ec535441ae02df4ebe3eaddbd20
e4c4bb92114c7e0cce9449685a917bc36192dd58
refs/heads/master
2022-12-21T20:19:59.184584
2019-08-05T12:25:22
2019-08-05T12:25:22
200,643,516
0
0
null
2022-12-16T07:46:34
2019-08-05T11:35:00
JavaScript
UTF-8
Java
false
false
26,509
java
package cn.pluto.po; import java.util.ArrayList; import java.util.Date; import java.util.List; public class IndexExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public IndexExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIidIsNull() { addCriterion("iid is null"); return (Criteria) this; } public Criteria andIidIsNotNull() { addCriterion("iid is not null"); return (Criteria) this; } public Criteria andIidEqualTo(Integer value) { addCriterion("iid =", value, "iid"); return (Criteria) this; } public Criteria andIidNotEqualTo(Integer value) { addCriterion("iid <>", value, "iid"); return (Criteria) this; } public Criteria andIidGreaterThan(Integer value) { addCriterion("iid >", value, "iid"); return (Criteria) this; } public Criteria andIidGreaterThanOrEqualTo(Integer value) { addCriterion("iid >=", value, "iid"); return (Criteria) this; } public Criteria andIidLessThan(Integer value) { addCriterion("iid <", value, "iid"); return (Criteria) this; } public Criteria andIidLessThanOrEqualTo(Integer value) { addCriterion("iid <=", value, "iid"); return (Criteria) this; } public Criteria andIidIn(List<Integer> values) { addCriterion("iid in", values, "iid"); return (Criteria) this; } public Criteria andIidNotIn(List<Integer> values) { addCriterion("iid not in", values, "iid"); return (Criteria) this; } public Criteria andIidBetween(Integer value1, Integer value2) { addCriterion("iid between", value1, value2, "iid"); return (Criteria) this; } public Criteria andIidNotBetween(Integer value1, Integer value2) { addCriterion("iid not between", value1, value2, "iid"); return (Criteria) this; } public Criteria andPanaltextIsNull() { addCriterion("panaltext is null"); return (Criteria) this; } public Criteria andPanaltextIsNotNull() { addCriterion("panaltext is not null"); return (Criteria) this; } public Criteria andPanaltextEqualTo(String value) { addCriterion("panaltext =", value, "panaltext"); return (Criteria) this; } public Criteria andPanaltextNotEqualTo(String value) { addCriterion("panaltext <>", value, "panaltext"); return (Criteria) this; } public Criteria andPanaltextGreaterThan(String value) { addCriterion("panaltext >", value, "panaltext"); return (Criteria) this; } public Criteria andPanaltextGreaterThanOrEqualTo(String value) { addCriterion("panaltext >=", value, "panaltext"); return (Criteria) this; } public Criteria andPanaltextLessThan(String value) { addCriterion("panaltext <", value, "panaltext"); return (Criteria) this; } public Criteria andPanaltextLessThanOrEqualTo(String value) { addCriterion("panaltext <=", value, "panaltext"); return (Criteria) this; } public Criteria andPanaltextLike(String value) { addCriterion("panaltext like", value, "panaltext"); return (Criteria) this; } public Criteria andPanaltextNotLike(String value) { addCriterion("panaltext not like", value, "panaltext"); return (Criteria) this; } public Criteria andPanaltextIn(List<String> values) { addCriterion("panaltext in", values, "panaltext"); return (Criteria) this; } public Criteria andPanaltextNotIn(List<String> values) { addCriterion("panaltext not in", values, "panaltext"); return (Criteria) this; } public Criteria andPanaltextBetween(String value1, String value2) { addCriterion("panaltext between", value1, value2, "panaltext"); return (Criteria) this; } public Criteria andPanaltextNotBetween(String value1, String value2) { addCriterion("panaltext not between", value1, value2, "panaltext"); return (Criteria) this; } public Criteria andBackgroundmusicIsNull() { addCriterion("backgroundmusic is null"); return (Criteria) this; } public Criteria andBackgroundmusicIsNotNull() { addCriterion("backgroundmusic is not null"); return (Criteria) this; } public Criteria andBackgroundmusicEqualTo(String value) { addCriterion("backgroundmusic =", value, "backgroundmusic"); return (Criteria) this; } public Criteria andBackgroundmusicNotEqualTo(String value) { addCriterion("backgroundmusic <>", value, "backgroundmusic"); return (Criteria) this; } public Criteria andBackgroundmusicGreaterThan(String value) { addCriterion("backgroundmusic >", value, "backgroundmusic"); return (Criteria) this; } public Criteria andBackgroundmusicGreaterThanOrEqualTo(String value) { addCriterion("backgroundmusic >=", value, "backgroundmusic"); return (Criteria) this; } public Criteria andBackgroundmusicLessThan(String value) { addCriterion("backgroundmusic <", value, "backgroundmusic"); return (Criteria) this; } public Criteria andBackgroundmusicLessThanOrEqualTo(String value) { addCriterion("backgroundmusic <=", value, "backgroundmusic"); return (Criteria) this; } public Criteria andBackgroundmusicLike(String value) { addCriterion("backgroundmusic like", value, "backgroundmusic"); return (Criteria) this; } public Criteria andBackgroundmusicNotLike(String value) { addCriterion("backgroundmusic not like", value, "backgroundmusic"); return (Criteria) this; } public Criteria andBackgroundmusicIn(List<String> values) { addCriterion("backgroundmusic in", values, "backgroundmusic"); return (Criteria) this; } public Criteria andBackgroundmusicNotIn(List<String> values) { addCriterion("backgroundmusic not in", values, "backgroundmusic"); return (Criteria) this; } public Criteria andBackgroundmusicBetween(String value1, String value2) { addCriterion("backgroundmusic between", value1, value2, "backgroundmusic"); return (Criteria) this; } public Criteria andBackgroundmusicNotBetween(String value1, String value2) { addCriterion("backgroundmusic not between", value1, value2, "backgroundmusic"); return (Criteria) this; } public Criteria andContactqqIsNull() { addCriterion("contactqq is null"); return (Criteria) this; } public Criteria andContactqqIsNotNull() { addCriterion("contactqq is not null"); return (Criteria) this; } public Criteria andContactqqEqualTo(String value) { addCriterion("contactqq =", value, "contactqq"); return (Criteria) this; } public Criteria andContactqqNotEqualTo(String value) { addCriterion("contactqq <>", value, "contactqq"); return (Criteria) this; } public Criteria andContactqqGreaterThan(String value) { addCriterion("contactqq >", value, "contactqq"); return (Criteria) this; } public Criteria andContactqqGreaterThanOrEqualTo(String value) { addCriterion("contactqq >=", value, "contactqq"); return (Criteria) this; } public Criteria andContactqqLessThan(String value) { addCriterion("contactqq <", value, "contactqq"); return (Criteria) this; } public Criteria andContactqqLessThanOrEqualTo(String value) { addCriterion("contactqq <=", value, "contactqq"); return (Criteria) this; } public Criteria andContactqqLike(String value) { addCriterion("contactqq like", value, "contactqq"); return (Criteria) this; } public Criteria andContactqqNotLike(String value) { addCriterion("contactqq not like", value, "contactqq"); return (Criteria) this; } public Criteria andContactqqIn(List<String> values) { addCriterion("contactqq in", values, "contactqq"); return (Criteria) this; } public Criteria andContactqqNotIn(List<String> values) { addCriterion("contactqq not in", values, "contactqq"); return (Criteria) this; } public Criteria andContactqqBetween(String value1, String value2) { addCriterion("contactqq between", value1, value2, "contactqq"); return (Criteria) this; } public Criteria andContactqqNotBetween(String value1, String value2) { addCriterion("contactqq not between", value1, value2, "contactqq"); return (Criteria) this; } public Criteria andContectemailIsNull() { addCriterion("contectemail is null"); return (Criteria) this; } public Criteria andContectemailIsNotNull() { addCriterion("contectemail is not null"); return (Criteria) this; } public Criteria andContectemailEqualTo(String value) { addCriterion("contectemail =", value, "contectemail"); return (Criteria) this; } public Criteria andContectemailNotEqualTo(String value) { addCriterion("contectemail <>", value, "contectemail"); return (Criteria) this; } public Criteria andContectemailGreaterThan(String value) { addCriterion("contectemail >", value, "contectemail"); return (Criteria) this; } public Criteria andContectemailGreaterThanOrEqualTo(String value) { addCriterion("contectemail >=", value, "contectemail"); return (Criteria) this; } public Criteria andContectemailLessThan(String value) { addCriterion("contectemail <", value, "contectemail"); return (Criteria) this; } public Criteria andContectemailLessThanOrEqualTo(String value) { addCriterion("contectemail <=", value, "contectemail"); return (Criteria) this; } public Criteria andContectemailLike(String value) { addCriterion("contectemail like", value, "contectemail"); return (Criteria) this; } public Criteria andContectemailNotLike(String value) { addCriterion("contectemail not like", value, "contectemail"); return (Criteria) this; } public Criteria andContectemailIn(List<String> values) { addCriterion("contectemail in", values, "contectemail"); return (Criteria) this; } public Criteria andContectemailNotIn(List<String> values) { addCriterion("contectemail not in", values, "contectemail"); return (Criteria) this; } public Criteria andContectemailBetween(String value1, String value2) { addCriterion("contectemail between", value1, value2, "contectemail"); return (Criteria) this; } public Criteria andContectemailNotBetween(String value1, String value2) { addCriterion("contectemail not between", value1, value2, "contectemail"); return (Criteria) this; } public Criteria andContectmobileIsNull() { addCriterion("contectmobile is null"); return (Criteria) this; } public Criteria andContectmobileIsNotNull() { addCriterion("contectmobile is not null"); return (Criteria) this; } public Criteria andContectmobileEqualTo(String value) { addCriterion("contectmobile =", value, "contectmobile"); return (Criteria) this; } public Criteria andContectmobileNotEqualTo(String value) { addCriterion("contectmobile <>", value, "contectmobile"); return (Criteria) this; } public Criteria andContectmobileGreaterThan(String value) { addCriterion("contectmobile >", value, "contectmobile"); return (Criteria) this; } public Criteria andContectmobileGreaterThanOrEqualTo(String value) { addCriterion("contectmobile >=", value, "contectmobile"); return (Criteria) this; } public Criteria andContectmobileLessThan(String value) { addCriterion("contectmobile <", value, "contectmobile"); return (Criteria) this; } public Criteria andContectmobileLessThanOrEqualTo(String value) { addCriterion("contectmobile <=", value, "contectmobile"); return (Criteria) this; } public Criteria andContectmobileLike(String value) { addCriterion("contectmobile like", value, "contectmobile"); return (Criteria) this; } public Criteria andContectmobileNotLike(String value) { addCriterion("contectmobile not like", value, "contectmobile"); return (Criteria) this; } public Criteria andContectmobileIn(List<String> values) { addCriterion("contectmobile in", values, "contectmobile"); return (Criteria) this; } public Criteria andContectmobileNotIn(List<String> values) { addCriterion("contectmobile not in", values, "contectmobile"); return (Criteria) this; } public Criteria andContectmobileBetween(String value1, String value2) { addCriterion("contectmobile between", value1, value2, "contectmobile"); return (Criteria) this; } public Criteria andContectmobileNotBetween(String value1, String value2) { addCriterion("contectmobile not between", value1, value2, "contectmobile"); return (Criteria) this; } public Criteria andContectaddressIsNull() { addCriterion("contectaddress is null"); return (Criteria) this; } public Criteria andContectaddressIsNotNull() { addCriterion("contectaddress is not null"); return (Criteria) this; } public Criteria andContectaddressEqualTo(String value) { addCriterion("contectaddress =", value, "contectaddress"); return (Criteria) this; } public Criteria andContectaddressNotEqualTo(String value) { addCriterion("contectaddress <>", value, "contectaddress"); return (Criteria) this; } public Criteria andContectaddressGreaterThan(String value) { addCriterion("contectaddress >", value, "contectaddress"); return (Criteria) this; } public Criteria andContectaddressGreaterThanOrEqualTo(String value) { addCriterion("contectaddress >=", value, "contectaddress"); return (Criteria) this; } public Criteria andContectaddressLessThan(String value) { addCriterion("contectaddress <", value, "contectaddress"); return (Criteria) this; } public Criteria andContectaddressLessThanOrEqualTo(String value) { addCriterion("contectaddress <=", value, "contectaddress"); return (Criteria) this; } public Criteria andContectaddressLike(String value) { addCriterion("contectaddress like", value, "contectaddress"); return (Criteria) this; } public Criteria andContectaddressNotLike(String value) { addCriterion("contectaddress not like", value, "contectaddress"); return (Criteria) this; } public Criteria andContectaddressIn(List<String> values) { addCriterion("contectaddress in", values, "contectaddress"); return (Criteria) this; } public Criteria andContectaddressNotIn(List<String> values) { addCriterion("contectaddress not in", values, "contectaddress"); return (Criteria) this; } public Criteria andContectaddressBetween(String value1, String value2) { addCriterion("contectaddress between", value1, value2, "contectaddress"); return (Criteria) this; } public Criteria andContectaddressNotBetween(String value1, String value2) { addCriterion("contectaddress not between", value1, value2, "contectaddress"); return (Criteria) this; } public Criteria andLastloginIsNull() { addCriterion("lastlogin is null"); return (Criteria) this; } public Criteria andLastloginIsNotNull() { addCriterion("lastlogin is not null"); return (Criteria) this; } public Criteria andLastloginEqualTo(Date value) { addCriterion("lastlogin =", value, "lastlogin"); return (Criteria) this; } public Criteria andLastloginNotEqualTo(Date value) { addCriterion("lastlogin <>", value, "lastlogin"); return (Criteria) this; } public Criteria andLastloginGreaterThan(Date value) { addCriterion("lastlogin >", value, "lastlogin"); return (Criteria) this; } public Criteria andLastloginGreaterThanOrEqualTo(Date value) { addCriterion("lastlogin >=", value, "lastlogin"); return (Criteria) this; } public Criteria andLastloginLessThan(Date value) { addCriterion("lastlogin <", value, "lastlogin"); return (Criteria) this; } public Criteria andLastloginLessThanOrEqualTo(Date value) { addCriterion("lastlogin <=", value, "lastlogin"); return (Criteria) this; } public Criteria andLastloginIn(List<Date> values) { addCriterion("lastlogin in", values, "lastlogin"); return (Criteria) this; } public Criteria andLastloginNotIn(List<Date> values) { addCriterion("lastlogin not in", values, "lastlogin"); return (Criteria) this; } public Criteria andLastloginBetween(Date value1, Date value2) { addCriterion("lastlogin between", value1, value2, "lastlogin"); return (Criteria) this; } public Criteria andLastloginNotBetween(Date value1, Date value2) { addCriterion("lastlogin not between", value1, value2, "lastlogin"); return (Criteria) this; } public Criteria andSpIsNull() { addCriterion("sp is null"); return (Criteria) this; } public Criteria andSpIsNotNull() { addCriterion("sp is not null"); return (Criteria) this; } public Criteria andSpEqualTo(String value) { addCriterion("sp =", value, "sp"); return (Criteria) this; } public Criteria andSpNotEqualTo(String value) { addCriterion("sp <>", value, "sp"); return (Criteria) this; } public Criteria andSpGreaterThan(String value) { addCriterion("sp >", value, "sp"); return (Criteria) this; } public Criteria andSpGreaterThanOrEqualTo(String value) { addCriterion("sp >=", value, "sp"); return (Criteria) this; } public Criteria andSpLessThan(String value) { addCriterion("sp <", value, "sp"); return (Criteria) this; } public Criteria andSpLessThanOrEqualTo(String value) { addCriterion("sp <=", value, "sp"); return (Criteria) this; } public Criteria andSpLike(String value) { addCriterion("sp like", value, "sp"); return (Criteria) this; } public Criteria andSpNotLike(String value) { addCriterion("sp not like", value, "sp"); return (Criteria) this; } public Criteria andSpIn(List<String> values) { addCriterion("sp in", values, "sp"); return (Criteria) this; } public Criteria andSpNotIn(List<String> values) { addCriterion("sp not in", values, "sp"); return (Criteria) this; } public Criteria andSpBetween(String value1, String value2) { addCriterion("sp between", value1, value2, "sp"); return (Criteria) this; } public Criteria andSpNotBetween(String value1, String value2) { addCriterion("sp not between", value1, value2, "sp"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
1c95ec39b521e20cb213e8ab2fac749a10453e89
5b323ddc52c74ac9a209b4f46573d264f066191a
/src/com/example/java/MaxValues.java
56934f1ffd20fd3e94cd4fa2c4e5c932911279a3
[]
no_license
creightonja/java_exercizes
b2b89de40032a35ef5655f510fd5bb20581a8b80
1924bbe4dc3ea84004e121e1de15513f690ec0ea
refs/heads/master
2021-01-10T13:16:28.184884
2015-11-29T20:05:20
2015-11-29T20:05:20
47,056,500
0
0
null
null
null
null
UTF-8
Java
false
false
323
java
package com.example.java; /** * Created by creightonja on 11/29/15. */ public class MaxValues { public static void main(String[] args) { byte b = 127; System.out.println("Byte: " + b); if (b < Byte.MAX_VALUE) { b++; } System.out.println("Byte: " + b); } }
8c5d9d3d9fe415dc7f7e5eb8a57fba37e769718f
7f0e68bfc4f5a9517f6f0d28e1ef262561b9feb6
/05/CarC.java
87875bbae3bc09b1c4f74529e0d74dc609f000d8
[]
no_license
wuzhitian/javaLearn
b2967091013b9ab587bb283e3078b13ffac64565
d6b03d44cf55af996252f600128b67f31ce93db0
refs/heads/master
2021-01-10T01:53:18.213645
2016-02-26T09:25:47
2016-02-26T09:25:47
52,072,144
0
0
null
null
null
null
UTF-8
Java
false
false
403
java
class Car { String color = "red"; int num = 4; void run() { System.out.println(color+"...."+num); } } class CarC { public static void main(String[] args) { Car c1 = new Car(); c1.run(); //red....4 c1.num = 5; c1.run(); //red....5 Car c2 = c1; c2.color = "green"; //green....4 c1.run(); // c2.num = "AA"; //不兼容的类型: String无法转换为int c1.run(); } }
dbf681861e0fdb127f11a1783d950751a87f677e
0ce375be091d02e85c3210d70d294594ad73d5a7
/JavaProjekat/src/gui/prikaz/ServisiGUI.java
9a3e674df14538b7da54de591f981c8d7f9fe5b6
[]
no_license
isak007/ServisAutomobilaProjekat
bcfb38ced1b336b4c2f4c64eb8cbdc3f3084d0aa
ef49820f7a4dce05076c1890fd658a122a5c3602
refs/heads/master
2022-11-26T16:06:50.854380
2020-07-31T10:59:55
2020-07-31T10:59:55
263,969,618
0
0
null
null
null
null
UTF-8
Java
false
false
11,935
java
package gui.prikaz; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JToolBar; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableModel; import aplikacija.Pronadji; import citanjePisanje.CitanjePisanje; import enumeracije.StatusServisa; import funkcije.AdminFunkcije; import gui.izmena.IzmenaServisaGUI; import modeli.Administrator; import modeli.Musterija; import modeli.Servis; import modeli.Serviser; import modeli.ServisniDeo; public class ServisiGUI extends JFrame{ // treba da dijele ovaj prikaz admin i serviser // id kao identifikator da bi znao GUI da li prikazuje za Admin ili za Servisera opcije private JToolBar mainToolbar = new JToolBar(); private JButton btnAdd = new JButton(); private JButton btnEdit = new JButton(); private JButton btnDelete = new JButton(); private JButton btnZavrsiServis = new JButton("Zavrsi servis"); private JLabel lblBrojBodova; private JLabel lblDug; private DefaultTableModel tableModel; private JTable servisiTabela; private String korisnikID; private Administrator admin; private Serviser serviser; private Musterija musterija; public ServisiGUI(String korisnikID) { AdminFunkcije af = new AdminFunkcije(null); af.inicijalizacijaPromjena(); this.korisnikID = korisnikID; this.admin = Pronadji.pronadjiAdmina(korisnikID, "", ""); this.serviser = Pronadji.pronadjiServisera(korisnikID, "", ""); this.musterija = Pronadji.pronadjiMusteriju(korisnikID, "", ""); setTitle("Servisi"); setSize(500, 300); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setLocationRelativeTo(null); initGUI(); initActions(); } private void initGUI() { ImageIcon addIcon = new ImageIcon(getClass().getResource("/slike/add.gif")); btnAdd.setIcon(addIcon); ImageIcon editIcon = new ImageIcon(getClass().getResource("/slike/edit.gif")); btnEdit.setIcon(editIcon); ImageIcon deleteIcon = new ImageIcon(getClass().getResource("/slike/remove.gif")); btnDelete.setIcon(deleteIcon); ArrayList<Servis> listaServisa = new ArrayList<Servis>(); if (musterija != null) { listaServisa = musterija.getListaSvihServisa(); mainToolbar.add(btnDelete); if(musterija.getListaZavrsenihServisa().size()>0) { String poruka = "Imate neotplacenih servisa. Da li zelite da iskoristite bodove za placanje?"; int izbor = JOptionPane.showConfirmDialog(null, poruka, "Potvrda", JOptionPane.YES_NO_OPTION); double dug = musterija.getDug(); double cenaServisa = 0; for (Servis servis : musterija.getListaZavrsenihServisa()) { servis.setOtplacen("da"); cenaServisa += servis.getCena(); for(ServisniDeo sd : servis.getListaDelova()) { cenaServisa += sd.getCena(); } } if(izbor == JOptionPane.YES_OPTION) { if (musterija.getBrojSakupljenihBodova() > 0) { double pocetniDug = cenaServisa; for (int i = 0; i < musterija.getBrojSakupljenihBodova(); i++) { cenaServisa -= pocetniDug*(2.0/100.0); } musterija.setBrojSakupljenihBodova(0); } else { JOptionPane.showMessageDialog(null, "Trenutno nemate sakupljenih bodova.", "Greska", JOptionPane.WARNING_MESSAGE); musterija.setBrojSakupljenihBodova(musterija.getBrojSakupljenihBodova()+1); if(musterija.getBrojSakupljenihBodova() > 10) { musterija.setBrojSakupljenihBodova(10); } } } else { musterija.setBrojSakupljenihBodova(musterija.getBrojSakupljenihBodova()+1); if(musterija.getBrojSakupljenihBodova() > 10) { musterija.setBrojSakupljenihBodova(10); } } JOptionPane.showMessageDialog(null, "Servisi otplaceni.\nCena servisa: "+cenaServisa, "Potvrda", JOptionPane.INFORMATION_MESSAGE); dug += cenaServisa; musterija.setDug(dug); musterija.setListaZavrsenihServisa(new ArrayList<Servis>()); CitanjePisanje.izmenaPodataka(CitanjePisanje.musterijaZaUpis(), "musterija.txt"); CitanjePisanje.izmenaPodataka(CitanjePisanje.servisZaUpis(), "servis.txt"); } lblBrojBodova = new JLabel(" Broj sakupljenih bodova: "+String.valueOf(musterija.getBrojSakupljenihBodova())); mainToolbar.add(lblBrojBodova); lblDug = new JLabel(" Dug: "+musterija.getDug()); mainToolbar.add(lblDug); } else { mainToolbar.add(btnAdd); mainToolbar.add(btnEdit); if (admin != null) { mainToolbar.add(btnDelete); listaServisa = Administrator.getListaSvihServisa(); } else if (serviser != null) { listaServisa = serviser.getListaServisa(); for (Servis servis : listaServisa) { if (servis.getStatusServisa().equals(StatusServisa.U_TOKU)){ mainToolbar.add(btnZavrsiServis); break; } } } } add(mainToolbar, BorderLayout.NORTH); String[] zaglavlja = new String[] {"ID", "Automobil ID", "Serviser", "Termin", "Opis","Status"}; Object[][] sadrzaj = new Object[listaServisa.size()][zaglavlja.length]; for(int i = 0; i< listaServisa.size(); i++) { Servis servis = listaServisa.get(i); sadrzaj[i][0] = servis.getId(); sadrzaj[i][1] = servis.getAutomobil().getId(); sadrzaj[i][2] = servis.getServiser().getKorisinickoIme(); sadrzaj[i][3] = servis.getTermin(); sadrzaj[i][4] = servis.getOpis(); sadrzaj[i][5] = servis.getStatusServisa().toString(); } // pravljenje tabele od korisnika tableModel = new DefaultTableModel(sadrzaj, zaglavlja); servisiTabela = new JTable(tableModel); servisiTabela.setRowSelectionAllowed(true); servisiTabela.setColumnSelectionAllowed(false); servisiTabela.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); servisiTabela.setDefaultEditor(Object.class, null); servisiTabela.getTableHeader().setReorderingAllowed(false); JScrollPane scrollPane = new JScrollPane(servisiTabela); add(scrollPane, BorderLayout.CENTER); } // trenutno gotovo akcija za brisanje korisnika... private void initActions() { btnDelete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int red = servisiTabela.getSelectedRow(); if(red == -1) { JOptionPane.showMessageDialog(null, "Morate odabrati red u tabeli.", "Greska", JOptionPane.WARNING_MESSAGE); } else { String servisID = tableModel.getValueAt(red, 0).toString(); Servis servis = Pronadji.pronadjiServis(servisID); if (musterija != null) { if (!servis.getStatusServisa().equals(StatusServisa.ZAKAZAN)) { JOptionPane.showMessageDialog(null, "Nije moguce otkazati ovaj servis.", "Greska", JOptionPane.WARNING_MESSAGE); } else { int izbor = JOptionPane.showConfirmDialog(null, "Da li ste sigurni da zelite da otkazete servis?", servisID + " - Porvrda otkazivanja", JOptionPane.YES_NO_OPTION); if(izbor == JOptionPane.YES_OPTION) { servis.setStatusServisa(StatusServisa.OTKAZAN); CitanjePisanje.izmenaPodataka(CitanjePisanje.servisZaUpis(), "servis.txt"); ServisiGUI.this.dispose(); ServisiGUI.this.setVisible(false); } } } else { int izbor = JOptionPane.showConfirmDialog(null, "Da li ste sigurni da zelite da obrisete servis?", servisID + " - Porvrda brisanja", JOptionPane.YES_NO_OPTION); if(izbor == JOptionPane.YES_OPTION) { AdminFunkcije af = new AdminFunkcije(null); servis.setObrisan("da"); tableModel.removeRow(red); // azuriranje fajla CitanjePisanje.izmenaPodataka(CitanjePisanje.servisZaUpis(), "servis.txt"); // uklanjanje iz liste af.dodajUkloniServis(servis, "ukloni"); } } } } }); // zavrsavanje servisa btnZavrsiServis.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int red = servisiTabela.getSelectedRow(); if(red == -1) { JOptionPane.showMessageDialog(null, "Morate odabrati red u tabeli.", "Greska", JOptionPane.WARNING_MESSAGE); } else { String servisID = tableModel.getValueAt(red, 0).toString(); Servis servis = Pronadji.pronadjiServis(servisID); if(servis.getStatusServisa().equals(StatusServisa.U_TOKU)) { int izbor = JOptionPane.showConfirmDialog(null, "Da li ste sigurni da zelite da zavrsite servis?", "Potvrda", JOptionPane.YES_NO_OPTION); if(izbor == JOptionPane.YES_OPTION) { if (servis.getCena() == 0) { String input = JOptionPane.showInputDialog("Unesite cenu servisa"); if (input != null) { try{ double cena = Double.parseDouble(input); servis.setCena(cena); servis.setStatusServisa(StatusServisa.ZAVRSEN); ArrayList<Servis> listaNeotplacenihS = servis.getAutomobil().getVlasnik().getListaZavrsenihServisa(); listaNeotplacenihS.add(servis); servis.getAutomobil().getVlasnik().setListaZavrsenihServisa(listaNeotplacenihS); CitanjePisanje.izmenaPodataka(CitanjePisanje.servisZaUpis(), "servis.txt"); ServisiGUI.this.dispose(); ServisiGUI.this.setVisible(false); } catch(NumberFormatException ex) { JOptionPane.showMessageDialog(null, "Niste uneli validnu cenu.", "Greska", JOptionPane.WARNING_MESSAGE); } } } else { servis.setStatusServisa(StatusServisa.ZAVRSEN); ArrayList<Servis> listaNeotplacenihS = servis.getAutomobil().getVlasnik().getListaZavrsenihServisa(); listaNeotplacenihS.add(servis); servis.getAutomobil().getVlasnik().setListaZavrsenihServisa(listaNeotplacenihS); CitanjePisanje.izmenaPodataka(CitanjePisanje.servisZaUpis(), "servis.txt"); ServisiGUI.this.dispose(); ServisiGUI.this.setVisible(false); } } } else { String poruka = "Nije moguce zavrsiti servis koji nije u toku."; JOptionPane.showMessageDialog(null, poruka, "Greska", JOptionPane.WARNING_MESSAGE); } } } }); // dodavanje korisnika, otvara drugi GUI prozor namijenjen za dodavanje/izmenu btnAdd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RezervacijeGUI rez = new RezervacijeGUI(korisnikID); rez.setVisible(true); ServisiGUI.this.dispose(); ServisiGUI.this.setVisible(false); } }); // izmena korisnika, isti prozor samo za izmenu btnEdit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int red = servisiTabela.getSelectedRow(); if(red == -1) { JOptionPane.showMessageDialog(null, "Morate odabrati red u tabeli.", "Greska", JOptionPane.WARNING_MESSAGE); } else { String servisID = tableModel.getValueAt(red, 0).toString(); Servis servis = Pronadji.pronadjiServis(servisID); if(servis.getStatusServisa().equals(StatusServisa.ZAKAZAN)) { IzmenaServisaGUI is = new IzmenaServisaGUI(korisnikID, servisID,"",""); is.setVisible(true); ServisiGUI.this.dispose(); ServisiGUI.this.setVisible(false); } else { String poruka = "Nije moguca izmena ovog servisa."; JOptionPane.showMessageDialog(null, poruka, "Greska", JOptionPane.WARNING_MESSAGE); } } } }); } }
[ "gandalf124@gandalf" ]
gandalf124@gandalf
8b3b670fd18b4e9771ca891ebf2ffb8b493a83d4
7c2ed4618f05a2bdf749fc4ebaa571a2d79a3717
/tst/testTriangle.java
73e2b963b715e868d0f556a635d36cf1877b22f4
[]
no_license
RigobertoVincent/EGR_323_assignments
0c72ca6724838918c7630db0f39d5f1c85aba54e
c034dffb01949a126d5b71424bcad3a2ccf4ac99
refs/heads/main
2023-04-09T02:49:01.205759
2021-04-22T03:20:22
2021-04-22T03:20:22
356,071,423
0
0
null
null
null
null
UTF-8
Java
false
false
1,512
java
import org.junit.Assert; import org.junit.Test; public class testTriangle { @Test public void equalateralTriTest(){ Triangle triangle = new Triangle(3,3,3); Assert.assertTrue(triangle.isEquilateral()); } @Test public void equalateralTriTest1(){ Triangle triangle = new Triangle(1,1,1); Assert.assertTrue(triangle.isEquilateral()); } @Test public void equalateralZeroTriTest(){ Triangle triangle = new Triangle(0,0,0); Assert.assertFalse("Zero cannot be a value",triangle.isEquilateral()); } @Test public void IscolisTriTest(){ Triangle triangle = new Triangle(3,4,3); Assert.assertTrue("", triangle.isIsosceles()); } @Test public void IscolisTriTest2(){ Triangle triangle = new Triangle(4,4,5); Assert.assertTrue("", triangle.isIsosceles()); } @Test public void scaleneTriTest(){ Triangle triangle = new Triangle(3,4,5); Assert.assertTrue("", triangle.isScalene()); } @Test public void scaleneTriTest1(){ Triangle triangle = new Triangle(5,4,3); Assert.assertTrue("", triangle.isScalene()); } @Test public void scaleneTriTest2(){ Triangle triangle = new Triangle(1,2,1); Assert.assertFalse("", triangle.isScalene()); } @Test public void scaleneTriTest3(){ Triangle triangle = new Triangle(1,0,1); Assert.assertFalse("", triangle.isScalene()); } }
e5bb98de17139a08c214a4b9e3f9173c334d66af
b6450cc5c18068a99bc3e2bc7064e119ed026fa6
/PomeloOrder/credit-help-server/src/main/java/com/ryit/credithelpserver/feign/hystrix/MessageFeignHystrix.java
efe035092a8498e877fc1228813bfc0cccc3defe
[ "Apache-2.0" ]
permissive
samphin/finish-projects
0f36eec553d49c04454a3871e85bd385f46173ae
19d2cb352e8c8209867573e6de00f144ddbe124e
refs/heads/master
2022-12-28T05:51:02.774038
2020-04-03T09:13:52
2020-04-03T09:13:52
225,137,147
1
2
Apache-2.0
2022-12-16T00:39:36
2019-12-01T09:38:16
Java
UTF-8
Java
false
false
749
java
package com.ryit.credithelpserver.feign.hystrix; import com.ryit.commons.entity.dto.PushMessageDto; import com.ryit.commons.web.exception.user.CustomException; import com.ryit.credithelpserver.feign.MessageFeignClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * @author: zhangweixun * @Date: 2019/10/18 0018下午 4:31 */ @Component public class MessageFeignHystrix implements MessageFeignClient { private Logger log = LoggerFactory.getLogger(MessageFeignHystrix.class); @Override public void push(PushMessageDto pushMessageDto) { log.error("极光推送消息服务中断"); throw new CustomException("极光推送消息服务中断"); } }
31d98aeb0032f5b11504ada0f59603bc0ac5c8d8
90ffdaebd7311b6eb9700ba0c7e1371f6c8153a3
/src/abmin/StudantData.java
ae2f48ea209a92010812b0f526e3514a696e8f98
[]
no_license
mookchayanis/UIDEMO_359211110064
74f31f41f330dba9ca03d93fa1d11714d0f82072
2af5caf7e1d5cf592915ae1eb8416b3c57e116ec
refs/heads/master
2021-04-27T11:29:28.088648
2018-02-25T10:10:51
2018-02-25T10:10:51
122,559,618
0
0
null
null
null
null
UTF-8
Java
false
false
2,081
java
package abmin; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class StudantData { //properties of object private final StringProperty id; private final StringProperty firstName; private final StringProperty lastName; private final StringProperty email; private final StringProperty DOB; //constrructir public StudantData(StringProperty id, StringProperty firstName, StringProperty lastName, StringProperty email, StringProperty DOB) { this.id = new SimpleStringProperty(id); this.firstName = new SimpleStringProperty(firstName); this.lastName = new SimpleStringProperty(lastName); this.email = new SimpleStringProperty(email); this.DOB = new SimpleStringProperty(DOB); //getter and setter methods public String getId() { return id.get(); }public StringProperty idProperty() { return id; } //public void setId(String id) { // this.id.set(id); }public String getFirstName() { return firstName.get(); }public StringProperty firstNameProperty() { return firstName; }public void setFirstName(String firstName) { this.firstName.set(firstName); }public String getLastName() { return lastName.get(); }public StringProperty lastNameProperty() { return lastName; }public void setLastName(String lastName) { this.lastName.set(lastName); }public String getEmail() { return email.get(); }public StringProperty emailProperty() { return email; }public void setEmail(String email) { this.email.set(email); }public String getDOB() { return DOB.get(); }public StringProperty DOBProperty() { return DOB; }public void setDOB(String DOB) { this.DOB.set(DOB); } }
37143bbf28b219f0e390084463ad7b502483cf14
ac863bcfbaddc257035bbac98475a86f3aa08d32
/src/com/tedu/entity/OrderItem.java
ac48830de01bc1d4764ea30090257e41e777f08b
[]
no_license
hunter6073/album-forever
fe923856a84b8127f82832f02095483feb8036a3
50c556f0465e888135cd5f6ef0db9f7635dadf4d
refs/heads/master
2020-06-13T06:03:24.291383
2019-08-03T15:49:58
2019-08-03T15:49:58
194,563,971
0
0
null
null
null
null
UTF-8
Java
false
false
1,406
java
package com.tedu.entity; import org.springframework.stereotype.Component; @Component public class OrderItem { private int id; private String receiptid; private String albumid; private String albumname; private float price; private String number; private String albumimage; private float subTotal; private float total; public int getId() { return id; } public void setId(int id) { this.id = id; } public void setAlbumid(String albumid) { this.albumid = albumid; } public String getAlbumid() { return albumid; } public void setNumber(String number) { this.number = number; } public String getNumber() { return number; } public void setReceiptid(String receiptid) { this.receiptid = receiptid; } public String getReceiptid() { return receiptid; } public void setPrice(float price) { this.price = price; } public float getPrice() { return price; } public void setAlbumname(String albumname) { this.albumname = albumname; } public String getAlbumname() { return albumname; } public void setSubTotal(float subTotal) { this.subTotal = subTotal; } public float getSubTotal() { return subTotal; } public void setTotal(float total) { this.total = total; } public float getTotal() { return total; } public void setAlbumimage(String albumimage) { this.albumimage = albumimage; } public String getAlbumimage() { return albumimage; } }
a67edc97e5815d58b3494e2f87fb1d12eeba60a0
3561496d1a3483db27933a7b1f6c4290a9088180
/src/test/java/pegasus/application/web/rest/UserJWTControllerIntTest.java
93f8ea862bcddee13237d91eea24293271e770b3
[]
no_license
pavindersingh/pegasus-app
20c13d0ad65e5d9590be5301f6399c9622fd1315
de597a00bee2c4fb33f19a53246c3dae3319930b
refs/heads/master
2020-03-28T04:51:20.702038
2018-09-06T22:33:34
2018-09-06T22:33:34
147,740,946
0
0
null
null
null
null
UTF-8
Java
false
false
4,871
java
package pegasus.application.web.rest; import pegasus.application.PegasusApp; import pegasus.application.domain.User; import pegasus.application.repository.UserRepository; import pegasus.application.security.jwt.TokenProvider; import pegasus.application.web.rest.errors.ExceptionTranslator; import pegasus.application.web.rest.vm.LoginVM; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.isEmptyString; import static org.hamcrest.Matchers.not; /** * Test class for the UserJWTController REST controller. * * @see UserJWTController */ @RunWith(SpringRunner.class) @SpringBootTest(classes = PegasusApp.class) public class UserJWTControllerIntTest { @Autowired private TokenProvider tokenProvider; @Autowired private AuthenticationManager authenticationManager; @Autowired private UserRepository userRepository; @Autowired private PasswordEncoder passwordEncoder; @Autowired private ExceptionTranslator exceptionTranslator; private MockMvc mockMvc; @Before public void setup() { UserJWTController userJWTController = new UserJWTController(tokenProvider, authenticationManager); this.mockMvc = MockMvcBuilders.standaloneSetup(userJWTController) .setControllerAdvice(exceptionTranslator) .build(); } @Test @Transactional public void testAuthorize() throws Exception { User user = new User(); user.setLogin("user-jwt-controller"); user.setEmail("[email protected]"); user.setActivated(true); user.setPassword(passwordEncoder.encode("test")); userRepository.saveAndFlush(user); LoginVM login = new LoginVM(); login.setUsername("user-jwt-controller"); login.setPassword("test"); mockMvc.perform(post("/api/authenticate") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(login))) .andExpect(status().isOk()) .andExpect(jsonPath("$.id_token").isString()) .andExpect(jsonPath("$.id_token").isNotEmpty()) .andExpect(header().string("Authorization", not(nullValue()))) .andExpect(header().string("Authorization", not(isEmptyString()))); } @Test @Transactional public void testAuthorizeWithRememberMe() throws Exception { User user = new User(); user.setLogin("user-jwt-controller-remember-me"); user.setEmail("[email protected]"); user.setActivated(true); user.setPassword(passwordEncoder.encode("test")); userRepository.saveAndFlush(user); LoginVM login = new LoginVM(); login.setUsername("user-jwt-controller-remember-me"); login.setPassword("test"); login.setRememberMe(true); mockMvc.perform(post("/api/authenticate") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(login))) .andExpect(status().isOk()) .andExpect(jsonPath("$.id_token").isString()) .andExpect(jsonPath("$.id_token").isNotEmpty()) .andExpect(header().string("Authorization", not(nullValue()))) .andExpect(header().string("Authorization", not(isEmptyString()))); } @Test @Transactional public void testAuthorizeFails() throws Exception { LoginVM login = new LoginVM(); login.setUsername("wrong-user"); login.setPassword("wrong password"); mockMvc.perform(post("/api/authenticate") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(login))) .andExpect(status().isUnauthorized()) .andExpect(jsonPath("$.id_token").doesNotExist()) .andExpect(header().doesNotExist("Authorization")); } }
706d91fb4afe2c971d3c1265ff3d9572b7a3a9bc
c84088fed6a7b4f392810bb166e66dbfe3df4286
/BackCRM/src/main/service/BackVisitService.java
3a6caae7a220c3bf6396d2b04dc5c7dd5a867949
[]
no_license
1Will/Work1
4c419b9013d2989c4bbe6721c155de609e5ce9b5
16e707588da13e9dede5f7de97ca53e15a7d5a78
refs/heads/master
2020-05-22T16:52:56.501596
2018-03-20T01:21:01
2018-03-20T01:21:01
84,697,600
0
0
null
null
null
null
GB18030
Java
false
false
726
java
package main.service; import java.util.List; import main.pojo.BackVisit; import org.hibernate.Session; public interface BackVisitService { public void saveBackVisit(BackVisit backVisit); public void updateBackVisit(BackVisit backVisit);//更新实体 public List<BackVisit> getBackVisitByDate(String date,String name);//根据日期和姓名返回backVisit集合 public List<BackVisit> getAllBackVisit(Long[] backVisitIds);//根据ids返回backlist集合 public List<BackVisit> getBackVisitByCustomerName(String customerName);//根据customerName 按回访日期倒序排列返回backlist集合 public BackVisit getBackVisitById(Long id);//根据id返回backlist public Session getSuperSession(); }
877db14a95ff60476f339bad2ee3ede6c3d5a4a4
be73270af6be0a811bca4f1710dc6a038e4a8fd2
/crash-reproduction-moho/results/XWIKI-14122-18-5-FEMO-WeightedSum:TestLen:CallDiversity/com/xpn/xwiki/store/XWikiHibernateStore_ESTest.java
9f5d8b60997a36d8e45b11166987502048ba7d7c
[]
no_license
STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application
cf118b23ecb87a8bf59643e42f7556b521d1f754
3bb39683f9c343b8ec94890a00b8f260d158dfe3
refs/heads/master
2022-07-29T14:44:00.774547
2020-08-10T15:14:49
2020-08-10T15:14:49
285,804,495
0
0
null
null
null
null
UTF-8
Java
false
false
564
java
/* * This file was automatically generated by EvoSuite * Sun Apr 05 11:19:38 UTC 2020 */ package com.xpn.xwiki.store; import org.junit.Test; import static org.junit.Assert.*; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true) public class XWikiHibernateStore_ESTest extends XWikiHibernateStore_ESTest_scaffolding { @Test public void notGeneratedAnyTest() { // EvoSuite did not generate any tests } }
f719ed04bbdea47858cbc660d60e45c3ed44ba57
8b6d7384da637d5b5fcb1dc5a8e6a4958256a234
/src/main/java/br/com/rag/apilivebus/api/travelhistory/TravelHistoryService.java
2d3f14575d49cc8a1853d358c322248a4c829191
[]
no_license
rafarvns/livebusapi
9b256fb661e8735d0ff185872918a98efbc2c303
0af0c02f9e9fce41e124dff21399ba4aed1d045e
refs/heads/master
2022-04-07T10:17:05.714129
2020-02-11T00:59:05
2020-02-11T00:59:05
215,102,504
0
0
null
null
null
null
UTF-8
Java
false
false
185
java
package br.com.rag.apilivebus.api.travelhistory; import br.com.rag.apilivebus.abstraction.IBaseService; public interface TravelHistoryService extends IBaseService<TravelHistory> { }
890e0cb8b6e248eca3cd7e729f1ac9f59664b0fb
92d8ff9a0b401ba0027fb99589747ffdd2f4d552
/spring_blog/src/main/java/spring/model/member/MemberDTO.java
7011296f5045213a980bf428c86312b265f31b99
[]
no_license
tkdgur4295/blog
11e55fb714a37f5d6fa04d3e2de18bb56ac94794
09f2f891bc8a79094724b586a6446847aa055a95
refs/heads/master
2021-01-19T01:45:39.432235
2017-03-09T04:12:30
2017-03-09T04:12:30
84,395,645
0
0
null
null
null
null
UTF-8
Java
false
false
2,043
java
package spring.model.member; import org.springframework.web.multipart.MultipartFile; public class MemberDTO { private String id; private String passwd; private String mname; private String tel; private String email; private String zipcode; private String address1; private String address2; private String job; private String mdate; private String fname; private MultipartFile fnameMF; private String grade; public MultipartFile getFnameMF() { return fnameMF; } public void setFnameMF(MultipartFile fnameMF) { this.fnameMF = fnameMF; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public String getMname() { return mname; } public void setMname(String mname) { this.mname = mname; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getZipcode() { return zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; } public String getAddress1() { return address1; } public void setAddress1(String address1) { this.address1 = address1; } public String getAddress2() { return address2; } public void setAddress2(String address2) { this.address2 = address2; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public String getMdate() { return mdate; } public void setMdate(String mdate) { this.mdate = mdate; } public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } }
[ "soldesk@s4" ]
soldesk@s4
08bb125c9bbb02cf9ad7cf0637ef90baaeb887e1
56456387c8a2ff1062f34780b471712cc2a49b71
/com/google/android/gms/drive/realtime/internal/zzm.java
1e46e1686a84f4e46a304bb16296617d050d1612
[]
no_license
nendraharyo/presensimahasiswa-sourcecode
55d4b8e9f6968eaf71a2ea002e0e7f08d16c5a50
890fc86782e9b2b4748bdb9f3db946bfb830b252
refs/heads/master
2020-05-21T11:21:55.143420
2019-05-10T19:03:56
2019-05-10T19:03:56
186,022,425
1
0
null
null
null
null
UTF-8
Java
false
false
4,129
java
package com.google.android.gms.drive.realtime.internal; import android.os.IInterface; import com.google.android.gms.common.data.DataHolder; import com.google.android.gms.drive.DriveId; import com.google.android.gms.drive.realtime.internal.event.ParcelableEventList; public abstract interface zzm extends IInterface { public abstract void zza(int paramInt, zzj paramzzj); public abstract void zza(int paramInt, zzo paramzzo); public abstract void zza(DriveId paramDriveId, zzo paramzzo); public abstract void zza(BeginCompoundOperationRequest paramBeginCompoundOperationRequest, zzo paramzzo); public abstract void zza(EndCompoundOperationRequest paramEndCompoundOperationRequest, zzj paramzzj); public abstract void zza(EndCompoundOperationRequest paramEndCompoundOperationRequest, zzo paramzzo); public abstract void zza(ParcelableIndexReference paramParcelableIndexReference, zzn paramzzn); public abstract void zza(zzc paramzzc); public abstract void zza(zzd paramzzd); public abstract void zza(zze paramzze); public abstract void zza(zzh paramzzh); public abstract void zza(zzi paramzzi); public abstract void zza(zzj paramzzj); public abstract void zza(zzl paramzzl); public abstract void zza(zzo paramzzo); public abstract void zza(String paramString, int paramInt1, int paramInt2, zzg paramzzg); public abstract void zza(String paramString, int paramInt1, int paramInt2, zzj paramzzj); public abstract void zza(String paramString, int paramInt, DataHolder paramDataHolder, zzg paramzzg); public abstract void zza(String paramString, int paramInt, DataHolder paramDataHolder, zzj paramzzj); public abstract void zza(String paramString, int paramInt, zzn paramzzn); public abstract void zza(String paramString, int paramInt, zzo paramzzo); public abstract void zza(String paramString1, int paramInt1, String paramString2, int paramInt2, zzj paramzzj); public abstract void zza(String paramString1, int paramInt, String paramString2, zzj paramzzj); public abstract void zza(String paramString, DataHolder paramDataHolder, zzj paramzzj); public abstract void zza(String paramString, zzf paramzzf); public abstract void zza(String paramString, zzj paramzzj); public abstract void zza(String paramString, zzk paramzzk); public abstract void zza(String paramString, zzl paramzzl); public abstract void zza(String paramString, zzn paramzzn); public abstract void zza(String paramString, zzo paramzzo); public abstract void zza(String paramString1, String paramString2, DataHolder paramDataHolder, zzj paramzzj); public abstract void zza(String paramString1, String paramString2, zzf paramzzf); public abstract void zza(String paramString1, String paramString2, zzg paramzzg); public abstract void zza(String paramString1, String paramString2, zzj paramzzj); public abstract void zza(boolean paramBoolean, zzo paramzzo); public abstract void zzb(zzc paramzzc); public abstract void zzb(zzj paramzzj); public abstract void zzb(zzl paramzzl); public abstract void zzb(zzo paramzzo); public abstract void zzb(String paramString, zzf paramzzf); public abstract void zzb(String paramString, zzl paramzzl); public abstract void zzb(String paramString, zzn paramzzn); public abstract void zzb(String paramString, zzo paramzzo); public abstract void zzb(String paramString1, String paramString2, zzf paramzzf); public abstract void zzc(zzc paramzzc); public abstract void zzc(zzo paramzzo); public abstract void zzc(String paramString, zzl paramzzl); public abstract void zzd(zzc paramzzc); public abstract void zze(zzc paramzzc); public abstract ParcelableEventList zzf(String paramString1, String paramString2, String paramString3); public abstract void zztT(); } /* Location: C:\Users\haryo\Desktop\enjarify-master\presensi-enjarify.jar!\com\google\android\gms\drive\realtime\internal\zzm.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
0813c772d1da488781c999b8c9430f3a01b9faf5
1fadc1383e6bb942729aa0de08fde13c86ea2ca1
/src/eclipse/lombok/eclipse/handlers/HandleTuple.java
05a464cd00983557a73915a74db82f7c3f6de775
[ "MIT" ]
permissive
abailly/lombok-pg
3d0650a5c0f9fb6a520f295ca3b74a5955123bcf
fcb65d1f0b7f2d2efa4392862c7a662564aa8f80
refs/heads/master
2021-01-21T00:56:36.602574
2012-05-12T13:02:11
2012-05-12T13:02:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
14,424
java
/* * Copyright © 2011 Philipp Eichhorn * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.ast.AST.*; import static lombok.core.util.Arrays.*; import static lombok.core.util.ErrorMessages.*; import static lombok.eclipse.handlers.Eclipse.*; import java.util.*; import lombok.*; import lombok.core.util.Each; import lombok.core.util.Is; import lombok.eclipse.EclipseASTAdapter; import lombok.eclipse.EclipseASTVisitor; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.ast.EclipseASTMaker; import lombok.eclipse.handlers.ast.EclipseMethod; import org.eclipse.jdt.internal.compiler.ASTVisitor; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.eclipse.jdt.internal.compiler.lookup.MethodScope; import org.mangosdk.spi.ProviderFor; /** * Handles the {@code lombok.Tuple.tuple} method call for eclipse. */ @ProviderFor(EclipseASTVisitor.class) public class HandleTuple extends EclipseASTAdapter { private final Set<String> methodNames = new HashSet<String>(); private int withVarCounter; @Override public void visitCompilationUnit(final EclipseNode top, final CompilationUnitDeclaration unit) { methodNames.clear(); withVarCounter = 0; } @Override public void visitLocal(final EclipseNode localNode, final LocalDeclaration local) { MessageSend initTupleCall = getTupelCall(localNode, local.initialization); if (initTupleCall != null) { final EclipseMethod method = EclipseMethod.methodOf(localNode, local); if (method == null) { localNode.addError(canBeUsedInBodyOfMethodsOnly("tuple")); } else if (handle(localNode, initTupleCall)) { methodNames.add(getMethodName(initTupleCall)); } } } @Override public void visitStatement(final EclipseNode statementNode, final Statement statement) { if (statement instanceof Assignment) { final Assignment assignment = (Assignment) statement; final MessageSend leftTupleCall = getTupelCall(statementNode, assignment.lhs); final MessageSend rightTupleCall = getTupelCall(statementNode, assignment.expression); if ((leftTupleCall != null) && (rightTupleCall != null)) { final EclipseMethod method = EclipseMethod.methodOf(statementNode, statement); if (method == null) { statementNode.addError(canBeUsedInBodyOfMethodsOnly("tuple")); } else if (handle(statementNode, leftTupleCall, rightTupleCall)) { methodNames.add(getMethodName(leftTupleCall)); methodNames.add(getMethodName(rightTupleCall)); } } } } private MessageSend getTupelCall(final EclipseNode node, final Expression expression) { if (expression instanceof MessageSend) { final MessageSend tupleCall = (MessageSend) expression; final String methodName = getMethodName(tupleCall); if (isMethodCallValid(node, methodName, Tuple.class, "tuple")) { return tupleCall; } } return null; } @Override public void endVisitCompilationUnit(final EclipseNode top, final CompilationUnitDeclaration unit) { for (String methodName : methodNames) { deleteMethodCallImports(top, methodName, Tuple.class, "tuple"); } } public boolean handle(final EclipseNode tupleInitNode, final MessageSend initTupleCall) { if (Is.empty(initTupleCall.arguments)) { return true; } int numberOfArguments = initTupleCall.arguments.length; List<LocalDeclaration> localDecls = new ArrayList<LocalDeclaration>(); String type = ((LocalDeclaration) tupleInitNode.get()).type.toString(); for (EclipseNode node : tupleInitNode.directUp().down()) { if (!(node.get() instanceof LocalDeclaration)) continue; LocalDeclaration localDecl = (LocalDeclaration) node.get(); if (!type.equals(localDecl.type.toString())) continue; localDecls.add(localDecl); if (localDecls.size() > numberOfArguments) { localDecls.remove(0); } if (node.equals(tupleInitNode)) { break; } } if (numberOfArguments != localDecls.size()) { tupleInitNode.addError(String.format("Argument mismatch on the right side. (required: %s found: %s)", localDecls.size(), numberOfArguments)); return false; } int index = 0; for (LocalDeclaration localDecl : localDecls) { localDecl.initialization = initTupleCall.arguments[index++]; } return true; } public boolean handle(final EclipseNode tupleAssignNode, final MessageSend leftTupleCall, final MessageSend rightTupleCall) { if (!validateTupel(tupleAssignNode, leftTupleCall, rightTupleCall)) return false; List<Statement> tempVarAssignments = new ArrayList<Statement>(); List<Statement> assignments = new ArrayList<Statement>(); List<String> varnames = collectVarnames(leftTupleCall.arguments); EclipseASTMaker builder = new EclipseASTMaker(tupleAssignNode, leftTupleCall); if (sameSize(leftTupleCall.arguments, rightTupleCall.arguments)) { Iterator<String> varnameIter = varnames.listIterator(); final Set<String> blacklistedNames = new HashSet<String>(); for (Expression arg : Each.elementIn(rightTupleCall.arguments)) { String varname = varnameIter.next(); final boolean canUseSimpleAssignment = new SimpleAssignmentAnalyser(blacklistedNames).scan(arg); blacklistedNames.add(varname); if (!canUseSimpleAssignment) { final TypeReference vartype = new VarTypeFinder(varname, tupleAssignNode.get()).scan(tupleAssignNode.top().get()); if (vartype != null) { String tempVarname = "$tuple" + withVarCounter++; tempVarAssignments.add(builder.build(LocalDecl(Type(vartype), tempVarname).makeFinal().withInitialization(Expr(arg)), Statement.class)); assignments.add(builder.build(Assign(Name(varname), Name(tempVarname)), Statement.class)); } else { tupleAssignNode.addError("Lombok-pg Bug. Unable to find vartype."); return false; } } else { assignments.add(builder.build(Assign(Name(varname), Expr(arg)), Statement.class)); } } } else { final TypeReference vartype = new VarTypeFinder(varnames.get(0), tupleAssignNode.get()).scan(tupleAssignNode.top().get()); if (vartype != null) { String tempVarname = "$tuple" + withVarCounter++; tempVarAssignments.add(builder.build(LocalDecl(Type(vartype).withDimensions(1), tempVarname).makeFinal().withInitialization(Expr(rightTupleCall.arguments[0])), Statement.class)); int arrayIndex = 0; for (String varname : varnames) { assignments.add(builder.build(Assign(Name(varname), ArrayRef(Name(tempVarname), Number(arrayIndex++))), Statement.class)); } } } tempVarAssignments.addAll(assignments); tryToInjectStatements(tupleAssignNode, tupleAssignNode.get(), tempVarAssignments); return true; } private boolean validateTupel(final EclipseNode tupleAssignNode, final MessageSend leftTupleCall, final MessageSend rightTupleCall) { if (!sameSize(leftTupleCall.arguments, rightTupleCall.arguments) && (rightTupleCall.arguments.length != 1)) { tupleAssignNode.addError("The left and right hand side of the assignment must have the same amount of arguments or" + " must have one array-type argument for the tuple assignment to work."); return false; } if (!containsOnlyNames(leftTupleCall.arguments)) { tupleAssignNode.addError("Only variable names are allowed as arguments of the left hand side in a tuple assignment."); return false; } return true; } private void tryToInjectStatements(final EclipseNode node, final ASTNode nodeThatUsesTupel, final List<Statement> statementsToInject) { EclipseNode parent = node; ASTNode statementThatUsesTupel = nodeThatUsesTupel; while ((!(parent.directUp().get() instanceof AbstractMethodDeclaration)) && (!(parent.directUp().get() instanceof Block))) { parent = parent.directUp(); statementThatUsesTupel = parent.get(); } Statement statement = (Statement) statementThatUsesTupel; EclipseNode grandParent = parent.directUp(); ASTNode block = grandParent.get(); if (block instanceof Block) { ((Block) block).statements = injectStatements(((Block) block).statements, statement, statementsToInject); } else if (block instanceof AbstractMethodDeclaration) { ((AbstractMethodDeclaration) block).statements = injectStatements(((AbstractMethodDeclaration) block).statements, statement, statementsToInject); } else { // this would be odd but what the hell return; } grandParent.rebuild(); } private static Statement[] injectStatements(final Statement[] statements, final Statement statement, final List<Statement> withCallStatements) { final List<Statement> newStatements = new ArrayList<Statement>(); for (Statement stat : statements) { if (stat == statement) { newStatements.addAll(withCallStatements); } else newStatements.add(stat); } return newStatements.toArray(new Statement[newStatements.size()]); } private List<String> collectVarnames(final Expression[] expressions) { List<String> varnames = new ArrayList<String>(); if (expressions != null) for (Expression expression : expressions) { varnames.add(new String(((SingleNameReference) expression).token)); } return varnames; } private boolean containsOnlyNames(final Expression[] expressions) { if (expressions != null) for (Expression expression : expressions) { if (!(expression instanceof SingleNameReference)) { return false; } } return true; } /** * Look for the type of a variable in the scope of the given expression. * <p> * {@link VarTypeFinder#scan(com.sun.source.tree.Tree, Void) VarTypeFinder.scan(Tree, Void)} will return the type of * a variable in the scope of the given expression. */ @RequiredArgsConstructor private static class VarTypeFinder extends ASTVisitor { private final String varname; private final ASTNode expr; private boolean lockVarname; private TypeReference vartype; public TypeReference scan(final ASTNode astNode) { if (astNode instanceof CompilationUnitDeclaration) { ((CompilationUnitDeclaration) astNode).traverse(this, (CompilationUnitScope) null); } else if (astNode instanceof MethodDeclaration) { ((MethodDeclaration) astNode).traverse(this, (ClassScope) null); } else { astNode.traverse(this, null); } return vartype; } @Override public boolean visit(final LocalDeclaration localDeclaration, final BlockScope scope) { return visit(localDeclaration); } @Override public boolean visit(final FieldDeclaration fieldDeclaration, final MethodScope scope) { return visit(fieldDeclaration); } @Override public boolean visit(final Argument argument, final BlockScope scope) { return visit(argument); } @Override public boolean visit(final Argument argument, final ClassScope scope) { return visit(argument); } @Override public boolean visit(final Assignment assignment, final BlockScope scope) { if ((expr != null) && (expr.equals(assignment))) { lockVarname = true; } return true; } public boolean visit(final AbstractVariableDeclaration variableDeclaration) { if (!lockVarname && varname.equals(new String(variableDeclaration.name))) { vartype = variableDeclaration.type; } return true; } } /** * Look for variable names that would break a simple assignment after transforming the tuple. * <p> * If {@link SimpleAssignmentAnalyser#scan(com.sun.source.tree.Tree, Void) AssignmentAnalyser.scan(Tree, Void)} * return {@code null} or {@code true} everything is fine, otherwise a temporary assignment is needed. */ @RequiredArgsConstructor private static class SimpleAssignmentAnalyser extends ASTVisitor { private final Set<String> blacklistedVarnames; private boolean canUseSimpleAssignment; public boolean scan(final ASTNode astNode) { canUseSimpleAssignment = true; if (astNode instanceof CompilationUnitDeclaration) { ((CompilationUnitDeclaration) astNode).traverse(this, (CompilationUnitScope) null); } else if (astNode instanceof MethodDeclaration) { ((MethodDeclaration) astNode).traverse(this, (ClassScope) null); } else { astNode.traverse(this, null); } return canUseSimpleAssignment; } @Override public boolean visit(final SingleNameReference singleNameReference, final BlockScope scope) { if (blacklistedVarnames.contains(new String(singleNameReference.token))) { canUseSimpleAssignment = false; return false; } return true; } } }
96b22a183e92b5bf36f7e03c9efb13680dacea5e
57873012a585f84f4ba332494eaba7457e9b894c
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/PID_Tuning/VeloPIDTuner.java
9e1fab2713d6cb610c854f51004836882672f640
[ "MIT" ]
permissive
Robosapiens-20/StateCompetition
67b41c0877cea75e2c89a25a5ac4083cc83ced75
ae0925571e77bf9707cbd2d4dfd87ea0ee35b467
refs/heads/master
2023-06-02T05:16:03.224714
2021-06-16T20:02:11
2021-06-16T20:02:11
376,587,037
0
0
null
null
null
null
UTF-8
Java
false
false
4,154
java
//package org.firstinspires.ftc.teamcode; // //import com.acmerobotics.dashboard.FtcDashboard; //import com.acmerobotics.dashboard.config.Config; //import com.acmerobotics.dashboard.telemetry.MultipleTelemetry; //import com.qualcomm.hardware.lynx.LynxModule; //import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; //import com.qualcomm.robotcore.eventloop.opmode.TeleOp; //import com.qualcomm.robotcore.hardware.DcMotor; //import com.qualcomm.robotcore.hardware.DcMotorEx; //import com.qualcomm.robotcore.hardware.DcMotorSimple; //import com.qualcomm.robotcore.hardware.PIDFCoefficients; //import com.qualcomm.robotcore.hardware.VoltageSensor; //import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; // //@Config //@TeleOp //public class VeloPIDTuner extends LinearOpMode { // public static PIDFCoefficients MOTOR_VELO_PID = new PIDFCoefficients(0, 0, 0, 0); // // private final FtcDashboard dashboard = FtcDashboard.getInstance(); // // private VoltageSensor batteryVoltageSensor; // // @Override // public void runOpMode() throws InterruptedException { // // Change my id // DcMotorEx myMotor = hardwareMap.get(DcMotorEx.class, "flywheelMotor1"); // // // Reverse as appropriate // // myMotor.setDirection(DcMotorSimple.Direction.REVERSE); // // for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { // module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); // } // // MotorConfigurationType motorConfigurationType = myMotor.getMotorType().clone(); // motorConfigurationType.setAchieveableMaxRPMFraction(1.0); // myMotor.setMotorType(motorConfigurationType); // // myMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER); // // batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); // setPIDFCoefficients(myMotor, MOTOR_VELO_PID); // // TuningController tuningController = new TuningController(); // // double lastKp = 0.0; // double lastKi = 0.0; // double lastKd = 0.0; // double lastKf = getMotorVelocityF(); // // telemetry = new MultipleTelemetry(telemetry, dashboard.getTelemetry()); // // telemetry.addLine("Ready!"); // telemetry.update(); // telemetry.clearAll(); // // waitForStart(); // // if (isStopRequested()) return; // // tuningController.start(); // // while (!isStopRequested() && opModeIsActive()) { // double targetVelo = tuningController.update(); // myMotor.setVelocity(targetVelo); // // telemetry.addData("targetVelocity", targetVelo); // // double motorVelo = myMotor.getVelocity(); // telemetry.addData("velocity", motorVelo); // telemetry.addData("error", targetVelo - motorVelo); // // telemetry.addData("upperBound", TuningController.rpmToTicksPerSecond(TuningController.TESTING_MAX_SPEED * 1.15)); // telemetry.addData("lowerBound", 0); // // if (lastKp != MOTOR_VELO_PID.p || lastKi != MOTOR_VELO_PID.i || lastKd != MOTOR_VELO_PID.d || lastKf != MOTOR_VELO_PID.f) { // setPIDFCoefficients(myMotor, MOTOR_VELO_PID); // // lastKp = MOTOR_VELO_PID.p; // lastKi = MOTOR_VELO_PID.i; // lastKd = MOTOR_VELO_PID.d; // lastKf = MOTOR_VELO_PID.f; // } // // tuningController.update(); // telemetry.update(); // } // } // // private void setPIDFCoefficients(DcMotorEx motor, PIDFCoefficients coefficients) { // motor.setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, new PIDFCoefficients( // coefficients.p, coefficients.i, coefficients.d, coefficients.f * 12 / batteryVoltageSensor.getVoltage() // )); // } // // public static double getMotorVelocityF() { // // see https://docs.google.com/document/d/1tyWrXDfMidwYyP_5H4mZyVgaEswhOC35gvdmP-V-5hA/edit#heading=h.61g9ixenznbx // return 32767 * 60.0 / (TuningController.MOTOR_MAX_RPM * TuningController.MOTOR_TICKS_PER_REV); // } //}
d4004a2592469322d8d1366099b641a4f199dcb4
6a670139a154425c3ca7ee049904bef6c9eb950b
/src/IUnionFind.java
7a9ee3ff64445f8ab086780da9c8f6542c1f1da2
[]
no_license
omar2562/ClusterizationGreedy
e11db014e22beaab40b97b063bcfa24a204536b5
79676502133fb7076b69ccd8e610220a9010a201
refs/heads/master
2021-01-20T05:52:22.813602
2014-05-15T04:26:46
2014-05-15T04:26:46
19,793,825
1
0
null
null
null
null
UTF-8
Java
false
false
141
java
public interface IUnionFind<T extends AbstractTree> { public void makeSet(T t); public T findSet(T t); public void union(T t1, T t2); }
490900fcc8702ea56085ebb3256c217f808611ba
0bc440aa05477b7002304f25fbba0bc0e7ced003
/app/src/main/java/com/app/phonebook/AsyncTasks/ContactsAsyncTask.java
ddfe7dc8ff8e3472e8a3807e12255570da973587
[]
no_license
gustavomachad/SQLiteCRUD
f6bf882b2311fef2747e7a3f17ba249083c462b0
ecd18de234680a10cdc45b624ca940692fa552d0
refs/heads/master
2021-09-11T13:53:21.181364
2018-04-08T10:40:25
2018-04-08T10:40:25
318,845,073
1
0
null
2020-12-05T17:14:57
2020-12-05T17:14:56
null
UTF-8
Java
false
false
10,174
java
package com.app.phonebook.AsyncTasks; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.support.design.widget.CoordinatorLayout; import android.support.v7.app.AlertDialog; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.app.phonebook.Adapters.ContactAdapter; import com.app.phonebook.Constants.Constants; import com.app.phonebook.Database.MyDatabase; import com.app.phonebook.Database.MyDatabaseFunctions; import com.app.phonebook.EditContact.EditContact; import com.app.phonebook.Model.ContactModel; import com.app.phonebook.R; import com.app.phonebook.TableStructure.TableContacts; import com.app.phonebook.Utils.OnTapListener; import java.util.ArrayList; /** * Created by Colinares on 4/6/2018. */ public class ContactsAsyncTask extends AsyncTask<Void, ContactModel, Void> { private CoordinatorLayout coordinatorLayout; private RecyclerView recyclerView; private LinearLayout noContacts; private Activity mActivity; private ContactAdapter mAdapter; private ArrayList<ContactModel> contactModels = new ArrayList<>(); private int[] contact_id, contact_age; private String[] contact_name, contact_number, contact_gender, date_created; private SQLiteDatabase mDb; //for custom preview private TextView preview_name, preview_number, preview_age, preview_gender, preview_date; private ImageView preview_genderImage; private LinearLayout linearLayoutEdit, linearLayoutDelete, linearLayoutClose; private Animation goFadeOut; public ContactsAsyncTask(CoordinatorLayout coordinatorLayout, RecyclerView recyclerView, LinearLayout noRecords, Activity mActivity) { this.coordinatorLayout = coordinatorLayout; this.recyclerView = recyclerView; this.noContacts = noRecords; this.mActivity = mActivity; goFadeOut = AnimationUtils.loadAnimation(this.mActivity, R.anim.fade_out); } @Override protected void onPreExecute() { mAdapter = new ContactAdapter(contactModels); recyclerView.setAdapter(mAdapter); } @Override protected Void doInBackground(Void... params) { initDatabase(); loadTrash(); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(ContactModel... values) { contactModels.add(values[0]); mAdapter.notifyDataSetChanged(); } @Override protected void onPostExecute(Void aVoid) { mAdapter.setOnTapListener(new OnTapListener() { @Override public void onTapView(int position) { previewContact(position); } }); } private void previewContact(final int position) { LayoutInflater layoutInflater = LayoutInflater.from(mActivity.getApplicationContext()); final View custom_preview_view = layoutInflater.inflate(R.layout.custom_preview_contact, null); initCustomLayoutViews(custom_preview_view); final AlertDialog.Builder preview = new AlertDialog.Builder(this.mActivity); preview.setCancelable(true); preview.setView(custom_preview_view); displayPreview(position); final AlertDialog dialog = preview.create(); dialog.show(); initOnClickListener(dialog, position); } private void initOnClickListener(final AlertDialog alertDialog, final int position) { linearLayoutEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { linearLayoutEdit.startAnimation(goFadeOut); Intent goEdit = new Intent(mActivity.getApplicationContext(), EditContact.class); goEdit.putExtra(Constants.EXTRA_ID, contact_id[position]); goEdit.putExtra(Constants.EXTRA_NAME, contact_name[position]); goEdit.putExtra(Constants.EXTRA_NUMBER, contact_number[position]); goEdit.putExtra(Constants.EXTRA_AGE, contact_age[position]); goEdit.putExtra(Constants.EXTRA_GENDER, contact_gender[position]); mActivity.startActivity(goEdit); alertDialog.dismiss(); mActivity.finish(); } }); linearLayoutDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { linearLayoutDelete.startAnimation(goFadeOut); deleteWarningDialog(alertDialog, position); } }); linearLayoutClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { linearLayoutClose.startAnimation(goFadeOut); alertDialog.dismiss(); } }); } private void deleteWarningDialog(final AlertDialog alertDialog, final int position) { final AlertDialog.Builder delete = new AlertDialog.Builder(this.mActivity); delete.setTitle("Warning"); delete.setMessage("Are you sure you want to delete " + contact_name[position].toUpperCase() + " from your contacts?"); delete.setCancelable(true); delete.setPositiveButton("No", null); delete.setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { goDelete(position); alertDialog.dismiss(); } }); delete.create().show(); } private void goDelete(final int position) { int id = contact_id[position]; Log.e("contact_id", id + ""); MyDatabaseFunctions.delete(id); mAdapter.refreshList(contactModels); initDatabase(); loadTrash(); deleteSuccessfulDialog(); } private void deleteSuccessfulDialog() { final AlertDialog.Builder delete = new AlertDialog.Builder(this.mActivity); delete.setTitle("Message"); delete.setMessage("Contact Deleted."); delete.setCancelable(true); delete.setPositiveButton("OK", null); delete.create().show(); } private void displayPreview(final int position) { preview_name.setText("Name : " + contact_name[position]); preview_number.setText("Number : " + contact_number[position]); preview_age.setText("Age : " + contact_age[position]); preview_gender.setText("Gender : " + contact_gender[position]); preview_date.setText("Date Created : " + date_created[position]); if (contact_gender[position].equals("Male")) { preview_genderImage.setImageResource(R.drawable.male); } else { preview_genderImage.setImageResource(R.drawable.female); } } private void initCustomLayoutViews(final View custom_preview_view) { preview_name = custom_preview_view.findViewById(R.id.preview_name); preview_number = custom_preview_view.findViewById(R.id.preview_number); preview_age = custom_preview_view.findViewById(R.id.preview_age); preview_gender = custom_preview_view.findViewById(R.id.preview_gender); preview_date = custom_preview_view.findViewById(R.id.preview_date); preview_genderImage = custom_preview_view.findViewById(R.id.preview_image); linearLayoutEdit = custom_preview_view.findViewById(R.id.linearEdit); linearLayoutDelete = custom_preview_view.findViewById(R.id.linearDelete); linearLayoutClose = custom_preview_view.findViewById(R.id.linearClose); } private void loadTrash() { int index = 0; String query = "SELECT * FROM " + TableContacts.TABLE_NAME + " ORDER BY " + TableContacts.COLUMN_NAME + " ASC"; Cursor cursor = mDb.rawQuery(query, null); cursor.moveToFirst(); contact_id = new int[cursor.getCount()]; contact_name = new String[cursor.getCount()]; contact_number = new String[cursor.getCount()]; contact_age = new int[cursor.getCount()]; contact_gender = new String[cursor.getCount()]; date_created = new String[cursor.getCount()]; if (cursor.getCount() == 0) { noContacts.setVisibility(View.VISIBLE); } else { noContacts.setVisibility(View.INVISIBLE); if (cursor.moveToFirst()) { do { contact_id[index] = cursor.getInt(cursor.getColumnIndex(TableContacts.COLUMN_ID)); contact_name[index] = cursor.getString(cursor.getColumnIndex(TableContacts.COLUMN_NAME)); contact_number[index] = cursor.getString(cursor.getColumnIndex(TableContacts.COLUMN_NUMBER)); contact_age[index] = cursor.getInt(cursor.getColumnIndex(TableContacts.COLUMN_AGE)); contact_gender[index] = cursor.getString(cursor.getColumnIndex(TableContacts.COLUMN_GENDER)); date_created[index] = cursor.getString(cursor.getColumnIndex(TableContacts.COLUMN_DATE_CREATED)); publishProgress(new ContactModel(contact_id[index], contact_age[index], contact_name[index], contact_number[index], contact_gender[index], date_created[index])); index++; } while (cursor.moveToNext()); } } } private void initDatabase() { mDb = MyDatabase.getInstance(mActivity).getReadableDatabase(); MyDatabaseFunctions.init(mActivity.getApplicationContext()); } }
4653da548802e76156642ae650257b047b35440c
e01c990804d5dfbb2010bff8dc01b2c1219471be
/workflow-service/src/main/java/com/gs/workflow/systemmanager/service/delegate/crime/PApportionToAnalystDelegate.java
a9a725176172350be5fbc876990c33c90fcd007f
[]
no_license
tanbinh123/springBoot-workflow-server
8676e489b171810d53fbb70f8aa0cad2dc817400
eb9679565e3f589ba2d624722c2833309cedea8c
refs/heads/master
2022-04-05T08:33:45.675734
2018-09-11T15:12:23
2018-09-11T15:12:23
477,142,911
1
0
null
2022-04-02T18:46:01
2022-04-02T18:46:00
null
UTF-8
Java
false
false
1,360
java
package com.gs.workflow.systemmanager.service.delegate.crime; import com.gs.workflow.systemmanager.service.serviceimpl.crime.WorkFlowServiceImpl; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * Created by zhangqiang on 2017/9/22. * 个人申请: 先检查分析员是否在线 * 1、在线 流程往下走 * 2、不在线 流程挂起 */ @Component("PApportionToAnalystDelegate") public class PApportionToAnalystDelegate implements JavaDelegate { @Value("${crime.server.url}") private String crimeServerUrl; @Autowired private WorkFlowServiceImpl workFlowServiceImpl; private Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public void execute(DelegateExecution execution) throws Exception { //传入角色类型 和业务类型 if (workFlowServiceImpl.apportionResolve(execution, "analyst","1")) { logger.info("Check analyst is online over!"); } execution.setVariable("auditor", ""); logger.info("Assignee to analyst task listener over!"); } }
ad2ed8429266e853bd0ac3c72ff7d54e659e7ed9
eff9d1e6ce4032c7a2618cf8b40922401f3d1ce0
/ls-java-core/src/main/java/com/ls/lishuai/concurrency/forkjoinpool/Main.java
c57063ddcdda3e999138042a448ef1f0aca57649
[]
no_license
lishuai2016/all
67d8ff5db911ca5c38b249172d3dcbf4234d49d7
aa7d6774611c21e126e628268a6abd020138974f
refs/heads/master
2022-12-09T11:03:08.571479
2019-08-18T16:38:41
2019-08-18T16:38:44
200,311,974
5
4
null
2022-11-16T07:57:51
2019-08-03T00:08:21
Java
UTF-8
Java
false
false
1,168
java
package com.ls.lishuai.concurrency.forkjoinpool; import java.util.List; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.TimeUnit; public class Main { /** * @param args */ public static void main(String[] args) { ProductlistGenerator g = new ProductlistGenerator(); List<Product> list = g.genetor(10000); Task task = new Task(list,0,list.size(),0.20); ForkJoinPool pool = new ForkJoinPool(); pool.execute(task); do { System.out.printf("main: thread count : %d\n",pool.getActiveThreadCount()); System.out.printf("main: thread steal : %d\n",pool.getStealCount()); System.out.printf("main: thread parallelism : %d\n",pool.getParallelism()); try { TimeUnit.MILLISECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } while (!task.isDone()); pool.shutdown(); if (task.isCompletedNormally()) { System.out.println("main: thread has completed!"); } for (int i = 0;i <list.size();i++) { Product p =list.get(i); if (p.getPrice() != 12) { System.out.printf("product %s : %f\n",p.getName(),p.getPrice()); } } System.out.println("main: end!"); } }
2c0bbd43fea5bc22d4a36f235fddeac2b33ed9e4
98613747055b7259b10396db5598886f4b643697
/org/bouncycastle/math/ec/ScaleXPointMap.java
3b8948b2c61949aee6d280999a0449d215e644a4
[]
no_license
welljsjs/jap_source
951104e2de49498cecf3029066e139658647a7b4
502ace868c62ed0ead9fd798f1bfe7bbdcdfeb82
refs/heads/master
2023-03-20T21:46:03.715948
2021-03-12T11:04:30
2021-03-12T11:13:52
347,038,436
1
0
null
null
null
null
UTF-8
Java
false
false
498
java
/* * Decompiled with CFR 0.150. */ package org.bouncycastle.math.ec; import org.bouncycastle.math.ec.ECFieldElement; import org.bouncycastle.math.ec.ECPoint; import org.bouncycastle.math.ec.ECPointMap; public class ScaleXPointMap implements ECPointMap { protected final ECFieldElement scale; public ScaleXPointMap(ECFieldElement eCFieldElement) { this.scale = eCFieldElement; } public ECPoint map(ECPoint eCPoint) { return eCPoint.scaleX(this.scale); } }
4be5b9724e57ea7f7c9fc2790858f313c391612f
409939dca0a8157342482d5d4e3745c3d2714cc8
/SG/src/com/kiro/sg/sponsor/smart/SmartSponsor.java
e91d986bdf36ce0b280cd119063880456a65bad3
[]
no_license
Kiro47/Chosen-SG
b4206eb98582bc40e5abbabc660777aab04a5099
108314d148dcfd4faa1c88da57a0d7a84610f112
refs/heads/master
2020-04-10T14:05:02.047293
2017-09-26T17:43:38
2017-09-26T17:43:38
68,174,603
0
0
null
null
null
null
UTF-8
Java
false
false
1,957
java
package com.kiro.sg.sponsor.smart; import com.kiro.sg.sponsor.smart.checks.ArmorCheck; import com.kiro.sg.sponsor.smart.checks.DefaultCheck; import com.kiro.sg.sponsor.smart.checks.HungerCheck; import com.kiro.sg.sponsor.smart.checks.WeaponCheck; import com.kiro.sg.utils.chat.ChatUtils; import com.kiro.sg.utils.chat.Msg; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import java.util.ArrayList; import java.util.List; public final class SmartSponsor { private static final String BORDER_FILL = ChatUtils.fill("-"); private static final String SMART_SPONSOR = ChatUtils.center("<> Smart Sponsor <>"); private static final List<SponsorCheck> checks = new ArrayList<>(); private static final int[] indecies; static { int weightSum = 0; SponsorCheck check; checks.add(check = new DefaultCheck()); weightSum += check.weight(); checks.add(check = new ArmorCheck()); weightSum += check.weight(); checks.add(check = new WeaponCheck()); weightSum += check.weight(); checks.add(check = new HungerCheck()); weightSum += check.weight(); indecies = new int[weightSum]; int cur = 0; for (int i = 0; i < checks.size(); i++) { int weight = checks.get(i).weight(); for (int j = 0; j < weight; j++) { indecies[cur++] = i; } } } private SmartSponsor() { } @EventHandler public static void sponsor(Player player) { Msg.msgPlayer(player, ChatColor.GOLD + BORDER_FILL); Msg.msgPlayer(player, ChatColor.GOLD + SMART_SPONSOR); int last = 0; int count = 0; SponsorCheck check; do { if (count++ == 6) { check = checks.get(0); continue; } int index = indecies[(int) (Math.random() * indecies.length)]; if (index != last) { check = checks.get(index); continue; } check = null; } while (check == null || !check.checkAndExecute(player)); Msg.msgPlayer(player, ChatColor.GOLD + BORDER_FILL); } }