code
stringlengths
73
34.1k
label
stringclasses
1 value
public void cleanupParams(int size, long interval) { timer.cancel(); timer.schedule(new Cleanup(content,size), interval, interval); }
java
public Content load(LogTarget logTarget, String dataRoot, String key, String mediaType, long _timeCheck) throws IOException { long timeCheck = _timeCheck; if(timeCheck<0) { timeCheck=checkInterval; // if time < 0, then use default } String fileName = dataRoot + '/' + key; Content c = content.get(key); ...
java
public<T> Future<Void> update(String pathinfo) throws APIException, CadiException { final int idx = pathinfo.indexOf('?'); final String qp; if(idx>=0) { qp=pathinfo.substring(idx+1); pathinfo=pathinfo.substring(0,idx); } else { qp=queryParams; } EClient<CT> client = client(); client.setMethod(P...
java
private static JaxInfo[] buildFields(Class<?> clazz, String defaultNS) throws SecurityException, NoSuchFieldException, ClassNotFoundException { ArrayList<JaxInfo> fields = null; // allow for lazy instantiation, because many structures won't have XmlType Class<?> cls = clazz; // Build up Method names from JAXB Ann...
java
public Result<List<Data>> readByUserRole(AuthzTrans trans, String user, String role) { return psUserInRole.read(trans, R_TEXT + " by User " + user + " and Role " + role, new Object[]{user,role}); }
java
public static byte[] encryptMD5 (byte[] input) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input); return md.digest(); }
java
public static boolean isEqual(byte ba1[], byte ba2[]) { if(ba1.length!=ba2.length)return false; for(int i = 0;i<ba1.length; ++i) { if(ba1[i]!=ba2[i])return false; } return true; }
java
public static String readString(DataInputStream is, byte[] _buff) throws IOException { int l = is.readInt(); byte[] buff = _buff; switch(l) { case -1: return null; case 0: return ""; default: // Cover case where there is a large string, without always allocating a large buffer. if(l>buff.length)...
java
public static void writeStringSet(DataOutputStream os, Collection<String> set) throws IOException { if(set==null) { os.writeInt(-1); } else { os.writeInt(set.size()); for(String s : set) { writeString(os, s); } } }
java
public static void writeStringMap(DataOutputStream os, Map<String,String> map) throws IOException { if(map==null) { os.writeInt(-1); } else { Set<Entry<String, String>> es = map.entrySet(); os.writeInt(es.size()); for(Entry<String,String> e : es) { writeString(os, e.getKey()); writeString(os, e....
java
public final static StringBuilder buildLine(Level level, StringBuilder sb, Object[] elements) { sb.append(level.name()); return buildLine(sb,elements); }
java
public void log(Level level, Object... elements) { if(willWrite.compareTo(level)<=0) { StringBuilder sb = buildLine(level, new StringBuilder(),elements); if(context==null) { System.out.println(sb.toString()); } else { context.log(sb.toString()); } } }
java
public void log(Exception e, Object... elements) { if(willWrite.compareTo(Level.ERROR)<=0) { StringBuilder sb = buildLine(Level.ERROR, new StringBuilder(),elements); if(context==null) { sb.append(e.toString()); System.out.println(sb.toString()); } else { context.log(sb.toString(),e); } } ...
java
public String getProperty(String string, String def) { String rv = null; if ( props != null ) rv = props.getProperty( string, def ); if(rv==null) { rv = context.getInitParameter(string); } return rv==null?def:rv; }
java
public void prime(LogTarget lt, int prime) throws APIException { for (int i = 0; i < prime; ++i) { Pooled<T> pt = new Pooled<T>(creator.create(), this, lt); synchronized (list) { list.addFirst(pt); ++count; } } }
java
public void drain() { synchronized (list) { for (int i = 0; i < list.size(); ++i) { Pooled<T> pt = list.remove(); creator.destroy(pt.content); pt.logTarget.log("Pool drained ", creator.toString()); } count = spares = 0; } }
java
public boolean validate() { boolean rv = true; synchronized (list) { for (Pooled<T> t : list) { if (!creator.isValid(t.content)) { rv = false; t.toss(); list.remove(t); } } } return rv; }
java
public T get(Env env) throws APIException { Thread t = Thread.currentThread(); T obj = objs.get(t); if(obj==null || refreshed>obj.created()) { try { obj = cnst.newInstance(new Object[]{env}); } catch (InvocationTargetException e) { throw new APIException(e.getTargetException()); } catch (Exceptio...
java
public void remove(Env env) { T obj = objs.remove(Thread.currentThread()); if(obj!=null) obj.destroy(env); }
java
public Result<List<Data>> readByUser(AuthzTrans trans, final String user) { DAOGetter getter = new DAOGetter(trans,dao()) { public Result<List<Data>> call() { // If the call is for THIS user, and it exists, get from TRANS, add to TRANS if not. if(user!=null && user.equals(trans.user())) { Result<List<...
java
public Rcli<CLIENT> clientAs(String apiVersion, ServletRequest req) throws CadiException { Rcli<CLIENT> cl = client(apiVersion); return cl.forUser(transferSS(((HttpServletRequest)req).getUserPrincipal())); }
java
public static final AAFCon<?> obtain(Object servletRequest) { if(servletRequest instanceof CadiWrap) { Lur lur = ((CadiWrap)servletRequest).getLur(); if(lur != null) { if(lur instanceof EpiLur) { AbsAAFLur<?> aal = (AbsAAFLur<?>) ((EpiLur)lur).subLur(AbsAAFLur.class); if(aal!=null) { return ...
java
public static String reverseDomain(String user) { StringBuilder sb = null; String[] split = Split.split('.',user); int at; for(int i=split.length-1;i>=0;--i) { if(sb == null) { sb = new StringBuilder(); } else { sb.append('.'); } if((at = split[i].indexOf('@'))>0) { sb.append(split[i].s...
java
public static synchronized boolean denyIP(String ip) { boolean rv = false; if(deniedIP==null) { deniedIP = new HashMap<String,Counter>(); deniedIP.put(ip, new Counter(ip)); // Noted duplicated for minimum time spent rv= true; } else if(deniedIP.get(ip)==null) { deniedIP.put(ip, new Counter(ip)); rv...
java
public static synchronized boolean removeDenyIP(String ip) { if(deniedIP!=null && deniedIP.remove(ip)!=null) { writeIP(); if(deniedIP.isEmpty()) { deniedIP=null; } return true; } return false; }
java
public static synchronized boolean denyID(String id) { boolean rv = false; if(deniedID==null) { deniedID = new HashMap<String,Counter>(); deniedID.put(id, new Counter(id)); // Noted duplicated for minimum time spent rv = true; } else if(deniedID.get(id)==null) { deniedID.put(id, new Counter(id)); r...
java
public static synchronized boolean removeDenyID(String id) { if(deniedID!=null && deniedID.remove(id)!=null) { writeID(); if(deniedID.isEmpty()) { deniedID=null; } return true; } return false; }
java
public AuthenticatedUser authenticate(Map<String, String> credentials) throws AuthenticationException { String username = (String)credentials.get("username"); if (username == null) { throw new AuthenticationException("'username' is missing"); } AAFAuthenticatedUser aau = new AAFAu...
java
public Result<List<Data>> readByUser(AuthzTrans trans, String user, int ... yyyymm) { if(yyyymm.length==0) { return Result.err(Status.ERR_BadData, "No or invalid yyyymm specified"); } Result<ResultSet> rs = readByUser.exec(trans, "user", user); if(rs.notOK()) { return Result.err(rs); } return ...
java
public Result<Void> addDescription(AuthzTrans trans, String ns, String type, String instance, String action, String description) { //TODO Invalidate? return dao().addDescription(trans, ns, type, instance, action, description); }
java
public static void xmlEscape(StringBuilder sb, Reader r) throws ParseException { try { int c; StringBuilder esc = new StringBuilder(); for(int cnt = 0;cnt<9 /*max*/; ++cnt) { if((c=r.read())<0)throw new ParseException("Invalid Data: Unfinished Escape Sequence"); if(c!=';') { esc.append((char)c)...
java
private Set<Permission> checkPermissions(AAFAuthenticatedUser aau, String type, String instance) { // Can perform ALL actions String fullName = aau.getFullName(); PermHolder ph = new PermHolder(aau); aafLur.fishOneOf(fullName, ph,type,instance,actions); return ph.permissions; }
java
public static double calc(String ... coords) { try { String [] array; switch(coords.length) { case 1: array = Split.split(',',coords[0]); if(array.length!=4)return -1; return calc( Double.parseDouble(array[0]), Double.parseDouble(array[1]), Double.parseDouble(array[2]), Double...
java
public boolean match(Permission p) { if(p instanceof AAFPermission) { AAFPermission ap = (AAFPermission)p; // Note: In AAF > 1.0, Accepting "*" from name would violate multi-tenancy // Current solution is only allow direct match on Type. // 8/28/2014 - added REGEX ability if(type.equals(ap.getNam...
java
private void movePerms(AuthzTrans trans, NsDAO.Data parent, StringBuilder sb, Result<List<PermDAO.Data>> rpdc) { Result<Void> rv; Result<PermDAO.Data> pd; if (rpdc.isOKhasData()) { for (PermDAO.Data pdd : rpdc.value) { String delP2 = pdd.type; if ("access".equals(delP2)) { continue; } ...
java
private void moveRoles(AuthzTrans trans, NsDAO.Data parent, StringBuilder sb, Result<List<RoleDAO.Data>> rrdc) { Result<Void> rv; Result<RoleDAO.Data> rd; if (rrdc.isOKhasData()) { for (RoleDAO.Data rdd : rrdc.value) { String delP2 = rdd.name; if ("admin".equals(delP2) || "owner".equals(delP2)) { ...
java
public Result<Void> addUserRole(AuthzTrans trans,UserRoleDAO.Data urData) { Result<Void> rv; if(Question.ADMIN.equals(urData.rname)) { rv = mayAddAdmin(trans, urData.ns, urData.user); } else if(Question.OWNER.equals(urData.rname)) { rv = mayAddOwner(trans, urData.ns, urData.user); } else { rv = checkVa...
java
public Result<Void> extendUserRole(AuthzTrans trans, UserRoleDAO.Data urData, boolean checkForExist) { // Check if record still exists if (checkForExist && q.userRoleDAO.read(trans, urData).notOKorIsEmpty()) { return Result.err(Status.ERR_UserRoleNotFound, "User Role does not exist"); } if (q.roleDAO.re...
java
public Lur get(int idx) { if(idx>=0 && idx<lurs.length) { return lurs[idx]; } return null; }
java
public boolean fish(String bait, Permission pond) { if(isDebug(bait)) { boolean rv = false; StringBuilder sb = new StringBuilder("Log for "); sb.append(bait); if(supports(bait)) { User<PERM> user = getUser(bait); if(user==null) { sb.append("\n\tUser is not in Cache"); } else { if(use...
java
public<A> void fishOneOf(String bait, A obj, String type, String instance, List<Action<A>> actions) { User<PERM> user = getUser(bait); if(user==null || (user.noPerms() && user.permExpired()))user = loadUser(bait); // return user==null?false:user.contains(pond); if(user!=null) { ReuseAAFPermission perm = new R...
java
public int cacheIdx(String key) { int h = 0; for (int i = 0; i < key.length(); i++) { h = 31*h + key.charAt(i); } if(h<0)h*=-1; return h%segSize; }
java
public static void startCleansing(AuthzEnv env, CachedDAO<?,?,?> ... dao) { for(CachedDAO<?,?,?> d : dao) { for(int i=0;i<d.segSize;++i) { startCleansing(env, d.table()+i); } } }
java
public Result<FutureDAO.Data> create(AuthzTrans trans, FutureDAO.Data data, String id) { // If ID is not set (typical), create one. if(data.id==null) { StringBuilder sb = new StringBuilder(trans.user()); sb.append(data.target); sb.append(System.currentTimeMillis()); data.id = UUID.nameUUIDFromByte...
java
public static Schema genSchema(Store env, String ... filenames) throws APIException { String schemaDir = env.get( env.staticSlot(EnvFactory.SCHEMA_DIR), EnvFactory.DEFAULT_SCHEMA_DIR); File dir = new File(schemaDir); if(!dir.exists())throw new APIException("Schema Directory " + schemaDir + " does not exis...
java
public int read(byte[] array, int offset, int length) { if(curr==null)return -1; int len; int count=0; while(length>0) { // loop through while there's data needed if((len=curr.remaining())>length) { // if enough data in curr buffer, use this code curr.get(array,offset,length); count+=length; len...
java
public void put(byte[] array, int offset, int length) { if(curr == null || curr.remaining()==0) { curr = ringGet(); bbs.add(curr); } int len; while(length>0) { if((len=curr.remaining())>length) { curr.put(array,offset,length); length=0; } else { // System.out.println(new String(array))...
java
public void setForRead() { for(ByteBuffer bb : bbs) { bb.flip(); } if(bbs.isEmpty()) { curr = null; idx = 0; } else { curr=bbs.get(0); idx=1; } }
java
public void done() { for(ByteBuffer bb : bbs) { ringPut(bb); } bbs.clear(); curr = null; }
java
public long skip(long n) { long skipped=0L; int skip; while(n>0) { if(n<(skip=curr.remaining())) { curr.position(curr.position()+(int)n); skipped+=skip; n=0; } else { curr.position(curr.limit()); skipped-=skip; if(idx<bbs.size()) { curr=bbs.get(idx++); n-=skip; } e...
java
public void reset() { for(ByteBuffer bb : bbs) { bb.position(0); } if(bbs.isEmpty()) { curr = null; idx = 0; } else { curr=bbs.get(0); idx=1; } }
java
public String pathParam(HttpServletRequest req, String key) { return match.param(req.getPathInfo(), key); }
java
public boolean isAuthorized(HttpServletRequest req) { if(all)return true; if(roles!=null) { for(String srole : roles) { if(req.isUserInRole(srole)) return true; } } return false; }
java
public void destroy() { // Synchronize, in case multiCadiFilters are used. synchronized(CadiHTTPManip.noAdditional) { if(--count<=0 && httpChecker!=null) { httpChecker.destroy(); httpChecker=null; access=null; pathExceptions=null; } } }
java
private boolean noAuthn(HttpServletRequest hreq) { if(pathExceptions!=null) { String pi = hreq.getPathInfo(); if(pi==null) return false; // JBoss sometimes leaves null for(String pe : pathExceptions) { if(pi.startsWith(pe))return true; } } return false; }
java
private PermConverter getConverter(HttpServletRequest hreq) { if(mapPairs!=null) { String pi = hreq.getPathInfo(); if(pi!=null) { for(Pair p: mapPairs) { if(pi.startsWith(p.name))return p.pc; } } } return NullPermConverter.singleton(); }
java
synchronized Route<TRANS> findOrCreate(HttpMethods meth, String path) { Route<TRANS> rv = null; for(int i=0;i<end;++i) { if(routes[i].resolvesTo(meth,path))rv = routes[i]; } if(rv==null) { if(end>=routes.length) { @SuppressWarnings("unchecked") Route<TRANS>[] temp = new Route[end+10]; Syst...
java
public Result<List<CertDAO.Data>> readID(AuthzTrans trans, final String id) { return dao().readID(trans, id); }
java
public void run(Cache<G> cache, Code<G> code) throws APIException, IOException { code.code(cache, xgen); }
java
@SuppressWarnings({ "unchecked", "rawtypes" }) public void run(State<Env> state, Trans trans, Cache cache, DynamicCode code) throws APIException, IOException { code.code(state, trans, cache, xgen); }
java
public void code(Cache<G> cache, G xgen) throws APIException, IOException { code(null, null,cache,xgen); }
java
public static BROWSER browser(AuthzTrans trans, Slot slot) { BROWSER br = trans.get(slot, null); if(br==null) { String agent = trans.agent(); int msie; if(agent.contains("iPhone") /* other phones? */) { br=BROWSER.iPhone; } else if ((msie = agent.indexOf("MSIE"))>=0) { msie+=5; int end = ag...
java
public void processJobChangeDataFile(String fileName, String falloutFileName, Date validDate) throws Exception { BufferedWriter writer = null; try { env.info().log("Reading file: " + fileName ); FileInputStream fstream = new FileInputS...
java
public Result<Void> addDescription(AuthzTrans trans, String ns, String type, String instance, String action, String description) { try { getSession(trans).execute(UPDATE_SP + TABLE + " SET description = '" + description + "' WHERE ns = '" + ns + "' AND type = '" + type + "'" + "AND instance = '" + inst...
java
@Override public List<Identity> getApprovers(AuthzTrans trans, String user) throws OrganizationException { Identity orgIdentity = getIdentity(trans, user); List<Identity> orgIdentitys = new ArrayList<Identity>(); if(orgIdentity!=null) { String supervisorID = orgIdentity.responsibleTo(); if (supervisorID.in...
java
private Address[] getAddresses(List<String> strAddresses, String delimiter) throws OrganizationException { Address[] addressArray = new Address[strAddresses.size()]; int count = 0; for (String addr : strAddresses) { try{ addressArray[count] = new InternetAddress(addr); coun...
java
public TypedCode<TRANS> add(HttpCode<TRANS,?> code, String ... others) { StringBuilder sb = new StringBuilder(); boolean first = true; for(String str : others) { if(first) { first = false; } else { sb.append(','); } sb.append(str); } parse(code, sb.toString()); return th...
java
public StringBuilder relatedTo(HttpCode<TRANS, ?> code, StringBuilder sb) { boolean first = true; for(Pair<String, Pair<HttpCode<TRANS, ?>, List<Pair<String, Object>>>> pair : types) { if(code==null || pair.y.x == code) { if(first) { first = false; } else { sb.append(','); } sb...
java
public Result<List<CredDAO.Data>> readNS(AuthzTrans trans, final String ns) { return dao().readNS(trans, ns); }
java
public Result<Void> addDescription(AuthzTrans trans, String ns, String name, String description) { //TODO Invalidate? return dao().addDescription(trans, ns, name, description); }
java
public static String domain2ns(String id) { int at = id.indexOf('@'); if (at >= 0) { String[] domain = id.substring(at + 1).split("\\."); StringBuilder ns = new StringBuilder(id.length()); boolean first = true; for (int i = domain.length - 1; i >= 0; --i) { if (first) { first = false; } els...
java
public boolean canMove(NsType nsType) { boolean rv; switch(nsType) { case DOT: case ROOT: case COMPANY: case UNKNOWN: rv = false; break; default: rv = true; } return rv; }
java
public String validate(String user, String password) throws IOException, CadiException { User<AAFPermission> usr = getUser(user); if(password.startsWith("enc:???")) { password = access.decrypt(password, true); } byte[] bytes = password.getBytes(); if(usr != null && usr.principal != null && usr.principal.g...
java
public static String convert(final String text, final List<String> vars) { String[] array = new String[vars.size()]; StringBuilder sb = new StringBuilder(); convert(sb,text,vars.toArray(array)); return sb.toString(); }
java
public static<R> Result<R> ok(R value) { return new Result<R>(value,OK,SUCCESS,null); }
java
public static<R> Result<R[]> ok(R value[]) { return new Result<R[]>(value,OK,SUCCESS,null).emptyList(value.length==0); }
java
public static<R> Result<List<R>> ok(List<R> value) { return new Result<List<R>>(value,OK,SUCCESS,null).emptyList(value.size()==0); }
java
public static<R> Result<R> err(int status, String details, String ... variables) { return new Result<R>(null,status,details,variables); }
java
public static<R> Result<R> err(Exception e) { return new Result<R>(null,ERR_General,e.getMessage(),EMPTY_VARS); }
java
public static<R> Result<R> create(R value, int status, String details, String ... vars) { return new Result<R>(value,status,details,vars); }
java
public RosettaDF<T> out(Data.TYPE type) { outType = type; defaultOut = getOut(type==Data.TYPE.DEFAULT?Data.TYPE.JSON:type); return this; }
java
public RosettaDF<T> rootMarshal(Marshal<T> marshal) { if(marshal instanceof DocMarshal) { this.marshal = marshal; } else { this.marshal = DocMarshal.root(marshal); } return this; }
java
public String encode(String str) throws IOException { byte[] array; try { array = str.getBytes(encoding); } catch (IOException e) { array = str.getBytes(); // take default } // Calculate expected size to avoid any buffer expansion copies within the ByteArrayOutput code ByteArr...
java
public void encode(InputStream is, OutputStream os) throws IOException { // StringBuilder sb = new StringBuilder((int)(estimate*1.255)); // try to get the right size of StringBuilder from start.. slightly more than 1.25 times int prev=0; int read, idx=0, line=0; boolean go; do { read = i...
java
public void decode(InputStream is, OutputStream os) throws IOException { int read, idx=0; int prev=0, index; while((read = is.read())>=0) { index = convert.convert(read); if(index>=0) { switch(++idx) { // 1 based cases, slightly faster ++ case 1: // index goes into first 6 bits o...
java
public byte[] keygen() throws IOException { byte inkey[] = new byte[0x600]; new SecureRandom().nextBytes(inkey); ByteArrayOutputStream baos = new ByteArrayOutputStream(0x800); base64url.encode(new ByteArrayInputStream(inkey), baos); return baos.toByteArray(); }
java
public static Symm obtain(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { base64url.decode(is, baos); } catch (IOException e) { // don't give clue throw new IOException("Invalid Key"); } byte[] bkey = baos.toByteArray(); if(bkey.length<0...
java
public static Symm obtain(File f) throws IOException { FileInputStream fis = new FileInputStream(f); try { return obtain(fis); } finally { fis.close(); } }
java
public String enpass(String password) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); enpass(password,baos); return new String(baos.toByteArray()); }
java
public void enpass(final String password, final OutputStream os) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); byte[] bytes = password.getBytes(); if(this.getClass().getSimpleName().startsWith("base64")) { // don't expose ...
java
public String depass(String password) throws IOException { if(password==null)return null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); depass(password,baos); return new String(baos.toByteArray()); }
java
public long depass(final String password, final OutputStream os) throws IOException { int offset = password.startsWith(ENC)?4:0; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ByteArrayInputStream bais = new ByteArrayInputStream(password.getBytes(),offset,password.length()-offset); e...
java
public Symm obtain(byte[] key) throws IOException { try { byte[] bytes = new byte[AES.AES_KEY_SIZE/8]; int offset = (Math.abs(key[(47%key.length)])+137)%(key.length-bytes.length); for(int i=0;i<bytes.length;++i) { bytes[i] = key[i+offset]; } aes = new AES(bytes,0,bytes.length); } catch (Exception ...
java
private boolean nob(String str, Pattern p) { return str==null || !p.matcher(str).matches(); }
java
public static void start(RestClient client, String root, boolean merge, boolean force) throws Exception { logger.info("starting automatic settings/mappings discovery"); // create templates List<String> templateNames = TemplateFinder.findTemplates(root); for (String templateName : templateNames) { createTemp...
java
public static List<String> findIndexNames(final String root) throws IOException, URISyntaxException { if (root == null) { return findIndexNames(); } logger.debug("Looking for indices in classpath under [{}].", root); final List<String> indexNames = new ArrayList<>(); ...
java
public static String readTemplate(String root, String template) throws IOException { if (root == null) { return readTemplate(template); } String settingsFile = root + "/" + Defaults.TemplateDir + "/" + template + Defaults.JsonFileExtension; return readFileFromClasspath(settingsFile); }
java
@Deprecated public static void createTemplate(Client client, String root, String template, boolean force) throws Exception { String json = TemplateSettingsReader.readTemplate(root, template); createTemplateWithJson(client, template, json, force); }
java
public static void createTemplate(RestClient client, String template, boolean force) throws Exception { String json = TemplateSettingsReader.readTemplate(template); createTemplateWithJson(client, template, json, force); }
java
public static void createTemplateWithJson(RestClient client, String template, String json, boolean force) throws Exception { if (isTemplateExist(client, template)) { if (force) { logger.debug("Template [{}] already exists. Force is set. Removing it.", template); removeTemplate(client, template); } else ...
java