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
310cfac3f9fd439e2d40a5c4a7eee28e8cca9809
36b8cbe8249c8c367220267ea10e29df2a76e2ae
/src/course/Teoria/ExStreams/Program.java
b931fcd5992f6ddf2f368a95bd353aae947f2218
[]
no_license
NicoHarabura/JavaCourse
fce487e45920ff1ba8c5988ad6856cd05c46cccc
d6d3d4520270ffba766132e406a8e1c647fe626c
refs/heads/master
2020-05-05T04:02:41.730916
2019-09-12T20:05:50
2019-09-12T20:05:50
179,695,409
0
0
null
null
null
null
ISO-8859-13
Java
false
false
789
java
package course.Teoria.ExStreams; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class Program { public static void main(String[] args) { List<Integer> list = Arrays.asList(3, 4, 5, 10, 7); Stream<Integer> st1 = list.stream().map(x -> x * 10); System.out.println(Arrays.toString(st1.toArray())); Stream<String> st2 = Stream.of("Maria", "Joćo", "Pedro"); System.out.println(Arrays.toString(st2.toArray())); Stream<Integer> st3 = Stream.iterate(0, x -> x + 2); System.out.println(Arrays.toString(st3.limit(10).toArray())); //FIBONATI Stream<Long> st4 = Stream.iterate(new long[]{ 0L, 1L }, p->new long[]{ p[1], p[0]+p[1] }).map(p -> p[0]); System.out.println(Arrays.toString(st4.limit(10).toArray())); } }
[ "nharabura@hotmail.com" ]
nharabura@hotmail.com
225675b1ddb09799d71a1451fe1a3b611720e0ad
a234d5cc513c6c871ae0c7863ff55c8fd35956a4
/java/src/main/java/org/dase/util/Writer.java
236da67de7685c951db2f8add7a2c8f98a47cb13
[]
no_license
md-k-sarker/XAI-HCBD
d5ce54f8598a788cb486ee1b935dc093112ee5b6
be05121e6b6471537af633896edaaeb53fe69cb1
refs/heads/master
2021-01-21T22:01:42.795278
2018-09-02T03:38:36
2018-09-02T03:38:36
95,147,108
0
0
null
null
null
null
UTF-8
Java
false
false
634
java
package org.dase.util; import java.io.BufferedWriter; import java.io.FileWriter; /** * This class will write statistics in disk. This class acts like a static class. * @author sarker * */ public class Writer { private Writer() { } public static boolean writeInDisk(String path, String msgs, boolean append) { try(BufferedWriter br = new BufferedWriter(new FileWriter(path,append))){ br.write(msgs); }catch(Exception E) { return false; } return true; } /** * This is for unit testing * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
[ "mdkamruzzamansarker@gmail.com" ]
mdkamruzzamansarker@gmail.com
bdaa9e9520d8adef115942c4ca246311055628fa
7862c51932a9e1201e76d01c0d6727f5970cdedd
/benchmarks/src/main/java/dispatch/PathologicPolymorphic.java
be31b64d4f7082a07d64ab3ebf4b144e8ec6e34a
[ "Apache-2.0" ]
permissive
jeffmaury/golo-lang
9c57bfc9e9250566842b13c96a6976b6ff7e6e19
6019821ff9129f627871e16fe5ce42208aeafe9d
refs/heads/master
2021-01-17T08:50:48.495405
2013-12-08T17:35:27
2013-12-08T17:35:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,352
java
/* * Copyright 2012-2013 Institut National des Sciences Appliquées de Lyon (INSA-Lyon) * * 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 dispatch; import java.lang.reflect.Method; import java.util.HashMap; import java.util.LinkedList; import java.util.TreeSet; public class PathologicPolymorphic { public static Object run() { Object[] data = data(); Object result = null; for (int i = 0; i < 200000; i++) { for (int j = 0; j < data.length; j++) { result = data[j].toString(); } } return result; } public static Object run_reflective_object() throws Throwable { Method toStringMethod = Object.class.getMethod("toString"); Object[] data = data(); Object result = null; for (int i = 0; i < 200000; i++) { for (int j = 0; j < data.length; j++) { result = toStringMethod.invoke(data[j]); } } return result; } public static Object run_reflective_pic() throws Throwable { HashMap<Class, Method> vtable = new HashMap<>(); Object[] data = data(); Object result = null; for (int i = 0; i < 200000; i++) { for (int j = 0; j < data.length; j++) { Class<?> type = data[j].getClass(); Method target = vtable.get(type); if (target == null) { target = type.getMethod("toString"); vtable.put(type, target); } result = target.invoke(data[j]); } } return result; } private static Object[] data() { return new Object[]{ "foo", 666, new Object(), "bar", 999, new LinkedList<>(), new HashMap<>(), new TreeSet<>(), new RuntimeException(), new IllegalArgumentException(), new IllegalStateException(), new Object(), new Exception() }; } }
[ "julien.ponge@insa-lyon.fr" ]
julien.ponge@insa-lyon.fr
99da24770985f416807395336fcad62be7a01434
dfe91841d077d5c3784ab026b4dc0348defa37fe
/CountPossibleEncodings.java
2977a224f51b5c85eb6566c37011eb39f5189ef0
[]
no_license
chaitanya552/my-java-programs
446361b3ed08b31f1ae8f8bb1f00e4b761258090
f324c9ada39eaf478b40e671f2441319e3d860b1
refs/heads/master
2022-02-18T08:00:34.739216
2019-09-20T06:11:42
2019-09-20T06:11:42
115,813,229
2
0
null
null
null
null
UTF-8
Java
false
false
1,390
java
public class CountPossibleEncodings { /** * It may be assumed that the input contains valid digits from 0 to 9 and there * are no leading 0′s, no extra trailing 0′s and no two or more consecutive 0′s. * * This is a recursive solution. Its time complexity is exponential: * T(n) = T(n-1) + T(n-2) + O(1) * * * @param digits * @return */ static int countEncodingsRecursive1(String digits){ // base case: int strLen = digits.length(); if(strLen==1 || strLen==0) return 1; int total=0; if(isValidNumber(digits)) total += 1; //A System.out.println("total now is"+ total); System.out.println(digits.substring(1)); total += countEncodingsRecursive1(digits.substring(1)); //b System.out.println("total at b "+total); if(strLen>2){ String prefix = digits.substring(0,2); System.out.println("prefix: " +prefix); String remain = digits.substring(2); System.out.println("remain: " +remain); if( isValidNumber(prefix) ) total += countEncodingsRecursive1(remain); } return total ; } static boolean isValidNumber(String str){ System.out.println("function isvalid number on "+ str); int val = Integer.valueOf(str); return (val>=0) && (val<=26); } public static void main(String[] args) { String str="123"; System.out.println(countEncodingsRecursive1(str)+" is answer"); } }
[ "chaitu10552@gmail.com" ]
chaitu10552@gmail.com
e291834aa978895f92c481a2e2ddd6bfe50ccfb2
6e378cf519841df03b83026572fd5ad2fde1a32d
/netflix-zuul-api-gateway-server/src/main/java/com/in28minutes/microservices/netflixzuulapigatewayserver/ZuulLoggingFilter.java
40d1809c102b757b5be015fc3d5086b467c1a506
[]
no_license
kendyjm/microservices-spring-cloud
fe29469ff1e4f9a574b39bf80eda863b290d0507
5ef362391f808fdf151a03f507d07920c296cd36
refs/heads/master
2022-12-10T01:40:49.114052
2020-09-04T20:06:34
2020-09-04T20:06:34
274,416,806
0
0
null
2020-09-04T20:06:35
2020-06-23T13:44:46
Java
UTF-8
Java
false
false
2,376
java
package com.in28minutes.microservices.netflixzuulapigatewayserver; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; @Component public class ZuulLoggingFilter extends ZuulFilter { private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * to classify a filter by type. Standard types in Zuul are "pre" for pre-routing filtering, * "route" for routing to an origin, "post" for post-routing filters, "error" for error handling. * We also support a "static" type for static responses see StaticResponseFilter. * Any filterType made be created or added and run by calling FilterProcessor.runFilters(type) * * @return A String representing that type */ @Override public String filterType() { return "pre"; // for pre-routing filtering } /** * filterOrder() must also be defined for a filter. Filters may have the same filterOrder if precedence is not * important for a filter. filterOrders do not need to be sequential. * * @return the int order of a filter */ @Override public int filterOrder() { return 1; } /** * a "true" return from this method means that the run() method should be invoked * * @return true if the run() method should be invoked. false will not invoke the run() method */ @Override public boolean shouldFilter() { return true; // true, executed for every requests } /** * if shouldFilter() is true, this method will be invoked. this method is the core method of a ZuulFilter * * @return Some arbitrary artifact may be returned. Current implementation ignores it. * @throws ZuulException if an error occurs during execution. */ @Override public Object run() throws ZuulException { // here is the complete logic of the filter // for now we just want to log the details of the requests HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); logger.info("Request -> {} request uri -> {}", request, request.getRequestURI()); return null; } }
[ "kendyjm@gmail.com" ]
kendyjm@gmail.com
76c26ec72193eafef29af7dae3324d36ede10d07
66d065f6c7e3573583526296c0de60f41d6defaa
/src/main/java/cn/hselfweb/mes/controller/WebController.java
e9498ab35be478e34a6037fa9a1626404e526636
[]
no_license
Cyberhan123/ManufacturingExecutionSystem
6f7fb206189a80ba9ef515becbf38d07641ac781
d4089fa968dc8c857c7f9760ff382769941730ff
refs/heads/master
2020-06-11T10:28:43.989968
2019-07-08T05:07:38
2019-07-08T05:07:38
193,931,608
0
0
null
null
null
null
UTF-8
Java
false
false
282
java
package cn.hselfweb.mes.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller class WebController { @RequestMapping(value = "/index") public String index() { return "index"; } }
[ "hanhan@corp.netease.com" ]
hanhan@corp.netease.com
08d3dffa8b54b917cf95d92efb8cde8defdf9be6
9db0123459a57a235028bb0a26f2fd0f2f228dfc
/threadwatchdog/src/main/java/com/android/liuzhuang/threadwatchdog/ui/ThreadDetailActivity.java
134d466dc3aba137f30851dacf71cd215df1108d
[]
no_license
helloyingying/ThreadWatchDog
cec9d170b88726543cdca95a0d10022b87c54095
fd79db16afb49ef6a2ee605c3cc302a25502df9b
refs/heads/master
2020-12-31T05:10:37.029754
2016-05-08T04:10:32
2016-05-08T04:10:32
58,296,120
2
0
null
null
null
null
UTF-8
Java
false
false
941
java
package com.android.liuzhuang.threadwatchdog.ui; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; import com.android.liuzhuang.threadwatchdog.R; public class ThreadDetailActivity extends Activity { public static final String EXTRA_KEY_TITLE = "thread_title"; public static final String EXTRA_KEY_STACK = "thread_stack"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_thread_detail); TextView title = (TextView) findViewById(R.id.title); TextView stack = (TextView) findViewById(R.id.stack); Intent intent = getIntent(); String titleStr = intent.getStringExtra(EXTRA_KEY_TITLE); String stackStr = intent.getStringExtra(EXTRA_KEY_STACK); title.setText(titleStr); stack.setText(stackStr); } }
[ "1439163149@qq.com" ]
1439163149@qq.com
549cae3c17c8e0b9b927f41f1e530a5da081368f
1a607c6d8d87cc01d3658bb32d600685e934e9d2
/src/main/java/com/kzw/entity/NoticeExample.java
2818cd3f7598520c979a49beedf40cf391afbf38
[]
no_license
kzw11/ssm_hrm
46592c8b61d6571248ce70c5ca3890f0526332f2
40e1e8b0b0d9fb8164afad23fdfe5c0297f3b3fa
refs/heads/master
2020-05-03T02:57:02.119517
2019-03-29T10:33:02
2019-03-29T10:33:02
178,384,464
0
0
null
null
null
null
UTF-8
Java
false
false
15,693
java
package com.kzw.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; public class NoticeExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public NoticeExample() { 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 andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andTitleIsNull() { addCriterion("title is null"); return (Criteria) this; } public Criteria andTitleIsNotNull() { addCriterion("title is not null"); return (Criteria) this; } public Criteria andTitleEqualTo(String value) { addCriterion("title =", value, "title"); return (Criteria) this; } public Criteria andTitleNotEqualTo(String value) { addCriterion("title <>", value, "title"); return (Criteria) this; } public Criteria andTitleGreaterThan(String value) { addCriterion("title >", value, "title"); return (Criteria) this; } public Criteria andTitleGreaterThanOrEqualTo(String value) { addCriterion("title >=", value, "title"); return (Criteria) this; } public Criteria andTitleLessThan(String value) { addCriterion("title <", value, "title"); return (Criteria) this; } public Criteria andTitleLessThanOrEqualTo(String value) { addCriterion("title <=", value, "title"); return (Criteria) this; } public Criteria andTitleLike(String value) { addCriterion("title like", value, "title"); return (Criteria) this; } public Criteria andTitleNotLike(String value) { addCriterion("title not like", value, "title"); return (Criteria) this; } public Criteria andTitleIn(List<String> values) { addCriterion("title in", values, "title"); return (Criteria) this; } public Criteria andTitleNotIn(List<String> values) { addCriterion("title not in", values, "title"); return (Criteria) this; } public Criteria andTitleBetween(String value1, String value2) { addCriterion("title between", value1, value2, "title"); return (Criteria) this; } public Criteria andTitleNotBetween(String value1, String value2) { addCriterion("title not between", value1, value2, "title"); return (Criteria) this; } public Criteria andContentIsNull() { addCriterion("content is null"); return (Criteria) this; } public Criteria andContentIsNotNull() { addCriterion("content is not null"); return (Criteria) this; } public Criteria andContentEqualTo(String value) { addCriterion("content =", value, "content"); return (Criteria) this; } public Criteria andContentNotEqualTo(String value) { addCriterion("content <>", value, "content"); return (Criteria) this; } public Criteria andContentGreaterThan(String value) { addCriterion("content >", value, "content"); return (Criteria) this; } public Criteria andContentGreaterThanOrEqualTo(String value) { addCriterion("content >=", value, "content"); return (Criteria) this; } public Criteria andContentLessThan(String value) { addCriterion("content <", value, "content"); return (Criteria) this; } public Criteria andContentLessThanOrEqualTo(String value) { addCriterion("content <=", value, "content"); return (Criteria) this; } public Criteria andContentLike(String value) { addCriterion("content like", value, "content"); return (Criteria) this; } public Criteria andContentNotLike(String value) { addCriterion("content not like", value, "content"); return (Criteria) this; } public Criteria andContentIn(List<String> values) { addCriterion("content in", values, "content"); return (Criteria) this; } public Criteria andContentNotIn(List<String> values) { addCriterion("content not in", values, "content"); return (Criteria) this; } public Criteria andContentBetween(String value1, String value2) { addCriterion("content between", value1, value2, "content"); return (Criteria) this; } public Criteria andContentNotBetween(String value1, String value2) { addCriterion("content not between", value1, value2, "content"); return (Criteria) this; } public Criteria andCreatetimeIsNull() { addCriterion("createtime is null"); return (Criteria) this; } public Criteria andCreatetimeIsNotNull() { addCriterion("createtime is not null"); return (Criteria) this; } public Criteria andCreatetimeEqualTo(Date value) { addCriterion("createtime =", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeNotEqualTo(Date value) { addCriterion("createtime <>", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeGreaterThan(Date value) { addCriterion("createtime >", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeGreaterThanOrEqualTo(Date value) { addCriterion("createtime >=", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeLessThan(Date value) { addCriterion("createtime <", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeLessThanOrEqualTo(Date value) { addCriterion("createtime <=", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeIn(List<Date> values) { addCriterion("createtime in", values, "createtime"); return (Criteria) this; } public Criteria andCreatetimeNotIn(List<Date> values) { addCriterion("createtime not in", values, "createtime"); return (Criteria) this; } public Criteria andCreatetimeBetween(Date value1, Date value2) { addCriterion("createtime between", value1, value2, "createtime"); return (Criteria) this; } public Criteria andCreatetimeNotBetween(Date value1, Date value2) { addCriterion("createtime not between", value1, value2, "createtime"); return (Criteria) this; } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Integer value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Integer> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "userId"); 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); } } }
[ "kuangziwen@peilian.com" ]
kuangziwen@peilian.com
1dd0ab178c9cb63a62d57ccfe335bb9527d332d9
821b5dd26496e011930fdfec9f335144549dea1b
/app/src/main/java/com/example/my/myuipractice/utils/StringUtils.java
6c6832c819fc358eed8adfc8fec0c9707c133bc0
[]
no_license
lzfengluo/UIpractice
57450b5f486ed7151d27d491e057109cad5874ff
deb2f37bf35758fb4db799834555cb0fe9dc599d
refs/heads/master
2021-06-26T15:28:53.752938
2020-10-27T07:19:35
2020-10-27T07:19:35
168,291,127
0
1
null
null
null
null
UTF-8
Java
false
false
3,929
java
package com.example.my.myuipractice.utils; import java.math.BigDecimal; public class StringUtils { public static String byteToHex(byte b) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() < 2) { hex = "0" + hex; } return hex; } public static String byteToHexString(byte[] b, int length) { String ret = ""; for (int i = 0; i < length; i++) { String hex = Integer.toHexString(b[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } ret += hex.toUpperCase(); } return ret; } public static String charToHexString(char[] data, int length) { byte[] bytes = new byte[2 * length]; int i; for (i = 0; i < length; i++) { bytes[2 * i] = (byte) (data[i] >> 8); bytes[2 * i + 1] = (byte) (data[i]); } return byteToHexString(bytes, 2 * length); } public static String stringToHexString(String s) { String str = ""; for (int i = 0; i < s.length(); i++) { int ch = (int) s.charAt(i); String s4 = Integer.toHexString(ch); str = str + s4; } return str; } public static char[] stringToChar(String value) { char[] WriteText = new char[(value.length() / 4)]; byte[] btemp = new byte[(value.length())]; for (int i = 0; i < btemp.length; i++) { btemp[i] = Byte.parseByte(value.substring(i, i + 1), 16); } for (int i = 0; i < WriteText.length; i++) { WriteText[i] = (char) (((btemp[i * 4 + 0] & 0x0f) << 12) | ((btemp[i * 4 + 1] & 0x0f) << 8) | ((btemp[i * 4 + 2] & 0x0f) << 4) | (btemp[i * 4 + 3] & 0x0f)); } return WriteText; } /** * 16进制的字符串表示转成字节数组 sl * * @param hexString 16进制格式的字符串 * @return 转换后的字节数组 **/ public static byte[] stringToByte(String hexString) { hexString = hexString.toLowerCase(); int length = hexString.length(); if (length % 2 != 0) { length = length + 1; } final byte[] byteArray = new byte[length / 2]; int k = 0; for (int i = 0; i < byteArray.length; i++) {// 因为是16进制,最多只会占用4位,转换成字节需要两个16进制的字符,高位在先 byte low; byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff); if ((k + 1) == hexString.length()) { low = 0; } else { low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff); } byteArray[i] = (byte) (high << 4 | low); k += 2; } return byteArray; } /** * 截取byte数组 * * @param data 原数组 * @param startInx 起始下标 * @param endInx 结束下标 * @return 返回截取后的byte[] */ public static byte[] subByteArray(byte[] data, int startInx, int endInx) { byte[] b1 = new byte[endInx - startInx]; System.arraycopy(data, startInx, b1, 0, endInx - startInx); return b1; } public static int byteArrayToInt(byte[] data) { int res = 0; res = (((data[0] & 0xFF) << 8) | (data[1] & 0xFF)); return res; } public static String HexstrToQ724(int val) throws Exception { int valuepint = val; // Math.Pow(2, 24); double value_q714 = valuepint * 1.0 / (new BigDecimal(2)).pow(24).intValue(); String q714 = String.valueOf(value_q714); if (value_q714 > 0) { return q714.substring(0, 6); } else { return q714.length() >= 7 ? q714.substring(0, 7) : q714; } } }
[ "zhichao.zhang@speedatagroup" ]
zhichao.zhang@speedatagroup
20ea6bc0af98749df9caa9bcbffa3cec1a5af0dc
f1ad468ee3ba18d963ee2a9dc90a9264ef3eb9cf
/PortfolioService/src/main/java/be/nielsvermeiren/PortfolioServiceApp.java
9090d30bcbac01e967dd6d91fee394fbf9a5c21c
[]
no_license
niels-vermeiren/spring-simple-microservices-poc
08d0f75b46026ca6cda38b0066d1a47bb7b1567d
885dbdb219d54b3c8e4957ce3dbd8030040ae130
refs/heads/main
2023-05-06T14:50:37.295979
2021-06-01T20:55:58
2021-06-01T20:55:58
372,955,049
0
0
null
2021-06-01T20:52:50
2021-06-01T20:35:10
null
UTF-8
Java
false
false
794
java
package be.nielsvermeiren; import be.nielsvermeiren.controller.ProjectController; import be.nielsvermeiren.proxy.CustomerServiceProxy; 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.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class PortfolioServiceApp { @Autowired ProjectController projectController; @Autowired CustomerServiceProxy customerServiceProxy; public static void main(String[] args) { SpringApplication.run(PortfolioServiceApp.class, args); } }
[ "unknown@example.com" ]
unknown@example.com
1a5f0ca7b3de65a9f5f0089d4920a4638f97d023
e72428c7ae1c3d9e54de094411ebe57a19238251
/src/test/java/com/divae/firstspirit/access/GuiScriptContextMockTest.java
926394f066f180a5c17ef126b82711a8605f0d42
[ "Apache-2.0" ]
permissive
diva-e/firstspirit-mocks
49e6c9dd2d73d12a8d301f93e843a551b18d1296
b9e34a8016faa327b775257fc444c2410ecf0c5a
refs/heads/master
2021-01-19T17:23:18.410303
2018-08-17T07:51:50
2018-08-17T07:51:50
82,452,920
1
2
Apache-2.0
2018-08-17T07:49:20
2017-02-19T11:03:20
Java
UTF-8
Java
false
false
812
java
package com.divae.firstspirit.access; import com.divae.firstspirit.MockTest; import org.junit.Test; import static com.divae.firstspirit.access.GuiScriptContextMock.guiScriptContextWith; import static com.divae.firstspirit.access.LanguageMock.languageWith; import static com.divae.firstspirit.access.project.ProjectMock.projectWith; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; public class GuiScriptContextMockTest extends MockTest { @Test public void testGuiScriptContextProjectWith() { assertThat(guiScriptContextWith(projectWith("project", 0, languageWith("DE"))), is(notNullValue())); } @Override protected Class<?> getFactoryClass() { return GuiScriptContextMock.class; } }
[ "christian.stornowski@diva-e.com" ]
christian.stornowski@diva-e.com
6a727f390b2777fdb816ad62c14872aecf975633
b1ddb33f915850afccaed09162bf084909936c2b
/app/src/main/java/com/bourne/caesar/impextutors/Utilities/SharedPreferencesStorage.java
d9b524fd2aae72f3edf00549056f54499df6c763
[]
no_license
CaesarBourne/CourseConfidential
4abb609e2ef9b529fce631f6b2bd22760110205c
6eca7f0274f4d03fd42540971b4c2cf31d82ce13
refs/heads/master
2020-04-13T05:18:28.097410
2019-06-27T15:28:22
2019-06-27T15:28:22
162,987,849
0
0
null
null
null
null
UTF-8
Java
false
false
4,815
java
package com.bourne.caesar.impextutors.Utilities; import android.content.Context; import android.content.SharedPreferences; public class SharedPreferencesStorage { public static final String SHARED_PREF_FILE ="sharedfile"; private Context mycontext; private static SharedPreferencesStorage newsharedInstance; private SharedPreferencesStorage(Context mycontext) { this.mycontext = mycontext; } public static synchronized SharedPreferencesStorage getSharedPrefInstance( Context mycontext){ if (newsharedInstance == null){ newsharedInstance = new SharedPreferencesStorage(mycontext); } return newsharedInstance; } public void saveCourseID( String CourseID){ SharedPreferences mysharedpreferences = mycontext.getSharedPreferences(SHARED_PREF_FILE, Context.MODE_PRIVATE); SharedPreferences.Editor sharededitor = mysharedpreferences.edit(); sharededitor.putString(Constants.IMPEX_COURSES_STORAGE, CourseID); sharededitor.apply(); } public void saveUserImage( String userImage){ SharedPreferences mysharedpreferences = mycontext.getSharedPreferences(SHARED_PREF_FILE, Context.MODE_PRIVATE); SharedPreferences.Editor sharededitor = mysharedpreferences.edit(); sharededitor.putString(Constants.IMPEX_USER_IMAGE, userImage); sharededitor.apply(); } public String getUserImages(String userImage){ SharedPreferences tokenSharedPreferences = mycontext.getSharedPreferences(SHARED_PREF_FILE, Context.MODE_PRIVATE); String userImageString = tokenSharedPreferences.getString(userImage, null); return userImageString; } public void saveCurrency( String currencyType){ SharedPreferences mysharedpreferences = mycontext.getSharedPreferences(SHARED_PREF_FILE, Context.MODE_PRIVATE); SharedPreferences.Editor sharededitor = mysharedpreferences.edit(); sharededitor.putString(Constants.IMPEX_CURRENCY, currencyType); sharededitor.apply(); } public String getCurrency(){ SharedPreferences tokenSharedPreferences = mycontext.getSharedPreferences(SHARED_PREF_FILE, Context.MODE_PRIVATE); String userImageString = tokenSharedPreferences.getString(Constants.IMPEX_CURRENCY, null); return userImageString; } // public void saveSession(String sessionString){ // SharedPreferences mysharedpreferences = mycontext.getSharedPreferences(SHARED_PREF_FILE, Context.MODE_PRIVATE); // SharedPreferences.Editor sharededitor = mysharedpreferences.edit(); // sharededitor.putString(Constants.SAVED_SESSION, sessionString); // sharededitor.apply(); // } // // public void saveUserId(int userid){ // SharedPreferences mysharedpreferences = mycontext.getSharedPreferences(SHARED_PREF_FILE, Context.MODE_PRIVATE); // SharedPreferences.Editor sharededitor = mysharedpreferences.edit(); // sharededitor.putInt(Constants.USER_ID, userid); // sharededitor.apply(); // } // // public boolean isLoggedIn(){ // SharedPreferences logsharedpreference = mycontext.getSharedPreferences(SHARED_PREF_FILE, Context.MODE_PRIVATE); // // boolean logedStatus = logsharedpreference.getInt(Constants.USER_ID, -1) != -1; // return logedStatus; // } // public String getBasicID(String tokenKey){ // SharedPreferences tokenSharedPreferences = mycontext.getSharedPreferences(SHARED_PREF_FILE, Context.MODE_PRIVATE); // String userToken = tokenSharedPreferences.getString(Constants.COOKIE_SAVED_USER, null); // return userToken; // } // public String getSession(String sessionKey){ // SharedPreferences tokenSharedPreferences = mycontext.getSharedPreferences(SHARED_PREF_FILE, Context.MODE_PRIVATE); // String session = tokenSharedPreferences.getString(sessionKey, null); // return session; // } public String getCoursePayStatus(String courseID){ SharedPreferences tokenSharedPreferences = mycontext.getSharedPreferences(SHARED_PREF_FILE, Context.MODE_PRIVATE); String userCookie = tokenSharedPreferences.getString(courseID, null); return userCookie; } public int getUserId(String useridKey){ SharedPreferences uidsharedPreferences = mycontext.getSharedPreferences(SHARED_PREF_FILE, Context.MODE_PRIVATE); int userId = uidsharedPreferences.getInt(useridKey, -1); return userId; } public void clearLogout(){ SharedPreferences logoutsharedpreferences = mycontext.getSharedPreferences(SHARED_PREF_FILE, Context.MODE_PRIVATE); SharedPreferences.Editor logoutsharededitor = logoutsharedpreferences.edit(); logoutsharededitor.clear(); logoutsharededitor.apply(); } }
[ "caesaradek@gmail.com" ]
caesaradek@gmail.com
e3439a932e54741817e41226dcf667c8391a3915
d9d7da23b729a1e91dcd44eefba82a06ed1e4c97
/Action.java
9437f986ab032059b1b5446f55ea18f914ecf449
[]
no_license
KGNavarro/JAVA-files
e176d238589f5d4edb28e72be4b77dfcbe76d174
423ad1b874d7742a39bac41f1aa44c188bc70c75
refs/heads/master
2020-04-17T19:32:56.290110
2019-02-05T00:52:51
2019-02-05T00:52:51
166,869,321
1
0
null
null
null
null
UTF-8
Java
false
false
929
java
package c.o.a.s.t; /** * * @author Kevin Navarro */ public class Action extends Option { String actionName = null; String actionDescription = null; public Action(){ } public Action(String actionName, String actionDescription){ this.actionName = actionName; this.actionDescription = actionDescription; } protected void useAction(){ } protected void initializeGameActions(){ Option attack = new Action(); Option castSpell = new Action(); Option dash = new Action(); Option disengage = new Action(); Option dodge = new Action(); Option help = new Action(); Option hide = new Action(); Option ready = new Action(); Option search = new Action(); Option object = new Action(); Option improvise = new Action(); } }
[ "noreply@github.com" ]
noreply@github.com
7adfca23dd94d1828396eb8cf96f460f784568c8
79998dae8da0dd034db597accf60c3f6a6e4bd98
/src/main/java/passerr/github/io/creational/factorymethod/BmwCar.java
c8fda1bd4e62c8bbd778a1a583e8558032c4e3c4
[]
no_license
PasseRR/DesignPatterns
1633774cbf872c4698f4300de7dd04aef1bf8dbe
03b06e0e1b049640814a6492eca8e36095338bb5
refs/heads/master
2023-08-21T14:29:13.763768
2023-08-10T09:07:07
2023-08-10T09:07:07
17,819,012
0
0
null
null
null
null
UTF-8
Java
false
false
256
java
package passerr.github.io.creational.factorymethod; /** * @author xiehai1 * @date 2017/07/12 22:08 * @Copyright(c) gome inc Gome Co.,LTD */ public class BmwCar implements Car { @Override public String getName() { return "Bmw"; } }
[ "xie__hai@sina.com" ]
xie__hai@sina.com
de792b4d013cb898361d9e77d181f2b005b093e7
eaf45eab3bb7741f314eec67856d5c3cd7d9b5c6
/src/main/java/commons/ArrayUtil.java
4d39f3f9b41468347e23b1ed58a37412aec6d092
[]
no_license
YuhanSun/Riso-Tree
5df61cd2bfb547612e2ca24acbcb305306509c84
1ae89af6fad0454dc553e63fd7c34479e2fdd0bc
refs/heads/wiki_rtree
2022-05-25T19:04:26.061084
2021-01-24T22:50:09
2021-01-24T22:50:09
84,517,622
2
1
null
2022-05-20T20:57:42
2017-03-10T04:01:38
Java
UTF-8
Java
false
false
2,457
java
package commons; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class ArrayUtil { public static <T extends Comparable<T>> boolean isSortedListEqual(List<T> l1, List<T> l2) { return l1.size() == l2.size() && l1.size() == sortedListIntersect(l1, l2).size(); } public static int[] iterableToIntArray(Iterable<Integer> iterable) { List<Integer> list = iterableToList(iterable); return listToArrayInt(list); } public static <T> List<T> iterableToList(Iterable<T> iterable) { List<T> res = new LinkedList<>(); for (T t : iterable) { res.add(t); } return res; } public static <T extends Comparable<T>> List<T> sortedListIntersect(List<T> l1, List<T> l2) { List<T> res = new ArrayList<>(l1.size() + l2.size()); int i = 0, j = 0; while (i < l1.size() && j < l2.size()) { if (l1.get(i).compareTo(l2.get(j)) < 0) i++; else { if (l1.get(i).compareTo(l2.get(j)) > 0) j++; else { res.add(l1.get(i)); i++; j++; } } } return res; } /** * Intersect two sorted list * * @param l1 * @param l2 * @return */ public static List<Integer> sortedListIntersect(List<Integer> l1, int[] l2) { List<Integer> res = new ArrayList<>(l1.size() + l2.length); int i = 0, j = 0; while (i < l1.size() && j < l2.length) { if (l1.get(i) < l2[j]) i++; else { if (l1.get(i) > l2[j]) j++; else { res.add(l2[j]); i++; j++; } } } return res; } /** * Convert an List to int[]. Because ArrayList.toArray() cannot work for int type. * * @param arrayList * @return */ public static int[] listToArrayInt(List<Integer> arrayList) { if (arrayList == null) { return null; } int[] res = new int[arrayList.size()]; int i = 0; for (int val : arrayList) { res[i] = val; i++; } return res; } public static List<Integer> intArrayToList(int[] array) { List<Integer> list = new ArrayList<>(array.length); for (int val : array) { list.add(val); } return list; } public static long Average(List<Long> arraylist) { if (arraylist.size() == 0) return -1; long sum = 0; for (long element : arraylist) sum += element; return sum / arraylist.size(); } }
[ "wdmzssyh@gmail.com" ]
wdmzssyh@gmail.com
da4b130e39c624e7aec8c3e8bba22eea86de1c90
bb4efc8889d33c147316ff2a2a962478e102bd26
/cpp/btp600/presentation/struts-2.0.6-all/struts-2.0.6/src/apps/showcase/src/main/java/org/apache/struts2/showcase/person/Person.java
fe4b323329fea1634d365ca862976a8f4a02a48d
[ "Apache-2.0" ]
permissive
tjduavis/bsd-toolkit
7fd0b24e9c9a72a5a64f80571b7ce01d4a61cd84
80deb263eca001bf23084e84db99c8cf02a0a333
refs/heads/master
2016-09-09T17:19:31.431634
2013-07-07T06:37:31
2013-07-07T06:37:31
11,229,216
1
1
null
null
null
null
UTF-8
Java
false
false
2,246
java
/* * $Id: Person.java 471756 2006-11-06 15:01:43Z husted $ * * 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.struts2.showcase.person; /** */ public class Person { Long id; String name; String lastName; public Person() { } public Person(Long id, String name, String lastName) { this.id = id; this.name = name; this.lastName = lastName; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Person person = (Person) o; if (id != null ? !id.equals(person.id) : person.id != null) return false; return true; } public int hashCode() { return (id != null ? id.hashCode() : 0); } public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", lastName='" + lastName + '\'' + '}'; } }
[ "tjduavis@tjduavis.local" ]
tjduavis@tjduavis.local
12152d7a36f48d9fc30606b321fc0ce9913c9d40
bcb2c4db5f57b4cf77f1535662c402b1d41dae85
/src/hu/timetable/model/service/Console.java
ddf300c41f2f61ddab10db2efa23b5da94acc7dc
[]
no_license
peterfazekas/2020-menetrend
661235decae0a87760b0cbb63714077b94884448
e09e7d4fbc800dfed6c293de628da19e82e65bb9
refs/heads/main
2023-03-07T20:56:22.977119
2021-02-19T10:16:13
2021-02-19T10:16:13
340,291,875
0
0
null
null
null
null
UTF-8
Java
false
false
560
java
package hu.timetable.model.service; import hu.timetable.model.domain.Time; import java.util.Scanner; public class Console { private final Scanner scanner; private final DataParser dataParser; public Console(Scanner scanner, DataParser dataParser) { this.scanner = scanner; this.dataParser = dataParser; } public Time readTime() { return dataParser.parseTime(scanner.nextLine()); } public int readInt() { int value = scanner.nextInt(); scanner.nextLine(); return value; } }
[ "v-pfazekas@hotels.com" ]
v-pfazekas@hotels.com
29a652e1fccac642e115d1e588caffac144f5eef
4de64c1e34bdaee5c77bdd71d47f344b08ca754f
/ServicesTracker/src/com/company/ServiceStatusChangeInfo.java
97765ce35f000db1a7ac21408fd7aa51f8c0d50a
[]
no_license
Paul-Kijtapart/MonitorServicesForMe
df76e73ca6523f0b5fb21ecb5c60a870d39aa6ed
2e208b437d4af1f6e16f293f5b232f76ff51c7c5
refs/heads/master
2021-01-19T23:05:26.039100
2017-04-21T00:20:36
2017-04-21T00:20:36
88,919,486
1
0
null
null
null
null
UTF-8
Java
false
false
825
java
package com.company; /** * Created by aor on 2017-04-19. */ public class ServiceStatusChangeInfo extends ServiceStatus { // Constants public static final String ADD_ACTION = "add"; public static final String DELETE_ACTION = "delete"; // States private String action; public ServiceStatusChangeInfo(String name, Integer pollingFrequency, String action) { super(name, pollingFrequency); this.action = action; } public ServiceStatusChangeInfo(ServiceStatus serviceStatus, String action) { this(serviceStatus.getName(), serviceStatus.getPollingFrequency(), action); } public String getAction() { return action; } @Override public String toString() { return super.toString() + " action " + this.action; } }
[ "scc385@gmail.com" ]
scc385@gmail.com
a83e040a641fa8b0ef8d23cf27662842efdb9a3b
92031d95e2ef562c3ce16ce7b744fd108e1d504a
/src/test/java/com/fpt/example/service/MailServiceIT.java
0e56fbd4feea297da3a09e79750fa7f9bdea8a8a
[]
no_license
azanulkhairi/jhipster
a78c1a1cb014a712b1d782e394856ba0a353a858
d45a6f3dd445b8e3188e45ac539ac1bf6b20e029
refs/heads/master
2022-12-24T08:57:44.350421
2019-07-05T07:53:25
2019-07-05T07:53:25
195,979,364
0
0
null
2022-12-16T05:01:48
2019-07-09T09:40:38
Java
UTF-8
Java
false
false
11,534
java
package com.fpt.example.service; import com.fpt.example.config.Constants; import com.fpt.example.TestJhipsterApp; import com.fpt.example.domain.User; import io.github.jhipster.config.JHipsterProperties; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.MessageSource; import org.springframework.mail.MailSendException; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.thymeleaf.spring5.SpringTemplateEngine; import javax.mail.Multipart; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.assertj.core.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; /** * Integration tests for {@link MailService}. */ @SpringBootTest(classes = TestJhipsterApp.class) public class MailServiceIT { private static String[] languages = { // jhipster-needle-i18n-language-constant - JHipster will add/remove languages in this array }; private static final Pattern PATTERN_LOCALE_3 = Pattern.compile("([a-z]{2})-([a-zA-Z]{4})-([a-z]{2})"); private static final Pattern PATTERN_LOCALE_2 = Pattern.compile("([a-z]{2})-([a-z]{2})"); @Autowired private JHipsterProperties jHipsterProperties; @Autowired private MessageSource messageSource; @Autowired private SpringTemplateEngine templateEngine; @Spy private JavaMailSenderImpl javaMailSender; @Captor private ArgumentCaptor<MimeMessage> messageCaptor; private MailService mailService; @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); doNothing().when(javaMailSender).send(any(MimeMessage.class)); mailService = new MailService(jHipsterProperties, javaMailSender, messageSource, templateEngine); } @Test public void testSendEmail() throws Exception { mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false); verify(javaMailSender).send(messageCaptor.capture()); MimeMessage message = messageCaptor.getValue(); assertThat(message.getSubject()).isEqualTo("testSubject"); assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent()).isInstanceOf(String.class); assertThat(message.getContent().toString()).isEqualTo("testContent"); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); } @Test public void testSendHtmlEmail() throws Exception { mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, true); verify(javaMailSender).send(messageCaptor.capture()); MimeMessage message = messageCaptor.getValue(); assertThat(message.getSubject()).isEqualTo("testSubject"); assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent()).isInstanceOf(String.class); assertThat(message.getContent().toString()).isEqualTo("testContent"); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public void testSendMultipartEmail() throws Exception { mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, false); verify(javaMailSender).send(messageCaptor.capture()); MimeMessage message = messageCaptor.getValue(); MimeMultipart mp = (MimeMultipart) message.getContent(); MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); ByteArrayOutputStream aos = new ByteArrayOutputStream(); part.writeTo(aos); assertThat(message.getSubject()).isEqualTo("testSubject"); assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent()).isInstanceOf(Multipart.class); assertThat(aos.toString()).isEqualTo("\r\ntestContent"); assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); } @Test public void testSendMultipartHtmlEmail() throws Exception { mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, true); verify(javaMailSender).send(messageCaptor.capture()); MimeMessage message = messageCaptor.getValue(); MimeMultipart mp = (MimeMultipart) message.getContent(); MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); ByteArrayOutputStream aos = new ByteArrayOutputStream(); part.writeTo(aos); assertThat(message.getSubject()).isEqualTo("testSubject"); assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent()).isInstanceOf(Multipart.class); assertThat(aos.toString()).isEqualTo("\r\ntestContent"); assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public void testSendEmailFromTemplate() throws Exception { User user = new User(); user.setLogin("john"); user.setEmail("john.doe@example.com"); user.setLangKey("en"); mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title"); verify(javaMailSender).send(messageCaptor.capture()); MimeMessage message = messageCaptor.getValue(); assertThat(message.getSubject()).isEqualTo("test title"); assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("<html>test title, http://127.0.0.1:8080, john</html>\n"); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public void testSendActivationEmail() throws Exception { User user = new User(); user.setLangKey(Constants.DEFAULT_LANGUAGE); user.setLogin("john"); user.setEmail("john.doe@example.com"); mailService.sendActivationEmail(user); verify(javaMailSender).send(messageCaptor.capture()); MimeMessage message = messageCaptor.getValue(); assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent().toString()).isNotEmpty(); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public void testCreationEmail() throws Exception { User user = new User(); user.setLangKey(Constants.DEFAULT_LANGUAGE); user.setLogin("john"); user.setEmail("john.doe@example.com"); mailService.sendCreationEmail(user); verify(javaMailSender).send(messageCaptor.capture()); MimeMessage message = messageCaptor.getValue(); assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent().toString()).isNotEmpty(); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public void testSendPasswordResetMail() throws Exception { User user = new User(); user.setLangKey(Constants.DEFAULT_LANGUAGE); user.setLogin("john"); user.setEmail("john.doe@example.com"); mailService.sendPasswordResetMail(user); verify(javaMailSender).send(messageCaptor.capture()); MimeMessage message = messageCaptor.getValue(); assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent().toString()).isNotEmpty(); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public void testSendEmailWithException() throws Exception { doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class)); mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false); } @Test public void testSendLocalizedEmailForAllSupportedLanguages() throws Exception { User user = new User(); user.setLogin("john"); user.setEmail("john.doe@example.com"); for (String langKey : languages) { user.setLangKey(langKey); mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title"); verify(javaMailSender, atLeastOnce()).send(messageCaptor.capture()); MimeMessage message = messageCaptor.getValue(); String propertyFilePath = "i18n/messages_" + getJavaLocale(langKey) + ".properties"; URL resource = this.getClass().getClassLoader().getResource(propertyFilePath); File file = new File(new URI(resource.getFile()).getPath()); Properties properties = new Properties(); properties.load(new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"))); String emailTitle = (String) properties.get("email.test.title"); assertThat(message.getSubject()).isEqualTo(emailTitle); assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("<html>" + emailTitle + ", http://127.0.0.1:8080, john</html>\n"); } } /** * Convert a lang key to the Java locale. */ private String getJavaLocale(String langKey) { String javaLangKey = langKey; Matcher matcher2 = PATTERN_LOCALE_2.matcher(langKey); if (matcher2.matches()) { javaLangKey = matcher2.group(1) + "_"+ matcher2.group(2).toUpperCase(); } Matcher matcher3 = PATTERN_LOCALE_3.matcher(langKey); if (matcher3.matches()) { javaLangKey = matcher3.group(1) + "_" + matcher3.group(2) + "_" + matcher3.group(3).toUpperCase(); } return javaLangKey; } }
[ "Tia.kartika@fsoft.com.vn" ]
Tia.kartika@fsoft.com.vn
dcaea46d9207d10944fdf54a9b912d53fbce9adf
25490a39cbbfd988f6ae7358245854b9529cdbbb
/vert-admin/src/main/java/com/zhaoyang/vert/module/system/service/NoticeService.java
5b7ad2e43e76eb00f430f68f372cc11373cf8e24
[]
no_license
qlnujsjlzy/vert
9c0b44fbb67427f5ad41ae385b54dff6bd08d8b0
c9af6a423a25398d13c1101a003af81c3723b4b2
refs/heads/master
2020-03-15T21:30:26.871074
2018-05-11T16:11:01
2018-05-11T16:11:16
132,356,169
0
0
null
null
null
null
UTF-8
Java
false
false
452
java
package com.zhaoyang.vert.module.system.service; import com.baomidou.mybatisplus.service.IService; import com.zhaoyang.vert.module.system.model.Notice; import java.util.List; import java.util.Map; /** * <p> * 通知表 服务类 * </p> * * @author : zhaoyang.li * @date : 2018/5/10 */ public interface NoticeService extends IService<Notice> { /** * 获取通知列表 */ List<Map<String, Object>> list(String condition); }
[ "lzhy719@163.com" ]
lzhy719@163.com
501660868a7142d2728b00f64cfd1c41a287623f
824f8b7593791c97954ce1519e1dd24d20c3e3cd
/src/creational/factory/concretecreator/example2/product/PaintingDocument.java
1ef596ec6ae494658b26002249bae63a44fcefd3
[]
no_license
vikaskundarapu/Design-Patterns
eedce6f8936eda3617eec595c4df27b657644ffb
e83d4fc3607bc7ebe984af64c4db6c6a88724fb9
refs/heads/master
2021-03-13T11:22:55.137768
2020-05-31T11:28:31
2020-05-31T11:28:31
246,675,121
0
0
null
null
null
null
UTF-8
Java
false
false
228
java
package creational.factory.concretecreator.example2.product; public class PaintingDocument implements Document { @Override public void printDocument() { System.out.println("Printing the PaintingDocument"); } }
[ "vikas.kundarapu@gmail.com" ]
vikas.kundarapu@gmail.com
de03b0a53df3dfced8d88a8f3158c760e72997ed
8ba459dbdeef57b128e9c9eff706571ea117ee34
/src/main/java/cn/itcast/travel/dao/OrderTest.java
baef67a029b06e0511f37ec074aea235f76823f0
[]
no_license
bkZhu/travel
2bfffaac546ff012c5f75cc4292518c3e385108b
fccae269fa06b0f6f4510fd0ed1d918c4f547b6d
refs/heads/main
2023-02-15T07:55:39.668891
2021-01-12T08:33:41
2021-01-12T08:33:41
328,904,456
0
0
null
null
null
null
UTF-8
Java
false
false
404
java
package cn.itcast.travel.dao; import cn.itcast.travel.dao.impl.OrderDaoImpl; import org.junit.Test; public class OrderTest { @Test public void OrderDaoTest(){ OrderDaoImpl o = new OrderDaoImpl(); System.out.println(o.findAll()); System.out.println(o.findByName("张三")); System.out.println(o.findNOrder()); System.out.println(o.findYOrder()); } }
[ "851058873@qq.com" ]
851058873@qq.com
ec6c54b03efef65e66a26ed833debcf968d2aa4e
64a7274fd81651fe8ba8beb00cf14aad3dbc2232
/ninja-appengine-blog/src/main/java/conf/Routes.java
10ee2ca181410b46ec0e7957cdf8e69902276569
[ "Apache-2.0" ]
permissive
h4ck4life/ninja-appengine
7abf9f9673115ba93085a53700888b5563c777da
622bd38aad31aacc1a5296a8fd64ad78a8a95819
refs/heads/master
2020-12-25T05:44:54.522047
2013-06-13T09:13:49
2013-06-13T09:13:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,531
java
/** * Copyright (C) 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 conf; import ninja.AssetsController; import ninja.Router; import ninja.application.ApplicationRoutes; import controllers.ApiController; import controllers.ApplicationController; import controllers.ArticleController; import controllers.LoginLogoutController; public class Routes implements ApplicationRoutes { /** * Using a (almost) nice DSL we can configure the router. * * The second argument NinjaModuleDemoRouter contains all routes of a * submodule. By simply injecting it we activate the routes. * * @param router * The default router of this application */ @Override public void init(Router router) { // puts test data into db: router.GET().route("/setup").with(ApplicationController.class, "setup"); /////////////////////////////////////////////////////////////////////// // Login / Logout /////////////////////////////////////////////////////////////////////// router.GET().route("/login").with(LoginLogoutController.class, "login"); router.POST().route("/login").with(LoginLogoutController.class, "loginPost"); router.GET().route("/logout").with(LoginLogoutController.class, "logout"); /////////////////////////////////////////////////////////////////////// // Create new article /////////////////////////////////////////////////////////////////////// router.GET().route("/article/new").with(ArticleController.class, "articleNew"); router.POST().route("/article/new").with(ArticleController.class, "articleNewPost"); /////////////////////////////////////////////////////////////////////// // Create new article /////////////////////////////////////////////////////////////////////// router.GET().route("/article/{id}").with(ArticleController.class, "articleShow"); /////////////////////////////////////////////////////////////////////// // Api for management of software /////////////////////////////////////////////////////////////////////// router.GET().route("/api/{username}/articles").with(ApiController.class, "getArticles"); router.POST().route("/api/{username}/article").with(ApiController.class, "postArticle"); /////////////////////////////////////////////////////////////////////// // Assets (pictures / javascript) /////////////////////////////////////////////////////////////////////// router.GET().route("/assets/.*").with(AssetsController.class, "serve"); /////////////////////////////////////////////////////////////////////// // Index / Catchall shows index page /////////////////////////////////////////////////////////////////////// router.GET().route("/.*").with(ApplicationController.class, "index"); } }
[ "raphael.andre.bauer@gmail.com" ]
raphael.andre.bauer@gmail.com
726d680b4ccfeab570e36e4b6229b5021fda1c7c
7e7821ab0a90d8a146adcd133eece9c157cb0bc5
/file-server/src/main/java/com/mcloud/fileserver/service/designPattern/cloudAbstractFactory/AliyunFactory.java
fc3f9b447c39b9c26bdfd6cebff9b53ab621bade
[]
no_license
vellerzheng/intelligent-storage
9e704b4ec88bf6a970464eb2b47291228c6391df
3487ef787a81a5589ef34d05e0206587d8386b36
refs/heads/master
2020-03-19T11:02:52.358129
2018-11-29T13:52:04
2018-11-29T13:52:04
136,425,021
1
0
null
null
null
null
UTF-8
Java
false
false
532
java
package com.mcloud.fileserver.service.designPattern.cloudAbstractFactory; import com.mcloud.fileserver.repository.entity.ConfAliyun; import com.mcloud.fileserver.service.cloud.CloudService; import com.mcloud.fileserver.service.cloud.impl.AliyunServiceImpl; /** * @Author: vellerzheng * @Description: * @Date:Created in 16:09 2018/6/7 * @Modify By: */ public class AliyunFactory implements Provider { @Override public CloudService produce(Object obj) { return new AliyunServiceImpl((ConfAliyun) obj); } }
[ "vellerzheng2012@163.com" ]
vellerzheng2012@163.com
49312a2b69d3a29328e5afb9062684113d43e39f
0bf65dd7d1216fc67fc7c063f97936ec68c483b2
/customer-service/src/main/java/com/onlineshopping/customerservice/CustomConfiguration.java
6e7b24020e38c245e2dcb7ef4c3689bc8d6793ba
[]
no_license
GayatriSW/MSA_CaseStudy
313b57168637e39837ae039d85868b44e2643ec2
b01eaeb334e65275f78de7e5ec00be176ef38dee
refs/heads/master
2020-11-23T18:41:30.361467
2019-12-17T07:00:42
2019-12-17T07:00:42
227,772,478
0
0
null
null
null
null
UTF-8
Java
false
false
892
java
package com.onlineshopping.customerservice; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Component; @RefreshScope @Component @ConfigurationProperties(prefix="customer-service") public class CustomConfiguration { private String queueName; private String exchange; private String routingkey; public String getQueueName() { return queueName; } public String getExchange() { return exchange; } public String getRoutingkey() { return routingkey; } public void setQueueName(String queueName) { this.queueName = queueName; } public void setExchange(String exchange) { this.exchange = exchange; } public void setRoutingkey(String routingkey) { this.routingkey = routingkey; } }
[ "student@win2012base" ]
student@win2012base
15d8c29a77645cf565ca710ad05fad8abd8605b0
1d9ea5de2bffe5c5371bec6cd348c201540ecce5
/emCardTools/src/main/java/emcardtools/SimulatedCard.java
8fad5b94ec2732472405a66fdc21eeea0b2890ca
[ "MIT" ]
permissive
mvondracek/PV204_smartcards_Emerald
a2e45418298893b590e1ff0be70b7c0b800dcda9
1e27348819799da9cff6f99a034774c3d2d65eef
refs/heads/dev
2023-04-02T10:28:49.904295
2023-03-22T23:31:04
2023-03-22T23:31:04
245,839,515
0
1
null
2020-04-23T20:35:46
2020-03-08T15:30:36
Java
UTF-8
Java
false
false
2,811
java
/* This file was merged and modified based on "JavaCard Template project with Gradle" which was published under MIT license included below. https://github.com/crocs-muni/javacard-gradle-template-edu License from 2020-04-18 https://github.com/crocs-muni/javacard-gradle-template-edu/blob/ebcb012a192092678eb9b7f198be5a6a26136f31/LICENSE ~~~ The MIT License (MIT) Copyright (c) 2015 Dusan Klinec, Martin Paljak, Petr Svenda 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 emcardtools; import javax.smartcardio.ATR; import javax.smartcardio.Card; import javax.smartcardio.CardChannel; import javax.smartcardio.CardException; /** * * @author Petr Svenda */ public class SimulatedCard extends Card { @Override public ATR getATR() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getProtocol() { throw new UnsupportedOperationException("Not supported yet."); } @Override public CardChannel getBasicChannel() { throw new UnsupportedOperationException("Not supported yet."); } @Override public CardChannel openLogicalChannel() throws CardException { throw new UnsupportedOperationException("Not supported yet."); } @Override public void beginExclusive() throws CardException { throw new UnsupportedOperationException("Not supported yet."); } @Override public void endExclusive() throws CardException { throw new UnsupportedOperationException("Not supported yet."); } @Override public byte[] transmitControlCommand(int i, byte[] bytes) throws CardException { throw new UnsupportedOperationException("Not supported yet."); } @Override public void disconnect(boolean bln) throws CardException { // do nothing } }
[ "vondracek.mar@gmail.com" ]
vondracek.mar@gmail.com
39e1f6e3555e4356238b16d283ce8549c0017c70
901c2693b04431ab96a557822649ff5a9dd0764c
/src/main/java/com/MySpringBoot2Application2.java
f470b8f5e74bd106e5c919b6bfa9cda06aedf5fd
[]
no_license
wangtianyang0/eclipse
8f4496618522415a5baeac5eb9e1a6f40adb1a93
c2dfdc2a621e1f1a5b4ebc28257273b196cb1c93
refs/heads/master
2021-09-09T09:59:49.076081
2018-03-15T00:56:23
2018-03-15T00:56:23
125,207,586
0
0
null
null
null
null
UTF-8
Java
false
false
5,198
java
package com; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.RedisTemplate; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Assert; import com.data.redis.util.RedisUtil; import com.MySpringBoot2ApplicationTests; import redis.clients.jedis.Jedis; import com.data.redis.usr.User; @EnableAutoConfiguration @ComponentScan @SpringBootApplication public class MySpringBoot2Application2 { @Autowired private static RedisTemplate<String, User> redisTemplate; @Test public void test() throws Exception { // 保存对象 // User user = new User("超人", 20); // redisTemplate.opsForValue().set(user.getUsername(), user); // user = new User("蝙蝠侠", 30); // redisTemplate.opsForValue().set(user.getUsername(), user); // user = new User("蜘蛛侠", 40); // redisTemplate.opsForValue().set(user.getUsername(), user); // System.out.println("This is the test---------"); // Assert.assertEquals(20, redisTemplate.opsForValue().get("超人").getAge().longValue()); // Assert.assertEquals(30, redisTemplate.opsForValue().get("蝙蝠侠").getAge().longValue()); // Assert.assertEquals(40, redisTemplate.opsForValue().get("蜘蛛侠").getAge().longValue()); } public static void main(String[] args) throws Exception { SpringApplication.run(MySpringBoot2Application2.class, args); //SpringApplication.run(MySpringBoot2ApplicationTests.class); System.out.println("-----------------"); System.out.println("This is spring-boot"); // Jedis jedis=new Jedis("10.124.3.1",7101); // for (int i = 0; i <1000; i++) { // jedis.del("key222"+i); // System.out.println("设置key"+i+"的数据到redis"); // Thread.sleep(2); // } // //执行保存,会在服务器下生成一个dump.rdb数据库文件 // jedis.save(); // jedis.close(); // System.out.println("写入完成"); Jedis jedis = RedisUtil.getJedis(); //jedis.set("key11111114","11111111111"); User user = new User(); // user.setUser("key11111555", "1257900000"); // Set<String> list1 = new HashSet<String>(); // list1 = user.getAllUser("key11111555"); // // // Map<String,String> map = user.getAllUserInformation("1000000000000001"); // // user.printAllUserInformation(user.getAllUserInformation("1000000000000001")); // user.updateUserInformationByUseID("1000000000000050", "100040", "23010345666666","1000000", "200", "system", "1"); // for (String key : map.keySet()) { // String a = "字段: " + key + " 值为: " + map.get(key); // System.out.println(a); // } // String cust_name = jedis.hget("1000000000000001", "CUST_NAME"); // System.out.println(cust_name); // Set<String> list2 = new HashSet<String>(); // Map<String,String> map = new HashMap<String,String>(); // list2 = jedis.hkeys("1000000000000001"); // map = jedis.hgetAll("1000000000000001"); // // for (String key : map.keySet()) { // System.out.println("key= " + key + " and value= " + map.get(key)); // } User user1 = new User(); Set<String> list3 = new HashSet<String>(); list3 = user1.getUSER_IDbyPSPT_ID("index\\011111111"); Iterator<String> it = list3.iterator(); while(it.hasNext()){ System.out.println((String)it.next()); } // for(String list: list2) // { // System.out.println(list); // } //user.deleteValue("1000000000000050", "USER_ID"); jedis.save(); jedis.close(); System.out.println("-------------------"); //private RedisTemplate<String, User> redisTemplate; // User user = new User("超人", 20); // redisTemplate.opsForValue().set(user.getUsername(), user); // user = new User("蝙蝠侠", 30); // redisTemplate.opsForValue().set(user.getUsername(), user); // user = new User("蜘蛛侠", 40); // redisTemplate.opsForValue().set(user.getUsername(), user); // System.out.println("This is the test---------"); // Assert.assertEquals(20, redisTemplate.opsForValue().get("超人").getAge().longValue()); // Assert.assertEquals(30, redisTemplate.opsForValue().get("蝙蝠侠").getAge().longValue()); // Assert.assertEquals(40, redisTemplate.opsForValue().get("蜘蛛侠").getAge().longValue()); // //MySpringBoot2Application mysb2 = new MySpringBoot2Application(); //mysb2.test(); System.out.println("----------------"); System.out.println("This is spring-boot-end"); } }
[ "2450940650@qq.com" ]
2450940650@qq.com
e05bb3484103d926e0db040a586d9de6c8debf1f
e90d1717e42304bcedeb0e156e7799aebb05d1fd
/provider/src/main/java/ruan/provider/elasticsearch/common/EsAsyncAction.java
204c1eb07851d546e4136e6fbecb4539ec128eba
[]
no_license
RBH123/parent
57d710f102f0298afc349411d09f88e3212b9542
fddd36f8486acab05849d43067ac076cdd651021
refs/heads/master
2023-03-10T16:22:13.349604
2021-02-26T10:02:51
2021-02-26T10:02:51
306,595,720
0
1
null
null
null
null
UTF-8
Java
false
false
869
java
package ruan.provider.elasticsearch.common; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.action.ActionListener; import org.elasticsearch.index.reindex.BulkByScrollResponse; import org.elasticsearch.index.reindex.BulkByScrollTask.Status; import org.springframework.stereotype.Component; import ruan.provider.common.ServerException; @Slf4j @Component public class EsAsyncAction implements ActionListener<BulkByScrollResponse> { @Override public void onResponse(BulkByScrollResponse response) { Status status = response.getStatus(); long total = status.getTotal(); log.info("累计操作成功:{}条", total); } @SneakyThrows @Override public void onFailure(Exception e) { log.error("操作es异常:{}", e); throw new ServerException("操作异常!"); } }
[ "rocky.ruan@shengyecapital.com" ]
rocky.ruan@shengyecapital.com
96129003f0aeefe355973da01745c9c50d6ae118
725dc02c939157f7059e439d4d1bfe998c870f2d
/product/src/product/DBConnection.java
cf7619e96c8113a3711702870299016db91f3677
[]
no_license
kabeersohail/Sudha
edb1c2a88fc7a024b519208d4e773426f0b577a6
f62aad421374d9c40d0616d94c7969671d46cb01
refs/heads/master
2022-04-01T17:03:29.242662
2020-01-23T12:41:30
2020-01-23T12:41:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
442
java
package product; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBConnection { public static void main(String[] args) { Connection con=null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection("jdbc:oracle:thin:@oracle02:1521:xe","training1","syntel123"); } catch (Exception e) { System.out.println(e); } } }
[ "noreply@github.com" ]
noreply@github.com
51e5c013db31890aeaa6eec2961945088d90bd54
62ab6b31d86568cad481ac1ba6c4f7c79f52b59d
/dvp-final/etude-de-cas/rdvmedecins-webjson-server/src/main/java/rdvmedecins/web/controllers/RdvMedecinsController.java
6ffbf545f30ce4a6f07f0c7a550a8a070ad891c7
[]
no_license
titaxman/THAHE
ec2ea87e05db0042a6763ad348f84d2e76e5ecc8
73c411558ee9002fc5d03b0542b24e156d6be8f2
refs/heads/master
2021-01-10T02:35:20.794781
2015-05-26T18:35:15
2015-05-26T18:35:15
36,356,130
0
0
null
null
null
null
UTF-8
Java
false
false
16,332
java
package rdvmedecins.web.controllers; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import rdvmedecins.domain.AgendaMedecinJour; import rdvmedecins.entities.Client; import rdvmedecins.entities.Creneau; import rdvmedecins.entities.Medecin; import rdvmedecins.entities.Rv; import rdvmedecins.web.helpers.Static; import rdvmedecins.web.models.ApplicationModel; import rdvmedecins.web.models.PostAjouterRv; import rdvmedecins.web.models.PostSupprimerRv; import rdvmedecins.web.models.Response; @RestController public class RdvMedecinsController { @Autowired private ApplicationModel application; @Autowired private RdvMedecinsCorsController rdvMedecinsCorsController; @Autowired private MappingJackson2HttpMessageConverter converter; // liste de messages private List<String> messages; // mapper JSON private ObjectMapper mapper; @PostConstruct public void init() { // messages d'erreur de l'application messages = application.getMessages(); // mapper JSON mapper = converter.getObjectMapper(); } // début méthodes locales // --------------------------------------------------------------- private Response<Medecin> getMedecin(long id) { // on récupère le médecin Medecin médecin = null; try { médecin = application.getMedecinById(id); } catch (Exception e1) { return new Response<Medecin>(1, Static.getErreursForException(e1), null); } // médecin existant ? if (médecin == null) { List<String> messages = new ArrayList<String>(); messages.add(String.format("Le médecin d'id [%s] n'existe pas", id)); return new Response<Medecin>(2, messages, null); } // ok return new Response<Medecin>(0, null, médecin); } private Response<Client> getClient(long id) { // on récupère le client Client client = null; try { client = application.getClientById(id); } catch (Exception e1) { return new Response<Client>(1, Static.getErreursForException(e1), null); } // client existant ? if (client == null) { List<String> messages = new ArrayList<String>(); messages.add(String.format("Le client d'id [%s] n'existe pas", id)); return new Response<Client>(2, messages, null); } // ok return new Response<Client>(0, null, client); } private Response<Rv> getRv(long id) { // on récupère le Rv Rv rv = null; try { rv = application.getRvById(id); } catch (Exception e1) { return new Response<Rv>(1, Static.getErreursForException(e1), null); } // Rv existant ? if (rv == null) { List<String> messages = new ArrayList<String>(); messages.add(String.format("Le rendez-vous d'id [%s] n'existe pas", id)); return new Response<Rv>(2, messages, null); } // ok return new Response<Rv>(0, null, rv); } private Response<Creneau> getCreneau(long id) { // on récupère le créneau Creneau créneau = null; try { créneau = application.getCreneauById(id); } catch (Exception e1) { return new Response<Creneau>(1, Static.getErreursForException(e1), null); } // créneau existant ? if (créneau == null) { List<String> messages = new ArrayList<String>(); messages.add(String.format("Le créneau d'id [%s] n'existe pas", id)); return new Response<Creneau>(2, messages, null); } // ok return new Response<Creneau>(0, null, créneau); } // liste des médecins @RequestMapping(value = "/getAllMedecins", method = RequestMethod.GET) public Response<List<Medecin>> getAllMedecins(HttpServletResponse response, @RequestHeader(value = "Origin", required = false) String origin) { // entêtes CORS rdvMedecinsCorsController.sendOptions(origin, response); // état de l'application if (messages != null) { return new Response<List<Medecin>>(-1, messages, null); } // liste des médecins try { return new Response<List<Medecin>>(0, null, application.getAllMedecins()); } catch (Exception e) { return new Response<List<Medecin>>(1, Static.getErreursForException(e), null); } } // liste des clients @RequestMapping(value = "/getAllClients", method = RequestMethod.GET) public Response<List<Client>> getAllClients(HttpServletResponse response, @RequestHeader(value = "Origin", required = false) String origin) { // entêtes CORS rdvMedecinsCorsController.sendOptions(origin, response); // état de l'application if (messages != null) { return new Response<List<Client>>(-1, messages, null); } // liste des clients try { return new Response<List<Client>>(0, null, application.getAllClients()); } catch (Exception e) { return new Response<List<Client>>(1, Static.getErreursForException(e), null); } } // liste des créneaux d'un médecin @RequestMapping(value = "/getAllCreneaux/{idMedecin}", method = RequestMethod.GET) public Response<List<Creneau>> getAllCreneaux(@PathVariable("idMedecin") long idMedecin, HttpServletResponse response, @RequestHeader(value = "Origin", required = false) String origin) { // entêtes CORS rdvMedecinsCorsController.sendOptions(origin, response); // état de l'application if (messages != null) { return new Response<List<Creneau>>(-1, messages, null); } // on récupère le médecin Response<Medecin> responseMedecin = getMedecin(idMedecin); if (responseMedecin.getStatus() != 0) { return new Response<List<Creneau>>(responseMedecin.getStatus(), responseMedecin.getMessages(), null); } Medecin médecin = responseMedecin.getBody(); // créneaux du médecin List<Creneau> créneaux = null; try { créneaux = application.getAllCreneaux(médecin.getId()); } catch (Exception e1) { return new Response<List<Creneau>>(3, Static.getErreursForException(e1), null); } // on rend la réponse SimpleBeanPropertyFilter creneauFilter = SimpleBeanPropertyFilter.serializeAllExcept("medecin"); mapper.setFilters(new SimpleFilterProvider().addFilter("creneauFilter", creneauFilter)); return new Response<List<Creneau>>(0, null, créneaux); } // liste des rendez-vous d'un médecin @RequestMapping(value = "/getRvMedecinJour/{idMedecin}/{jour}", method = RequestMethod.GET) public Response<List<Rv>> getRvMedecinJour(@PathVariable("idMedecin") long idMedecin, @PathVariable("jour") String jour, HttpServletResponse response, @RequestHeader(value = "Origin", required = false) String origin) { // entêtes CORS rdvMedecinsCorsController.sendOptions(origin, response); // état de l'application if (messages != null) { return new Response<List<Rv>>(-1, messages, null); } // on vérifie la date Date jourAgenda = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sdf.setLenient(false); try { jourAgenda = sdf.parse(jour); } catch (ParseException e) { List<String> messages = new ArrayList<String>(); messages.add(String.format("La date [%s] est invalide", jour)); return new Response<List<Rv>>(3, messages, null); } // on récupère le médecin Response<Medecin> responseMedecin = getMedecin(idMedecin); if (responseMedecin.getStatus() != 0) { return new Response<List<Rv>>(responseMedecin.getStatus(), responseMedecin.getMessages(), null); } Medecin médecin = responseMedecin.getBody(); // liste de ses rendez-vous List<Rv> rvs = null; try { rvs = application.getRvMedecinJour(médecin.getId(), jourAgenda); } catch (Exception e1) { return new Response<List<Rv>>(4, Static.getErreursForException(e1), null); } // on rend la réponse SimpleBeanPropertyFilter rvFilter = SimpleBeanPropertyFilter.serializeAllExcept(); SimpleBeanPropertyFilter creneauFilter = SimpleBeanPropertyFilter.serializeAllExcept("medecin"); mapper.setFilters(new SimpleFilterProvider().addFilter("rvFilter", rvFilter).addFilter("creneauFilter", creneauFilter)); return new Response<List<Rv>>(0, null, rvs); } @RequestMapping(value = "/getClientById/{id}", method = RequestMethod.GET) public Response<Client> getClientById(@PathVariable("id") long id, HttpServletResponse response, @RequestHeader(value = "Origin", required = false) String origin) { // entêtes CORS rdvMedecinsCorsController.sendOptions(origin, response); // état de l'application if (messages != null) { return new Response<Client>(-1, messages, null); } // on récupère le client return getClient(id); } @RequestMapping(value = "/getMedecinById/{id}", method = RequestMethod.GET) public Response<Medecin> getMedecinById(@PathVariable("id") long id, HttpServletResponse response, @RequestHeader(value = "Origin", required = false) String origin) { // entêtes CORS rdvMedecinsCorsController.sendOptions(origin, response); // état de l'application if (messages != null) { return new Response<Medecin>(-1, messages, null); } // on récupère le médecin return getMedecin(id); } @RequestMapping(value = "/getRvById/{id}", method = RequestMethod.GET) public Response<Rv> getRvById(@PathVariable("id") long id, HttpServletResponse response, @RequestHeader(value = "Origin", required = false) String origin) { // entêtes CORS rdvMedecinsCorsController.sendOptions(origin, response); // état de l'application if (messages != null) { return new Response<Rv>(-1, messages, null); } // on rend le rv SimpleBeanPropertyFilter rvFilter = SimpleBeanPropertyFilter.serializeAllExcept("client", "creneau"); mapper.setFilters(new SimpleFilterProvider().addFilter("rvFilter", rvFilter)); return getRv(id); } @RequestMapping(value = "/getCreneauById/{id}", method = RequestMethod.GET) public Response<Creneau> getCreneauById(@PathVariable("id") long id, HttpServletResponse response, @RequestHeader(value = "Origin", required = false) String origin) { // entêtes CORS rdvMedecinsCorsController.sendOptions(origin, response); // état de l'application if (messages != null) { return new Response<Creneau>(-1, messages, null); } // on rend le créneau SimpleBeanPropertyFilter creneauFilter = SimpleBeanPropertyFilter.serializeAllExcept("medecin"); mapper.setFilters(new SimpleFilterProvider().addFilter("creneauFilter", creneauFilter)); return getCreneau(id); } @RequestMapping(value = "/ajouterRv", method = RequestMethod.POST, consumes = "application/json; charset=UTF-8") public Response<Rv> ajouterRv(@RequestBody PostAjouterRv post, HttpServletResponse response, @RequestHeader(value = "Origin", required = false) String origin) { // entêtes CORS rdvMedecinsCorsController.sendOptions(origin, response); // état de l'application if (messages != null) { return new Response<Rv>(-1, messages, null); } // on récupère les valeurs postées String jour = post.getJour(); long idCreneau = post.getIdCreneau(); long idClient = post.getIdClient(); // on vérifie la date Date jourAgenda = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sdf.setLenient(false); try { jourAgenda = sdf.parse(jour); } catch (ParseException e) { List<String> messages = new ArrayList<String>(); messages.add(String.format("La date [%s] est invalide", jour)); return new Response<Rv>(6, messages, null); } // on récupère le créneau Response<Creneau> responseCréneau = getCreneau(idCreneau); if (responseCréneau.getStatus() != 0) { return new Response<Rv>(responseCréneau.getStatus(), responseCréneau.getMessages(), null); } Creneau créneau = (Creneau) responseCréneau.getBody(); // on récupère le client Response<Client> responseClient = getClient(idClient); if (responseClient.getStatus() != 0) { return new Response<Rv>(responseClient.getStatus() + 2, responseClient.getMessages(), null); } Client client = responseClient.getBody(); // on ajoute le Rv Rv rv = null; try { rv = application.ajouterRv(jourAgenda, créneau, client); } catch (Exception e1) { return new Response<Rv>(5, Static.getErreursForException(e1), null); } // on rend la réponse SimpleBeanPropertyFilter rvFilter = SimpleBeanPropertyFilter.serializeAllExcept(); SimpleBeanPropertyFilter creneauFilter = SimpleBeanPropertyFilter.serializeAllExcept("medecin"); mapper.setFilters(new SimpleFilterProvider().addFilter("rvFilter", rvFilter).addFilter("creneauFilter", creneauFilter)); return new Response<Rv>(0, null, rv); } @RequestMapping(value = "/supprimerRv", method = RequestMethod.POST, consumes = "application/json; charset=UTF-8") public Response<Void> supprimerRv(@RequestBody PostSupprimerRv post, HttpServletResponse response, @RequestHeader(value = "Origin", required = false) String origin) { // entêtes CORS rdvMedecinsCorsController.sendOptions(origin, response); // état de l'application if (messages != null) { return new Response<Void>(-1, messages, null); } // on récupère les valeurs postées long idRv = post.getIdRv(); // on récupère le rv Response<Rv> responseRv = getRv(idRv); if (responseRv.getStatus() != 0) { return new Response<Void>(responseRv.getStatus(), responseRv.getMessages(), null); } // suppression du rv try { application.supprimerRv(idRv); } catch (Exception e1) { return new Response<Void>(3, Static.getErreursForException(e1), null); } // ok return new Response<Void>(0, null, null); } @RequestMapping(value = "/getAgendaMedecinJour/{idMedecin}/{jour}", method = RequestMethod.GET) public Response<AgendaMedecinJour> getAgendaMedecinJour(@PathVariable("idMedecin") long idMedecin, @PathVariable("jour") String jour, HttpServletResponse response, @RequestHeader(value = "Origin", required = false) String origin) { // entêtes CORS rdvMedecinsCorsController.sendOptions(origin, response); // état de l'application if (messages != null) { return new Response<AgendaMedecinJour>(-1, messages, null); } // on vérifie la date Date jourAgenda = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sdf.setLenient(false); try { jourAgenda = sdf.parse(jour); } catch (ParseException e) { List<String> messages = new ArrayList<String>(); messages.add(String.format("La date [%s] est invalide", jour)); return new Response<AgendaMedecinJour>(3, messages, null); } // on récupère le médecin Response<Medecin> responseMedecin = getMedecin(idMedecin); if (responseMedecin.getStatus() != 0) { return new Response<AgendaMedecinJour>(responseMedecin.getStatus(), responseMedecin.getMessages(), null); } Medecin médecin = responseMedecin.getBody(); // on récupère son agenda AgendaMedecinJour agenda = null; try { agenda = application.getAgendaMedecinJour(médecin.getId(), jourAgenda); } catch (Exception e1) { return new Response<AgendaMedecinJour>(4, Static.getErreursForException(e1), agenda); } // on rend l'agenda SimpleBeanPropertyFilter rvFilter = SimpleBeanPropertyFilter.serializeAllExcept(); SimpleBeanPropertyFilter creneauFilter = SimpleBeanPropertyFilter.serializeAllExcept("medecin"); mapper.setFilters(new SimpleFilterProvider().addFilter("rvFilter", rvFilter).addFilter("creneauFilter", creneauFilter)); return new Response<AgendaMedecinJour>(0, null, agenda); } @RequestMapping(value = "/authenticate", method = RequestMethod.GET) public Response<Void> authenticate(HttpServletResponse response, @RequestHeader(value = "Origin", required = false) String origin) { // entêtes CORS rdvMedecinsCorsController.sendOptions(origin, response); // réponse return new Response<Void>(0, null, null); } }
[ "Administrateur@COM01.Heliadis.local" ]
Administrateur@COM01.Heliadis.local
c2deb321f7786259e20cbe59a082a5d5e86f9d13
92067c14e9e572a85dc17a0616d6af8e4b92fac2
/src/main/java/com/hitex/yousim/repository/StockModelPriceRepository.java
8a8d8a03e3e1ef09a3023dd0179e8767c53f0388
[]
no_license
vanhai1601/SimTest
e8f8e93ab981312c491a04f070df1cdf1b961396
e4f37bba2cebd267e24cafd510896ec5c7d7968c
refs/heads/master
2023-09-03T10:22:40.229987
2021-11-23T14:48:00
2021-11-23T14:48:00
431,137,966
0
0
null
null
null
null
UTF-8
Java
false
false
506
java
package com.hitex.yousim.repository; import com.hitex.yousim.model.StockModelPrice; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository public interface StockModelPriceRepository extends JpaRepository<StockModelPrice, Integer> { @Query(value = "select smp from StockModelPrice smp where smp.stockModelId = ?1") StockModelPrice findSmpByStockModelId(int stockModelId); }
[ "vanhai160197@gmail.com" ]
vanhai160197@gmail.com
9f772dea8a130252eb9a422c441d9cf2df7f81b1
b7d59303c214f1d1bc0fd8faa6d3460bd9f24f24
/src/myProj/abc.java
1ff2cd7fd601e168197853838bcf937ab5510726
[]
no_license
MayuraSardessai/test
8ba87adc934fca79ecad387019b662576665357e
900e82d7210320d503d5c976cc23b6bf71f232b9
refs/heads/master
2020-12-25T18:23:06.230070
2015-07-09T18:43:32
2015-07-09T18:43:32
38,801,188
0
0
null
null
null
null
UTF-8
Java
false
false
44
java
package myProj; public class abc { }
[ "mayuravsardessai@gmail.com" ]
mayuravsardessai@gmail.com
3198632a9a097be8508bdefa5409ae1adef17ad2
826642720da414981580c599a32dce9ba2179da1
/sources/kotlinx/coroutines/flow/FlowKt__BuildersKt$flowViaChannel$1.java
4d03cf2769f1ecd7a3b5292d733e0c8e96934895
[]
no_license
bclehmann/abtracetogether_1.0.1.apk_disassembled
be60aa11b4f798952de68b985a138019cc79a4ab
562cb759f0b45007ac4d3db171926654393ebc0b
refs/heads/master
2022-11-07T11:13:17.926766
2020-06-20T04:55:34
2020-06-20T04:55:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,040
java
package kotlinx.coroutines.flow; import kotlin.Metadata; import kotlin.ResultKt; import kotlin.Unit; import kotlin.coroutines.Continuation; import kotlin.coroutines.intrinsics.IntrinsicsKt; import kotlin.coroutines.jvm.internal.DebugMetadata; import kotlin.coroutines.jvm.internal.SuspendLambda; import kotlin.jvm.functions.Function2; import kotlin.jvm.internal.Intrinsics; import kotlinx.coroutines.channels.ProduceKt; import kotlinx.coroutines.channels.ProducerScope; @Metadata(bv = {1, 0, 3}, d1 = {"\u0000\u0010\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002\u0010\u0000\u001a\u00020\u0001\"\u0004\b\u0000\u0010\u0002*\b\u0012\u0004\u0012\u0002H\u00020\u0003HŠ@¢\u0006\u0004\b\u0004\u0010\u0005"}, d2 = {"<anonymous>", "", "T", "Lkotlinx/coroutines/channels/ProducerScope;", "invoke", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"}, k = 3, mv = {1, 1, 15}) @DebugMetadata(c = "kotlinx.coroutines.flow.FlowKt__BuildersKt$flowViaChannel$1", f = "Builders.kt", i = {0}, l = {194}, m = "invokeSuspend", n = {"$this$channelFlow"}, s = {"L$0"}) /* compiled from: Builders.kt */ final class FlowKt__BuildersKt$flowViaChannel$1 extends SuspendLambda implements Function2<ProducerScope<? super T>, Continuation<? super Unit>, Object> { final /* synthetic */ Function2 $block; Object L$0; int label; private ProducerScope p$; FlowKt__BuildersKt$flowViaChannel$1(Function2 function2, Continuation continuation) { this.$block = function2; super(2, continuation); } public final Continuation<Unit> create(Object obj, Continuation<?> continuation) { Intrinsics.checkParameterIsNotNull(continuation, "completion"); FlowKt__BuildersKt$flowViaChannel$1 flowKt__BuildersKt$flowViaChannel$1 = new FlowKt__BuildersKt$flowViaChannel$1(this.$block, continuation); flowKt__BuildersKt$flowViaChannel$1.p$ = (ProducerScope) obj; return flowKt__BuildersKt$flowViaChannel$1; } public final Object invoke(Object obj, Object obj2) { return ((FlowKt__BuildersKt$flowViaChannel$1) create(obj, (Continuation) obj2)).invokeSuspend(Unit.INSTANCE); } public final Object invokeSuspend(Object obj) { Object coroutine_suspended = IntrinsicsKt.getCOROUTINE_SUSPENDED(); int i = this.label; if (i == 0) { ResultKt.throwOnFailure(obj); ProducerScope producerScope = this.p$; this.$block.invoke(producerScope, producerScope.getChannel()); this.L$0 = producerScope; this.label = 1; if (ProduceKt.awaitClose$default(producerScope, null, this, 1, null) == coroutine_suspended) { return coroutine_suspended; } } else if (i == 1) { ProducerScope producerScope2 = (ProducerScope) this.L$0; ResultKt.throwOnFailure(obj); } else { throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine"); } return Unit.INSTANCE; } }
[ "bclehmann@yahoo.ca" ]
bclehmann@yahoo.ca
66372b7f3ae28deeed2d34a242baee9ed35e3420
1c5e962ddefc905e7b30f008a0c0a2714a5f6972
/src/main/java/calculate/Multiplication.java
1a9d99506ed342abaf97ae57561dc3f1b5f6cb3f
[]
no_license
eugeneni/JavaCourseOrlov
ee3426bc1d36b999d2a7526ec5fedd791238d31e
965355c68100efd3ab8945732a80fa62255a0372
refs/heads/master
2021-06-28T12:57:20.944445
2019-05-26T13:18:17
2019-05-26T13:18:17
169,750,759
0
1
null
2020-10-13T11:56:02
2019-02-08T14:56:23
Java
UTF-8
Java
false
false
220
java
package calculate; public class Multiplication implements BinaryOperation { @Override public double returnResultFor(double leftOperand, double rightOperand) { return leftOperand * rightOperand; } }
[ "inizelnik@gmail.com" ]
inizelnik@gmail.com
78ffa2e00ff3fd56ad453595b3475817342d7f8f
5a3932ee5513d20e57d9a28f7650bd73bc48f022
/photographic-core/src/main/java/com/heav/photographic/core/common/util/MapRender.java
bb75e919a9040fcced8402239e4be2f3299d2cc4
[]
no_license
helubo0573/photographicManage
2ffbdc46b6d7829d1ee0bc4f4a3c14699c6b21ad
303c8de6c45e2ab94c3a6525c946b9d9786d2ff2
refs/heads/master
2022-12-23T09:39:28.557991
2020-04-12T05:43:22
2020-04-12T05:43:22
240,825,758
0
0
null
2022-12-16T07:47:28
2020-02-16T03:34:27
Java
UTF-8
Java
false
false
1,679
java
package com.heav.photographic.core.common.util; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings({ "unchecked", "rawtypes" }) public class MapRender { private Collection<Map> mapList; private Map renders = new HashMap(); public static final Logger logger = LoggerFactory.getLogger(MapRender.class); public MapRender(Collection<Map> mapList) { this.mapList = mapList; } public interface Render { Object render(Object value, Object key, Map map, Object[] results); } public MapRender registerRender(Object[][] renders) { this.renders = new HashMap(); for (Object[] render : renders) { this.renders.put(render[0], (Render) render[1]); } return this; } public Collection<Map> render() { Collection<Map> newMapList = null; try { newMapList = mapList.getClass().newInstance(); for (Map item : mapList) { Map newMap = item.getClass().newInstance(); newMap.putAll(item); newMapList.add(newMap); for (Object renderKey : renders.entrySet()) { Render render = (Render) renders.get(renderKey); Object value = item.get(renderKey); if (item.containsKey(renderKey)) { Object[] par = new Object[2]; value = render.render(value, renderKey, item, par); newMap.put(renderKey, value); if (par[0] != null && par[1] != null) { newMap.put(par[0], par[1]); } } } } mapList.clear(); mapList.addAll(newMapList); } catch (InstantiationException | IllegalAccessException e) { logger.error(e.getMessage(), e); } return newMapList; } }
[ "helubo_cn@hotmail.com" ]
helubo_cn@hotmail.com
1decfa64738fd20714789f52a9597b4a35bd933d
3d693e6b6a6c46499d48646f6fbe3d938b5e7cb2
/drools-core-dr/src/org/drools/marshalling/impl/OutputMarshaller.java
759e332fbb4e7ddce0d9d3729a34b7160d30c5c4
[]
no_license
jorgemfk/dr-drools
1101fd5c8c849731b1088c6a95ed1778952c79a3
8b3fc1db5919a88b3e07aeebb3ba2178ea700a07
refs/heads/master
2020-06-02T15:26:08.465658
2015-01-27T06:15:47
2015-01-27T06:15:47
29,899,027
1
1
null
null
null
null
UTF-8
Java
false
false
37,772
java
/* * Copyright 2010 JBoss Inc * * 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.drools.marshalling.impl; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import org.drools.InitialFact; import org.drools.base.ClassObjectType; import org.drools.common.AgendaItem; import org.drools.common.DefaultAgenda; import org.drools.common.EqualityKey; import org.drools.common.InternalFactHandle; import org.drools.common.InternalRuleBase; import org.drools.common.InternalWorkingMemory; import org.drools.common.InternalWorkingMemoryEntryPoint; import org.drools.common.LogicalDependency; import org.drools.common.NodeMemory; import org.drools.common.ObjectStore; import org.drools.common.RuleFlowGroupImpl; import org.drools.common.WorkingMemoryAction; import org.drools.core.util.ObjectHashMap; import org.drools.core.util.ObjectHashSet; import org.drools.marshalling.ObjectMarshallingStrategy; import org.drools.process.instance.WorkItem; import org.drools.reteoo.BetaNode; import org.drools.reteoo.LeftTuple; import org.drools.reteoo.LeftTuple; import org.drools.reteoo.LeftTupleSink; import org.drools.reteoo.NodeTypeEnums; import org.drools.reteoo.ObjectTypeNode; import org.drools.reteoo.ReteooWorkingMemory; import org.drools.reteoo.RightTuple; import org.drools.reteoo.RuleTerminalNode; import org.drools.reteoo.AccumulateNode.AccumulateContext; import org.drools.reteoo.AccumulateNode.AccumulateMemory; import org.drools.reteoo.FromNode.FromMemory; import org.drools.rule.EntryPoint; import org.drools.rule.Rule; import org.drools.spi.Activation; import org.drools.spi.ActivationGroup; import org.drools.spi.AgendaGroup; import org.drools.spi.PropagationContext; import org.drools.spi.RuleFlowGroup; public class OutputMarshaller { private static ProcessMarshaller processMarshaller = createProcessMarshaller(); private static ProcessMarshaller createProcessMarshaller() { try { return ProcessMarshallerFactory.newProcessMarshaller(); } catch (IllegalArgumentException e) { return null; } } public static void writeSession(MarshallerWriteContext context) throws IOException { ReteooWorkingMemory wm = (ReteooWorkingMemory) context.wm; final boolean multithread = wm.isPartitionManagersActive(); // is multi-thread active? if( multithread ) { context.writeBoolean( true ); wm.stopPartitionManagers(); } else { context.writeBoolean( false ); } context.writeInt( wm.getFactHandleFactory().getId() ); context.writeLong( wm.getFactHandleFactory().getRecency() ); ////context.out.println( "FactHandleFactory int:" + wm.getFactHandleFactory().getId() + " long:" + wm.getFactHandleFactory().getRecency() ); InternalFactHandle handle = context.wm.getInitialFactHandle(); context.writeInt( handle.getId() ); context.writeLong( handle.getRecency() ); //context.out.println( "InitialFact int:" + handle.getId() + " long:" + handle.getRecency() ); context.writeLong( wm.getPropagationIdCounter() ); //context.out.println( "PropagationCounter long:" + wm.getPropagationIdCounter() ); writeAgenda( context ); writeFactHandles( context ); writeActionQueue( context ); writeTruthMaintenanceSystem( context ); if ( context.marshalProcessInstances && processMarshaller != null ) { processMarshaller.writeProcessInstances( context ); } if ( context.marshalWorkItems && processMarshaller != null ) { processMarshaller.writeWorkItems( context ); } if ( processMarshaller != null ) { processMarshaller.writeProcessTimers( context ); } if( multithread ) { wm.startPartitionManagers(); } } public static void writeAgenda(MarshallerWriteContext context) throws IOException { InternalWorkingMemory wm = context.wm; DefaultAgenda agenda = (DefaultAgenda) wm.getAgenda(); Map<String, ActivationGroup> activationGroups = agenda.getActivationGroupsMap(); AgendaGroup[] agendaGroups = (AgendaGroup[]) agenda.getAgendaGroupsMap().values().toArray( new AgendaGroup[agenda.getAgendaGroupsMap().size()] ); Arrays.sort( agendaGroups, AgendaGroupSorter.instance ); for ( AgendaGroup group : agendaGroups ) { context.writeShort( PersisterEnums.AGENDA_GROUP ); context.writeUTF( group.getName() ); context.writeBoolean( group.isActive() ); } context.writeShort( PersisterEnums.END ); LinkedList<AgendaGroup> focusStack = agenda.getStackList(); for ( Iterator<AgendaGroup> it = focusStack.iterator(); it.hasNext(); ) { AgendaGroup group = it.next(); context.writeShort( PersisterEnums.AGENDA_GROUP ); context.writeUTF( group.getName() ); } context.writeShort( PersisterEnums.END ); RuleFlowGroupImpl[] ruleFlowGroups = (RuleFlowGroupImpl[]) agenda.getRuleFlowGroupsMap().values().toArray( new RuleFlowGroupImpl[agenda.getRuleFlowGroupsMap().size()] ); Arrays.sort( ruleFlowGroups, RuleFlowGroupSorter.instance ); for ( RuleFlowGroupImpl group : ruleFlowGroups ) { context.writeShort( PersisterEnums.RULE_FLOW_GROUP ); //group.write( context ); context.writeUTF( group.getName() ); context.writeBoolean( group.isActive() ); context.writeBoolean( group.isAutoDeactivate() ); Map<Long, String> nodeInstances = group.getNodeInstances(); context.writeInt( nodeInstances.size() ); for (Map.Entry<Long, String> entry: nodeInstances.entrySet()) { context.writeLong( entry.getKey() ); context.writeUTF( entry.getValue() ); } } context.writeShort( PersisterEnums.END ); } public static class AgendaGroupSorter implements Comparator<AgendaGroup> { public static final AgendaGroupSorter instance = new AgendaGroupSorter(); public int compare(AgendaGroup group1, AgendaGroup group2) { return group1.getName().compareTo( group2.getName() ); } } public static class RuleFlowGroupSorter implements Comparator<RuleFlowGroup> { public static final RuleFlowGroupSorter instance = new RuleFlowGroupSorter(); public int compare(RuleFlowGroup group1, RuleFlowGroup group2) { return group1.getName().compareTo( group2.getName() ); } } public static void writeActionQueue(MarshallerWriteContext context) throws IOException { ReteooWorkingMemory wm = (ReteooWorkingMemory) context.wm; WorkingMemoryAction[] queue = wm.getActionQueue().toArray( new WorkingMemoryAction[wm.getActionQueue().size()] ); for ( int i = queue.length - 1; i >= 0; i-- ) { context.writeShort( PersisterEnums.WORKING_MEMORY_ACTION ); queue[i].write( context ); } context.writeShort( PersisterEnums.END ); } public static void writeTruthMaintenanceSystem(MarshallerWriteContext context) throws IOException { ObjectOutputStream stream = context.stream; ObjectHashMap assertMap = context.wm.getTruthMaintenanceSystem().getAssertMap(); EqualityKey[] keys = new EqualityKey[assertMap.size()]; org.drools.core.util.Iterator it = assertMap.iterator(); int i = 0; for ( org.drools.core.util.ObjectHashMap.ObjectEntry entry = (org.drools.core.util.ObjectHashMap.ObjectEntry) it.next(); entry != null; entry = (org.drools.core.util.ObjectHashMap.ObjectEntry) it.next() ) { EqualityKey key = (EqualityKey) entry.getKey(); keys[i++] = key; } Arrays.sort( keys, EqualityKeySorter.instance ); // write the assert map of Equality keys for ( EqualityKey key : keys ) { stream.writeShort( PersisterEnums.EQUALITY_KEY ); stream.writeInt( key.getStatus() ); InternalFactHandle handle = key.getFactHandle(); stream.writeInt( handle.getId() ); //context.out.println( "EqualityKey int:" + key.getStatus() + " int:" + handle.getId() ); if ( key.getOtherFactHandle() != null && !key.getOtherFactHandle().isEmpty() ) { for ( InternalFactHandle handle2 : key.getOtherFactHandle() ) { stream.writeShort( PersisterEnums.FACT_HANDLE ); stream.writeInt( handle2.getId() ); //context.out.println( "OtherHandle int:" + handle2.getId() ); } } stream.writeShort( PersisterEnums.END ); } stream.writeShort( PersisterEnums.END ); } public static class EqualityKeySorter implements Comparator<EqualityKey> { public static final EqualityKeySorter instance = new EqualityKeySorter(); public int compare(EqualityKey key1, EqualityKey key2) { return key1.getFactHandle().getId() - key2.getFactHandle().getId(); } } public static void writeFactHandles(MarshallerWriteContext context) throws IOException { ObjectOutputStream stream = context.stream; InternalWorkingMemory wm = context.wm; ObjectMarshallingStrategyStore objectMarshallingStrategyStore = context.objectMarshallingStrategyStore; writeInitialFactHandleRightTuples( context ); stream.writeInt( wm.getObjectStore().size() ); // Write out FactHandles for ( InternalFactHandle handle : orderFacts( wm.getObjectStore() ) ) { //stream.writeShort( PersisterEnums.FACT_HANDLE ); //InternalFactHandle handle = (InternalFactHandle) it.next(); writeFactHandle( context, stream, objectMarshallingStrategyStore, handle ); writeRightTuples( handle, context ); } writeInitialFactHandleLeftTuples( context ); writeLeftTuples( context ); writePropagationContexts( context ); writeActivations( context ); } private static void writeFactHandle(MarshallerWriteContext context, ObjectOutputStream stream, ObjectMarshallingStrategyStore objectMarshallingStrategyStore, int type, InternalFactHandle handle) throws IOException { stream.writeInt( type ); stream.writeInt( handle.getId() ); stream.writeLong( handle.getRecency() ); //context.out.println( "Object : int:" + handle.getId() + " long:" + handle.getRecency() ); //context.out.println( handle.getObject() ); Object object = handle.getObject(); int index = objectMarshallingStrategyStore.getStrategy( object ); ObjectMarshallingStrategy strategy = objectMarshallingStrategyStore.getStrategy( index ); stream.writeInt( index ); strategy.write( stream, object ); if( handle.getEntryPoint() instanceof InternalWorkingMemoryEntryPoint ){ String entryPoint = ((InternalWorkingMemoryEntryPoint)handle.getEntryPoint()).getEntryPoint().getEntryPointId(); if(entryPoint!=null && !entryPoint.equals("")){ stream.writeBoolean(true); stream.writeUTF(entryPoint); } else{ stream.writeBoolean(false); } }else{ stream.writeBoolean(false); } } private static void writeFactHandle(MarshallerWriteContext context, ObjectOutputStream stream, ObjectMarshallingStrategyStore objectMarshallingStrategyStore, InternalFactHandle handle) throws IOException { writeFactHandle( context, stream, objectMarshallingStrategyStore, 0, handle ); } public static InternalFactHandle[] orderFacts(ObjectStore objectStore) { // this method is just needed for testing purposes, to allow round tripping int size = objectStore.size(); InternalFactHandle[] handles = new InternalFactHandle[size]; int i = 0; for ( Iterator it = objectStore.iterateFactHandles(); it.hasNext(); ) { handles[i++] = (InternalFactHandle) it.next(); } Arrays.sort( handles, new HandleSorter() ); return handles; } public static class HandleSorter implements Comparator<InternalFactHandle> { public int compare(InternalFactHandle h1, InternalFactHandle h2) { return h1.getId() - h2.getId(); } } public static void writeInitialFactHandleRightTuples(MarshallerWriteContext context) throws IOException { ObjectOutputStream stream = context.stream; InternalRuleBase ruleBase = context.ruleBase; ObjectTypeNode initialFactNode = ruleBase.getRete().getEntryPointNode( EntryPoint.DEFAULT ).getObjectTypeNodes().get( ClassObjectType.InitialFact_ObjectType ); // do we write the fact to the objecttypenode memory if ( initialFactNode != null ) { ObjectHashSet initialFactMemory = (ObjectHashSet) context.wm.getNodeMemory( initialFactNode ); if ( initialFactMemory != null && !initialFactMemory.isEmpty() ) { //context.out.println( "InitialFactMemory true int:" + initialFactNode.getId() ); stream.writeBoolean( true ); stream.writeInt( initialFactNode.getId() ); //context.out.println( "InitialFact RightTuples" ); writeRightTuples( context.wm.getInitialFactHandle(), context ); } else { //context.out.println( "InitialFactMemory false " ); stream.writeBoolean( false ); } } else { //context.out.println( "InitialFactMemory false " ); stream.writeBoolean( false ); } } public static void writeInitialFactHandleLeftTuples(MarshallerWriteContext context) throws IOException { ObjectOutputStream stream = context.stream; //context.out.println( "InitialFact LeftTuples Start" ); InternalFactHandle handle = context.wm.getInitialFactHandle(); for ( LeftTuple leftTuple = handle.getFirstLeftTuple(); leftTuple != null; leftTuple = (LeftTuple) leftTuple.getLeftParentNext() ) { stream.writeShort( PersisterEnums.LEFT_TUPLE ); stream.writeInt( leftTuple.getLeftTupleSink().getId() ); //context.out.println( "LeftTuple sinkId:" + leftTuple.getLeftTupleSink().getId() ); writeLeftTuple( leftTuple, context, true ); } stream.writeShort( PersisterEnums.END ); //context.out.println( "InitialFact LeftTuples End" ); } public static void writeRightTuples(InternalFactHandle handle, MarshallerWriteContext context) throws IOException { ObjectOutputStream stream = context.stream; //context.out.println( "RightTuples Start" ); for (RightTuple rightTuple = handle.getFirstRightTuple(); rightTuple != null; rightTuple = (RightTuple) rightTuple.getHandleNext() ) { stream.writeShort( PersisterEnums.RIGHT_TUPLE ); writeRightTuple( rightTuple, context ); } stream.writeShort( PersisterEnums.END ); //context.out.println( "RightTuples END" ); } public static void writeRightTuple(RightTuple rightTuple, MarshallerWriteContext context) throws IOException { ObjectOutputStream stream = context.stream; InternalWorkingMemory wm = context.wm; // right tuples created in a "FromNode" have no sink, so we need to handle that appropriatelly int id = rightTuple.getRightTupleSink() != null ? rightTuple.getRightTupleSink().getId() : -1; stream.writeInt( id ); //context.out.println( "RightTuple sinkId:" + (rightTuple.getRightTupleSink() != null ? rightTuple.getRightTupleSink().getId() : -1) ); } public static void writeLeftTuples(MarshallerWriteContext context) throws IOException { ObjectOutputStream stream = context.stream; InternalWorkingMemory wm = context.wm; // Write out LeftTuples //context.out.println( "LeftTuples Start" ); for ( InternalFactHandle handle : orderFacts( wm.getObjectStore() ) ) { //InternalFactHandle handle = (InternalFactHandle) it.next(); for ( LeftTuple leftTuple = handle.getFirstLeftTuple(); leftTuple != null; leftTuple = (LeftTuple) leftTuple.getLeftParentNext() ) { stream.writeShort( PersisterEnums.LEFT_TUPLE ); stream.writeInt( leftTuple.getLeftTupleSink().getId() ); stream.writeInt( handle.getId() ); //context.out.println( "LeftTuple sinkId:" + leftTuple.getLeftTupleSink().getId() + " handleId:" + handle.getId() ); writeLeftTuple( leftTuple, context, true ); } } stream.writeShort( PersisterEnums.END ); //context.out.println( "LeftTuples End" ); } public static void writeLeftTuple(LeftTuple leftTuple, MarshallerWriteContext context, boolean recurse) throws IOException { ObjectOutputStream stream = context.stream; InternalRuleBase ruleBase = context.ruleBase; InternalWorkingMemory wm = context.wm; LeftTupleSink sink = leftTuple.getLeftTupleSink(); switch ( sink.getType() ) { case NodeTypeEnums.JoinNode : { //context.out.println( "JoinNode" ); for ( LeftTuple childLeftTuple = leftTuple.getFirstChild(); childLeftTuple != null; childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext() ) { stream.writeShort( PersisterEnums.RIGHT_TUPLE ); stream.writeInt( childLeftTuple.getLeftTupleSink().getId() ); stream.writeInt( childLeftTuple.getRightParent().getFactHandle().getId() ); //context.out.println( "RightTuple int:" + childLeftTuple.getLeftTupleSink().getId() + " int:" + childLeftTuple.getRightParent().getFactHandle().getId() ); writeLeftTuple( childLeftTuple, context, recurse ); } stream.writeShort( PersisterEnums.END ); //context.out.println( "JoinNode --- END" ); break; } case NodeTypeEnums.EvalConditionNode : { //context.out.println( ".... EvalConditionNode" ); for ( LeftTuple childLeftTuple = leftTuple.getFirstChild(); childLeftTuple != null; childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext() ) { stream.writeShort( PersisterEnums.LEFT_TUPLE ); stream.writeInt( childLeftTuple.getLeftTupleSink().getId() ); writeLeftTuple( childLeftTuple, context, recurse ); } stream.writeShort( PersisterEnums.END ); //context.out.println( "---- EvalConditionNode --- END" ); break; } case NodeTypeEnums.NotNode : case NodeTypeEnums.ForallNotNode : { if ( leftTuple.getBlocker() == null ) { // is not blocked so has children stream.writeShort( PersisterEnums.LEFT_TUPLE_NOT_BLOCKED ); for ( LeftTuple childLeftTuple = leftTuple.getFirstChild(); childLeftTuple != null; childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext() ) { stream.writeShort( PersisterEnums.LEFT_TUPLE ); stream.writeInt( childLeftTuple.getLeftTupleSink().getId() ); writeLeftTuple( childLeftTuple, context, recurse ); } stream.writeShort( PersisterEnums.END ); } else { stream.writeShort( PersisterEnums.LEFT_TUPLE_BLOCKED ); stream.writeInt( leftTuple.getBlocker().getFactHandle().getId() ); } break; } case NodeTypeEnums.ExistsNode : { if ( leftTuple.getBlocker() == null ) { // is blocked so has children stream.writeShort( PersisterEnums.LEFT_TUPLE_NOT_BLOCKED ); } else { stream.writeShort( PersisterEnums.LEFT_TUPLE_BLOCKED ); stream.writeInt( leftTuple.getBlocker().getFactHandle().getId() ); for ( LeftTuple childLeftTuple = leftTuple.getFirstChild(); childLeftTuple != null; childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext() ) { stream.writeShort( PersisterEnums.LEFT_TUPLE ); stream.writeInt( childLeftTuple.getLeftTupleSink().getId() ); writeLeftTuple( childLeftTuple, context, recurse ); } stream.writeShort( PersisterEnums.END ); } break; } case NodeTypeEnums.AccumulateNode : { //context.out.println( ".... AccumulateNode" ); // accumulate nodes generate new facts on-demand and need special procedures when serializing to persistent storage AccumulateMemory memory = (AccumulateMemory) context.wm.getNodeMemory( (BetaNode) sink ); AccumulateContext accctx = (AccumulateContext) memory.betaMemory.getCreatedHandles().get( leftTuple ); // first we serialize the generated fact handle writeFactHandle( context, stream, context.objectMarshallingStrategyStore, accctx.result.getFactHandle() ); // then we serialize the associated accumulation context stream.writeObject( accctx.context ); // then we serialize the boolean propagated flag stream.writeBoolean( accctx.propagated ); // then we serialize all the propagated tuples for ( LeftTuple childLeftTuple = leftTuple.getFirstChild(); childLeftTuple != null; childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext() ) { if( leftTuple.getLeftTupleSink().getId() == childLeftTuple.getLeftTupleSink().getId()) { // this is a matching record, so, associate the right tuples //context.out.println( "RightTuple(match) int:" + childLeftTuple.getLeftTupleSink().getId() + " int:" + childLeftTuple.getRightParent().getFactHandle().getId() ); stream.writeShort( PersisterEnums.RIGHT_TUPLE ); stream.writeInt( childLeftTuple.getRightParent().getFactHandle().getId() ); } else { // this is a propagation record //context.out.println( "RightTuple(propagation) int:" + childLeftTuple.getLeftTupleSink().getId() + " int:" + childLeftTuple.getRightParent().getFactHandle().getId() ); stream.writeShort( PersisterEnums.LEFT_TUPLE ); stream.writeInt( childLeftTuple.getLeftTupleSink().getId() ); writeLeftTuple( childLeftTuple, context, recurse ); } } stream.writeShort( PersisterEnums.END ); //context.out.println( "---- AccumulateNode --- END" ); break; } case NodeTypeEnums.RightInputAdaterNode : { //context.out.println( ".... RightInputAdapterNode" ); // RIANs generate new fact handles on-demand to wrap tuples and need special procedures when serializing to persistent storage ObjectHashMap memory = (ObjectHashMap) context.wm.getNodeMemory( (NodeMemory) sink ); InternalFactHandle ifh = (InternalFactHandle) memory.get( leftTuple ); // first we serialize the generated fact handle ID //context.out.println( "FactHandle id:"+ifh.getId() ); stream.writeInt( ifh.getId() ); stream.writeLong( ifh.getRecency() ); writeRightTuples( ifh, context ); stream.writeShort( PersisterEnums.END ); //context.out.println( "---- RightInputAdapterNode --- END" ); break; } case NodeTypeEnums.FromNode: { //context.out.println( ".... FromNode" ); // FNs generate new fact handles on-demand to wrap objects and need special procedures when serializing to persistent storage FromMemory memory = (FromMemory) context.wm.getNodeMemory( (NodeMemory) sink ); Map<Object, RightTuple> matches = (Map<Object, RightTuple>) memory.betaMemory.getCreatedHandles().get( leftTuple ); for ( RightTuple rightTuples : matches.values() ) { // first we serialize the generated fact handle ID stream.writeShort( PersisterEnums.FACT_HANDLE ); writeFactHandle( context, stream, context.objectMarshallingStrategyStore, rightTuples.getFactHandle() ); writeRightTuples( rightTuples.getFactHandle(), context ); } stream.writeShort( PersisterEnums.END ); for ( LeftTuple childLeftTuple = leftTuple.getFirstChild(); childLeftTuple != null; childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext() ) { stream.writeShort( PersisterEnums.RIGHT_TUPLE ); stream.writeInt( childLeftTuple.getLeftTupleSink().getId() ); stream.writeInt( childLeftTuple.getRightParent().getFactHandle().getId() ); //context.out.println( "RightTuple int:" + childLeftTuple.getLeftTupleSink().getId() + " int:" + childLeftTuple.getRightParent().getFactHandle().getId() ); writeLeftTuple( childLeftTuple, context, recurse ); } stream.writeShort( PersisterEnums.END ); //context.out.println( "---- FromNode --- END" ); break; } case NodeTypeEnums.UnificationNode : { //context.out.println( ".... UnificationNode" ); for ( LeftTuple childLeftTuple = leftTuple.getFirstChild(); childLeftTuple != null; childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext() ) { stream.writeShort( PersisterEnums.LEFT_TUPLE ); stream.writeInt( childLeftTuple.getLeftTupleSink().getId() ); writeFactHandle( context, stream, context.objectMarshallingStrategyStore, 1, childLeftTuple.getLastHandle() ); writeLeftTuple( childLeftTuple, context, recurse ); } stream.writeShort( PersisterEnums.END ); //context.out.println( "---- EvalConditionNode --- END" ); break; } case NodeTypeEnums.RuleTerminalNode : { //context.out.println( "RuleTerminalNode" ); int pos = context.terminalTupleMap.size(); context.terminalTupleMap.put( leftTuple, pos ); break; } } } public static void writeActivations(MarshallerWriteContext context) throws IOException { ObjectOutputStream stream = context.stream; Entry<LeftTuple, Integer>[] entries = context.terminalTupleMap.entrySet().toArray( new Entry[context.terminalTupleMap.size()] ); Arrays.sort( entries, TupleSorter.instance ); //Map<LeftTuple, Integer> tuples = context.terminalTupleMap; if ( entries.length != 0 ) { for ( Entry<LeftTuple, Integer> entry : entries ) { if (entry.getKey().getObject() != null) { LeftTuple leftTuple = entry.getKey(); stream.writeShort(PersisterEnums.ACTIVATION); writeActivation(context, leftTuple, (AgendaItem) leftTuple .getObject(), (RuleTerminalNode) leftTuple .getLeftTupleSink()); } } } stream.writeShort( PersisterEnums.END ); } public static class TupleSorter implements Comparator<Entry<LeftTuple, Integer>> { public static final TupleSorter instance = new TupleSorter(); public int compare(Entry<LeftTuple, Integer> e1, Entry<LeftTuple, Integer> e2) { return e1.getValue() - e2.getValue(); } } public static void writeActivation(MarshallerWriteContext context, LeftTuple leftTuple, AgendaItem agendaItem, RuleTerminalNode ruleTerminalNode) throws IOException { ObjectOutputStream stream = context.stream; stream.writeLong( agendaItem.getActivationNumber() ); stream.writeInt( context.terminalTupleMap.get( leftTuple ) ); stream.writeInt( agendaItem.getSalience() ); Rule rule = agendaItem.getRule(); stream.writeUTF( rule.getPackage() ); stream.writeUTF( rule.getName() ); //context.out.println( "Rule " + rule.getPackage() + "." + rule.getName() ); //context.out.println( "AgendaItem long:" + agendaItem.getPropagationContext().getPropagationNumber() ); stream.writeLong( agendaItem.getPropagationContext().getPropagationNumber() ); if ( agendaItem.getActivationGroupNode() != null ) { stream.writeBoolean( true ); //context.out.println( "ActivationGroup bool:" + true ); stream.writeUTF( agendaItem.getActivationGroupNode().getActivationGroup().getName() ); //context.out.println( "ActivationGroup string:" + agendaItem.getActivationGroupNode().getActivationGroup().getName() ); } else { stream.writeBoolean( false ); //context.out.println( "ActivationGroup bool:" + false ); } stream.writeBoolean( agendaItem.isActivated() ); //context.out.println( "AgendaItem bool:" + agendaItem.isActivated() ); org.drools.core.util.LinkedList list = agendaItem.getLogicalDependencies(); if ( list != null && !list.isEmpty() ) { for ( LogicalDependency node = (LogicalDependency) list.getFirst(); node != null; node = (LogicalDependency) node.getNext() ) { stream.writeShort( PersisterEnums.LOGICAL_DEPENDENCY ); stream.writeInt( ((InternalFactHandle) node.getFactHandle()).getId() ); //context.out.println( "Logical Depenency : int " + ((InternalFactHandle) node.getFactHandle()).getId() ); } } stream.writeShort( PersisterEnums.END ); } public static void writePropagationContexts(MarshallerWriteContext context) throws IOException { ObjectOutputStream stream = context.stream; Entry<LeftTuple, Integer>[] entries = context.terminalTupleMap.entrySet().toArray( new Entry[context.terminalTupleMap.size()] ); Arrays.sort( entries, TupleSorter.instance ); //Map<LeftTuple, Integer> tuples = context.terminalTupleMap; if ( entries.length != 0 ) { Map<Long, PropagationContext> pcMap = new HashMap<Long, PropagationContext>(); for ( Entry<LeftTuple, Integer> entry : entries ) { LeftTuple leftTuple = entry.getKey(); if (leftTuple.getObject() != null) { PropagationContext pc = ((Activation)leftTuple.getObject()).getPropagationContext(); if (!pcMap.containsKey(pc.getPropagationNumber())) { stream.writeShort(PersisterEnums.PROPAGATION_CONTEXT); writePropagationContext(context, pc); pcMap.put(pc.getPropagationNumber(), pc); } } } } stream.writeShort( PersisterEnums.END ); } public static void writePropagationContext(MarshallerWriteContext context, PropagationContext pc) throws IOException { ObjectOutputStream stream = context.stream; Map<LeftTuple, Integer> tuples = context.terminalTupleMap; stream.writeInt( pc.getType() ); Rule ruleOrigin = pc.getRuleOrigin(); if ( ruleOrigin != null ) { stream.writeBoolean( true ); stream.writeUTF( ruleOrigin.getPackage() ); stream.writeUTF( ruleOrigin.getName() ); } else { stream.writeBoolean( false ); } LeftTuple tupleOrigin = pc.getLeftTupleOrigin(); if ( tupleOrigin != null && tuples.containsKey( tupleOrigin )) { stream.writeBoolean( true ); stream.writeInt( tuples.get( tupleOrigin ) ); } else { stream.writeBoolean( false ); } stream.writeLong( pc.getPropagationNumber() ); if ( pc.getFactHandleOrigin() != null ) { stream.writeInt( ((InternalFactHandle)pc.getFactHandleOrigin()).getId() ); } else { stream.writeInt( -1 ); } stream.writeInt( pc.getActiveActivations() ); stream.writeInt( pc.getDormantActivations() ); stream.writeUTF( pc.getEntryPoint().getEntryPointId() ); } public static void writeWorkItem(MarshallerWriteContext context, WorkItem workItem) throws IOException { ObjectOutputStream stream = context.stream; stream.writeLong(workItem.getId()); stream.writeLong(workItem.getProcessInstanceId()); stream.writeUTF(workItem.getName()); stream.writeInt(workItem.getState()); //Work Item Parameters Map<String, Object> parameters = workItem.getParameters(); Collection<Object> notNullValues = new ArrayList<Object>(); for(Object value: parameters.values()){ if(value != null){ notNullValues.add(value); } } stream.writeInt(notNullValues.size()); for (String key : parameters.keySet()) { Object object = parameters.get(key); if(object != null){ stream.writeUTF(key); int index = context.objectMarshallingStrategyStore.getStrategy(object); stream.writeInt(index); ObjectMarshallingStrategy strategy = context.objectMarshallingStrategyStore.getStrategy(index); if(strategy.accept(object)){ strategy.write(stream, object); } } } } }
[ "jorgemfk1@gmail.com" ]
jorgemfk1@gmail.com
ccd4af62a8d149c953dc0d5d41d2125d69829e3f
5d62283efd06d31a86b98d007e777c7500ce5a69
/app/src/main/java/com/yidankeji/cheng/ebuyhouse/housemodule/activity/SubmitRoom02Activity.java
4f2947bb5b22894e5ddce317010baa1888837969
[]
no_license
nianshaofanghua/Ebuyhouse
100f314c3612b4354ffc16d6121e3dc2ceb1b30c
7a0ed599aeceacf91e6d0d71ab64000ced9e2a39
refs/heads/master
2021-10-28T08:19:18.287935
2019-04-23T02:01:40
2019-04-23T02:01:40
182,903,013
0
0
null
null
null
null
UTF-8
Java
false
false
34,376
java
package com.yidankeji.cheng.ebuyhouse.housemodule.activity; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.support.annotation.IdRes; import android.support.v4.content.res.ResourcesCompat; import android.text.InputType; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import com.luck.picture.lib.PictureSelector; import com.luck.picture.lib.config.PictureConfig; import com.luck.picture.lib.entity.LocalMedia; import com.luck.picture.lib.tools.PictureFileUtils; import com.tsy.sdk.myokhttp.response.RawResponseHandler; import com.wevey.selector.dialog.DialogOnClickListener; import com.wevey.selector.dialog.MDEditDialog; import com.wevey.selector.dialog.NormalAlertDialog; import com.yidankeji.cheng.ebuyhouse.R; import com.yidankeji.cheng.ebuyhouse.activity.EditContentActivity; import com.yidankeji.cheng.ebuyhouse.application.NewRawResponseHandler; import com.yidankeji.cheng.ebuyhouse.filtermodule.activity.FilerHouseTypeActivity; import com.yidankeji.cheng.ebuyhouse.adapter.XiangCeAdapter; import com.yidankeji.cheng.ebuyhouse.application.MyApplication; import com.yidankeji.cheng.ebuyhouse.loginmodule.activity.SignInPWActivity; import com.yidankeji.cheng.ebuyhouse.mode.FilterMode; import com.yidankeji.cheng.ebuyhouse.mode.PostRoom.PostRoomMode; import com.yidankeji.cheng.ebuyhouse.utils.Constant; import com.yidankeji.cheng.ebuyhouse.utils.CryptAES; import com.yidankeji.cheng.ebuyhouse.utils.LoadingUtils; import com.yidankeji.cheng.ebuyhouse.utils.PhotoView.PhotoViewUtils; import com.yidankeji.cheng.ebuyhouse.utils.SharedPreferencesUtils; import com.yidankeji.cheng.ebuyhouse.utils.ToastUtils; import com.yidankeji.cheng.ebuyhouse.utils.WindowUtils; import com.yidankeji.cheng.ebuyhouse.utils.popwindow.ImageLogoUtils; import com.yidankeji.cheng.ebuyhouse.utils.popwindow.LanRenDialog; import org.json.JSONObject; import org.xutils.common.Callback; import org.xutils.http.RequestParams; import org.xutils.x; import java.io.File; import java.util.ArrayList; import java.util.List; import me.weyye.hipermission.HiPermission; import me.weyye.hipermission.PermissionCallback; import me.weyye.hipermission.PermissionItem; import static com.makeramen.roundedimageview.RoundedImageView.TAG; import static com.yidankeji.cheng.ebuyhouse.utils.LoadingUtils.dismiss; public class SubmitRoom02Activity extends Activity implements View.OnClickListener ,XiangCeAdapter.OnItemClickListening{ private TimeCount time = new TimeCount(60000, 1000); private ArrayList<String> submitImageList = new ArrayList<>(); private ArrayList<String> xiangceList = new ArrayList<>(); private PostRoomMode mainMode; private MDEditDialog nameDialog; private TextView tv_properytypes , tv_squarefeet , tv_yearbuild ,tv_lotsize ,tv_daysonebuyhouse , tv_price ,comdetails , tv_getcode , tv_wuyefei; private EditText ed_name , ed_phone , ed_code; private GridView gv_xiangce; private XiangCeAdapter adapter; private TextView submit; private Activity activity; private NormalAlertDialog giveupSubmitDialog; private NormalAlertDialog normalAlertDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_submit_room02); activity = SubmitRoom02Activity.this; mainMode = (PostRoomMode) getIntent().getSerializableExtra("postroomMode"); if (mainMode == null){ ToastUtils.showToast(this , "Sorry, data is lost"); finish(); } initView(); initPermission(); } private void initPermission() { List<PermissionItem> permissionItems = new ArrayList<>(); permissionItems.add(new PermissionItem(Manifest.permission.CAMERA, "Camera", R.drawable.permission_ic_camera)); permissionItems.add(new PermissionItem(Manifest.permission.WRITE_EXTERNAL_STORAGE, "write", R.drawable.permission_ic_location)); permissionItems.add(new PermissionItem(Manifest.permission.READ_EXTERNAL_STORAGE, "read", R.drawable.permission_ic_location)); HiPermission.create(SubmitRoom02Activity.this) .title("Permission to apply for") .filterColor(ResourcesCompat.getColor(getResources(), R.color.zhutise, getTheme())) .msg("To function properly, please agree to permissions!") .permissions(permissionItems) .style(R.style.PermissionBlueStyle) .checkMutiPermission(new PermissionCallback() { @Override public void onClose() { } @Override public void onFinish() { } @Override public void onDeny(String permission, int position) { } @Override public void onGuarantee(String permission, int position) { } }); } private void initView(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); FrameLayout yincang = (FrameLayout) findViewById(R.id.submitroom_yincang); yincang.setVisibility(View.VISIBLE); int statusBarHeight = WindowUtils.getStatusBarHeight(this); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)yincang.getLayoutParams(); params.height = statusBarHeight; yincang.setLayoutParams(params); } ImageView back = (ImageView) findViewById(R.id.action_bar_back); back.setOnClickListener(this); TextView title = (TextView) findViewById(R.id.action_bar_title); title.setText("Post a Room"); /**/ tv_properytypes = (TextView) findViewById(R.id.filter_text_properytypes); tv_properytypes.setOnClickListener(this); tv_price = (TextView) findViewById(R.id.filter_text_price); tv_price.setOnClickListener(this); /**/ RadioGroup bedsRadioGroup = (RadioGroup) findViewById(R.id.filter_radiogroup_beds); bedsRadioGroup.setOnCheckedChangeListener(bedsListener); RadioGroup bathsRadioGroup = (RadioGroup) findViewById(R.id.filter_radiogroup_baths); bathsRadioGroup.setOnCheckedChangeListener(bathsListener); RadioGroup kitchensRadioGroup = (RadioGroup) findViewById(R.id.filter_radiogroup_kitchens); kitchensRadioGroup.setOnCheckedChangeListener(kitchenListener); /**/ tv_squarefeet = (TextView)findViewById(R.id.filter_text_squarefeet); tv_squarefeet.setOnClickListener(this); tv_lotsize = (TextView) findViewById(R.id.filter_text_lotsize); tv_lotsize.setOnClickListener(this); tv_wuyefei = (TextView) findViewById(R.id.filter_text_wuyefei); tv_wuyefei.setOnClickListener(this); tv_yearbuild = (TextView) findViewById(R.id.filter_text_yearbuild); tv_yearbuild.setOnClickListener(this); comdetails = (TextView) findViewById(R.id.filter_text_comdetails); comdetails.setOnClickListener(this); /**/ gv_xiangce = (GridView) findViewById(R.id.xiangce_gridview); adapter = new XiangCeAdapter(this , xiangceList); adapter.setListening(this); gv_xiangce.setAdapter(adapter); /**/ ed_name = (EditText) findViewById(R.id.filter_lianxi_name); ed_phone = (EditText) findViewById(R.id.filter_lianxi_phone); ed_code = (EditText) findViewById(R.id.filter_lianxi_code); tv_getcode = (TextView) findViewById(R.id.filter_lianxi_getcode); tv_getcode.setOnClickListener(this); submit = (TextView) findViewById(R.id.submitroom_rent); submit.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.action_bar_back: GiveupSubmit(); break; case R.id.filter_text_properytypes: Intent intent = new Intent(SubmitRoom02Activity.this , FilerHouseTypeActivity.class); startActivityForResult(intent , 101); break; case R.id.filter_text_price: getNameDialog("price"); break; case R.id.filter_text_squarefeet: getNameDialog("squarefeet"); break; case R.id.filter_text_lotsize: getNameDialog("lotsize"); break; case R.id.filter_text_wuyefei: getNameDialog("wuyefei"); break; case R.id.filter_text_yearbuild: getNameDialog("yearbuild"); break; case R.id.filter_text_comdetails: String str = comdetails.getText().toString().trim(); Intent intent1 = new Intent(SubmitRoom02Activity.this , EditContentActivity.class); intent1.putExtra("content" , str); startActivityForResult(intent1 , 101); break; case R.id.filter_lianxi_getcode: getCode(); break; case R.id.submitroom_rent: // getCodeIsRight(); getSubmitData(); break; } } /** * 提示是否要放弃本次上传 */ private void GiveupSubmit(){ giveupSubmitDialog = new NormalAlertDialog.Builder(activity) .setHeight(0.23f).setWidth(0.65f).setTitleVisible(true) .setTitleText("System hint").setTitleTextColor(R.color.text_heise) .setContentText("Will you abandon this upload") .setContentTextColor(R.color.text_heise) .setLeftButtonText("Cancel").setLeftButtonTextColor(R.color.text_hei) .setRightButtonText("Determine") .setRightButtonTextColor(R.color.text_heise) .setOnclickListener(new DialogOnClickListener() { @Override public void clickLeftButton(View view) { giveupSubmitDialog.dismiss(); } @Override public void clickRightButton(View view) { giveupSubmitDialog.dismiss(); finish(); } }).build(); giveupSubmitDialog.show(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == event.KEYCODE_BACK){ GiveupSubmit(); } return true; } /** * 点击其他区域 键盘消失 */ @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { View v = getCurrentFocus(); if (WindowUtils.isShouldHideInput(v, ev)) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } return super.dispatchTouchEvent(ev); } if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); } /** * 验证码倒计时 */ class TimeCount extends CountDownTimer { public TimeCount(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } @Override public void onTick(long millisUntilFinished) { String show = "Resend after "+millisUntilFinished / 1000 + " seconds"; tv_getcode.setText(show); tv_getcode.setClickable(false); tv_getcode.setTextColor(getResources().getColor(R.color.baise)); tv_getcode.setBackgroundResource(R.drawable.shape_bg_huiradio); } @Override public void onFinish() { tv_getcode.setText("Invitation"); tv_getcode.setClickable(true); tv_getcode.setTextColor(getResources().getColor(R.color.zhutise)); tv_getcode.setBackgroundResource(R.drawable.shape_layout_zhutisebiankuang); } } /** * 获取验证码 */ private void getCode(){ String phone = WindowUtils.getEditTextContent(ed_phone); if (phone.isEmpty()){ ToastUtils.showToast(activity , "Please enter your mobile number"); return; } if (phone.length() != 11){ ToastUtils.showToast(activity , "Please enter the correct phone number"); return; } time.start(); sendPhoneCodeHttp("edit"); } /** * 获取短信验证码 * 1. 获取随机串 */ public void sendPhoneCodeHttp(final String model){ String androidId = MyApplication.androidId; Log.i(TAG+"获取手机验证码" , Constant.getrandomcode+androidId+"/token?"+"jti="+androidId); MyApplication.getmMyOkhttp().get() .url(Constant.getrandomcode+androidId+"/token?"+"jti="+androidId) .tag(this) .enqueue(new NewRawResponseHandler(SubmitRoom02Activity.this) { @Override public void onSuccess(Object object,int statusCode, String response) { Log.i(TAG+"获取手机验证码" , response); try { if (response != null){ JSONObject jsonObject = new JSONObject(response); int state = jsonObject.getInt("state"); if (state == 1){ JSONObject content = jsonObject.getJSONObject("content"); JSONObject data = content.getJSONObject("data"); String token = data.getString("token"); getPhoneCodeHttp(token , model); }else if(state==703){ new LanRenDialog((Activity) activity).onlyLogin(); }else { ToastUtils.showToast(activity , jsonObject.getString("message")); } } } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(Object object,int statusCode, String error_msg) { Log.i(TAG+"获取手机验证码" , error_msg); ToastUtils.showToast(activity , "getrandomcode_error"); } }); } /** * 获取短信验证码 * @param token */ public void getPhoneCodeHttp(String token , String model){ String androidId = MyApplication.androidId; String aesToken2 = null; try { aesToken2 = CryptAES.aesEncryptString(token, "0ad0095f18b64004"); } catch (Exception e) { e.printStackTrace(); } String uri = Constant.getrandomcode+androidId+"/send/"+model; Log.i(TAG+"获取短信验证码" , uri) ; MyApplication.getmMyOkhttp().post() .url(uri) .addParam("aesToken" , aesToken2) .addParam("phoneNumber" , WindowUtils.getEditTextContent(ed_phone)) .enqueue(new NewRawResponseHandler(SubmitRoom02Activity.this) { @Override public void onSuccess(Object object,int statusCode, String response) { Log.i(TAG+"获取短信验证码" , response) ; try { if (response != null){ JSONObject jsonObject = new JSONObject(response); int state = jsonObject.getInt("state"); if (state != 1){ ToastUtils.showToast(activity , jsonObject.getString("message")); if(state==703){ new LanRenDialog((Activity) activity).onlyLogin(); } } } } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(Object object,int statusCode, String error_msg) { Log.i(TAG+"获取短信验证码" , error_msg) ; ToastUtils.showToast(activity , getString(R.string.net_erro)); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //城市类型 if (requestCode == 101 && resultCode == 1005){ FilterMode houseTypemode = (FilterMode) data.getSerializableExtra("houseType"); Log.i(TAG+"data" , houseTypemode.getType()); tv_properytypes.setText(houseTypemode.getType()); mainMode.setPost_housetypeid(houseTypemode.getId()); mainMode.setPost_housetypename(houseTypemode.getType()); } //详情信息 if (requestCode == 101 && resultCode == 1006){ String content = data.getStringExtra("content"); if (content != null){ comdetails.setText(content); }else{ comdetails.setText(""); content = ""; } mainMode.setPost_details(content); } if (resultCode == RESULT_OK) { switch (requestCode) { case PictureConfig.CHOOSE_REQUEST: List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data); for (int i = 0; i < selectList.size() ; i++) { String path = selectList.get(i).getCompressPath(); xiangceList.add(path); } WindowUtils.setGridViewHeightBasedOnChildren(gv_xiangce , 4); adapter.notifyDataSetChanged(); postImageToService(selectList); break; } } } RadioGroup.OnCheckedChangeListener bedsListener = new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) { RadioButton radioButton = (RadioButton) group.findViewById(checkedId); String tag = (String) radioButton.getTag(); mainMode.setPost_bedsnum(tag); } }; RadioGroup.OnCheckedChangeListener bathsListener = new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) { RadioButton radioButton = (RadioButton) group.findViewById(checkedId); String tag = (String) radioButton.getTag(); mainMode.setPost_bathsnum(tag); } }; RadioGroup.OnCheckedChangeListener kitchenListener = new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) { RadioButton radioButton = (RadioButton) group.findViewById(checkedId); String tag = (String) radioButton.getTag(); mainMode.setPost_kitchensnum(tag); } }; /** * 输入对话框 */ private void getNameDialog(final String tag){ nameDialog = new MDEditDialog.Builder(SubmitRoom02Activity.this) .setTitleVisible(true).setTitleText("Please enter").setTitleTextSize(20) .setTitleTextColor(R.color.text_heise).setContentText("").setContentTextSize(18) .setMaxLength(7).setHintText("").setMaxLines(1) .setContentTextColor(R.color.line_huise).setButtonTextSize(14) .setLeftButtonTextColor(R.color.text_hui).setLeftButtonText("Cancle") .setRightButtonTextColor(R.color.text_heise).setRightButtonText("OK") .setLineColor(R.color.text_heise) .setInputTpye(InputType.TYPE_CLASS_NUMBER) .setOnclickListener(new MDEditDialog.OnClickEditDialogListener() { @Override public void clickLeftButton(View view, String editText) { nameDialog.dismiss(); } @Override public void clickRightButton(View view, String editText) { nameDialog.dismiss(); setDataFormDialog(tag , editText); } }).setMinHeight(0.3f).setWidth(0.8f).build(); nameDialog.show(); } /** * 输入对话框赋值 */ private void setDataFormDialog(String tag , String values){ switch (tag){ case "price": tv_price.setText(values); mainMode.setPost_price(values); break; case "squarefeet": tv_squarefeet.setText(values); mainMode.setPost_livesqft(values); break; case "lotsize": tv_lotsize.setText(values); mainMode.setPost_lotsize(values); break; case "wuyefei": tv_wuyefei.setText(values); mainMode.setPost_wuyefei(values); break; case "yearbuild": tv_yearbuild.setText(values); mainMode.setPost_yearbuilder(values); break; } } @Override public void onitemClickListening(View view, int position) { if (xiangceList.size() == position){ if (xiangceList.size() <= 8){ int num = 8 - xiangceList.size(); Log.i(TAG+"相册选择" , num+""); new ImageLogoUtils(SubmitRoom02Activity.this).getImageLogoDialog(num); } }else{ PhotoViewUtils.getPhotoView(activity , xiangceList , 0); } } /** * 网络上传图片 */ int a ; private void postImageToService(final List<LocalMedia> selectList){ String token = SharedPreferencesUtils.getToken(SubmitRoom02Activity.this); for (int i = 0; i < selectList.size() ; i++) { a = i; submit.setClickable(false); RequestParams params = new RequestParams(Constant.uhead+"house/file?"); params.setMultipart(true); params.addHeader("Authorization" , "Bearer "+token); params.addBodyParameter("file" , new File(selectList.get(i).getCompressPath())); x.http().post(params, new Callback.CommonCallback<String>() { @Override public void onSuccess(String result) { Log.i(TAG+"上传图片" , result); getJSONData(result); } @Override public void onError(Throwable ex, boolean isOnCallback) { Log.i(TAG+"上传图片" , ex.toString()); } @Override public void onCancelled(CancelledException cex) { Log.i(TAG+"上传图片" , cex.toString()); } @Override public void onFinished() { submit.setText("Uploading images"); if ((a+1) == selectList.size()){ submit.setClickable(true); submit.setText("Submit"); } } }); } } /** * 上传房屋图片解析数据 */ private void getJSONData(String json){ try { if (json != null){ JSONObject jsonObject = new JSONObject(json); int state = jsonObject.getInt("state"); if (state == 1){ JSONObject content = jsonObject.getJSONObject("content"); JSONObject data = content.getJSONObject("data"); String img_url = data.getString("img_url"); submitImageList.add(img_url); }else{ ToastUtils.showToast(SubmitRoom02Activity.this ,jsonObject.getString("message") ); } } } catch (Exception e) { e.printStackTrace(); } } /** * 短信验证码 */ private void getCodeIsRight(){ String codeNum = WindowUtils.getEditTextContent(ed_code); if (codeNum == null || codeNum.equals("")){ ToastUtils.showToast(activity , "Please enter the verification code"); return; } LoadingUtils.showDialog(activity); MyApplication.getmMyOkhttp().post() .url(Constant.yanzhengCode) .addParam("account" , WindowUtils.getEditTextContent(ed_phone)) .addParam("code" , codeNum) .addParam("model" , "edit") .enqueue(new NewRawResponseHandler(SubmitRoom02Activity.this) { @Override public void onSuccess(Object object,int statusCode, String response) { Log.i(TAG+"验证验证码" , response); LoadingUtils.dismiss(); try { JSONObject jsonObject = new JSONObject(response); int state = jsonObject.getInt("state"); if (state == 1){ getSubmitData(); } else if(state==703){ new LanRenDialog((Activity) activity).onlyLogin(); }else { ToastUtils.showToast(activity , "Please enter the correct verification code"); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(Object object,int statusCode, String error_msg) { Log.i(TAG+"验证验证码" , error_msg); LoadingUtils.dismiss(); } }); } /** * 提交数据 */ private void getSubmitData(){ String post_housetypeid = mainMode.getPost_housetypeid(); if (post_housetypeid == null){ ToastUtils.showToast(SubmitRoom02Activity.this , "The housing type is empty"); return; } String post_price = mainMode.getPost_price(); if (post_price == null){ ToastUtils.showToast(SubmitRoom02Activity.this , "The price of the house is empty"); return; } String post_livesqft = mainMode.getPost_livesqft(); if (post_livesqft == null){ ToastUtils.showToast(SubmitRoom02Activity.this , "The living area is empty"); return; } String post_lotsize = mainMode.getPost_lotsize(); if (post_lotsize == null){ ToastUtils.showToast(SubmitRoom02Activity.this , "The lotsize is empty"); return; } String post_wuyefei = mainMode.getPost_wuyefei(); if (post_wuyefei == null){ ToastUtils.showToast(SubmitRoom02Activity.this , "Property charges are vacant"); return; } String post_yearbuilder = mainMode.getPost_yearbuilder(); if (post_yearbuilder == null){ ToastUtils.showToast(SubmitRoom02Activity.this , "Construction age cannot be empty"); return; } String lianxiname = WindowUtils.getEditTextContent(ed_name); if (lianxiname == null || lianxiname.equals("")){ ToastUtils.showToast(SubmitRoom02Activity.this , "Contact names cannot be empty"); return; } String lianxiPhone = WindowUtils.getEditTextContent(ed_phone); if (lianxiPhone == null || lianxiPhone.equals("")){ ToastUtils.showToast(SubmitRoom02Activity.this , "The contact phone cannot be empty"); return; } if (lianxiPhone.length() != 11){ ToastUtils.showToast(SubmitRoom02Activity.this , "Please fill in the correct phone number"); return; } if (xiangceList.size() == 0){ ToastUtils.showToast(SubmitRoom02Activity.this , "Please select your image"); return; } String imageURL = ""; String imagezhutu = ""; for (int i = 0; i < submitImageList.size() ; i++) { if (i == 0){ imagezhutu = submitImageList.get(i); imageURL = submitImageList.get(i); }else{ imageURL = imageURL+","+submitImageList.get(i); } } LoadingUtils.showDialog(SubmitRoom02Activity.this); String token = SharedPreferencesUtils.getToken(SubmitRoom02Activity.this); MyApplication.getmMyOkhttp().post() .url(Constant.addHouseMessage) .addParam("id" , "") .addParam("contact_id" , "") .addHeader("Authorization" , "Bearer "+token) .addParam("fk_city_id" , mainMode.getFk_city_id()) .addParam("fk_state_id" , mainMode.getFk_state_id()) .addParam("price" , post_price) .addParam("property_price" , post_wuyefei) .addParam("fk_category_id" , post_housetypeid) .addParam("street" , mainMode.getName()) .addParam("zip" , mainMode.getZip()) .addParam("bedroom" , mainMode.getPost_bedsnum()) .addParam("bathroom" , mainMode.getPost_bathsnum()) .addParam("kitchen" , mainMode.getPost_kitchensnum()) .addParam("lot_sqft" , post_lotsize) .addParam("living_sqft" , post_livesqft) .addParam("latitude" , mainMode.getLat()+"") .addParam("longitude" , mainMode.getLon()+"") .addParam("year_build" , post_yearbuilder) .addParam("img_url" , imagezhutu) .addParam("img_code" , imageURL) .addParam("release_type" , mainMode.getRelease_type()) .addParam("description" , mainMode.getPost_details()) .addParam("name" , lianxiname) .addParam("phone_number" , lianxiPhone) .enqueue(new NewRawResponseHandler(SubmitRoom02Activity.this) { @Override public void onSuccess(Object object,int statusCode, String response) { Log.i(TAG+"上传" , response); dismiss(); try { JSONObject jsonObject = new JSONObject(response); int state = jsonObject.getInt("state"); if (state == 1){ getSubmitSuccess(state , "Uploaded successfully"); }else if(state==703){ new LanRenDialog((Activity) activity).onlyLogin(); }else { getSubmitSuccess(state , jsonObject.getString("message")); } } catch (Exception e) { e.printStackTrace(); ToastUtils.showToast(SubmitRoom02Activity.this , getString(R.string.json_erro)); } } @Override public void onFailure(Object object,int statusCode, String error_msg) { Log.i(TAG+"上传" , error_msg); dismiss(); getSubmitSuccess(3 , "Network connection failed"); } }); } /** * 上传成功提示 */ private void getSubmitSuccess(final int state , String str){ normalAlertDialog = new NormalAlertDialog.Builder(SubmitRoom02Activity.this) .setHeight(0.23f).setWidth(0.65f).setTitleVisible(true) .setTitleText("System hint").setTitleTextColor(R.color.colorPrimary) .setContentText(str).setContentTextColor(R.color.colorPrimaryDark) .setSingleMode(true).setSingleButtonText("Close") .setSingleButtonTextColor(R.color.colorAccent).setCanceledOnTouchOutside(true) .setSingleListener(new View.OnClickListener() { @Override public void onClick(View v) { if (state == 1){ PictureFileUtils.deleteCacheDirFile(activity); finish(); }else{ normalAlertDialog.dismiss(); } } }).build(); normalAlertDialog.show(); } }
[ "770846757@qq.com" ]
770846757@qq.com
cbb6a9592a9c8808bca4b3cf7d4eaf925e794c3b
12358faec06ebf150504bbe49a802b1fd8f54baa
/eclipse-workspace/bytebank-herdado-conta/src/br/com/bytebank/banco/test/TesteSacaException.java
f17e0de695cafd686be3469178f39ebd3b422573
[]
no_license
paty-feital/Java-I
e822c3c7449bda55e72197403b503b4f19468964
4d13efbc5be866db8a52bd1f5872a1c8c8276c98
refs/heads/master
2023-03-22T19:29:34.286975
2021-03-22T01:04:19
2021-03-22T01:04:19
328,454,565
0
0
null
null
null
null
UTF-8
Java
false
false
407
java
package br.com.bytebank.banco.test; import br.com.bytebank.banco.modelo.*; public class TesteSacaException { public static void main(String[] args) { Conta c = new ContaCorrente(123, 321); c.deposita(100.0); try { c.saca(250.0); } catch(SaldoInsuficienteException ex) { System.out.println("Ex: " + ex.getMessage()); } System.out.println("Saldo atual: " + c.getSaldo()); } }
[ "74514587+paty-feital@users.noreply.github.com" ]
74514587+paty-feital@users.noreply.github.com
2dbb08be998b47498fff69c11135243776ef9075
516f4db845d53fc644cf214d7768db372d9f903f
/src/main/java/com/svan/veille/site/bsmt/service/NewsService.java
9ea3eafcb936dc5810e7b15c69ebbe3e7da88e0d
[]
no_license
svan001/site-bsmt
2494b8b965c4a328d72f39094051561b23e17fcc
92a3d412cd421f600f3b9e3643741eca7c423ef8
refs/heads/master
2020-03-23T02:32:11.290031
2018-07-14T21:58:15
2018-07-14T21:58:15
140,978,930
0
0
null
null
null
null
UTF-8
Java
false
false
756
java
/** * 2014 * 6 nov. 2014 22:27:12 * @author stephane stephane.gronowski@gmail.com */ package com.svan.veille.site.bsmt.service; import java.util.List; import com.svan.veille.site.bsmt.dto.NewsDTO; /** * * 6 nov. 2014 22:27:12 * * @author stephane stephane.gronowski@gmail.com * */ public interface NewsService { /** * Return the last news * * @param limit * nb max de news * @return */ public List<NewsDTO> getLastNews(Integer limit); /** * Return the news * * @param id * @return the news or <code>null</code> */ public NewsDTO getById(Long id); /** * Add a news * * @param newsDTO * @return */ public NewsDTO addNews(NewsDTO newsDTO); }
[ "stephane.gronowski@gmail.com" ]
stephane.gronowski@gmail.com
c3dbb5cbef980e39ad04ff726f93707ab3cda653
271756a99ded5fc540ef5eb6fe5a569509501636
/core/src/main/java/ar/com/fenixxiii/game/graphics/DrawParameter.java
16eac8a960fb7261f42721420747733c1d5bc4f0
[]
no_license
llamas77/F13-PRUEBA
251469149eda0f48665f551203ff191f2924dfe1
e20e2d9aeb54ad6b1eb785badcfc06e04a84e436
refs/heads/master
2020-03-17T01:22:45.257477
2018-05-12T14:14:34
2018-05-12T14:14:34
133,150,220
0
0
null
null
null
null
UTF-8
Java
false
false
6,562
java
package ar.com.fenixxiii.game.graphics; import com.badlogic.gdx.graphics.Color; import static com.badlogic.gdx.graphics.GL20.GL_ONE; import static com.badlogic.gdx.graphics.GL20.GL_SRC_ALPHA; /** * Contiene los parametros para usar al renderizar algo * * color: color de cada vértice * alpha: cantidad de transparencia que luego se combina con el color. * light: indica si brilla o no (si cambia el clima y está activo, el color no se altera) * center: indica si el sprite va centrado * animated: si es una animación, indica si se reproduce o no. * rotation: indica la inclinación. Se expresa en grados (va de 0f a 360f) * scaleX, scaleY: indica un aumento de tamaño en X o Y, valor > 1 para mas grande, < 1 para mas chico. * flipX, flipY: indica si el sprite se voltea de forma horizontal o vertical. * blend: indica si se le aplica el efecto de blend al sprite * blendSrcFunc, blendDstFunc: variar para cambiar el efecto de blend por defecto, por otro. */ public class DrawParameter { private Color[] color; private float[] alpha; private boolean light; private boolean center; private boolean animated; private float rotation; private float scaleX; private float scaleY; private boolean flipX; private boolean flipY; private boolean blend; private int blendSrcFunc; private int blendDstFunc; /** * Crea el conjunto de Parámetros asignando a cada uno los valores más comunes */ public DrawParameter() { setColor(Color.WHITE); setAlpha(1f); this.scaleX = 1; this.scaleY = 1; this.blendSrcFunc = GL_SRC_ALPHA; this.blendDstFunc = GL_ONE; } /** * Devuelve el array de colores */ public Color[] getColors() { return color; } /** * Setea un array de colores */ public void setColors(Color[] color) { this.color = color; } /** * Devuelve el color de uno de los vértices (útil cuando todos los vertices tienen el mismo color) */ public Color getColor() { return color[0]; } /** * Setea un mismo color para todos los vértices, especificando Color */ public void setColor(Color color) { setColor(color.r, color.g, color.b); } public void setColor(int r, int g, int b) { setColor((float)r/255, (float)g/255, (float)b/255); } /** * Setea un mismo color para todos los vértices, especificando cada componente */ public void setColor(float r, float g, float b) { this.color = new Color[4]; for (int i = 0; i < this.color.length; i++) { this.color[i] = new Color(r, g, b, 1); } } /** * Devuelve el color de un vértice específico */ public Color getVertColor(int vert) { return color[vert]; } /** * Setea el color de un vértice específico, especificando Color */ public void setVertColor(int vert, Color color) { this.color[vert] = color; } public void setVertColor(int vert, int r, int g, int b) { setVertColor(vert, (float)r/255, (float)g/255, (float)b/255); } /** * Setea el color de un vértice específico, especificando cada componente */ public void setVertColor(int vert, float r, float g, float b) { this.color[vert] = new Color(r, g, b, 1); } public float[] getAlphas() { return alpha; } /** * Devuelve el conjunto de alphas de todos los vértices */ public void setAlpha(int alpha) { setAlpha((float)alpha/255); } /** * Setea un mísmo alpha para todos los vértices */ public void setAlpha(float alpha) { this.alpha = new float[4]; for (int i = 0; i < this.alpha.length; i++) { this.alpha[i] = alpha; } } public void setAlphas(float[] alphas) { for (int i = 0; i < alpha.length; i++) { setVertAlpha(i, alphas[i]); } } public void setVertAlpha(int vert, int alpha) { setVertAlpha(vert, (float)alpha/255); } /** * Setea un alpha a un vértice específico */ public void setVertAlpha(int vert, float alpha) { this.alpha[vert] = alpha; } /** * Devuelve el alpha de un vértice */ public float getVertAlpha(int vert) { return alpha[vert]; } public boolean isLight() { return light; } public void setLight(boolean light) { this.light = light; } public boolean isCenter() { return center; } public void setCenter(boolean center) { this.center = center; } public boolean isAnimated() { return animated; } public void setAnimated(boolean animated) { this.animated = animated; } public float getRotation() { return rotation; } /** * Setea los grados del ángulo de inclinación */ public void setRotation(float rotation) { this.rotation = rotation; } public float getScaleX() { return scaleX; } public void setScaleX(float scaleX) { this.scaleX = scaleX; } public float getScaleY() { return scaleY; } /** * Setea la misma escala para ambos ejes */ public void setScale(float scaleXY) { this.scaleX = scaleXY; this.scaleY = scaleXY; } public void setScaleY(float scaleY) { this.scaleY = scaleY; } public boolean isFlipX() { return flipX; } public void setFlipX(boolean flipX) { this.flipX = flipX; } public boolean isFlipY() { return flipY; } public void setFlipY(boolean flipY) { this.flipY = flipY; } /** * Voltea el sprite de forma horizontal y vertical simultaneamente. */ public void setFlip(boolean flipXY) { this.flipX = flipXY; this.flipY = flipXY; } public boolean isFlip() { return this.flipX && this.flipY; } public boolean isBlend() { return blend; } public void setBlend(boolean blend) { this.blend = blend; } public int getBlendSrcFunc() { return blendSrcFunc; } public void setBlendSrcFunc(int blendSrcFunc) { this.blendSrcFunc = blendSrcFunc; } public int getBlendDstFunc() { return blendDstFunc; } public void setBlendDstFunc(int blendDstFunc) { this.blendDstFunc = blendDstFunc; } }
[ "llamas077@hotmail.com" ]
llamas077@hotmail.com
b8aaa4c87e2bdfec956e171e277d61476a0a966b
faf1c6c46a1327b6bb1d512475545a5856d2e744
/Java Udemy/EjemploEstatico/src/main/java/mx/com/rlr/ejemploestatico/EjemploEstatico (2020_03_05 03_17_26 UTC).java
10028ae2d9f61a3f165ff3473f05deb0fe510e44
[]
no_license
ElRobert17L/Proyectos_Java
29c7346ade0a0d0316d1c7bf6b08e39bca671101
fff46649659f825831308810d34d2dc4d5cafe55
refs/heads/master
2022-11-14T23:18:45.266366
2020-07-07T01:16:39
2020-07-07T01:16:39
277,001,530
0
0
null
null
null
null
UTF-8
Java
false
false
514
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 mx.com.rlr.ejemploestatico; /** * * @author rob-c */ public class EjemploEstatico { public static void main(String[] args) { Persona p1 = new Persona("Roberto"); System.out.println(p1); Persona p2 = new Persona("Karla"); System.out.println(p2); } }
[ "rob017led@gmail.com" ]
rob017led@gmail.com
75238455fad3cc1b02358ab7ab9e7d215821a9a1
f5964fb44e2015b4d824ce1cedc02b84a80db35a
/iris-rpc/iris-rpc-api/src/main/java/com/leibangzhu/iris/protocol/ProtocolFactory.java
3f41f903789e75ba9f9365f94543fe73097ffb91
[]
no_license
LiWenGu/iris
77a5f80b032aa27fca484464b6e93f8ccb5f3bf7
51824b56c1a93e0a4ca2a39c1d15cac576916012
refs/heads/dev
2022-04-27T16:39:02.824752
2019-11-07T17:08:47
2019-11-07T17:08:47
217,238,565
3
1
null
2020-10-13T16:57:20
2019-10-24T07:30:25
Java
UTF-8
Java
false
false
357
java
package com.leibangzhu.iris.protocol; import com.leibangzhu.coco.ExtensionLoader; import java.util.Arrays; public class ProtocolFactory { private static Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getDefaultExtension(Arrays.asList("filter")); public static Protocol getProtocol() { return protocol; } }
[ "liwenguang_dev@163.com" ]
liwenguang_dev@163.com
9d0d760d88c554807379d81184ffc7ccff41707e
3602d4507c83c616b7d56fb3c66db27cde2efa84
/Intermediate/StackTest.java
d6e50fe0d13c41fff2055ada17334d02f4da1797
[]
no_license
Deepak3994/java-assignment1
dd59698f8011fc16a5e9a49006830f9036be4bd3
3109347528553f6f05115fe0385030d71b5bba66
refs/heads/master
2021-01-12T11:43:49.321560
2016-11-11T06:58:40
2016-11-11T06:58:40
72,280,711
0
0
null
null
null
null
UTF-8
Java
false
false
214
java
class StackTest extends StackOperations { public static void main(String args[]) { StackOperations s = new StackOperations(); s.push(10).push(20).push(30); s.display(); //s.pop(); //s.display(); } }
[ "meetdeepaknayak03@gmail.com" ]
meetdeepaknayak03@gmail.com
099492b735e3f32a03f580a81b901b348d675fd3
64c40e66f02346b79063fefe4c150d08345a2865
/src/main/java/org/asciidoc/intellij/ui/ExtractIncludeDialog.java
60dc59cd9c290658e9c0ab233c8be7270f4c8c62
[ "Apache-2.0" ]
permissive
ardlank/asciidoctor-intellij-plugin
258774237e4510549f99d40dd7cf19c7e3724aee
5c88a9bd9451c1f95a2f877598e17f606cc6a850
refs/heads/master
2020-08-27T02:47:21.984397
2019-10-22T11:17:31
2019-10-22T11:17:31
217,223,644
1
0
Apache-2.0
2019-10-24T06:07:19
2019-10-24T06:07:17
null
UTF-8
Java
false
false
8,318
java
package org.asciidoc.intellij.ui; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.UndoConfirmationPolicy; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.ValidationInfo; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.ui.NameSuggestionsField; import com.intellij.refactoring.ui.RefactoringDialog; import com.intellij.util.IncorrectOperationException; import org.asciidoc.intellij.file.AsciiDocFileType; import org.asciidoc.intellij.psi.AsciiDocBlock; import org.asciidoc.intellij.psi.AsciiDocBlockId; import org.asciidoc.intellij.psi.AsciiDocBlockMacro; import org.asciidoc.intellij.psi.AsciiDocSection; import org.asciidoc.intellij.psi.AsciiDocUtil; import org.asciidoc.intellij.util.FilenameUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; public class ExtractIncludeDialog extends RefactoringDialog { private final Editor myEditor; private final PsiFile myFile; private NameSuggestionsField myFilename; public static PsiElement getElementToExtract(@NotNull Editor editor, @NotNull PsiFile file) { PsiElement element = AsciiDocUtil.getStatementAtCaret(editor, file); if (element == null) { return null; } if (element.getParent() != null && element.getParent() instanceof AsciiDocBlockMacro) { element = element.getParent(); } if (element instanceof AsciiDocBlockMacro && "include".equals(((AsciiDocBlockMacro) element).getMacroName())) { return null; } while ((element instanceof AsciiDocBlockMacro || (!(element instanceof AsciiDocBlock) && !(element instanceof AsciiDocSection))) && element.getParent() != null) { element = element.getParent(); } if (element instanceof AsciiDocBlock || element instanceof AsciiDocSection) { return element; } return null; } public ExtractIncludeDialog(@NotNull Project project, Editor editor, PsiFile file) { super(project, false); this.myEditor = editor; this.myFile = file; String filename = "include"; PsiElement element = getElementToExtract(editor, file); if (element != null) { AsciiDocBlockId id = PsiTreeUtil.findChildOfType(element, AsciiDocBlockId.class); if (id != null) { filename = id.getName(); } } myFilename = new NameSuggestionsField(new String[]{filename + "." + AsciiDocFileType.INSTANCE.getDefaultExtension()}, myProject, AsciiDocFileType.INSTANCE, myEditor); myFilename.selectNameWithoutExtension(); setTitle("Extract Include Directive"); init(); } @Nullable @Override protected ValidationInfo doValidate() { if (myFilename.getEnteredName().trim().length() == 0) { return new ValidationInfo("Please enter include file name!", myFilename); } if (!FilenameUtils.getName(getFilename()).equals(getFilename())) { return new ValidationInfo("Specifying a different directory is currently not supported."); } try { myFile.getContainingDirectory().checkCreateFile(getFilename()); } catch (IncorrectOperationException e) { return new ValidationInfo("Unable to create file: " + e.getMessage(), myFilename); } return super.doValidate(); } @Override protected boolean postponeValidation() { return false; } @Nullable @Override protected JComponent createCenterPanel() { JPanel panel = new JPanel(new GridLayout(1, 0)); JPanel addFilename = new JPanel(new BorderLayout()); JLabel filenameLabel = new JLabel("File Name: "); filenameLabel.setLabelFor(myFilename); addFilename.add(filenameLabel, BorderLayout.LINE_START); myFilename.setPreferredSize(new Dimension(200, 0)); addFilename.add(myFilename, BorderLayout.LINE_END); panel.add(addFilename); return panel; } @Override protected boolean hasHelpAction() { return false; } @Override protected boolean hasPreviewButton() { return false; } @Override public JComponent getPreferredFocusedComponent() { return myFilename.getFocusableComponent(); } @Override protected void doAction() { ApplicationManager.getApplication().runWriteAction(() -> CommandProcessor.getInstance().executeCommand(myProject, () -> { try { TextRange range = getTextRange(myEditor, myFile); String newFileName = getFilename(); PsiFile asciiDocFile = PsiFileFactory.getInstance(myProject).createFileFromText(newFileName, AsciiDocFileType.INSTANCE, myEditor.getDocument().getText(range)); PsiFile newFile = (PsiFile) myFile.getContainingDirectory().add(asciiDocFile); StringBuilder sb = new StringBuilder(); sb.append("include::"); int offset = sb.length(); sb.append(newFileName).append("[]"); int start = range.getStartOffset(); int end = range.getEndOffset(); // the include block macro needs to be on its own line. // if we can't reuse the newlines of the current selection, add newlines as necessary if (start != 0 && !myEditor.getDocument().getText(TextRange.create(start - 1, start)).equals("\n")) { sb.insert(0, "\n"); offset++; while (start > 0 && myEditor.getDocument().getText(TextRange.create(start - 1, start)).equals(" ")) { start--; } } if (end != myEditor.getDocument().getTextLength() && !myEditor.getDocument().getText(TextRange.create(end, end + 1)).equals("\n")) { sb.append("\n"); while (end != myEditor.getDocument().getTextLength() && myEditor.getDocument().getText(TextRange.create(end, end + 1)).equals(" ")) { end++; } } myEditor.getDocument().replaceString(start, end, sb.toString()); myEditor.getCaretModel().moveToOffset(start + offset); myEditor.getCaretModel().getPrimaryCaret().removeSelection(); newFile.navigate(true); close(DialogWrapper.OK_EXIT_CODE); } catch (Exception e) { setErrorText("Unable to create include"); } }, getTitle(), getGroupId(), UndoConfirmationPolicy.REQUEST_CONFIRMATION)); } private static TextRange getTextRange(@NotNull Editor myEditor, @NotNull PsiFile myFile) { SelectionModel selectionModel = myEditor.getSelectionModel(); int start, end; if (selectionModel.getSelectionStart() != selectionModel.getSelectionEnd()) { start = selectionModel.getSelectionStart(); end = selectionModel.getSelectionEnd(); } else { PsiElement element = getElementToExtract(myEditor, myFile); if (element != null) { start = element.getTextOffset(); end = element.getTextOffset() + element.getTextLength(); } else { element = AsciiDocUtil.getStatementAtCaret(myEditor, myFile); if (element != null) { // use start/end of current element and expand to begin/end of line start = element.getTextOffset(); end = element.getTextOffset() + element.getTextLength(); while (start > 0 && !myEditor.getDocument().getText(TextRange.create(start - 1, start)).equals("\n")) { start--; } while (end != myEditor.getDocument().getTextLength() && !myEditor.getDocument().getText(TextRange.create(end, end + 1)).equals("\n")) { end++; } } else { return TextRange.EMPTY_RANGE; } } } return TextRange.create(start, end); } private String getGroupId() { return AsciiDocFileType.INSTANCE.getName(); } @Override protected boolean areButtonsValid() { if (doValidate() != null) { return false; } return super.areButtonsValid(); } private String getFilename() { return myFilename.getEnteredName().trim(); } }
[ "alexander.schwartz@gmx.net" ]
alexander.schwartz@gmx.net
e0e6ff4600193253eb4ef69cb2676e9232b6c796
4572083a4b8ffd7b22094d0eecf6b98e61b4da9b
/src/main/java/service/ChangePasswordService.java
f43e93b7b0e24ddf9b36ffa5459ce1dc84e7f1c7
[]
no_license
sincheon90/WebPro
837fd9594512f73c78939c35db8cc572f154c885
44550c2c5a3d521e0f97a7ff119dcc4628a08db4
refs/heads/main
2023-04-19T17:36:59.261716
2021-05-13T10:37:12
2021-05-13T10:37:12
366,971,841
0
0
null
null
null
null
UTF-8
Java
false
false
605
java
package service; import org.springframework.transaction.annotation.Transactional; import domain.Member; import domain.MemberDao; import exception.MemberNotFoundException; public class ChangePasswordService { private MemberDao memberDao; @Transactional public void changePassword(String email, String oldPwd, String newPwd) { Member member = memberDao.selectByEmail(email); if (member == null) throw new MemberNotFoundException(); member.changePassword(oldPwd, newPwd); memberDao.update(member); } public void setMemberDao(MemberDao memberDao) { this.memberDao = memberDao; } }
[ "sincheon90@gmail.com" ]
sincheon90@gmail.com
fe8e7d9ecd74b226cf57884da07290c34e95c844
2b102b7ab4448a0b1732f72469bb12eb1590d0a6
/tradetunnel-ap/src/test/java/com/ip/tradetunnel/TradetunnelApApplicationTests.java
9fd4f16f4cefecfc6bb6fa3206e0191235055071
[]
no_license
HimanshuChhabra/TradeTunnel
fb276c3ecf714478bfc19cddfec80041f106d7f4
529080fc166301bdd5146bec09cf4d027880d8e0
refs/heads/master
2020-03-24T02:19:54.342334
2018-07-26T03:11:28
2018-07-26T03:11:28
142,371,703
0
0
null
null
null
null
UTF-8
Java
false
false
342
java
package com.ip.tradetunnel; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class TradetunnelApApplicationTests { @Test public void contextLoads() { } }
[ "himanshu.chhabra9304@gmail.com" ]
himanshu.chhabra9304@gmail.com
380c42c92c7beb407cb7856871838276a7ce8ec8
4983469c369203d1cc944dfd38622cb922e05620
/01. Source Code/02. Android/SwipeSafe/app/src/main/java/nts/swipesafe/fragment/FragmentCompetition.java
9c40edf2d1e62a0e4d91fd57c60e9b0bad603bfa
[]
no_license
TamDao97/E-learning
76ebe2436bfe3a263df1d8cb6f6dcce3921bbbf0
e654b55dcb6349c908fa6e7f4e771879d0844c35
refs/heads/master
2023-05-31T07:02:45.984733
2021-06-09T15:10:44
2021-06-09T15:10:44
375,396,621
0
0
null
null
null
null
UTF-8
Java
false
false
2,252
java
package nts.swipesafe.fragment; import android.app.Dialog; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.fragment.app.Fragment; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import nts.swipesafe.R; public class FragmentCompetition extends Fragment { private View view; private WebView webViewCompetition; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_competition, container, false); initComponent(); confirmSecurity(); // Inflate the layout for this fragment return view; } private void initComponent() { webViewCompetition = view.findViewById(R.id.webViewCompetition); webViewCompetition.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return false; } }); webViewCompetition.getSettings().setJavaScriptEnabled(true); webViewCompetition.loadUrl("https://forms.office.com/Pages/ResponsePage.aspx?id=PBS9SA8yBUeKHDkp1wRFSKxA-zjxQ3lHvmvHZfEE2DxUOE1GWjk3QlhKSjNUTVQ2WlU0N1ExSkM2US4u"); } public void confirmSecurity() { final Dialog dialog = new Dialog(getContext()); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.getWindow().getAttributes().windowAnimations = R.style.DialogTheme; dialog.setContentView(R.layout.popup_info_security); dialog.show(); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { dialog.hide(); } }, 15000); } }
[ "tamdc8897@gmail.com" ]
tamdc8897@gmail.com
5eed365ad435c7646a73a1bad2a11ebd08f97f36
40687daec264358f319578e5d0ea9eebfb43e859
/ThreadFilesHandling/src/main/java/com/srm/threads/java/filehandling/ThreadFilesHandling/BaseManager.java
cc4f716dbeb58ebf3c4498abdf54b28be3d32795
[]
no_license
shinyfelicitav21/Java-usecase
1a200bad67655cf0768c174d74e920383275cc28
51d049a6c9c083640542666bd67253999c9e752c
refs/heads/master
2023-05-02T08:45:02.401034
2021-05-12T13:20:10
2021-05-12T13:20:10
364,289,740
0
0
null
null
null
null
UTF-8
Java
false
false
687
java
package com.srm.threads.java.filehandling.ThreadFilesHandling; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections4.ListUtils; public abstract class BaseManager { protected List<TextFile> getFiles(String location){ File[] files=new File(location).listFiles(); List <TextFile> textFiles= new ArrayList<>(); int count=0; for(File file:files) { textFiles.add(new TextFile(++count,file.getName(),location,new java.util.Date())); } return textFiles; } protected List<List<TextFile>> getPages(List<TextFile> files,int count) { return ListUtils.partition(files, count); } }
[ "Admin@DESKTOP-8PIN619" ]
Admin@DESKTOP-8PIN619
339ebe5620004d10d0c950c657ce284aceee902b
af1321f4186a7b1412d9d1e2608597eaf8d7b7ae
/src/main/java/TachografReaderUI/file/CardBlockFile.java
98cda27a7af912a6bad7c1c3d7c45ea331e6d78b
[]
no_license
AskmeKolaric/Askme5DesktopApp
0cdb1d75f5775c8c80a7878c4bb1c5449cf3e6c1
304fa0200a561a3871da6acdaf0f0665c2aa50c7
refs/heads/main
2023-04-03T10:52:48.370275
2021-04-14T20:31:50
2021-04-14T20:31:50
348,289,549
1
0
null
null
null
null
UTF-8
Java
false
false
12,705
java
/** * */ package TachografReaderUI.file; import java.io.IOException; import java.util.*; import TachografReaderUI.file.certificate.Signature; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import TachografReaderUI.file.driverCardBlock.CardControlActivityDataRecord; import TachografReaderUI.file.driverCardBlock.CardDrivingLicenceInformation; import TachografReaderUI.file.driverCardBlock.CardPlaceDailyWorkPeriod; import TachografReaderUI.file.driverCardBlock.DriverCardApplicationIdentification; import TachografReaderUI.file.driverCardBlock.Fid; import TachografReaderUI.helpers.Number; import TachografReaderUI.file.driverCardBlock.CardCertificate; import TachografReaderUI.file.driverCardBlock.CardChipIdentification; import TachografReaderUI.file.driverCardBlock.CardCurrentUse; import TachografReaderUI.file.driverCardBlock.CardDriverActivity; import TachografReaderUI.file.driverCardBlock.CardEventData; import TachografReaderUI.file.driverCardBlock.CardFaultData; import TachografReaderUI.file.driverCardBlock.CardIccIdentification; import TachografReaderUI.file.driverCardBlock.CardIdentification; import TachografReaderUI.file.driverCardBlock.CardVehiclesUsed; import TachografReaderUI.file.driverCardBlock.LastCardDownload; import TachografReaderUI.file.driverCardBlock.MemberStateCertificate; import TachografReaderUI.file.driverCardBlock.SpecificConditionRecord; public class CardBlockFile { private String nameFile=null; // block file of driver card @JsonIgnore private CardIccIdentification icc = null; @JsonIgnore private CardChipIdentification ic = null; @JsonIgnore private DriverCardApplicationIdentification application_identification = null; @JsonIgnore private CardCertificate card_certificate = null; @JsonIgnore private MemberStateCertificate ca_certificate = null; @JsonIgnore private CardIdentification identification = null; @JsonIgnore private LastCardDownload card_download = null; @JsonIgnore private CardDrivingLicenceInformation driving_lincense_info = null; @JsonIgnore private CardEventData event_data = null; @JsonIgnore private CardFaultData fault_data = null; @JsonIgnore private CardDriverActivity driver_activity_data = null; @JsonIgnore private CardVehiclesUsed vehicles_used = null; @JsonIgnore private CardPlaceDailyWorkPeriod places = null; @JsonIgnore private CardCurrentUse current_usage = null; @JsonIgnore private CardControlActivityDataRecord control_activity_data = null; @JsonIgnore private SpecificConditionRecord specific_conditions = null; @JsonIgnore private byte[] fileArray; private boolean sid=false; private HashMap<String, Block> listBlock; public CardBlockFile() { } @SuppressWarnings({ "unchecked", "rawtypes" }) public CardBlockFile(byte[] bytes) throws Exception { HashMap<String, Block> lista = new HashMap(); this.listBlock=new HashMap(); try { int start=0; while( start < bytes.length){ int fid = Number.getNumber(Arrays.copyOfRange(bytes, start, start += 2)); if(this.existe_Fid(fid)){ byte tipo = bytes[start]; start += 1; Integer longitud = (int) Number.getNumber(Arrays.copyOfRange(bytes, start, start += 2)); byte[] datos = new byte[longitud]; datos = Arrays.copyOfRange(bytes, start, start += longitud); if (tipo == 0) { Block block = (Block) FactoriaBloques.getFactoria(fid, datos); if (block != null) { this.listBlock.put(block.getFID(), (Block) block); }else{ this.listBlock.get(nameBlock(fid)).setSignature(new Signature(datos)); } }else{ this.listBlock.get(nameBlock(fid)).setSignature(new Signature(datos)); } }else{ throw new Error("Block not found"); } } } catch (IOException e) { System.out.println(e.getMessage()); } this.asignarBloques(); } private void asignarBloques() { this.icc = (CardIccIdentification) this.listBlock.get(Fid.EF_ICC .toString()); this.ic = (CardChipIdentification) this.listBlock.get(Fid.EF_IC .toString()); this.application_identification = (DriverCardApplicationIdentification) this.listBlock .get(Fid.EF_APPLICATION_IDENTIFICATION.toString()); this.card_certificate = (CardCertificate) this.listBlock .get(Fid.EF_CARD_CERTIFICATE.toString()); this.ca_certificate = (MemberStateCertificate) this.listBlock .get(Fid.EF_CA_CERTIFICATE.toString()); this.identification = (CardIdentification) this.listBlock .get(Fid.EF_IDENTIFICATION.toString()); this.card_download = (LastCardDownload) this.listBlock .get(Fid.EF_CARD_DOWNLOAD.toString()); this.driving_lincense_info = (CardDrivingLicenceInformation) this.listBlock .get(Fid.EF_DRIVING_LICENSE_INFO.toString()); this.event_data = (CardEventData) this.listBlock .get(Fid.EF_EVENTS_DATA.toString()); this.fault_data = (CardFaultData) this.listBlock .get(Fid.EF_FAULTS_DATA.toString()); this.driver_activity_data = (CardDriverActivity) this.listBlock .get(Fid.EF_DRIVER_ACTIVITY_DATA.toString()); this.vehicles_used = (CardVehiclesUsed) this.listBlock .get(Fid.EF_VEHICLES_USED.toString()); this.vehicles_used.setNoOfCardVehicleRecords(this.application_identification.getNoOfCardVehicleRecords().getNoOfCardVehicleRecords()); this.places = (CardPlaceDailyWorkPeriod) this.listBlock .get(Fid.EF_PLACES.toString()); if (this.places!=null) this.places.setNoOfCArdPlaceRecords(this.application_identification .getNoOfCardPlaceRecords().getNoOfCardPlaceRecords()); this.current_usage = (CardCurrentUse) this.listBlock .get(Fid.EF_CURRENT_USAGE.toString()); this.control_activity_data = (CardControlActivityDataRecord) this.listBlock .get(Fid.EF_CONTROL_ACTIVITY_DATA.toString()); this.specific_conditions = (SpecificConditionRecord) this.listBlock .get(Fid.EF_SPECIFIC_CONDITIONS.toString()); } private String nameBlock(int fid){ String str=""; switch (fid) { case 0x0002: str=Fid.EF_ICC.toString(); break; case 0x0005: str=Fid.EF_IC.toString(); break; case 0x0501: str=Fid.EF_APPLICATION_IDENTIFICATION.toString(); break; case 0xc100: str=Fid.EF_CARD_CERTIFICATE.toString(); break; case 0xc108: str=Fid.EF_CA_CERTIFICATE.toString(); break; case 0x0520: str=Fid.EF_IDENTIFICATION.toString(); break; case 0x050E: str=Fid.EF_CARD_DOWNLOAD.toString(); break; case 0x0521: str=Fid.EF_DRIVING_LICENSE_INFO.toString(); break; case 0x0502: str=Fid.EF_EVENTS_DATA.toString(); break; case 0x0503: // Faults data str=Fid.EF_FAULTS_DATA.toString(); break; case 0x0504: // Driver activity data str=Fid.EF_DRIVER_ACTIVITY_DATA.toString(); break; case 0x0505:// vehicles uses str=Fid.EF_VEHICLES_USED.toString(); break; case 0x0506: // Places str=Fid.EF_PLACES.toString(); break; case 0x0507: // Currents usage str=Fid.EF_CURRENT_USAGE.toString(); break; case 0x0508: // Control activity data str=Fid.EF_CONTROL_ACTIVITY_DATA.toString(); break; case 0x0522: str=Fid.EF_SPECIFIC_CONDITIONS.toString(); break; default: break; } return str; } private boolean existe_Fid(int fid) { Fid[] list_fid = Fid.values(); boolean ok = false; for (int i = 0; i < list_fid.length; i++) { if (list_fid[i].getId() == fid) { ok = true; i = list_fid.length; } } return ok; } public CardIccIdentification getIcc() { return icc; } public void setIcc(CardIccIdentification icc) { this.icc = icc; } public CardChipIdentification getIc() { return ic; } public void setIc(CardChipIdentification ic) { this.ic = ic; } public DriverCardApplicationIdentification getApplication_identification() { return application_identification; } public void setApplication_identification( DriverCardApplicationIdentification application_identification) { this.application_identification = application_identification; } public CardCertificate getCard_certificate() { return card_certificate; } public void setCard_certificate(CardCertificate card_certificate) { this.card_certificate = card_certificate; } public MemberStateCertificate getCa_certificate() { return ca_certificate; } public void setCa_certificate(MemberStateCertificate ca_certificate) { this.ca_certificate = ca_certificate; } public CardIdentification getIdentification() { return identification; } public void setIdentification(CardIdentification identification) { this.identification = identification; } public LastCardDownload getCard_download() { return card_download; } public void setCard_download(LastCardDownload card_download) { this.card_download = card_download; } public CardDrivingLicenceInformation getDriving_lincense_info() { return driving_lincense_info; } public void setDriving_lincense_info( CardDrivingLicenceInformation driving_lincense_info) { this.driving_lincense_info = driving_lincense_info; } public CardEventData getEvent_data() { return event_data; } public void setEvent_data(CardEventData event_data) { this.event_data = event_data; } public CardFaultData getFault_data() { return fault_data; } public void setFault_data(CardFaultData fault_data) { this.fault_data = fault_data; } public CardDriverActivity getDriver_activity_data() { return driver_activity_data; } public void setDriver_activity_data(CardDriverActivity driver_activity_data) { this.driver_activity_data = driver_activity_data; } public CardVehiclesUsed getVehicles_used() { return vehicles_used; } public void setVehicles_used(CardVehiclesUsed vehicles_used) { this.vehicles_used = vehicles_used; } public CardPlaceDailyWorkPeriod getPlaces() { return places; } public void setPlaces(CardPlaceDailyWorkPeriod places) { this.places = places; } public CardCurrentUse getCurrent_usage() { return current_usage; } public void setCurrent_usage(CardCurrentUse current_usage) { this.current_usage = current_usage; } public CardControlActivityDataRecord getControl_activity_data() { return control_activity_data; } public void setControl_activity_data( CardControlActivityDataRecord control_activity_data) { this.control_activity_data = control_activity_data; } public SpecificConditionRecord getSpecific_conditions() { return specific_conditions; } public void setSpecific_conditions( SpecificConditionRecord specific_conditions) { this.specific_conditions = specific_conditions; } @Override public String toString() { return "CardBlockFile [nameFile=" + nameFile + ", icc=" + icc + ", ic=" + ic + ", application_identification=" + application_identification + ", card_certificate=" + card_certificate + ", ca_certificate=" + ca_certificate + ", identification=" + identification + ", card_download=" + card_download + ", driving_lincense_info=" + driving_lincense_info + ", event_data=" + event_data + ", fault_data=" + fault_data + ", driver_activity_data=" + driver_activity_data + ", vehicles_used=" + vehicles_used + ", places=" + places + ", current_usage=" + current_usage + ", control_activity_data=" + control_activity_data + ", specific_conditions=" + specific_conditions + ", sid=" + sid + ", listBlock=" + listBlock + "]"; } public String getNameFile() { return nameFile; } public void setNameFile(String nameFile) { this.nameFile = nameFile; } public boolean isSid() { return sid; } public void setSid(boolean sid) { this.sid = sid; } public HashMap<String, Block> getListBlock() { return listBlock; } public void setListBlock(HashMap<String, Block> listBlock) { this.listBlock = listBlock; } public byte[] getFileArray() { return fileArray; } public void setFileArray(byte[] fileArray) { this.fileArray = fileArray; } @JsonIgnore public String getJson() { ObjectMapper mapper = new ObjectMapper(); String str = ""; try { str = mapper.writeValueAsString(this); } catch (JsonProcessingException e) { e.printStackTrace(); } return str; } }
[ "marko.kolaric@datasys.at" ]
marko.kolaric@datasys.at
e5f45455260b7b1625ea402afab73d398a2ca037
e6b60213c006b3f162fe40b05a8b3c700404ed2e
/proj-core/src/main/java/com/proj/appservice/DealerSignTypeAppService.java
52a28a39531f0282d5fc723ac6d4a870b0fcec39
[]
no_license
sengeiou/enterpriseProjwondersun
bec1c520181bf8b84250f61793488a9e4b3dacc4
537bc0e98bebfc9054f297f6cdc380cd309870ef
refs/heads/main
2023-01-24T16:55:41.429031
2020-12-04T14:27:24
2020-12-04T14:27:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
822
java
package com.proj.appservice; import com.arlen.eaf.core.dto.APIResult; import com.arlen.eaf.core.dto.PageReq; import com.arlen.eaf.core.dto.PageResult; import com.proj.dto.DealerSignTypeDTO; import java.util.List; import java.util.Map; /** * 经销商签收方式 */ public interface DealerSignTypeAppService { APIResult<DealerSignTypeDTO> getById(String id); APIResult<String> create(DealerSignTypeDTO dto); APIResult<String> update(DealerSignTypeDTO dto); APIResult<String> delete(String id); APIResult<List<DealerSignTypeDTO>> getChildList(); APIResult<PageResult<Map>> getPageListBySql(PageReq pageReq); APIResult<Boolean> queryByDealerId(String dealerId); APIResult<Boolean> isAutoReceive(String dealerId); APIResult<String> getAutoDeliveryStore(String dealerId); }
[ "arlenchen@ehsure.com" ]
arlenchen@ehsure.com
a31dce25c59692827d021e6512b7b259cb6031ca
c1a5ab86a51e4c5dbde4c92776953d0d1ef1cdae
/src/main/java/com/robert/JavaUtil/redis/RandomUtils.java
be35a7fe8a972b2942b773582bb2b8604c768f05
[]
no_license
mengjianzhou/zsMgr
42fa2244ab826a94b1a3ed293d78685e974cf5a6
d059a6fa1602ba504f09e045ce4d1ec30a92c934
refs/heads/master
2021-07-24T04:05:50.538121
2016-10-17T08:33:04
2016-10-17T08:33:04
66,474,159
0
0
null
null
null
null
UTF-8
Java
false
false
307
java
package com.robert.JavaUtil.redis; import java.util.Random; public class RandomUtils { public static void main(String[] args) { Random random = new Random(); System.out.println(); int num=20; while(num!=(random.nextInt(20))){ System.out.println("..."); } System.out.println("20"); } }
[ "zhaobo@zillionfortune.com" ]
zhaobo@zillionfortune.com
99860c5731e3a70f18ed4c36cf400f2bd3fd69c9
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/java/neo4j/2017/12/StubKernelTransaction.java
bbd469e2dd6aeae96833332f9156d71e7a4a2f6f
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
Java
false
false
6,019
java
/* * Copyright (c) 2002-2017 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel.builtinprocs; import java.util.Optional; import org.neo4j.internal.kernel.api.CursorFactory; import org.neo4j.internal.kernel.api.ExplicitIndexRead; import org.neo4j.internal.kernel.api.ExplicitIndexWrite; import org.neo4j.internal.kernel.api.Locks; import org.neo4j.internal.kernel.api.NodeCursor; import org.neo4j.internal.kernel.api.PropertyCursor; import org.neo4j.internal.kernel.api.Read; import org.neo4j.internal.kernel.api.SchemaRead; import org.neo4j.internal.kernel.api.SchemaWrite; import org.neo4j.internal.kernel.api.TokenRead; import org.neo4j.internal.kernel.api.TokenWrite; import org.neo4j.internal.kernel.api.Write; import org.neo4j.internal.kernel.api.security.SecurityContext; import org.neo4j.kernel.api.KernelTransaction; import org.neo4j.kernel.api.ReadOperations; import org.neo4j.kernel.api.Statement; import org.neo4j.kernel.api.exceptions.Status; import org.neo4j.kernel.api.exceptions.TransactionFailureException; public class StubKernelTransaction implements KernelTransaction { private final ReadOperations readOperations; StubKernelTransaction( ReadOperations readOperations ) { this.readOperations = readOperations; } @Override public Statement acquireStatement() { return new StubStatement( readOperations ); } @Override public void success() { throw new UnsupportedOperationException( "not implemented" ); } @Override public void failure() { throw new UnsupportedOperationException( "not implemented" ); } @Override public Read dataRead() { throw new UnsupportedOperationException( "not implemented" ); } @Override public Write dataWrite() { throw new UnsupportedOperationException( "not implemented" ); } @Override public ExplicitIndexRead indexRead() { throw new UnsupportedOperationException( "not implemented" ); } @Override public ExplicitIndexWrite indexWrite() { throw new UnsupportedOperationException( "not implemented" ); } @Override public TokenRead tokenRead() { throw new UnsupportedOperationException( "not implemented" ); } @Override public TokenWrite tokenWrite() { throw new UnsupportedOperationException( "not implemented" ); } @Override public SchemaRead schemaRead() { throw new UnsupportedOperationException( "not implemented" ); } @Override public SchemaWrite schemaWrite() { throw new UnsupportedOperationException( "not implemented" ); } @Override public Locks locks() { throw new UnsupportedOperationException( "not implemented" ); } @Override public CursorFactory cursors() { throw new UnsupportedOperationException( "not implemented" ); } @Override public long closeTransaction() throws TransactionFailureException { throw new UnsupportedOperationException( "not implemented" ); } @Override public boolean isOpen() { throw new UnsupportedOperationException( "not implemented" ); } @Override public SecurityContext securityContext() { throw new UnsupportedOperationException( "not implemented" ); } @Override public Optional<Status> getReasonIfTerminated() { throw new UnsupportedOperationException( "not implemented" ); } @Override public boolean isTerminated() { return false; } @Override public void markForTermination( Status reason ) { throw new UnsupportedOperationException( "not implemented" ); } @Override public long lastTransactionTimestampWhenStarted() { throw new UnsupportedOperationException( "not implemented" ); } @Override public long lastTransactionIdWhenStarted() { throw new UnsupportedOperationException( "not implemented" ); } @Override public long startTime() { throw new UnsupportedOperationException( "not implemented" ); } @Override public long timeout() { throw new UnsupportedOperationException( "not implemented" ); } @Override public void registerCloseListener( CloseListener listener ) { throw new UnsupportedOperationException( "not implemented" ); } @Override public Type transactionType() { throw new UnsupportedOperationException( "not implemented" ); } @Override public long getTransactionId() { throw new UnsupportedOperationException( "not implemented" ); } @Override public long getCommitTime() { throw new UnsupportedOperationException( "not implemented" ); } @Override public Revertable overrideWith( SecurityContext context ) { throw new UnsupportedOperationException( "not implemented" ); } @Override public NodeCursor nodeCursor() { throw new UnsupportedOperationException( "not implemented" ); } @Override public PropertyCursor propertyCursor() { throw new UnsupportedOperationException( "not implemented" ); } }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
3348123c6f8d7c195c14b78f0449553eb9c24e4d
fa92aba7be5254a52d775d787b729f91a75e05ae
/src/main/java/site/tkgup/pojo/annotation/UserDao.java
98ae150159dbfde1cf7025e2c6b9d76c8f8fd702
[]
no_license
tkgup/springstudy
a1f0b79860281301be210a2bd611304b9ffba2a5
d463bf684c6dcf62b092fae32c8626add0b41293
refs/heads/master
2022-10-13T02:35:59.967317
2020-06-14T08:52:59
2020-06-14T08:52:59
272,037,536
0
0
null
null
null
null
UTF-8
Java
false
false
202
java
package site.tkgup.pojo.annotation; import org.springframework.stereotype.Service; @Service("usreService") public class UserDao { public void save(){ System.out.println("userDao save.."); } }
[ "tkgup@qq.com" ]
tkgup@qq.com
748d71c172b9fbf6bff3757129cb0e6c8c274c7f
dc480b9d58a983c86e38771c2baa467283989424
/src/tables/Main4.java
9e8acae01991fe0bde6a460800f3efa18993d611
[]
no_license
krzysztoffff/BasicExercises
01a4aec30c1a6252780b0fd963f4ae0aafd191db
38f8ba528ffec6612d2e4e6348b3e42f3d2bb651
refs/heads/master
2021-09-05T05:52:31.317228
2018-01-24T15:36:37
2018-01-24T15:36:37
118,116,603
0
0
null
null
null
null
UTF-8
Java
false
false
582
java
package tables; import java.util.Arrays; public class Main4 { public static void main(String[] args) { int rev [] = new int [10]; rev = createTab(); System.out.println(Arrays.toString(rev)); } static int [] createTab(){ int numbers [] = {1, 5, 8, 6, 4, 3, 5, 81, 8, 32}; int reverse [] = new int [10]; for (int i=0; i<numbers.length; i++){ reverse [i] = numbers[numbers.length -i - 1]; //int j = reverse.length - 1; //reverse[j] = numbers[i]; //j--; } return reverse; } }
[ "krzycho@pozaprawem.pl" ]
krzycho@pozaprawem.pl
069d04f4983a5954a7ac74e0b9dfa7299123a5e0
a6c24c4bbe775486b8b6991bfac226c772c64c5f
/Lekcije/lekcija_7/NasumicanKarakter.java
8713b8d4996653d898fdc8122807a7369e954b9a
[]
no_license
DeveloperJavaJunior/Exercises
511c30d240427a08e06828a8977bb8e589c68d9f
810c02740852232bea65648d173b520429ef23d9
refs/heads/master
2021-09-01T22:23:58.270517
2017-12-28T22:27:56
2017-12-28T22:27:56
115,189,829
1
0
null
null
null
null
UTF-8
Java
false
false
908
java
package lekcija_7; public class NasumicanKarakter { /** Metoda koja generise nasumican karakter u rsponu od char1 do char2 */ public static char vratiNasumicanKarakter(char char1, char char2) { return (char) (char1 + Math.random() * (char2 - char1 + 1)); } /** Metoda koja generise nasumicno malo slovo */ public static char VratiNasumicnoMaloSlovo() { return vratiNasumicanKarakter('a', 'z'); } /** Metoda koja generise nasumicno veliko slovo */ public static char VratiNasumicnoVelikoSlovo() { return vratiNasumicanKarakter('A', 'Z'); } /** Metoda koja generise nasumicni brojcani karakter */ public static char VratiNasumicniBrojcaniKarakter() { return vratiNasumicanKarakter('0', '9'); } /** Metoda koja generise nasumican karakter */ public static char VratiNasumicanKarakter() { return vratiNasumicanKarakter('\u0000', '\uFFFF'); } }
[ "noreply@github.com" ]
noreply@github.com
73dd0298fc077c7cbf2ef3a215bf1e17e08d736f
50d78013f941f382e20425ad277e28f7d1034354
/src/main/java/com/controller/kgate/BookController.java
5a4100adccbb90281505f3cfcd4a6aa9cce9a329
[]
no_license
Suhel123/CrudWebService
7c9920b6b30ccb751e5ca772cd91f0259fd9fcdb
0d732a05c5ed8d524e9f2bccb6a42b2f3d416379
refs/heads/master
2020-04-28T16:36:55.165591
2019-03-13T12:39:41
2019-03-13T12:39:41
175,414,429
0
0
null
null
null
null
UTF-8
Java
false
false
2,148
java
package com.controller.kgate; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.kagte.service.BookServcie; import com.kgate.model.Book; @RestController public class BookController { @Autowired BookServcie bookServcie; /*---Add new book---*/ @PostMapping(value="/booksave") ResponseEntity<?> save(@RequestBody Book book){ System.out.println("BookController.save()"); long id=bookServcie.save(book); return ResponseEntity.ok().body("new book save"+id); } /*---Get a book by id---*/ @GetMapping(value="/{id}") ResponseEntity<?> get(@PathVariable("id") long id){ Book book=bookServcie.get(id); System.out.println("BookController.get()"); return ResponseEntity.ok("body save data" +book); } /*---get all books---*/ @GetMapping(value="/booksave") ResponseEntity <List<Book>>list(){ System.out.println("BookController.list()"); List<Book> book=bookServcie.list(); System.out.println("BookController.list()"); return ResponseEntity.ok().body(book); } /*---Update a book by id---*/ @PutMapping("/{id}") public ResponseEntity<?> update(@PathVariable("id") long id, @RequestBody Book book) { bookServcie.update(id, book); return ResponseEntity.ok().body("Book has been updated successfully."); } /*---Detete a book by id---*/ @DeleteMapping("/book/{id}") public ResponseEntity<?> delete(@PathVariable("id") long id) { bookServcie.deleteData(id); return ResponseEntity.ok().body("Book has been deleted successfully."); } }
[ "suhailakhan86@gmail.com" ]
suhailakhan86@gmail.com
608ccf8eadd1ee99a9c078c0874858f465154866
cc2cfae43e7164768fa95f9fb997a49b1e28c92a
/src/main/java/ch/quantasy/mqtt/agents/led/abilities/WaveAdjustableBrightness.java
ad9ce2a65829e175b9225b3888a314a65dec5619
[]
no_license
knr1/ch.quantasy.tinkerforge.mqtt.agents
8e8e43e8af596ed823e9b6b77813d1b27320c277
cc4c768f2ecaf3042555f2fd469db82bad5ad32c
refs/heads/master
2021-01-19T12:36:40.869305
2018-06-24T21:18:48
2018-06-24T21:18:48
88,041,165
0
1
null
null
null
null
UTF-8
Java
false
false
8,036
java
/* * "TiMqWay" * * TiMqWay(tm): A gateway to provide an MQTT-View for the Tinkerforge(tm) world (Tinkerforge-MQTT-Gateway). * * Copyright (c) 2016 Bern University of Applied Sciences (BFH), * Research Institute for Security in the Information Society (RISIS), Wireless Communications & Secure Internet of Things (WiCom & SIoT), * Quellgasse 21, CH-2501 Biel, Switzerland * * Licensed under Dual License consisting of: * 1. GNU Affero General Public License (AGPL) v3 * and * 2. Commercial license * * * 1. This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * 2. Licensees holding valid commercial licenses for TiMqWay may use this file in * accordance with the commercial license agreement provided with the * Software or, alternatively, in accordance with the terms contained in * a written agreement between you and Bern University of Applied Sciences (BFH), * Research Institute for Security in the Information Society (RISIS), Wireless Communications & Secure Internet of Things (WiCom & SIoT), * Quellgasse 21, CH-2501 Biel, Switzerland. * * * For further information contact <e-mail: reto.koenig@bfh.ch> * * */ package ch.quantasy.mqtt.agents.led.abilities; import ch.quantasy.mqtt.gateway.client.GatewayClient; import ch.quantasy.gateway.binding.tinkerforge.ledStrip.LEDFrame; import ch.quantasy.gateway.binding.tinkerforge.ledStrip.LEDStripDeviceConfig; import ch.quantasy.gateway.binding.tinkerforge.ledStrip.LEDStripServiceContract; import ch.quantasy.gateway.binding.tinkerforge.ledStrip.LedStripIntent; import java.util.ArrayList; import java.util.List; /** * * @author reto */ public class WaveAdjustableBrightness extends AnLEDAbility { private final LEDFrame prototypeLEDFrame; private double brightness = 1; private double ambientBrightness; private double targetBrightness; private double step; private final List<LEDFrame> frames; public synchronized double getTargetBrightness() { return targetBrightness; } public synchronized double getStep() { return step; } public synchronized double getBrightness() { return brightness; } public synchronized void setTargetBrightness(double targetBrightness, double step) { if (this.targetBrightness != targetBrightness) { synchronized (frames) { frames.clear(); } this.targetBrightness = targetBrightness; } this.step = step; notifyAll(); } /** * Can be between 0 and infinity * * @param brightness * @param brightness */ public synchronized void setBrightness(double brightness) { this.brightness = brightness; this.notifyAll(); } public synchronized void changeAmbientBrightness(double ambientBrightness) { this.ambientBrightness += ambientBrightness; this.ambientBrightness = Math.min(0, Math.max(-1, this.ambientBrightness)); this.notifyAll(); super.setLEDFrame(new LEDFrame(prototypeLEDFrame, Math.max(0, Math.min(1, brightness + this.ambientBrightness)))); } public synchronized double getAmbientBrightness() { return ambientBrightness; } public WaveAdjustableBrightness(GatewayClient gatewayClient, LEDStripServiceContract ledServiceContract, LEDStripDeviceConfig config) { super(gatewayClient, ledServiceContract, config); LedStripIntent intent = new LedStripIntent(); intent.config = config; gatewayClient.getPublishingCollector().readyToPublish(ledServiceContract.INTENT, intent); frames = new ArrayList<>(); double[] sineChannels = new double[super.getConfig().getChipType().getNumberOfChannels()]; prototypeLEDFrame = super.getNewLEDFrame(); for (int i = 0; i < prototypeLEDFrame.getNumberOfLEDs(); i++) { for (int channel = 0; channel < sineChannels.length; channel++) { sineChannels[channel] = Math.sin((i / (120.0 - (30 * channel))) * Math.PI * 2); prototypeLEDFrame.setColor(channel, i, (short) (127.0 + (sineChannels[channel] * 127.0))); } } gatewayClient.subscribe(ledServiceContract.EVENT_LEDs_RENDERED, this); } public void clearFrames() { synchronized (this) { synchronized (frames) { frames.clear(); } super.setLEDFrame(super.getNewLEDFrame()); } } public void run() { LEDFrame currentLEDFrame = new LEDFrame(prototypeLEDFrame, 1.0); super.setLEDFrame(currentLEDFrame); try { short maxValue = 0; while (true) { while (frames.size() < 150 && (getBrightness() + getAmbientBrightness() > 0 || getTargetBrightness() > 0) && (getAmbientBrightness() >= -1)) { LEDFrame newLEDFrame = super.getNewLEDFrame(); synchronized (this) { double targetBrightness = getTargetBrightness(); double brightness = getBrightness(); double ambientBrightness = getAmbientBrightness(); double step = getStep(); if (brightness + ambientBrightness > targetBrightness) { brightness = Math.max(brightness - step, targetBrightness - ambientBrightness); this.setBrightness(brightness); } else if (brightness < targetBrightness) { brightness = Math.min(brightness + step, targetBrightness); this.setBrightness(brightness); } } for (int channel = 0; channel < currentLEDFrame.getNumberOfChannels(); channel++) { for (int i = 1; i < currentLEDFrame.getNumberOfLEDs(); i++) { newLEDFrame.setColor(channel, i, currentLEDFrame.getColor(channel, i - 1)); } newLEDFrame.setColor(channel, 0, currentLEDFrame.getColor(channel, getConfig().getNumberOfLEDs() - 1)); } synchronized (frames) { frames.add(new LEDFrame(newLEDFrame, Math.max(0, Math.min(1, brightness + ambientBrightness)))); } currentLEDFrame = newLEDFrame; } synchronized (frames) { super.setLEDFrames(frames); if (!frames.isEmpty()) { maxValue = frames.get(frames.size() - 1).getMaxValue(); } frames.clear(); } Thread.sleep(getConfig().getFrameDurationInMilliseconds() * 20); synchronized (this) { while (getCounter() > 100 || (getBrightness() + getAmbientBrightness() <= 0 && getTargetBrightness() <= 0) || (getAmbientBrightness() <= -1 && maxValue == 0)) { wait(getConfig().getFrameDurationInMilliseconds() * 1000); } } } } catch (InterruptedException ex) { System.out.printf("%s: Is interrupted: ", Thread.currentThread()); } } }
[ "knr1@bfh.ch" ]
knr1@bfh.ch
ded4570724a28d644974b636f96a71b9c1521a19
664dab4621e7b37a4b58acab267fbc3a23c05b93
/android/app/src/main/java/com/xtkj/paopaoxiche/model/update/DownloadManager.java
2738d446d7d5bb41b82a7144bbb552501774778a
[]
no_license
paopaoxiche/XiangTanKeJi
0f0d21a1ba88327f86fa0fde4a00d231bccb9cf7
6f4e67b96eb5927d334f104201410735e3b23f53
refs/heads/master
2021-06-25T07:56:52.750773
2019-06-13T16:25:16
2019-06-13T16:25:16
140,244,470
1
0
null
null
null
null
UTF-8
Java
false
false
4,984
java
package com.xtkj.paopaoxiche.model.update; import android.os.AsyncTask; import android.os.Environment; import android.text.TextUtils; import android.widget.Toast; import com.xtkj.paopaoxiche.application.BaseApplication; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class DownloadManager { private static final String TAG = "DownloadManager"; private static AsyncDownload asyncDownload; /** * 下载APK * * @param url APK链接 * @param callback 回调 */ public static void downloadAPK(String url, DownloadAPKCallback callback) { if (TextUtils.isEmpty(url) || callback == null) { return; } if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Toast.makeText(BaseApplication.getContext(), "没有sdcard存储空间,无法下载", Toast.LENGTH_LONG).show(); return; } File downloadFile = new File(Environment.getExternalStorageDirectory().getPath(), "paopaoxiche.apk"); if (downloadFile.exists()) { downloadFile.delete(); } asyncDownload = new AsyncDownload(url, downloadFile, callback); asyncDownload.execute(); } /** * 取消下载 */ public static void cancelDown() { if (null == asyncDownload) { return; } asyncDownload.cancelCall(); asyncDownload.cancel(true); } /** * 下载 * * @author Money */ private static class AsyncDownload extends AsyncTask<Void, Long, Boolean> { private final String url; private final DownloadAPKCallback callback; private final File file; private Call call; public AsyncDownload(String url, File downloadFile, DownloadAPKCallback callback) { this.url = url; this.file = downloadFile; this.callback = callback; } @Override protected Boolean doInBackground(Void... params) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(2, TimeUnit.SECONDS); builder.readTimeout(30, TimeUnit.SECONDS); OkHttpClient client = builder.build(); Request.Builder requestBuilder = new Request.Builder(); InputStream inputStream = null; FileOutputStream fileOutputStream = null; Response response = null; try { requestBuilder.url(url); Request request = requestBuilder.build(); call = client.newCall(request); response = call.execute(); if (response.code() == 200) { inputStream = response.body().byteStream(); byte[] buff = new byte[1024 * 2]; int len = 0; long total = response.body().contentLength(); long download = 0; publishProgress(0L, total); fileOutputStream = new FileOutputStream(file); while ((len = inputStream.read(buff)) != -1) { if (call.isCanceled()) { return false; } download += len; fileOutputStream.write(buff, 0, len); publishProgress(download, total); } } else { return false; } } catch (Exception exception) { return false; } finally { if (null != response) { response.body().close(); } if (null != call && !call.isCanceled()) { call.cancel(); } if (null != inputStream) { try { inputStream.close(); } catch (IOException exception) { } } if (null != fileOutputStream) { try { fileOutputStream.flush(); fileOutputStream.close(); } catch (IOException exception) { } } } return true; } @Override protected void onProgressUpdate(Long... values) { callback.progress(values[0], values[1]); } @Override protected void onPostExecute(Boolean isSuccess) { callback.result(isSuccess, file); } public void cancelCall() { if (null != call) { call.cancel(); } } } }
[ "liqk@fsmeeting.com" ]
liqk@fsmeeting.com
452f744662e75dd77c3d93f934e888cfe1475f8b
8782051a18d608de4c0c64229153f1636b60c528
/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/AddReturnTypeFix.java
bfec8dc90320a5804c3386e89253aa04eedef17a
[ "Apache-2.0" ]
permissive
DavyLin/intellij-community
1401c4b79fae36bbcfd6fa540496c29edfd80c83
713829cd75a25e2f8fa43439771dd3a7feb1df9d
refs/heads/master
2020-12-25T05:16:52.553204
2012-06-27T23:02:15
2012-06-27T23:03:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,157
java
/* * Copyright 2000-2012 JetBrains s.r.o. * * 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.jetbrains.plugins.groovy.intentions.style; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.annotator.GroovyAnnotator; import org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; /** * @author Max Medvedev */ public class AddReturnTypeFix implements IntentionAction { @NotNull @Override public String getText() { return GroovyIntentionsBundle.message("add.return.type"); } @NotNull @Override public String getFamilyName() { return GroovyIntentionsBundle.message("add.return.type.to.method.declaration"); } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { GrMethod method = findMethod(editor, file); return method != null && !method.isConstructor(); } @Nullable private static GrMethod findMethod(Editor editor, PsiFile file) { final int offset = editor.getCaretModel().getOffset(); final PsiElement at = file.findElementAt(offset); if (at == null) return null; if (at.getParent() instanceof GrReturnStatement) { final GrReturnStatement returnStatement = ((GrReturnStatement)at.getParent()); final PsiElement word = returnStatement.getReturnWord(); if (!word.getTextRange().contains(offset)) return null; final GroovyPsiElement returnOwner = PsiTreeUtil.getParentOfType(returnStatement, GrClosableBlock.class, GrMethod.class); if (returnOwner instanceof GrMethod) { final GrTypeElement returnTypeElement = ((GrMethod)returnOwner).getReturnTypeElementGroovy(); if (returnTypeElement == null) { return (GrMethod)returnOwner; } } return null; } final GrMethod method = PsiTreeUtil.getParentOfType(at, GrMethod.class, false, GrTypeDefinition.class, GrClosableBlock.class); if (method != null && GroovyAnnotator.getMethodHeaderTextRange(method).contains(offset)) { if (method.getReturnTypeElementGroovy() == null) { return method; } } return null; } @Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { final GrMethod method = findMethod(editor, file); if (method == null) return; PsiType type = method.getInferredReturnType(); if (type == null) type = PsiType.getJavaLangObject(PsiManager.getInstance(project), file.getResolveScope()); type = TypesUtil.unboxPrimitiveTypeWrapper(type); method.setReturnType(type); } @Override public boolean startInWriteAction() { return true; } }
[ "maxim.medvedev@jetbrains.com" ]
maxim.medvedev@jetbrains.com
b9102528fbc0ffc0e0c4961ba951baa8faf3e3c1
5464903138f4cc46b22991b99391f015753cfb58
/exercises/RedditLikeProject/app/src/main/java/com/example/android/redditlikeproject/ViewModel/Main.java
94c611f4c77669d310da914c677477b637d6a6e4
[]
no_license
OmarHP/android-training
9bf9d72dc48ce59849af5ba23da56e24517ea348
50f5fd2d2e4a82a891094efec88d97747214ef64
refs/heads/master
2021-08-15T19:10:37.895733
2017-11-18T04:26:19
2017-11-18T04:26:19
107,309,827
0
0
null
null
null
null
UTF-8
Java
false
false
3,113
java
package com.example.android.redditlikeproject.ViewModel; import android.annotation.SuppressLint; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.MutableLiveData; import com.example.android.redditlikeproject.data.entities.Comment; import com.example.android.redditlikeproject.data.entities.Post; import java.util.ArrayList; import java.util.List; import io.reactivex.Observable; import io.reactivex.ObservableSource; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; /** * Created by Aptivist-U001 on 11/14/2017. */ public class Main { public static void main(String[] args) { // MutableLiveData<String> userId = new MutableLiveData<>(); // userId.setValue("omar"); // LiveData<User> user = Transformations.switchMap(userId, id -> getUser(id) ); // Observable.range(0, 20) // .map(new Function<Integer, Integer>() { // @Override // public Integer apply(Integer integer) throws Exception { // return integer * 2; // } // }) // .flatMap(new Function<Integer, ObservableSource<?>>() { // // @Override // public ObservableSource<?> apply(Integer integer) throws Exception { // return Observable.just(integer / 2, integer % 2); // } // }) // .subscribe(System.out::println); List<Author> authors = new ArrayList<>(); List<Book> books = new ArrayList<Book>(); Observable.range(1, 10) .map(index -> new Author(index, "Name" + index)) .toList() .subscribe(list -> authors.addAll(list)); books.add(new Book(1, 1, "Some Book")); books.add(new Book(2, 1, "Some Book")); books.add(new Book(3, 2, "Some Book")); books.add(new Book(4, 2, "Some Book")); books.add(new Book(5, 2, "Some Book")); books.add(new Book(6, 3, "Some Book")); books.add(new Book(6, 4, "Some Book")); Observable.just(authors).map(new Function<List<Author>, List<Author>>() { @Override public List<Author> apply(List<Author> authors) throws Exception { for(Author author: authors){ author.extra = "extra1"; } return authors; } }).forEach(authors1 -> Observable.fromArray(authors1.toArray()).forEach(o -> System.out.println(((Author)o).extra))); } private static class Author { public Integer id; public String name; public Object extra; public Author(Integer id, String name) { this.name = name ; } } private static class Book{ public Integer id; public Integer authorId; public String name; public Book(Integer sbn, Integer authorId, String name) { this.id = sbn; this.authorId = authorId; this.name = name; } } }
[ "omar.hp90@gmail.com" ]
omar.hp90@gmail.com
db1588aac02933c47c285b7e05ee1ded47f276b5
ca0e9689023cc9998c7f24b9e0532261fd976e0e
/src/android/support/v4/app/ac.java
4d81f753e80b18ef6e66f6264149cc68bbc56b62
[]
no_license
honeyflyfish/com.tencent.mm
c7e992f51070f6ac5e9c05e9a2babd7b712cf713
ce6e605ff98164359a7073ab9a62a3f3101b8c34
refs/heads/master
2020-03-28T15:42:52.284117
2016-07-19T16:33:30
2016-07-19T16:33:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
198
java
package android.support.v4.app; final class ac implements af.b.a {} /* Location: * Qualified Name: android.support.v4.app.ac * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
[ "reverseengineeringer@hackeradmin.com" ]
reverseengineeringer@hackeradmin.com
577e33d831df93f9fe7dcff45d117340e5245ff8
b06acf556b750ac1fa5b28523db7188c05ead122
/IfcXML/src/org/tech/iai/ifc/xml/ifc/_2x3/final_/impl/IfcRotationalStiffnessMeasureTypeImpl.java
7c0b8f7a4e08ff7b3057ca26b4f9523ee281601d
[]
no_license
christianharrington/MDD
3500afbe5e1b1d1a6f680254095bb8d5f63678ba
64beecdaed65ac22b0047276c616c269913afd7f
refs/heads/master
2021-01-10T21:42:53.686724
2012-12-17T03:27:05
2012-12-17T03:27:05
6,157,471
1
0
null
null
null
null
UTF-8
Java
false
false
8,497
java
/** */ package org.tech.iai.ifc.xml.ifc._2x3.final_.impl; import java.math.BigInteger; import java.util.List; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.tech.iai.ifc.xml.ifc._2x3.final_.FinalPackage; import org.tech.iai.ifc.xml.ifc._2x3.final_.IfcRotationalStiffnessMeasureType; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ifc Rotational Stiffness Measure Type</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.tech.iai.ifc.xml.ifc._2x3.final_.impl.IfcRotationalStiffnessMeasureTypeImpl#getValue <em>Value</em>}</li> * <li>{@link org.tech.iai.ifc.xml.ifc._2x3.final_.impl.IfcRotationalStiffnessMeasureTypeImpl#getId <em>Id</em>}</li> * <li>{@link org.tech.iai.ifc.xml.ifc._2x3.final_.impl.IfcRotationalStiffnessMeasureTypeImpl#getPath <em>Path</em>}</li> * <li>{@link org.tech.iai.ifc.xml.ifc._2x3.final_.impl.IfcRotationalStiffnessMeasureTypeImpl#getPos <em>Pos</em>}</li> * </ul> * </p> * * @generated */ public class IfcRotationalStiffnessMeasureTypeImpl extends EObjectImpl implements IfcRotationalStiffnessMeasureType { /** * The default value of the '{@link #getValue() <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getValue() * @generated * @ordered */ protected static final double VALUE_EDEFAULT = 0.0; /** * The cached value of the '{@link #getValue() <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getValue() * @generated * @ordered */ protected double value = VALUE_EDEFAULT; /** * The default value of the '{@link #getId() <em>Id</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getId() * @generated * @ordered */ protected static final String ID_EDEFAULT = null; /** * The cached value of the '{@link #getId() <em>Id</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getId() * @generated * @ordered */ protected String id = ID_EDEFAULT; /** * The default value of the '{@link #getPath() <em>Path</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPath() * @generated * @ordered */ protected static final List<String> PATH_EDEFAULT = null; /** * The cached value of the '{@link #getPath() <em>Path</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPath() * @generated * @ordered */ protected List<String> path = PATH_EDEFAULT; /** * The default value of the '{@link #getPos() <em>Pos</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPos() * @generated * @ordered */ protected static final List<BigInteger> POS_EDEFAULT = null; /** * The cached value of the '{@link #getPos() <em>Pos</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPos() * @generated * @ordered */ protected List<BigInteger> pos = POS_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfcRotationalStiffnessMeasureTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return FinalPackage.eINSTANCE.getIfcRotationalStiffnessMeasureType(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setValue(double newValue) { double oldValue = value; value = newValue; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__VALUE, oldValue, value)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getId() { return id; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setId(String newId) { String oldId = id; id = newId; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__ID, oldId, id)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public List<String> getPath() { return path; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPath(List<String> newPath) { List<String> oldPath = path; path = newPath; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__PATH, oldPath, path)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public List<BigInteger> getPos() { return pos; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPos(List<BigInteger> newPos) { List<BigInteger> oldPos = pos; pos = newPos; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__POS, oldPos, pos)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__VALUE: return getValue(); case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__ID: return getId(); case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__PATH: return getPath(); case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__POS: return getPos(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__VALUE: setValue((Double)newValue); return; case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__ID: setId((String)newValue); return; case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__PATH: setPath((List<String>)newValue); return; case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__POS: setPos((List<BigInteger>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__VALUE: setValue(VALUE_EDEFAULT); return; case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__ID: setId(ID_EDEFAULT); return; case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__PATH: setPath(PATH_EDEFAULT); return; case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__POS: setPos(POS_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__VALUE: return value != VALUE_EDEFAULT; case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__ID: return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id); case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__PATH: return PATH_EDEFAULT == null ? path != null : !PATH_EDEFAULT.equals(path); case FinalPackage.IFC_ROTATIONAL_STIFFNESS_MEASURE_TYPE__POS: return POS_EDEFAULT == null ? pos != null : !POS_EDEFAULT.equals(pos); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (value: "); result.append(value); result.append(", id: "); result.append(id); result.append(", path: "); result.append(path); result.append(", pos: "); result.append(pos); result.append(')'); return result.toString(); } } //IfcRotationalStiffnessMeasureTypeImpl
[ "christian@harrington.dk" ]
christian@harrington.dk
02953ad9c638124651af96fdb6c9a2ee9f0f7d50
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/17/17_347441feecfbdd2176a5920c5fcbcaac3ec5eede/Hfs/17_347441feecfbdd2176a5920c5fcbcaac3ec5eede_Hfs_s.java
1056c1588a00138a5188897479c490bd482aaaba
[]
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
13,459
java
/* * Copyright (c) 2007-2009 Concurrent, Inc. All Rights Reserved. * * Project and contact information: http://www.cascading.org/ * * This file is part of the Cascading project. * * Cascading 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 3 of the License, or * (at your option) any later version. * * Cascading 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 Cascading. If not, see <http://www.gnu.org/licenses/>. */ package cascading.tap; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import cascading.scheme.Scheme; import cascading.scheme.SequenceFile; import cascading.tap.hadoop.TapCollector; import cascading.tap.hadoop.TapIterator; import cascading.tuple.Fields; import cascading.tuple.TupleEntryCollector; import cascading.tuple.TupleEntryIterator; import cascading.tuple.hadoop.TupleSerialization; import cascading.util.Util; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobConf; import org.apache.log4j.Logger; /** * Class Hfs is the base class for all Hadoop file system access. Use {@link Dfs}, {@link Lfs}, or {@link S3fs} * for resources specific to Hadoop Distributed file system, the Local file system, or Amazon S3, respectively. * <p/> * Use the Hfs class if the 'kind' of resource is unknown at design time. To use, prefix a scheme to the 'stringPath'. Where * <code>hdfs://...</code> will denonte Dfs, <code>file://...</code> will denote Lfs, and * <code>s3://aws_id:aws_secret@bucket/...</code> will denote S3fs. * <p/> * Call {@link #setTemporaryDirectory(java.util.Map, String)} to use a different temporary file directory path * other than the current Hadoop default path. */ public class Hfs extends Tap { /** Field LOG */ private static final Logger LOG = Logger.getLogger( Hfs.class ); /** Field serialVersionUID */ private static final long serialVersionUID = 1L; /** Field TEMPORARY_DIRECTORY */ private static final String TEMPORARY_DIRECTORY = "cascading.tmp.dir"; /** Field stringPath */ String stringPath; /** Field uriScheme */ transient URI uriScheme; /** Field path */ transient Path path; /** Field paths */ private transient FileStatus[] statuses; /** * Method setTemporaryDirectory sets the temporary directory on the given properties object. * * @param properties of type Map<Object,Object> * @param tempDir of type String */ public static void setTemporaryDirectory( Map<Object, Object> properties, String tempDir ) { properties.put( TEMPORARY_DIRECTORY, tempDir ); } /** * Methdo getTemporaryDirectory returns the configured temporary directory from the given properties object. * * @param properties of type Map<Object,Object> * @return a String or null if not set */ public static String getTemporaryDirectory( Map<Object, Object> properties ) { return (String) properties.get( TEMPORARY_DIRECTORY ); } protected Hfs() { } protected Hfs( Scheme scheme ) { super( scheme ); } /** * Constructor Hfs creates a new Hfs instance. * * @param fields of type Fields * @param stringPath of type String */ public Hfs( Fields fields, String stringPath ) { super( new SequenceFile( fields ) ); setStringPath( stringPath ); } /** * Constructor Hfs creates a new Hfs instance. * * @param fields of type Fields * @param stringPath of type String * @param replace of type boolean */ public Hfs( Fields fields, String stringPath, boolean replace ) { super( new SequenceFile( fields ), replace ? SinkMode.REPLACE : SinkMode.KEEP ); setStringPath( stringPath ); } /** * Constructor Hfs creates a new Hfs instance. * * @param fields of type Fields * @param stringPath of type String * @param sinkMode of type SinkMode */ public Hfs( Fields fields, String stringPath, SinkMode sinkMode ) { super( new SequenceFile( fields ), sinkMode ); setStringPath( stringPath ); if( sinkMode == SinkMode.APPEND ) throw new IllegalArgumentException( "appends are not supported" ); } /** * Constructor Hfs creates a new Hfs instance. * * @param scheme of type Scheme * @param stringPath of type String */ public Hfs( Scheme scheme, String stringPath ) { super( scheme ); setStringPath( stringPath ); } /** * Constructor Hfs creates a new Hfs instance. * * @param scheme of type Scheme * @param stringPath of type String * @param replace of type boolean */ public Hfs( Scheme scheme, String stringPath, boolean replace ) { super( scheme, replace ? SinkMode.REPLACE : SinkMode.KEEP ); setStringPath( stringPath ); } /** * Constructor Hfs creates a new Hfs instance. * * @param scheme of type Scheme * @param stringPath of type String * @param sinkMode of type SinkMode */ public Hfs( Scheme scheme, String stringPath, SinkMode sinkMode ) { super( scheme, sinkMode ); setStringPath( stringPath ); } protected void setStringPath( String stringPath ) { this.stringPath = Util.normalizeUrl( stringPath ); } protected void setUriScheme( URI uriScheme ) { this.uriScheme = uriScheme; } protected URI getURIScheme( JobConf jobConf ) throws IOException { if( uriScheme != null ) return uriScheme; uriScheme = makeURIScheme( jobConf ); return uriScheme; } protected URI makeURIScheme( JobConf jobConf ) throws IOException { try { URI uriScheme = null; if( LOG.isDebugEnabled() ) LOG.debug( "handling path: " + stringPath ); URI uri = new URI( stringPath ); String schemeString = uri.getScheme(); String authority = uri.getAuthority(); if( LOG.isDebugEnabled() ) { LOG.debug( "found scheme: " + schemeString ); LOG.debug( "found authority: " + authority ); } if( schemeString != null && authority != null ) uriScheme = new URI( schemeString + "://" + uri.getAuthority() ); else if( schemeString != null ) uriScheme = new URI( schemeString + ":///" ); else uriScheme = getDefaultFileSystem( jobConf ).getUri(); if( LOG.isDebugEnabled() ) LOG.debug( "using uri scheme: " + uriScheme ); return uriScheme; } catch( URISyntaxException exception ) { throw new TapException( "could not determine scheme from path: " + getPath(), exception ); } } @Override public boolean isWriteDirect() { return super.isWriteDirect() || stringPath != null && stringPath.matches( "(^https?://.*$)|(^s3tp://.*$)" ); } protected FileSystem getDefaultFileSystem( JobConf jobConf ) throws IOException { return FileSystem.get( jobConf ); } protected FileSystem getFileSystem( JobConf jobConf ) throws IOException { return FileSystem.get( getURIScheme( jobConf ), jobConf ); } /** @see Tap#getPath() */ @Override public Path getPath() { if( path != null ) return path; if( stringPath == null ) throw new IllegalStateException( "path not initialized" ); path = new Path( stringPath ); return path; } @Override public Path getQualifiedPath( JobConf conf ) throws IOException { return getPath().makeQualified( getFileSystem( conf ) ); } @Override public void sourceInit( JobConf conf ) throws IOException { Path qualifiedPath = getQualifiedPath( conf ); for( Path exitingPath : FileInputFormat.getInputPaths( conf ) ) { if( exitingPath.equals( qualifiedPath ) ) throw new TapException( "may not add duplicate paths, found: " + exitingPath ); } FileInputFormat.addInputPath( conf, qualifiedPath ); super.sourceInit( conf ); makeLocal( conf, qualifiedPath, "forcing job to local mode, via source: " ); TupleSerialization.setSerializations( conf ); // allows Hfs to be used independent of Flow } @Override public void sinkInit( JobConf conf ) throws IOException { // do not delete if initialized from within a task if( isReplace() && conf.get( "mapred.task.partition" ) == null ) deletePath( conf ); Path qualifiedPath = getQualifiedPath( conf ); FileOutputFormat.setOutputPath( conf, qualifiedPath ); super.sinkInit( conf ); makeLocal( conf, qualifiedPath, "forcing job to local mode, via sink: " ); TupleSerialization.setSerializations( conf ); // allows Hfs to be used independent of Flow } private void makeLocal( JobConf conf, Path qualifiedPath, String infoMessage ) { if( !conf.get( "mapred.job.tracker", "" ).equalsIgnoreCase( "local" ) && qualifiedPath.toUri().getScheme().equalsIgnoreCase( "file" ) ) { if( LOG.isInfoEnabled() ) LOG.info( infoMessage + toString() ); conf.set( "mapred.job.tracker", "local" ); // force job to run locally } } @Override public boolean makeDirs( JobConf conf ) throws IOException { if( LOG.isDebugEnabled() ) LOG.debug( "making dirs: " + getQualifiedPath( conf ) ); return getFileSystem( conf ).mkdirs( getPath() ); } @Override public boolean deletePath( JobConf conf ) throws IOException { if( LOG.isDebugEnabled() ) LOG.debug( "deleting: " + getQualifiedPath( conf ) ); // do not delete the root directory if( getQualifiedPath( conf ).depth() == 0 ) return true; return getFileSystem( conf ).delete( getPath(), true ); } @Override public boolean pathExists( JobConf conf ) throws IOException { return getFileSystem( conf ).exists( getPath() ); } @Override public long getPathModified( JobConf conf ) throws IOException { FileStatus fileStatus = getFileSystem( conf ).getFileStatus( getPath() ); if( !fileStatus.isDir() ) return fileStatus.getModificationTime(); makeStatuses( conf ); // statuses is empty, return 0 if( statuses == null || statuses.length == 0 ) return 0; long date = 0; // filter out directories as we don't recurse into sub dirs for( FileStatus status : statuses ) { if( !status.isDir() ) date = Math.max( date, status.getModificationTime() ); } return date; } protected Path getTempPath( JobConf conf ) { String tempDir = conf.get( TEMPORARY_DIRECTORY ); if( tempDir == null ) tempDir = conf.get( "hadoop.tmp.dir" ); return new Path( tempDir ); } protected String makeTemporaryPathDir( String name ) { return name.replaceAll( "[\\W\\s]+", "_" ) + Integer.toString( (int) ( 10000000 * Math.random() ) ); } /** * Given a file-system object, it makes an array of paths * * @param conf of type JobConf * @throws IOException on failure */ private void makeStatuses( JobConf conf ) throws IOException { if( statuses != null ) return; statuses = getFileSystem( conf ).listStatus( getPath() ); } /** @see Object#toString() */ @Override public String toString() { if( stringPath != null ) return getClass().getSimpleName() + "[\"" + getScheme() + "\"]" + "[\"" + Util.sanitizeUrl( stringPath ) + "\"]"; // sanitize else return getClass().getSimpleName() + "[\"" + getScheme() + "\"]" + "[not initialized]"; } /** @see Tap#equals(Object) */ @Override public boolean equals( Object object ) { if( this == object ) return true; if( object == null || getClass() != object.getClass() ) return false; if( !super.equals( object ) ) return false; Hfs hfs = (Hfs) object; if( stringPath != null ? !stringPath.equals( hfs.stringPath ) : hfs.stringPath != null ) return false; return true; } /** @see Tap#hashCode() */ @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + ( stringPath != null ? stringPath.hashCode() : 0 ); return result; } public TupleEntryIterator openForRead( JobConf conf ) throws IOException { return new TupleEntryIterator( getSourceFields(), new TapIterator( this, conf ) ); } public TupleEntryCollector openForWrite( JobConf conf ) throws IOException { return new TapCollector( this, conf ); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
6323129099881e0f209a930b9486c6570873c8f5
fadafd211456ca35f1bdbb51de65e65b51406bf5
/api/src/main/java/com/skronawi/tokenservice/jwt/api/UserInfo.java
bbda34d1bc1836169223e567e7cabc8b5be33b95
[]
no_license
sikron/jwt-token-service
8bebe760fe2f9572f224845e42f42070c0255c2f
dd0719dd8ee422e6e846d3bd18933c2431b01cdb
refs/heads/master
2021-01-10T03:52:03.988944
2016-03-29T14:36:39
2016-03-29T14:36:39
54,982,568
0
0
null
null
null
null
UTF-8
Java
false
false
235
java
package com.skronawi.tokenservice.jwt.api; import java.util.List; public interface UserInfo { String getUsername(); void setUsername(String username); List<String> getRoles(); void setRoles(List<String> roles); }
[ "skronawi@gmx.net" ]
skronawi@gmx.net
1cfd1a2cbe789bb0e76d1d20f1c98aa7efe5819d
c9899ad565d342b3a8af0e3e03a39fad2c29eb43
/app/src/androidTest/java/com/m3libea/flickster/ExampleInstrumentedTest.java
ab256a5501775852fa0ce9a578ef5fef25002138
[ "Apache-2.0" ]
permissive
m3libea/flickster
6f7152efac0b2aadc0b146d74a6afa2b9786c80f
662813f137748c09cecea7b74fa5935b1ec01737
refs/heads/master
2021-01-18T07:24:45.202048
2017-09-17T20:24:54
2017-09-17T20:24:54
84,288,039
0
0
null
2017-09-15T21:40:20
2017-03-08T06:45:33
Java
UTF-8
Java
false
false
746
java
package com.m3libea.flickster; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.m3libea.flickster", appContext.getPackageName()); } }
[ "rociorommor@gmail.com" ]
rociorommor@gmail.com
8868cc3554ce4504c48b1029db37841466e3a96d
05f05843f73112de4affa046958073d4c76dffbd
/src/sample/VueNbCoupIHMFX.java
e3c03c5f1f7942ab7f3c69a5ee4325d6bcad9933
[]
no_license
pavielraphael/sukoban
e84880292d33847f0a5f71cdc9ddba00ca391e3c
aad52a5ee8ddc26fbe3c8bc80e413e95d64a8d77
refs/heads/master
2020-04-09T16:45:12.169227
2018-12-06T17:58:09
2018-12-06T17:58:09
160,462,224
0
0
null
2018-12-05T04:47:06
2018-12-05T04:47:06
null
UTF-8
Java
false
false
394
java
package sample; import javafx.scene.control.Label; public class VueNbCoupIHMFX { Controleur controleur; Label label = new Label("0"); CommandeInt commande; public VueNbCoupIHMFX(Controleur controleur) { this.controleur=controleur; commande = controleur.commandeNbCoup(); } public void dessine() { label.setText(commande.exec()+""); } }
[ "kamelmalk96@gmail.com" ]
kamelmalk96@gmail.com
b37391db5b899130013583be8ae53500cfab9cb8
a337ca5deac6b9361a430db428b713fbed35e97f
/src/interfaceImplementations/DefaultDealer.java
3d94d2630cb9960fa72c79cd2ce2e453bb3f3d5b
[]
no_license
ppoppe/DealOrNoDeal
26a70fed94441305d1a98f14dcb5bc7c14dafe5e
4daf95a2c835925f4d79dd53350ac4986774b8af
refs/heads/master
2021-01-01T15:55:24.639959
2014-03-19T02:26:35
2014-03-19T02:26:35
17,329,185
1
0
null
null
null
null
UTF-8
Java
false
false
524
java
package interfaceImplementations; import gameEngine.Dealer; import gameEngine.Stage; public class DefaultDealer implements Dealer { public int makeOffer(Stage stage){ // for now, just offer 5% less than the average value double offer = stage.scoreboard.averageValue(); offer = offer*.95; // Do some quantizing so the numbers look nice double rounder; if (offer<1000) rounder=100; else if (offer<10000) rounder=1000; else rounder=10000; return (int) (Math.round(offer/rounder)*rounder); } }
[ "ppoppe.2005@gmail.com" ]
ppoppe.2005@gmail.com
42e3ae34c6ca977bc0def503bd438a715f6c9061
6785e9f6f0aa227e62e37b8b3b49bf3bc30d45c6
/OpenHarmonyAPP开发学习源码体系/5、常用布局源码/jltfdysjbj_电影应用手机布局/entry/src/test/java/com/example/phonemeiju/ExampleTest.java
a03fc67a21a3c62907d9fa83efbc99919764b1c4
[ "Apache-2.0" ]
permissive
gsshch/OpenHarmony
18a612005f3f1a3427ab6f5caa2d1cbfa5ce77fa
fe6f2676806a57257a58e31c52dc3c8cbc692fe9
refs/heads/master
2023-04-26T01:19:05.396475
2021-06-01T05:57:39
2021-06-01T05:57:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
130
java
package com.example.phonemeiju; import org.junit.Test; public class ExampleTest { @Test public void onStart() { } }
[ "657943010@qq.com" ]
657943010@qq.com
b8fdc0dcb0d8cd6bc0af380d7772c28706446dae
4c5a33c3ad23c3beb029a3fac10f840b49f38124
/src/main/java/com/gs/gss/codegolf/tester/SolutionFactory.java
1892efd5b46009faebaeb01e01b97742ed053d3a
[]
no_license
amcgc/tester
368d5de101dc0d96c1a98819edc96a5c4f2fb077
e678b1fc0b82ce55ecc91cf0b934a30906efeea2
refs/heads/master
2016-09-09T14:10:48.399436
2014-07-13T20:16:34
2014-07-13T20:16:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
447
java
package com.gs.gss.codegolf.tester; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import com.gs.gss.codegolf.solution.Solution; import com.gs.gss.codegolf.solution.mcgale; public class SolutionFactory { private SolutionFactory(){}; public static Set<Solution> getSolutions() { Set<Solution> solutions = new HashSet<Solution>(); solutions.add(new mcgale()); return solutions; } }
[ "alex.cheers@gmail.com" ]
alex.cheers@gmail.com
965c979ad7b507c1dfd8cb7396e19bf9cf304165
55b604d0500698e1d1c7d45499bea598e9486e57
/Array_String/Remove/Remove_nth_Node_from_end_of_List.java
ef159f444c35787ff1bcd3ddb9bede33677062b0
[ "MIT" ]
permissive
Yujia-Xiao/Leetcode
f4daef4146cf9674d5fb27249fc3f9693986591a
45e15f911d6beada99b712253cbec51881dbb1f4
refs/heads/master
2020-04-06T13:11:51.673328
2018-09-11T06:19:46
2018-09-11T06:19:46
47,289,017
9
3
null
null
null
null
UTF-8
Java
false
false
1,728
java
/* 19. Remove Nth Node From End of List QuestionEditorial Solution My Submissions Total Accepted: 117624 Total Submissions: 388831 Difficulty: Easy Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Try to do this in one pass. Hide Tags Linked List Two Pointers */ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode fast = head; ListNode slow = head; ListNode pre = null; for(int i=0;i<n;i++){ if(head!=null)fast=fast.next; else return head; } while(fast!=null){ fast=fast.next; pre=slow; slow=slow.next; } if(pre!=null)pre.next=slow.next; else head=slow.next; return head; } } public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0); dummy.next=head; ListNode fast = head; ListNode slow = head; ListNode pre = dummy; for(int i=0;i<n;i++){ if(fast!=null)fast=fast.next; else return dummy.next; } while(fast!=null){ fast=fast.next; pre=slow; slow=slow.next; } pre.next=slow.next; return dummy.next; } }
[ "xiao_samantha@yahoo.com" ]
xiao_samantha@yahoo.com
9362376f9ce9ddc349a2e7d41b393ff1458d31e3
55b5acbead42480af8fd606b1f4cd3490ec4e278
/src/py/com/gasto/controlador/InformeControlador.java
5aa1db66a7077e4beba6cf924000f65c14d4c86e
[]
no_license
Hermenegil2/GASTO_DIARIO_001
8d50c685a39f172836653cbfdc6e0741df0c4569
a388fe864b84c6dfbcc79cd2e9e2777c92455e3f
refs/heads/master
2021-01-11T15:28:54.440192
2017-01-29T16:26:54
2017-01-29T16:26:54
80,356,402
0
0
null
null
null
null
UTF-8
Java
false
false
2,858
java
package py.com.gasto.controlador; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.table.DefaultTableModel; import py.com.gasto.dao.InformaDAO; import py.com.gasto.menu.InformeMenu; import py.com.gasto.model.Informe; public class InformeControlador implements ActionListener{ private InformeMenu ventana; public InformeControlador (InformeMenu v){ this.ventana=v; ventana.getBtnProceder().addActionListener(this); ventana.getBtnMayorCompra().addActionListener(this); } private void listarInforme(){ if (ventana.getLimite().getText().isEmpty()) { DefaultTableModel modelo=(DefaultTableModel) ventana.getTable().getModel(); ArrayList<Informe>info=InformaDAO.traerInformeTodo(); Object[] fila=new Object[modelo.getColumnCount()]; for (int i = 0; i < info.size(); i++) { fila[0]=info.get(i).getCodigo(); fila[1]=info.get(i).getDescripcion(); fila[2]=info.get(i).getCantidad(); fila[3]=info.get(i).getPrecio(); fila[4]=info.get(i).getTipo(); fila[5]=info.get(i).getFecha(); modelo.addRow(fila); } } else { ArrayList<Informe> info=new ArrayList<Informe>(); Integer limi=Integer.parseInt(ventana.getLimite().getText()); //String ord=String.valueOf(ventana.getOrden().getSelectedIndex()); info=InformaDAO.traerInforme(limi); if (info !=null) { DefaultTableModel modelo=(DefaultTableModel) ventana.getTable().getModel(); Object[] fila=new Object[modelo.getColumnCount()]; for (int i = 0; i < info.size(); i++) { fila[0]=info.get(i).getCodigo(); fila[1]=info.get(i).getDescripcion(); fila[2]=info.get(i).getCantidad(); fila[3]=info.get(i).getPrecio(); fila[4]=info.get(i).getTipo(); fila[5]=info.get(i).getFecha(); modelo.addRow(fila); } } } } private void listarMayorCompra(){ DefaultTableModel modelo=(DefaultTableModel) ventana.getTable().getModel(); ArrayList<Informe>lista=InformaDAO.MayorCompra(); Object[] fila=new Object[modelo.getColumnCount()]; for (int i = 0; i < lista.size(); i++) { fila[1]=lista.get(i).getDescripcion(); fila[2]=lista.get(i).getCantidad(); fila[3]=lista.get(i).getPrecio(); fila[4]=lista.get(i).getTipo(); modelo.addRow(fila); } } public void limpiarTabla() { DefaultTableModel modelo=(DefaultTableModel) ventana.getTable().getModel(); for (int i = 0; i < ventana.getTable().getRowCount(); i++) { modelo.removeRow(i); i-=1; } } @Override public void actionPerformed(ActionEvent e) { if (e.getSource().equals(ventana.getBtnProceder())) { limpiarTabla(); listarInforme(); } if (e.getSource().equals(ventana.getBtnMayorCompra())) { limpiarTabla(); listarMayorCompra(); }} }
[ "Hermenegildo851276@outlook.com" ]
Hermenegildo851276@outlook.com
df71d9c18dd689d4a89ff8f99a36300e37d97143
38df4005cf0221282efde2440f56017c257906de
/src/main/java/com/csgb/etatcivil/domain/Personne.java
0c6d68a319f8e6bee6892631119f23964a262495
[]
no_license
isenbProjectTeam/ETAT_CIVIL
faae90de54d1ecc557ae47b0cf1d0c46390ec5f7
7c054570be3a38ac5cd2f0b41f110cbcf2ffcb37
refs/heads/master
2021-01-19T15:10:42.428723
2017-04-14T20:42:01
2017-04-14T20:42:01
88,094,577
0
0
null
null
null
null
UTF-8
Java
false
false
4,700
java
package com.csgb.etatcivil.domain; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.springframework.data.elasticsearch.annotations.Document; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.time.ZonedDateTime; import java.util.Objects; import com.csgb.etatcivil.domain.enumeration.Genre; /** * A Personne. */ @Entity @Table(name = "personne") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName = "personne") public class Personne implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Column(name = "nom", nullable = false) private String nom; @NotNull @Column(name = "prenom", nullable = false) private String prenom; @NotNull @Enumerated(EnumType.STRING) @Column(name = "genre", nullable = false) private Genre genre; @Column(name = "fonction") private String fonction; @NotNull @Column(name = "date_naissance", nullable = false) private ZonedDateTime dateNaissance; @ManyToOne(optional = false) @NotNull private Adresse adresse; @ManyToOne(optional = false) @NotNull private Ville lieuNaissance; @ManyToOne private Personne pere; @ManyToOne private Personne mere; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNom() { return nom; } public Personne nom(String nom) { this.nom = nom; return this; } public void setNom(String nom) { this.nom = nom; } public String getPrenom() { return prenom; } public Personne prenom(String prenom) { this.prenom = prenom; return this; } public void setPrenom(String prenom) { this.prenom = prenom; } public Genre getGenre() { return genre; } public Personne genre(Genre genre) { this.genre = genre; return this; } public void setGenre(Genre genre) { this.genre = genre; } public String getFonction() { return fonction; } public Personne fonction(String fonction) { this.fonction = fonction; return this; } public void setFonction(String fonction) { this.fonction = fonction; } public ZonedDateTime getDateNaissance() { return dateNaissance; } public Personne dateNaissance(ZonedDateTime dateNaissance) { this.dateNaissance = dateNaissance; return this; } public void setDateNaissance(ZonedDateTime dateNaissance) { this.dateNaissance = dateNaissance; } public Adresse getAdresse() { return adresse; } public Personne adresse(Adresse adresse) { this.adresse = adresse; return this; } public void setAdresse(Adresse adresse) { this.adresse = adresse; } public Ville getLieuNaissance() { return lieuNaissance; } public Personne lieuNaissance(Ville ville) { this.lieuNaissance = ville; return this; } public void setLieuNaissance(Ville ville) { this.lieuNaissance = ville; } public Personne getPere() { return pere; } public Personne pere(Personne personne) { this.pere = personne; return this; } public void setPere(Personne personne) { this.pere = personne; } public Personne getMere() { return mere; } public Personne mere(Personne personne) { this.mere = personne; return this; } public void setMere(Personne personne) { this.mere = personne; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Personne personne = (Personne) o; if (personne.id == null || id == null) { return false; } return Objects.equals(id, personne.id); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "Personne{" + "id=" + id + ", nom='" + nom + "'" + ", prenom='" + prenom + "'" + ", genre='" + genre + "'" + ", fonction='" + fonction + "'" + ", dateNaissance='" + dateNaissance + "'" + '}'; } }
[ "mr.sowoumar@gmail.com" ]
mr.sowoumar@gmail.com
c6ca3d7e10b1b3223f7095ab59ea26c0dfda75ca
9254e7279570ac8ef687c416a79bb472146e9b35
/sofa-20190815/src/main/java/com/aliyun/sofa20190815/models/DeleteLinkeLinklogKnowledgeRequest.java
3056cbe94101ec744232d361a95f6d59eba66ea5
[ "Apache-2.0" ]
permissive
lquterqtd/alibabacloud-java-sdk
3eaa17276dd28004dae6f87e763e13eb90c30032
3e5dca8c36398469e10cdaaa34c314ae0bb640b4
refs/heads/master
2023-08-12T13:56:26.379027
2021-10-19T07:22:15
2021-10-19T07:22:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
657
java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.sofa20190815.models; import com.aliyun.tea.*; public class DeleteLinkeLinklogKnowledgeRequest extends TeaModel { @NameInMap("Id") public String id; public static DeleteLinkeLinklogKnowledgeRequest build(java.util.Map<String, ?> map) throws Exception { DeleteLinkeLinklogKnowledgeRequest self = new DeleteLinkeLinklogKnowledgeRequest(); return TeaModel.build(map, self); } public DeleteLinkeLinklogKnowledgeRequest setId(String id) { this.id = id; return this; } public String getId() { return this.id; } }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
a88e73e50fd317800e54a9fddd6d5b74c2e2c9c4
d32ba46b8b94fce375240a2e57c9f9bda1c53c54
/NetworkAnalysis/app/src/main/java/ca/unb/mobiledev/networkanalysis/TestViewModel.java
8a252bba495e769afe70e7381e51cda267149658
[]
no_license
Lyon-CHEN/NetworkAnalysis
f3fd73c5279e15a5f62d8b16f2c9f5d54250aa05
40ba02a4ef6bf86bd9daab9e0fd6da1c4e5ff891
refs/heads/main
2023-04-15T11:13:51.363903
2021-04-15T01:49:57
2021-04-15T01:49:57
338,174,809
2
2
null
2021-04-11T19:21:15
2021-02-11T22:58:15
Java
UTF-8
Java
false
false
9,039
java
package ca.unb.mobiledev.networkanalysis; import android.app.Application; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.view.View; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import ca.unb.mobiledev.networkanalysis.network.Constant; import fr.bmartel.speedtest.SpeedTestReport; import fr.bmartel.speedtest.SpeedTestSocket; import fr.bmartel.speedtest.inter.ISpeedTestListener; import fr.bmartel.speedtest.model.SpeedTestError; public class TestViewModel extends AndroidViewModel { private static final String TAG = "TestViewModel"; public static final int DOWNLOAD_MESSAGE_PROGRESS_CODE = 100001; public static final int DOWNLOAD_MESSAGE_CODE = 100004; public static final int DOWNLOAD_MESSAGE_FAIL_CODE = 100002; public static final int DOWNLOAD_MESSAGE_COMPLETE_CODE = 100003; public static final int UPLOAD_MESSAGE_PROGRESS_CODE = 200001; public static final int UPLOAD_MESSAGE_CODE = 200004; public static final int UPLOAD_MESSAGE_FAIL_CODE = 200002; public static final int UPLOAD_MESSAGE_COMPLETE_CODE = 200003; private MutableLiveData<String> mDownloadSpeed; private MutableLiveData<String> mUploadSpeed; private MutableLiveData<Integer> mDownloadProgress; private MutableLiveData<Integer> mUploadProgress; static Handler handler; private Semaphore mLock ; private static int mTestStep=0; private DecimalFormat mDecimalFormat2; public LiveData<String> getDownloadSpeed() { return mDownloadSpeed; } public LiveData<Integer> getDownloadProgress() { return mDownloadProgress; } public LiveData<String> getUploadSpeed() { return mUploadSpeed; } public LiveData<Integer> getUploadProgress() { return mUploadProgress; } public TestViewModel(@NonNull Application application) { super(application); mDownloadSpeed = new MutableLiveData<String>(); mDownloadProgress = new MutableLiveData<Integer>(); mUploadSpeed = new MutableLiveData<String>(); mUploadProgress = new MutableLiveData<Integer>(); mLock = new Semaphore(1); mDecimalFormat2 =new DecimalFormat("#.00"); handler = new Handler(Looper.getMainLooper(), new Handler.Callback() { public boolean handleMessage(Message msg) { switch (msg.what){ case DOWNLOAD_MESSAGE_PROGRESS_CODE: if(msg.obj!=null) mDownloadProgress.postValue((Integer) msg.obj); break; case DOWNLOAD_MESSAGE_CODE: if(msg.obj!=null) mDownloadSpeed.postValue("Rate in KB /s : " + mDecimalFormat2.format(msg.obj)); break; case DOWNLOAD_MESSAGE_COMPLETE_CODE: mDownloadProgress.postValue(Constant.PROGRESS_MAX); mDownloadSpeed.postValue("Download Average Rate in KB /s : " + mDecimalFormat2.format(msg.obj)); break; case UPLOAD_MESSAGE_PROGRESS_CODE: if(msg.obj!=null) mUploadProgress.postValue((Integer) msg.obj); break; case UPLOAD_MESSAGE_CODE: if(msg.obj!=null) mUploadSpeed.postValue("Rate in KB /s : " + mDecimalFormat2.format(msg.obj)); break; case UPLOAD_MESSAGE_COMPLETE_CODE: mUploadProgress.postValue(Constant.PROGRESS_MAX); mUploadSpeed.postValue("Upload Average Rate in KB /s : " + mDecimalFormat2.format(msg.obj)); break; } return false; }; }); new DownloadTestTask().execute(); new UploadTestTask().execute(); } public void testRun(){ new DownloadTestTask().execute(); new UploadTestTask().execute(); } class DownloadTestTask extends AsyncTask<Void, Void, String> { private final static String testUrl = "http://ipv4.ikoula.testdebit.info/10M.iso"; @Override protected String doInBackground(Void... params) { try { mLock.acquire(); } catch (InterruptedException e){ } SpeedTestSocket speedTestSocket = new SpeedTestSocket(); // add a listener to wait for speedtest completion and progress speedTestSocket.addSpeedTestListener(new ISpeedTestListener() { @Override public void onCompletion(SpeedTestReport report) { // called when download/upload is finished Message message = Message.obtain(); message.obj = report.getTransferRateOctet().divide( new BigDecimal(1000)); message.what = DOWNLOAD_MESSAGE_COMPLETE_CODE; handler .sendMessage(message); mLock.release(); //Log.v("speedtest", "[COMPLETED] rate in bit/s : " + report.getTransferRateBit()); } @Override public void onError(SpeedTestError speedTestError, String errorMessage) { // called when a download/upload error occur } @Override public void onProgress(float percent, SpeedTestReport report) { // called to notify download/upload progress Message message = Message.obtain(); message.obj = (int)percent; message.what = DOWNLOAD_MESSAGE_PROGRESS_CODE; handler .sendMessage(message); Message message2 = Message.obtain(); message2.obj = report.getTransferRateOctet().divide( new BigDecimal(1000)); message2.what = DOWNLOAD_MESSAGE_CODE; handler .sendMessage(message2); //Log.v("speedtest", "[PROGRESS] progress : " + (int)percent + "%"); //Log.v("speedtest", "[PROGRESS] rate in octet/s : " + report.getTransferRateOctet()); //Log.v("speedtest", "[PROGRESS] rate in bit/s : " + report.getTransferRateBit()); } }); speedTestSocket.startDownload(testUrl); return null; } } class UploadTestTask extends AsyncTask<Void, Void, String> { private final static String testUrl = "http://ipv4.ikoula.testdebit.info/"; @Override protected String doInBackground(Void... params) { try { mLock.acquire(); } catch (InterruptedException e){ } SpeedTestSocket speedTestSocket = new SpeedTestSocket(); // add a listener to wait for speedtest completion and progress speedTestSocket.addSpeedTestListener(new ISpeedTestListener() { @Override public void onCompletion(SpeedTestReport report) { // called when download/upload is finished Message message = Message.obtain(); message.obj = report.getTransferRateOctet().divide( new BigDecimal(1000)); message.what = UPLOAD_MESSAGE_COMPLETE_CODE; handler .sendMessage(message); mLock.release(); } @Override public void onError(SpeedTestError speedTestError, String errorMessage) { // called when a download/upload error occur } @Override public void onProgress(float percent, SpeedTestReport report) { // called to notify download/upload progress Message message = Message.obtain(); message.obj = (int)percent; message.what = UPLOAD_MESSAGE_PROGRESS_CODE; handler .sendMessage(message); Message message2 = Message.obtain(); message2.obj = report.getTransferRateOctet().divide( new BigDecimal(1000)); message2.what = UPLOAD_MESSAGE_CODE; handler .sendMessage(message2); } }); speedTestSocket.startUpload(testUrl, 10000000); return null; } } }
[ "sosokey@gmail.com" ]
sosokey@gmail.com
94935e7393b36b9f2dac5d2637e094e8cd4f80ab
11ca8f1f89b79c83d16549e1e84cb839d4936ad8
/examples/src/main/java/net/sourceforge/stripes/examples/quickstart/DivideCalculatorRestActionBean.java
ffec040f234bd51775d4338610911a92b0e1bf41
[ "Apache-2.0" ]
permissive
costalfy/stripes
7d68c1bab40ba528146f60bd4d3f70fcade2348b
13257fed2565c8bd230a8ac9192d7556a4490bf3
refs/heads/master
2023-04-27T04:56:16.360798
2022-11-29T13:43:41
2022-11-29T13:43:41
236,000,649
0
1
Apache-2.0
2023-04-14T23:34:12
2020-01-24T12:40:51
Java
UTF-8
Java
false
false
1,847
java
package net.sourceforge.stripes.examples.quickstart; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.examples.bugzooky.ext.Public; import net.sourceforge.stripes.validation.Validate; import net.sourceforge.stripes.validation.ValidationErrors; import net.sourceforge.stripes.validation.ValidationMethod; /** * A very simple calculator action. * @author Tim Fennell */ @Public @RestActionBean @UrlBinding( "/calculate/divide" ) public class DivideCalculatorRestActionBean implements ActionBean { private ActionBeanContext context; @Validate(required=true) private double numberOne; @Validate(required=true) private double numberTwo; private String errorMessage; public ActionBeanContext getContext() { return context; } public void setContext(ActionBeanContext context) { this.context = context; } /** An event handler method that divides number one by number two. */ public Resolution post() { double result = numberOne / numberTwo; return new JsonResolution( Double.toString(result) ); } /** * An example of a custom validation that checks that division operations * are not dividing by zero. */ @ValidationMethod(on="post") public void avoidDivideByZero(ValidationErrors errors) { if (this.numberTwo == 0) { //errors.add("numberTwo", new JsonError("Dividing by zero is not allowed.")); errorMessage = "Dividing by zero is not allowed."; } } public void setNumberOne( double numberOne ) { this.numberOne = numberOne; } public void setNumberTwo( double numberTwo ) { this.numberTwo = numberTwo; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
[ "andy.costanza@ucm.be" ]
andy.costanza@ucm.be
6acdf9e6420e87983e5e5c49b91597f6e6841e81
278b98024631513105b09210fe6375f8f46c610d
/accessing-data-jpa/src/main/java/com/example/accessingdatajpa/CustomerRepository.java
fa083c5f7148264584f7e0f971f3c226a9b406c0
[ "MIT" ]
permissive
nicktien007/Nick.SpringBootPractice
f8981d58f6bcfe0e4cdd55887536145c8e73c95c
ee14dd52c750b4906612001e85b22672820b905b
refs/heads/master
2021-05-24T07:38:59.009899
2021-01-29T06:39:30
2021-01-29T06:39:30
253,454,211
0
0
null
null
null
null
UTF-8
Java
false
false
285
java
package com.example.accessingdatajpa; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface CustomerRepository extends CrudRepository<Customer,Long> { List<Customer> findByLastName(String lastName); Customer findById(long id); }
[ "trojanhorse0077@gmail.com" ]
trojanhorse0077@gmail.com
340a593627a4c9df8cd03470eb8a21b9bd474f73
5bb9b31420c3fa27f690540ce9f793e04d0c326c
/krt170130/krt170130/EnumerateTopological.java
3ac430e3a25d656edfbeecff54b9fbd23edeaf0a
[]
no_license
thakkark1313/PERT
dd3f21042a822789895631bada54abf7e30c5bef
e8d566606dfe2a506431e28530f620863d631220
refs/heads/master
2020-04-08T03:13:51.806830
2018-11-26T04:56:28
2018-11-26T04:56:28
158,967,272
0
0
null
null
null
null
UTF-8
Java
false
false
6,204
java
/* Starter code for enumerating topological orders of a DAG * @author * Utkarsh Gandhi (usg170030) * Khushboo Desai (kxd180009) * Esha Punjabi (ehp170000) * Karan Thakker (krt170130) */ package krt170130; import rbk.Graph; import rbk.Graph.GraphAlgorithm; import rbk.Graph.Vertex; import rbk.Graph.Edge; import rbk.Graph.Factory; import java.util.HashMap; import java.util.List; /* * Purpose * Parameters * Precondition * PostCondition * Return type */ public class EnumerateTopological extends GraphAlgorithm<EnumerateTopological.EnumVertex> { boolean print; // Set to true to print array in visit long count; // Number of permutations or combinations visited Selector sel; // Selector to decide whether to enumerate permutations with precedence constraints List <Vertex> finishList; // TO store topological order of a graph. HashMap<Vertex, Integer> inDegree; // Storing In Degree for each vertex. public EnumerateTopological(Graph g) { super(g, new EnumVertex()); print = false; count = 0; sel = new Selector(); this.finishList = DFS.topologicalOrder1(g); // Finding topological order of the given DAG. this.inDegree = getInDegree(); // Setting up Indegree for each vertex } /* * Purpose To form inDegree for each vertex of the graph * Return Returns HashMap of Vertex and it's indegree. */ private HashMap<Vertex,Integer> getInDegree() { HashMap <Vertex, Integer> hm = new HashMap<>(); for (Vertex v: g) { hm.put(v, v.inDegree()); } return hm; } static class EnumVertex implements Factory { EnumVertex() { } public EnumVertex make(Vertex u) { return new EnumVertex(); } } class Selector extends Enumerate.Approver<Vertex> { /* * Purpose To Check whether to select a vertex for permutation. * Parameters Vertex to be checked * Return type Returns value whether the vertex is selected or not. */ @Override public boolean select(Vertex u) { if(inDegree.get(u) == 0) { for (Edge edge: g.outEdges(u)) { inDegree.put(edge.otherEnd(u), inDegree.get(edge.otherEnd(u)) - 1); } return true; } return false; } @Override /* * Purpose To unselect the vertex and do postprocessing. * Parameters Vertex u */ public void unselect(Vertex u) { for (Edge edge: g.outEdges(u)) { inDegree.put(edge.otherEnd(u), inDegree.get(edge.otherEnd(u)) + 1); } } @Override /* * Purpose To print first k elements of the array. * Parameters Array to be printed and the limit k. */ public void visit(Vertex[] arr, int k) { count++; if(print) { for(Vertex u: arr) { System.out.print(u + " "); } System.out.println(); } } } // To do: LP4; return the number of topological orders of g /* * Purpose Method to enumerate all the valid topological orders ot the graph. * Parameters Flag to indicate whether to print the enumerations or not. * Return type Returns the number of valid topological orders. */ public long enumerateTopological(boolean flag) { if(this.finishList == null || this.finishList.size() == 0) { throw new IllegalArgumentException("Not a valid DAG"); } print = flag; permute(this.finishList.size()); return count; } /* * Purpose To print first k elements of the array. * Parameters Array to be printed and the limit k. */ private void visit(List <Vertex> current) { if(this.print) { for (Vertex v: current) { System.out.print(v + " "); } System.out.println(); } count++; } /* * Purpose Permute the topological sequence * Parameters integer denoting number of elements which can be possible permuted. */ public void permute(int c) { // To do for LP4 if( c == 0 ) { visit(this.finishList); return; } int d = this.finishList.size() - c; if(this.sel.select(this.finishList.get(d))) { permute(c-1); this.sel.unselect(this.finishList.get(d)); } for (int i=d+1; i<this.finishList.size();i++) { if(this.sel.select(this.finishList.get(i))) { swap(d, i); permute(c - 1); swap(d, i); this.sel.unselect(this.finishList.get(i)); } } } /* * Purpose Fucntion to swap the elements. * Parameters Indices of the element that are to be swapped. */ private void swap(int d, int i) { Vertex temp = this.finishList.get(d); this.finishList.set(d, this.finishList.get(i)); this.finishList.set(i, temp); } //-------------------static methods---------------------- public static long countTopologicalOrders(Graph g) { EnumerateTopological et = new EnumerateTopological(g); return et.enumerateTopological(false); } public static long enumerateTopologicalOrders(Graph g) { EnumerateTopological et = new EnumerateTopological(g); return et.enumerateTopological(true); } public static void main(String[] args) { int VERBOSE = 0; if(args.length > 0) { VERBOSE = Integer.parseInt(args[0]); } Graph g = Graph.readDirectedGraph(new java.util.Scanner(System.in)); Graph.Timer t = new Graph.Timer(); long result; if(VERBOSE > 0) { result = enumerateTopologicalOrders(g); } else { result = countTopologicalOrders(g); } System.out.println("\n" + result + "\n" + t.end()); } }
[ "thakkark1313@gmail.com" ]
thakkark1313@gmail.com
00ad04c7540240dc1b1dcd4fd7c73b8b8fe88ff8
fb6b1031a53ebaa63c33e7ffe4bc2f2357aced0d
/2018/11月/miaosha_idea/src/main/java/com/loooody/miaosha/service/MiaoshaUserService.java
fbdcb121b13031f2f44dd0586878abcc284c416e
[]
no_license
loooody/Lvxiaohui
a72fc979a65e9557791eff7abd80b6ff4d10c097
9df7e3e64a013910d427918e5c011a0949278b3b
refs/heads/master
2022-12-21T00:07:52.818091
2019-06-13T07:49:14
2019-06-13T07:49:14
140,280,879
0
0
null
2022-12-16T11:29:44
2018-07-09T12:16:44
Java
UTF-8
Java
false
false
2,686
java
package com.loooody.miaosha.service; import com.loooody.miaosha.dao.MiaoshaUserDao; import com.loooody.miaosha.domain.MiaoshaUser; import com.loooody.miaosha.exception.GlobalException; import com.loooody.miaosha.redis.MiaoshaUserKey; import com.loooody.miaosha.redis.RedisService; import com.loooody.miaosha.result.CodeMsg; import com.loooody.miaosha.util.MD5Util; import com.loooody.miaosha.util.UUIDUtil; import com.loooody.miaosha.vo.LoginVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.stereotype.Service; import org.thymeleaf.util.StringUtils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.util.UUID; @Service public class MiaoshaUserService { public static final String COOKIE_NAME_TOKEN = "token"; @Autowired MiaoshaUserDao miaoshaUserDao; @Autowired RedisService redisService; public MiaoshaUser getById(long id) { return miaoshaUserDao.getById(id); } public boolean login(HttpServletResponse response, LoginVo loginVo) { if (loginVo == null) { throw new GlobalException(CodeMsg.SERVER_ERROR); } String mobile = loginVo.getMobile(); String formPass = loginVo.getPassword(); //判断手机是否存在 MiaoshaUser user = getById(Long.parseLong(mobile)); if (user == null) { throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST); } //验证密码 String dbPass = user.getPassword(); String saltDB = user.getSalt(); String calPass = MD5Util.formPassToDBPass(formPass, saltDB); if (!calPass.equals(dbPass)) { throw new GlobalException(CodeMsg.PASSWORD_ERROR); } //cookie String token = UUIDUtil.uuid(); addCookie(response, token, user); return true; } public MiaoshaUser getByToken(HttpServletResponse response, String token) { if (StringUtils.isEmpty(token)) { return null; } MiaoshaUser user = redisService.get(MiaoshaUserKey.token, token, MiaoshaUser.class); if (user != null) { addCookie(response, token, user); } return user; } private void addCookie(HttpServletResponse response, String token, MiaoshaUser user) { //cookie redisService.set(MiaoshaUserKey.token, token, user); Cookie cookie = new Cookie(COOKIE_NAME_TOKEN, token); cookie.setMaxAge(MiaoshaUserKey.token.expireSeconds()); cookie.setPath("/"); response.addCookie(cookie); } }
[ "319667916@qq.com" ]
319667916@qq.com
cf1d69e98abf432f4d46518f4b3b787a2adcccd7
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/8/8_4580057e772b60433272af5cd691825748892693/BrowserActivity/8_4580057e772b60433272af5cd691825748892693_BrowserActivity_t.java
223209c1a05e6ca5401aa17dbc31abaec5c5d784
[]
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
191,944
java
/* * Copyright (C) 2006 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.android.browser; import com.google.android.googleapps.IGoogleLoginService; import com.google.android.googlelogin.GoogleLoginServiceConstants; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.app.SearchManager; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.DialogInterface.OnCancelListener; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.DrawFilter; import android.graphics.Paint; import android.graphics.PaintFlagsDrawFilter; import android.graphics.Picture; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.hardware.SensorListener; import android.hardware.SensorManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.net.WebAddress; import android.net.http.EventHandler; import android.net.http.SslCertificate; import android.net.http.SslError; import android.os.AsyncTask; import android.os.Bundle; import android.os.Debug; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.os.Process; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemClock; import android.provider.Browser; import android.provider.ContactsContract; import android.provider.ContactsContract.Intents.Insert; import android.provider.Downloads; import android.provider.MediaStore; import android.text.IClipboard; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.util.Regex; import android.util.AttributeSet; import android.util.Log; import android.view.ContextMenu; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem.OnMenuItemClickListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.DecelerateInterpolator; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.DownloadListener; import android.webkit.GeolocationPermissions; import android.webkit.HttpAuthHandler; import android.webkit.PluginManager; import android.webkit.SslErrorHandler; import android.webkit.URLUtil; import android.webkit.WebChromeClient; import android.webkit.WebChromeClient.CustomViewCallback; import android.webkit.WebHistoryItem; import android.webkit.WebIconDatabase; import android.webkit.WebStorage; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.text.ParseException; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedList; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class BrowserActivity extends Activity implements View.OnCreateContextMenuListener, DownloadListener { /* Define some aliases to make these debugging flags easier to refer to. * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG". */ private final static boolean DEBUG = com.android.browser.Browser.DEBUG; private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED; private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED; private IGoogleLoginService mGls = null; private ServiceConnection mGlsConnection = null; private SensorManager mSensorManager = null; // These are single-character shortcuts for searching popular sources. private static final int SHORTCUT_INVALID = 0; private static final int SHORTCUT_GOOGLE_SEARCH = 1; private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2; private static final int SHORTCUT_DICTIONARY_SEARCH = 3; private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4; /* Whitelisted webpages private static HashSet<String> sWhiteList; static { sWhiteList = new HashSet<String>(); sWhiteList.add("cnn.com/"); sWhiteList.add("espn.go.com/"); sWhiteList.add("nytimes.com/"); sWhiteList.add("engadget.com/"); sWhiteList.add("yahoo.com/"); sWhiteList.add("msn.com/"); sWhiteList.add("amazon.com/"); sWhiteList.add("consumerist.com/"); sWhiteList.add("google.com/m/news"); } */ private void setupHomePage() { final Runnable getAccount = new Runnable() { public void run() { // Lower priority Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); // get the default home page String homepage = mSettings.getHomePage(); try { if (mGls == null) return; if (!homepage.startsWith("http://www.google.")) return; if (homepage.indexOf('?') == -1) return; String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED); String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE); // three cases: // // hostedUser == googleUser // The device has only a google account // // hostedUser != googleUser // The device has a hosted account and a google account // // hostedUser != null, googleUser == null // The device has only a hosted account (so far) // developers might have no accounts at all if (hostedUser == null) return; if (googleUser == null || !hostedUser.equals(googleUser)) { String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1); homepage = homepage.replace("?", "/a/" + domain + "?"); } } catch (RemoteException ignore) { // Login service died; carry on } catch (RuntimeException ignore) { // Login service died; carry on } finally { finish(homepage); } } private void finish(final String homepage) { mHandler.post(new Runnable() { public void run() { mSettings.setHomePage(BrowserActivity.this, homepage); resumeAfterCredentials(); // as this is running in a separate thread, // BrowserActivity's onDestroy() may have been called, // which also calls unbindService(). if (mGlsConnection != null) { // we no longer need to keep GLS open unbindService(mGlsConnection); mGlsConnection = null; } } }); } }; final boolean[] done = { false }; // Open a connection to the Google Login Service. The first // time the connection is established, set up the homepage depending on // the account in a background thread. mGlsConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { mGls = IGoogleLoginService.Stub.asInterface(service); if (done[0] == false) { done[0] = true; Thread account = new Thread(getAccount); account.setName("GLSAccount"); account.start(); } } public void onServiceDisconnected(ComponentName className) { mGls = null; } }; bindService(GoogleLoginServiceConstants.SERVICE_INTENT, mGlsConnection, Context.BIND_AUTO_CREATE); } private static class ClearThumbnails extends AsyncTask<File, Void, Void> { @Override public Void doInBackground(File... files) { if (files != null) { for (File f : files) { if (!f.delete()) { Log.e(LOGTAG, f.getPath() + " was not deleted"); } } } return null; } } /** * This layout holds everything you see below the status bar, including the * error console, the custom view container, and the webviews. */ private FrameLayout mBrowserFrameLayout; @Override public void onCreate(Bundle icicle) { if (LOGV_ENABLED) { Log.v(LOGTAG, this + " onStart"); } super.onCreate(icicle); // test the browser in OpenGL // requestWindowFeature(Window.FEATURE_OPENGL); setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); mResolver = getContentResolver(); // If this was a web search request, pass it on to the default web // search provider and finish this activity. if (handleWebSearchIntent(getIntent())) { finish(); return; } // // start MASF proxy service // //Intent proxyServiceIntent = new Intent(); //proxyServiceIntent.setComponent // (new ComponentName( // "com.android.masfproxyservice", // "com.android.masfproxyservice.MasfProxyService")); //startService(proxyServiceIntent, null); mSecLockIcon = Resources.getSystem().getDrawable( android.R.drawable.ic_secure); mMixLockIcon = Resources.getSystem().getDrawable( android.R.drawable.ic_partial_secure); FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView() .findViewById(com.android.internal.R.id.content); mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this) .inflate(R.layout.custom_screen, null); mContentView = (FrameLayout) mBrowserFrameLayout.findViewById( R.id.main_content); mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout .findViewById(R.id.error_console); mCustomViewContainer = (FrameLayout) mBrowserFrameLayout .findViewById(R.id.fullscreen_custom_content); frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS); mTitleBar = new TitleBar(this); // Create the tab control and our initial tab mTabControl = new TabControl(this); // Open the icon database and retain all the bookmark urls for favicons retainIconsOnStartup(); // Keep a settings instance handy. mSettings = BrowserSettings.getInstance(); mSettings.setTabControl(mTabControl); mSettings.loadFromDb(this); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser"); /* enables registration for changes in network status from http stack */ mNetworkStateChangedFilter = new IntentFilter(); mNetworkStateChangedFilter.addAction( ConnectivityManager.CONNECTIVITY_ACTION); mNetworkStateIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( ConnectivityManager.CONNECTIVITY_ACTION)) { NetworkInfo info = (NetworkInfo) intent.getParcelableExtra( ConnectivityManager.EXTRA_NETWORK_INFO); onNetworkToggle( (info != null) ? info.isConnected() : false); } } }; IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addDataScheme("package"); mPackageInstallationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); final String packageName = intent.getData() .getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra( Intent.EXTRA_REPLACING, false); if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) { // if it is replacing, refreshPlugins() when adding return; } PackageManager pm = BrowserActivity.this.getPackageManager(); PackageInfo pkgInfo = null; try { pkgInfo = pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS); } catch (PackageManager.NameNotFoundException e) { return; } if (pkgInfo != null) { String permissions[] = pkgInfo.requestedPermissions; if (permissions == null) { return; } boolean permissionOk = false; for (String permit : permissions) { if (PluginManager.PLUGIN_PERMISSION.equals(permit)) { permissionOk = true; break; } } if (permissionOk) { PluginManager.getInstance(BrowserActivity.this) .refreshPlugins( Intent.ACTION_PACKAGE_ADDED .equals(action)); } } } }; registerReceiver(mPackageInstallationReceiver, filter); if (!mTabControl.restoreState(icicle)) { // clear up the thumbnail directory if we can't restore the state as // none of the files in the directory are referenced any more. new ClearThumbnails().execute( mTabControl.getThumbnailDir().listFiles()); // there is no quit on Android. But if we can't restore the state, // we can treat it as a new Browser, remove the old session cookies. CookieManager.getInstance().removeSessionCookie(); final Intent intent = getIntent(); final Bundle extra = intent.getExtras(); // Create an initial tab. // If the intent is ACTION_VIEW and data is not null, the Browser is // invoked to view the content by another application. In this case, // the tab will be close when exit. UrlData urlData = getUrlDataFromIntent(intent); final TabControl.Tab t = mTabControl.createNewTab( Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() != null, intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl); mTabControl.setCurrentTab(t); attachTabToContentView(t); WebView webView = t.getWebView(); if (extra != null) { int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0); if (scale > 0 && scale <= 1000) { webView.setInitialScale(scale); } } // If we are not restoring from an icicle, then there is a high // likely hood this is the first run. So, check to see if the // homepage needs to be configured and copy any plugins from our // asset directory to the data partition. if ((extra == null || !extra.getBoolean("testing")) && !mSettings.isLoginInitialized()) { setupHomePage(); } if (urlData.isEmpty()) { if (mSettings.isLoginInitialized()) { webView.loadUrl(mSettings.getHomePage()); } else { waitForCredentials(); } } else { if (extra != null) { urlData.setPostData(extra .getByteArray(Browser.EXTRA_POST_DATA)); } urlData.loadIn(webView); } } else { // TabControl.restoreState() will create a new tab even if // restoring the state fails. attachTabToContentView(mTabControl.getCurrentTab()); } // Read JavaScript flags if it exists. String jsFlags = mSettings.getJsFlags(); if (jsFlags.trim().length() != 0) { mTabControl.getCurrentWebView().setJsFlags(jsFlags); } } @Override protected void onNewIntent(Intent intent) { TabControl.Tab current = mTabControl.getCurrentTab(); // When a tab is closed on exit, the current tab index is set to -1. // Reset before proceed as Browser requires the current tab to be set. if (current == null) { // Try to reset the tab in case the index was incorrect. current = mTabControl.getTab(0); if (current == null) { // No tabs at all so just ignore this intent. return; } mTabControl.setCurrentTab(current); attachTabToContentView(current); resetTitleAndIcon(current.getWebView()); } final String action = intent.getAction(); final int flags = intent.getFlags(); if (Intent.ACTION_MAIN.equals(action) || (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) { // just resume the browser return; } if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) || Intent.ACTION_WEB_SEARCH.equals(action)) { // If this was a search request (e.g. search query directly typed into the address bar), // pass it on to the default web search provider. if (handleWebSearchIntent(intent)) { return; } UrlData urlData = getUrlDataFromIntent(intent); if (urlData.isEmpty()) { urlData = new UrlData(mSettings.getHomePage()); } urlData.setPostData(intent .getByteArrayExtra(Browser.EXTRA_POST_DATA)); final String appId = intent .getStringExtra(Browser.EXTRA_APPLICATION_ID); if (Intent.ACTION_VIEW.equals(action) && !getPackageName().equals(appId) && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { TabControl.Tab appTab = mTabControl.getTabFromId(appId); if (appTab != null) { Log.i(LOGTAG, "Reusing tab for " + appId); // Dismiss the subwindow if applicable. dismissSubWindow(appTab); // Since we might kill the WebView, remove it from the // content view first. removeTabFromContentView(appTab); // Recreate the main WebView after destroying the old one. // If the WebView has the same original url and is on that // page, it can be reused. boolean needsLoad = mTabControl.recreateWebView(appTab, urlData.mUrl); if (current != appTab) { switchToTab(mTabControl.getTabIndex(appTab)); if (needsLoad) { urlData.loadIn(appTab.getWebView()); } } else { // If the tab was the current tab, we have to attach // it to the view system again. attachTabToContentView(appTab); if (needsLoad) { urlData.loadIn(appTab.getWebView()); } } return; } else { // No matching application tab, try to find a regular tab // with a matching url. appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl); if (appTab != null) { if (current != appTab) { switchToTab(mTabControl.getTabIndex(appTab)); } // Otherwise, we are already viewing the correct tab. } else { // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url // will be opened in a new tab unless we have reached // MAX_TABS. Then the url will be opened in the current // tab. If a new tab is created, it will have "true" for // exit on close. openTabAndShow(urlData, true, appId); } } } else { if ("about:debug".equals(urlData.mUrl)) { mSettings.toggleDebugSettings(); return; } // Get rid of the subwindow if it exists dismissSubWindow(current); urlData.loadIn(current.getWebView()); } } } private int parseUrlShortcut(String url) { if (url == null) return SHORTCUT_INVALID; // FIXME: quick search, need to be customized by setting if (url.length() > 2 && url.charAt(1) == ' ') { switch (url.charAt(0)) { case 'g': return SHORTCUT_GOOGLE_SEARCH; case 'w': return SHORTCUT_WIKIPEDIA_SEARCH; case 'd': return SHORTCUT_DICTIONARY_SEARCH; case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH; } } return SHORTCUT_INVALID; } /** * Launches the default web search activity with the query parameters if the given intent's data * are identified as plain search terms and not URLs/shortcuts. * @return true if the intent was handled and web search activity was launched, false if not. */ private boolean handleWebSearchIntent(Intent intent) { if (intent == null) return false; String url = null; final String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action)) { url = intent.getData().toString(); } else if (Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) || Intent.ACTION_WEB_SEARCH.equals(action)) { url = intent.getStringExtra(SearchManager.QUERY); } return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA), intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); } /** * Launches the default web search activity with the query parameters if the given url string * was identified as plain search terms and not URL/shortcut. * @return true if the request was handled and web search activity was launched, false if not. */ private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) { if (inUrl == null) return false; // In general, we shouldn't modify URL from Intent. // But currently, we get the user-typed URL from search box as well. String url = fixUrl(inUrl).trim(); // URLs and site specific search shortcuts are handled by the regular flow of control, so // return early. if (Regex.WEB_URL_PATTERN.matcher(url).matches() || ACCEPTED_URI_SCHEMA.matcher(url).matches() || parseUrlShortcut(url) != SHORTCUT_INVALID) { return false; } Browser.updateVisitedHistory(mResolver, url, false); Browser.addSearchUrl(mResolver, url); Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.putExtra(SearchManager.QUERY, url); if (appData != null) { intent.putExtra(SearchManager.APP_DATA, appData); } if (extraData != null) { intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData); } intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName()); startActivity(intent); return true; } private UrlData getUrlDataFromIntent(Intent intent) { String url = null; if (intent != null) { final String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action)) { url = smartUrlFilter(intent.getData()); if (url != null && url.startsWith("content:")) { /* Append mimetype so webview knows how to display */ String mimeType = intent.resolveType(getContentResolver()); if (mimeType != null) { url += "?" + mimeType; } } if ("inline:".equals(url)) { return new InlinedUrlData( intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT), intent.getType(), intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING), intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL)); } } else if (Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) || Intent.ACTION_WEB_SEARCH.equals(action)) { url = intent.getStringExtra(SearchManager.QUERY); if (url != null) { mLastEnteredUrl = url; // Don't add Urls, just search terms. // Urls will get added when the page is loaded. if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) { Browser.updateVisitedHistory(mResolver, url, false); } // In general, we shouldn't modify URL from Intent. // But currently, we get the user-typed URL from search box as well. url = fixUrl(url); url = smartUrlFilter(url); String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&"; if (url.contains(searchSource)) { String source = null; final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA); if (appData != null) { source = appData.getString(SearchManager.SOURCE); } if (TextUtils.isEmpty(source)) { source = GOOGLE_SEARCH_SOURCE_UNKNOWN; } url = url.replace(searchSource, "&source=android-"+source+"&"); } } } } return new UrlData(url); } /* package */ static String fixUrl(String inUrl) { // FIXME: Converting the url to lower case // duplicates functionality in smartUrlFilter(). // However, changing all current callers of fixUrl to // call smartUrlFilter in addition may have unwanted // consequences, and is deferred for now. int colon = inUrl.indexOf(':'); boolean allLower = true; for (int index = 0; index < colon; index++) { char ch = inUrl.charAt(index); if (!Character.isLetter(ch)) { break; } allLower &= Character.isLowerCase(ch); if (index == colon - 1 && !allLower) { inUrl = inUrl.substring(0, colon).toLowerCase() + inUrl.substring(colon); } } if (inUrl.startsWith("http://") || inUrl.startsWith("https://")) return inUrl; if (inUrl.startsWith("http:") || inUrl.startsWith("https:")) { if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) { inUrl = inUrl.replaceFirst("/", "//"); } else inUrl = inUrl.replaceFirst(":", "://"); } return inUrl; } /** * Looking for the pattern like this * * * * * * * *** * ******* * * * * * * * * */ private final SensorListener mSensorListener = new SensorListener() { private long mLastGestureTime; private float[] mPrev = new float[3]; private float[] mPrevDiff = new float[3]; private float[] mDiff = new float[3]; private float[] mRevertDiff = new float[3]; public void onSensorChanged(int sensor, float[] values) { boolean show = false; float[] diff = new float[3]; for (int i = 0; i < 3; i++) { diff[i] = values[i] - mPrev[i]; if (Math.abs(diff[i]) > 1) { show = true; } if ((diff[i] > 1.0 && mDiff[i] < 0.2) || (diff[i] < -1.0 && mDiff[i] > -0.2)) { // start track when there is a big move, or revert mRevertDiff[i] = mDiff[i]; mDiff[i] = 0; } else if (diff[i] > -0.2 && diff[i] < 0.2) { // reset when it is flat mDiff[i] = mRevertDiff[i] = 0; } mDiff[i] += diff[i]; mPrevDiff[i] = diff[i]; mPrev[i] = values[i]; } if (false) { // only shows if we think the delta is big enough, in an attempt // to detect "serious" moves left/right or up/down Log.d("BrowserSensorHack", "sensorChanged " + sensor + " (" + values[0] + ", " + values[1] + ", " + values[2] + ")" + " diff(" + diff[0] + " " + diff[1] + " " + diff[2] + ")"); Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " " + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff(" + mRevertDiff[0] + " " + mRevertDiff[1] + " " + mRevertDiff[2] + ")"); } long now = android.os.SystemClock.uptimeMillis(); if (now - mLastGestureTime > 1000) { mLastGestureTime = 0; float y = mDiff[1]; float z = mDiff[2]; float ay = Math.abs(y); float az = Math.abs(z); float ry = mRevertDiff[1]; float rz = mRevertDiff[2]; float ary = Math.abs(ry); float arz = Math.abs(rz); boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary; boolean gestZ = az > 3.5f && arz > 1.0f && az > arz; if ((gestY || gestZ) && !(gestY && gestZ)) { WebView view = mTabControl.getCurrentWebView(); if (view != null) { if (gestZ) { if (z < 0) { view.zoomOut(); } else { view.zoomIn(); } } else { view.flingScroll(0, Math.round(y * 100)); } } mLastGestureTime = now; } } } public void onAccuracyChanged(int sensor, int accuracy) { // TODO Auto-generated method stub } }; @Override protected void onResume() { super.onResume(); if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this); } if (!mActivityInPause) { Log.e(LOGTAG, "BrowserActivity is already resumed."); return; } mTabControl.resumeCurrentTab(); mActivityInPause = false; resumeWebViewTimers(); if (mWakeLock.isHeld()) { mHandler.removeMessages(RELEASE_WAKELOCK); mWakeLock.release(); } if (mCredsDlg != null) { if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) { // In case credential request never comes back mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000); } } registerReceiver(mNetworkStateIntentReceiver, mNetworkStateChangedFilter); WebView.enablePlatformNotifications(); if (mSettings.doFlick()) { if (mSensorManager == null) { mSensorManager = (SensorManager) getSystemService( Context.SENSOR_SERVICE); } mSensorManager.registerListener(mSensorListener, SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_FASTEST); } else { mSensorManager = null; } } /** * Since the actual title bar is embedded in the WebView, and removing it * would change its appearance, create a temporary title bar to go at * the top of the screen while the menu is open. */ private TitleBar mFakeTitleBar; /** * Holder for the fake title bar. It will have a foreground shadow, as well * as a white background, so the fake title bar looks like the real one. */ private ViewGroup mFakeTitleBarHolder; /** * Layout parameters for the fake title bar within mFakeTitleBarHolder */ private FrameLayout.LayoutParams mFakeTitleBarParams = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); /** * Keeps track of whether the options menu is open. This is important in * determining whether to show or hide the title bar overlay. */ private boolean mOptionsMenuOpen; /** * Only meaningful when mOptionsMenuOpen is true. This variable keeps track * of whether the configuration has changed. The first onMenuOpened call * after a configuration change is simply a reopening of the same menu * (i.e. mIconView did not change). */ private boolean mConfigChanged; /** * Whether or not the options menu is in its smaller, icon menu form. When * true, we want the title bar overlay to be up. When false, we do not. * Only meaningful if mOptionsMenuOpen is true. */ private boolean mIconView; @Override public boolean onMenuOpened(int featureId, Menu menu) { if (Window.FEATURE_OPTIONS_PANEL == featureId) { if (mOptionsMenuOpen) { if (mConfigChanged) { // We do not need to make any changes to the state of the // title bar, since the only thing that happened was a // change in orientation mConfigChanged = false; } else { if (mIconView) { // Switching the menu to expanded view, so hide the // title bar. hideFakeTitleBar(); mIconView = false; } else { // Switching the menu back to icon view, so show the // title bar once again. showFakeTitleBar(); mIconView = true; } } } else { // The options menu is closed, so open it, and show the title showFakeTitleBar(); mOptionsMenuOpen = true; mConfigChanged = false; mIconView = true; } } return true; } /** * Special class used exclusively for the shadow drawn underneath the fake * title bar. The shadow does not need to be drawn if the WebView * underneath is scrolled to the top, because it will draw directly on top * of the embedded shadow. */ private static class Shadow extends View { private WebView mWebView; public Shadow(Context context, AttributeSet attrs) { super(context, attrs); } public void setWebView(WebView view) { mWebView = view; } @Override public void draw(Canvas canvas) { // In general onDraw is the method to override, but we care about // whether or not the background gets drawn, which happens in draw() if (mWebView == null || mWebView.getScrollY() > getHeight()) { super.draw(canvas); } // Need to invalidate so that if the scroll position changes, we // still draw as appropriate. invalidate(); } } private void showFakeTitleBar() { final View decor = getWindow().peekDecorView(); if (mFakeTitleBar == null && mActiveTabsPage == null && !mActivityInPause && decor != null && decor.getWindowToken() != null) { Rect visRect = new Rect(); if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) { if (LOGD_ENABLED) { Log.d(LOGTAG, "showFakeTitleBar visRect failed"); } return; } final WebView webView = getTopWindow(); mFakeTitleBar = new TitleBar(this); mFakeTitleBar.setTitleAndUrl(null, webView.getUrl()); mFakeTitleBar.setProgress(webView.getProgress()); mFakeTitleBar.setFavicon(webView.getFavicon()); updateLockIconToLatest(); WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); // Add the title bar to the window manager so it can receive touches // while the menu is up WindowManager.LayoutParams params = new WindowManager.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); params.gravity = Gravity.TOP; WebView mainView = mTabControl.getCurrentWebView(); boolean atTop = mainView != null && mainView.getScrollY() == 0; params.windowAnimations = atTop ? 0 : com.android.internal.R.style.Animation_DropDownDown; // XXX : Without providing an offset, the fake title bar will be // placed underneath the status bar. Use the global visible rect // of mBrowserFrameLayout to determine the bottom of the status bar params.y = visRect.top; // Add a holder for the title bar. It also holds a shadow to show // below the title bar. if (mFakeTitleBarHolder == null) { mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this) .inflate(R.layout.title_bar_bg, null); } Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById( R.id.shadow); shadow.setWebView(mainView); mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams); manager.addView(mFakeTitleBarHolder, params); } } @Override public void onOptionsMenuClosed(Menu menu) { mOptionsMenuOpen = false; if (!mInLoad) { hideFakeTitleBar(); } else if (!mIconView) { // The page is currently loading, and we are in expanded mode, so // we were not showing the menu. Show it once again. It will be // removed when the page finishes. showFakeTitleBar(); } } private void hideFakeTitleBar() { if (mFakeTitleBar == null) return; WindowManager.LayoutParams params = (WindowManager.LayoutParams) mFakeTitleBarHolder.getLayoutParams(); WebView mainView = mTabControl.getCurrentWebView(); // Although we decided whether or not to animate based on the current // scroll position, the scroll position may have changed since the // fake title bar was displayed. Make sure it has the appropriate // animation/lack thereof before removing. params.windowAnimations = mainView != null && mainView.getScrollY() == 0 ? 0 : com.android.internal.R.style.Animation_DropDownDown; WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); manager.updateViewLayout(mFakeTitleBarHolder, params); mFakeTitleBarHolder.removeView(mFakeTitleBar); manager.removeView(mFakeTitleBarHolder); mFakeTitleBar = null; } /** * Special method for the fake title bar to call when displaying its context * menu, since it is in its own Window, and its parent does not show a * context menu. */ /* package */ void showTitleBarContextMenu() { if (null == mTitleBar.getParent()) { return; } openContextMenu(mTitleBar); } /** * onSaveInstanceState(Bundle map) * onSaveInstanceState is called right before onStop(). The map contains * the saved state. */ @Override protected void onSaveInstanceState(Bundle outState) { if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this); } // the default implementation requires each view to have an id. As the // browser handles the state itself and it doesn't use id for the views, // don't call the default implementation. Otherwise it will trigger the // warning like this, "couldn't save which view has focus because the // focused view XXX has no id". // Save all the tabs mTabControl.saveState(outState); } @Override protected void onPause() { super.onPause(); if (mActivityInPause) { Log.e(LOGTAG, "BrowserActivity is already paused."); return; } mTabControl.pauseCurrentTab(); mActivityInPause = true; if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) { mWakeLock.acquire(); mHandler.sendMessageDelayed(mHandler .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT); } // Clear the credentials toast if it is up if (mCredsDlg != null && mCredsDlg.isShowing()) { mCredsDlg.dismiss(); } mCredsDlg = null; // FIXME: This removes the active tabs page and resets the menu to // MAIN_MENU. A better solution might be to do this work in onNewIntent // but then we would need to save it in onSaveInstanceState and restore // it in onCreate/onRestoreInstanceState if (mActiveTabsPage != null) { removeActiveTabPage(true); } cancelStopToast(); // unregister network state listener unregisterReceiver(mNetworkStateIntentReceiver); WebView.disablePlatformNotifications(); if (mSensorManager != null) { mSensorManager.unregisterListener(mSensorListener); } } @Override protected void onDestroy() { if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this); } super.onDestroy(); if (mTabControl == null) return; // Remove the current tab and sub window TabControl.Tab t = mTabControl.getCurrentTab(); if (t != null) { dismissSubWindow(t); removeTabFromContentView(t); } // Destroy all the tabs mTabControl.destroy(); WebIconDatabase.getInstance().close(); if (mGlsConnection != null) { unbindService(mGlsConnection); mGlsConnection = null; } // // stop MASF proxy service // //Intent proxyServiceIntent = new Intent(); //proxyServiceIntent.setComponent // (new ComponentName( // "com.android.masfproxyservice", // "com.android.masfproxyservice.MasfProxyService")); //stopService(proxyServiceIntent); unregisterReceiver(mPackageInstallationReceiver); } @Override public void onConfigurationChanged(Configuration newConfig) { mConfigChanged = true; super.onConfigurationChanged(newConfig); if (mPageInfoDialog != null) { mPageInfoDialog.dismiss(); showPageInfo( mPageInfoView, mPageInfoFromShowSSLCertificateOnError.booleanValue()); } if (mSSLCertificateDialog != null) { mSSLCertificateDialog.dismiss(); showSSLCertificate( mSSLCertificateView); } if (mSSLCertificateOnErrorDialog != null) { mSSLCertificateOnErrorDialog.dismiss(); showSSLCertificateOnError( mSSLCertificateOnErrorView, mSSLCertificateOnErrorHandler, mSSLCertificateOnErrorError); } if (mHttpAuthenticationDialog != null) { String title = ((TextView) mHttpAuthenticationDialog .findViewById(com.android.internal.R.id.alertTitle)).getText() .toString(); String name = ((TextView) mHttpAuthenticationDialog .findViewById(R.id.username_edit)).getText().toString(); String password = ((TextView) mHttpAuthenticationDialog .findViewById(R.id.password_edit)).getText().toString(); int focusId = mHttpAuthenticationDialog.getCurrentFocus() .getId(); mHttpAuthenticationDialog.dismiss(); showHttpAuthentication(mHttpAuthHandler, null, null, title, name, password, focusId); } if (mFindDialog != null && mFindDialog.isShowing()) { mFindDialog.onConfigurationChanged(newConfig); } } @Override public void onLowMemory() { super.onLowMemory(); mTabControl.freeMemory(); } private boolean resumeWebViewTimers() { if ((!mActivityInPause && !mPageStarted) || (mActivityInPause && mPageStarted)) { CookieSyncManager.getInstance().startSync(); WebView w = mTabControl.getCurrentWebView(); if (w != null) { w.resumeTimers(); } return true; } else { return false; } } private boolean pauseWebViewTimers() { if (mActivityInPause && !mPageStarted) { CookieSyncManager.getInstance().stopSync(); WebView w = mTabControl.getCurrentWebView(); if (w != null) { w.pauseTimers(); } return true; } else { return false; } } // FIXME: Do we want to call this when loading google for the first time? /* * This function is called when we are launching for the first time. We * are waiting for the login credentials before loading Google home * pages. This way the user will be logged in straight away. */ private void waitForCredentials() { // Show a toast mCredsDlg = new ProgressDialog(this); mCredsDlg.setIndeterminate(true); mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg)); // If the user cancels the operation, then cancel the Google // Credentials request. mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST)); mCredsDlg.show(); // We set a timeout for the retrieval of credentials in onResume() // as that is when we have freed up some CPU time to get // the login credentials. } /* * If we have received the credentials or we have timed out and we are * showing the credentials dialog, then it is time to move on. */ private void resumeAfterCredentials() { if (mCredsDlg == null) { return; } // Clear the toast if (mCredsDlg.isShowing()) { mCredsDlg.dismiss(); } mCredsDlg = null; // Clear any pending timeout mHandler.removeMessages(CANCEL_CREDS_REQUEST); // Load the page WebView w = mTabControl.getCurrentWebView(); if (w != null) { w.loadUrl(mSettings.getHomePage()); } // Update the settings, need to do this last as it can take a moment // to persist the settings. In the mean time we could be loading // content. mSettings.setLoginInitialized(this); } // Open the icon database and retain all the icons for visited sites. private void retainIconsOnStartup() { final WebIconDatabase db = WebIconDatabase.getInstance(); db.open(getDir("icons", 0).getPath()); try { Cursor c = Browser.getAllBookmarks(mResolver); if (!c.moveToFirst()) { c.deactivate(); return; } int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL); do { String url = c.getString(urlIndex); db.retainIconForPageUrl(url); } while (c.moveToNext()); c.deactivate(); } catch (IllegalStateException e) { Log.e(LOGTAG, "retainIconsOnStartup", e); } } // Helper method for getting the top window. WebView getTopWindow() { return mTabControl.getCurrentTopWebView(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.browser, menu); mMenu = menu; updateInLoadMenuItems(); return true; } /** * As the menu can be open when loading state changes * we must manually update the state of the stop/reload menu * item */ private void updateInLoadMenuItems() { if (mMenu == null) { return; } MenuItem src = mInLoad ? mMenu.findItem(R.id.stop_menu_id): mMenu.findItem(R.id.reload_menu_id); MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id); dest.setIcon(src.getIcon()); dest.setTitle(src.getTitle()); } @Override public boolean onContextItemSelected(MenuItem item) { // chording is not an issue with context menus, but we use the same // options selector, so set mCanChord to true so we can access them. mCanChord = true; int id = item.getItemId(); switch (id) { // For the context menu from the title bar case R.id.title_bar_share_page_url: case R.id.title_bar_copy_page_url: WebView mainView = mTabControl.getCurrentWebView(); if (null == mainView) { return false; } if (id == R.id.title_bar_share_page_url) { Browser.sendString(this, mainView.getUrl()); } else { copy(mainView.getUrl()); } break; // -- Browser context menu case R.id.open_context_menu_id: case R.id.open_newtab_context_menu_id: case R.id.bookmark_context_menu_id: case R.id.save_link_context_menu_id: case R.id.share_link_context_menu_id: case R.id.copy_link_context_menu_id: final WebView webView = getTopWindow(); if (null == webView) { return false; } final HashMap hrefMap = new HashMap(); hrefMap.put("webview", webView); final Message msg = mHandler.obtainMessage( FOCUS_NODE_HREF, id, 0, hrefMap); webView.requestFocusNodeHref(msg); break; default: // For other context menus return onOptionsItemSelected(item); } mCanChord = false; return true; } private Bundle createGoogleSearchSourceBundle(String source) { Bundle bundle = new Bundle(); bundle.putString(SearchManager.SOURCE, source); return bundle; } /** * Overriding this to insert a local information bundle */ @Override public boolean onSearchRequested() { if (mOptionsMenuOpen) closeOptionsMenu(); String url = (getTopWindow() == null) ? null : getTopWindow().getUrl(); startSearch(mSettings.getHomePage().equals(url) ? null : url, true, createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false); return true; } @Override public void startSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch) { if (appSearchData == null) { appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE); } super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch); } /** * Switch tabs. Called by the TitleBarSet when sliding the title bar * results in changing tabs. * @param index Index of the tab to change to, as defined by * mTabControl.getTabIndex(Tab t). * @return boolean True if we successfully switched to a different tab. If * the indexth tab is null, or if that tab is the same as * the current one, return false. */ /* package */ boolean switchToTab(int index) { TabControl.Tab tab = mTabControl.getTab(index); TabControl.Tab currentTab = mTabControl.getCurrentTab(); if (tab == null || tab == currentTab) { return false; } if (currentTab != null) { // currentTab may be null if it was just removed. In that case, // we do not need to remove it removeTabFromContentView(currentTab); } mTabControl.setCurrentTab(tab); attachTabToContentView(tab); resetTitleIconAndProgress(); updateLockIconToLatest(); return true; } /* package */ TabControl.Tab openTabToHomePage() { return openTabAndShow(mSettings.getHomePage(), false, null); } /* package */ void closeCurrentWindow() { final TabControl.Tab current = mTabControl.getCurrentTab(); if (mTabControl.getTabCount() == 1) { // This is the last tab. Open a new one, with the home // page and close the current one. TabControl.Tab newTab = openTabToHomePage(); closeTab(current); return; } final TabControl.Tab parent = current.getParentTab(); int indexToShow = -1; if (parent != null) { indexToShow = mTabControl.getTabIndex(parent); } else { final int currentIndex = mTabControl.getCurrentIndex(); // Try to move to the tab to the right indexToShow = currentIndex + 1; if (indexToShow > mTabControl.getTabCount() - 1) { // Try to move to the tab to the left indexToShow = currentIndex - 1; } } if (switchToTab(indexToShow)) { // Close window closeTab(current); } } private ActiveTabsPage mActiveTabsPage; /** * Remove the active tabs page. * @param needToAttach If true, the active tabs page did not attach a tab * to the content view, so we need to do that here. */ /* package */ void removeActiveTabPage(boolean needToAttach) { mContentView.removeView(mActiveTabsPage); mActiveTabsPage = null; mMenuState = R.id.MAIN_MENU; if (needToAttach) { attachTabToContentView(mTabControl.getCurrentTab()); } getTopWindow().requestFocus(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (!mCanChord) { // The user has already fired a shortcut with this hold down of the // menu key. return false; } if (null == getTopWindow()) { return false; } if (mMenuIsDown) { // The shortcut action consumes the MENU. Even if it is still down, // it won't trigger the next shortcut action. In the case of the // shortcut action triggering a new activity, like Bookmarks, we // won't get onKeyUp for MENU. So it is important to reset it here. mMenuIsDown = false; } switch (item.getItemId()) { // -- Main menu case R.id.new_tab_menu_id: openTabToHomePage(); break; case R.id.goto_menu_id: onSearchRequested(); break; case R.id.bookmarks_menu_id: bookmarksOrHistoryPicker(false); break; case R.id.active_tabs_menu_id: mActiveTabsPage = new ActiveTabsPage(this, mTabControl); removeTabFromContentView(mTabControl.getCurrentTab()); hideFakeTitleBar(); mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS); mActiveTabsPage.requestFocus(); mMenuState = EMPTY_MENU; break; case R.id.add_bookmark_menu_id: Intent i = new Intent(BrowserActivity.this, AddBookmarkPage.class); WebView w = getTopWindow(); i.putExtra("url", w.getUrl()); i.putExtra("title", w.getTitle()); i.putExtra("touch_icon_url", w.getTouchIconUrl()); i.putExtra("thumbnail", createScreenshot(w)); startActivity(i); break; case R.id.stop_reload_menu_id: if (mInLoad) { stopLoading(); } else { getTopWindow().reload(); } break; case R.id.back_menu_id: getTopWindow().goBack(); break; case R.id.forward_menu_id: getTopWindow().goForward(); break; case R.id.close_menu_id: // Close the subwindow if it exists. if (mTabControl.getCurrentSubWindow() != null) { dismissSubWindow(mTabControl.getCurrentTab()); break; } closeCurrentWindow(); break; case R.id.homepage_menu_id: TabControl.Tab current = mTabControl.getCurrentTab(); if (current != null) { dismissSubWindow(current); current.getWebView().loadUrl(mSettings.getHomePage()); } break; case R.id.preferences_menu_id: Intent intent = new Intent(this, BrowserPreferencesPage.class); startActivityForResult(intent, PREFERENCES_PAGE); break; case R.id.find_menu_id: if (null == mFindDialog) { mFindDialog = new FindDialog(this); } mFindDialog.setWebView(getTopWindow()); mFindDialog.show(); mMenuState = EMPTY_MENU; break; case R.id.select_text_id: getTopWindow().emulateShiftHeld(); break; case R.id.page_info_menu_id: showPageInfo(mTabControl.getCurrentTab(), false); break; case R.id.classic_history_menu_id: bookmarksOrHistoryPicker(true); break; case R.id.share_page_menu_id: Browser.sendString(this, getTopWindow().getUrl(), getText(R.string.choosertitle_sharevia).toString()); break; case R.id.dump_nav_menu_id: getTopWindow().debugDump(); break; case R.id.zoom_in_menu_id: getTopWindow().zoomIn(); break; case R.id.zoom_out_menu_id: getTopWindow().zoomOut(); break; case R.id.view_downloads_menu_id: viewDownloads(null); break; case R.id.window_one_menu_id: case R.id.window_two_menu_id: case R.id.window_three_menu_id: case R.id.window_four_menu_id: case R.id.window_five_menu_id: case R.id.window_six_menu_id: case R.id.window_seven_menu_id: case R.id.window_eight_menu_id: { int menuid = item.getItemId(); for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) { if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) { TabControl.Tab desiredTab = mTabControl.getTab(id); if (desiredTab != null && desiredTab != mTabControl.getCurrentTab()) { switchToTab(id); } break; } } } break; default: if (!super.onOptionsItemSelected(item)) { return false; } // Otherwise fall through. } mCanChord = false; return true; } public void closeFind() { mMenuState = R.id.MAIN_MENU; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // This happens when the user begins to hold down the menu key, so // allow them to chord to get a shortcut. mCanChord = true; // Note: setVisible will decide whether an item is visible; while // setEnabled() will decide whether an item is enabled, which also means // whether the matching shortcut key will function. super.onPrepareOptionsMenu(menu); switch (mMenuState) { case EMPTY_MENU: if (mCurrentMenuState != mMenuState) { menu.setGroupVisible(R.id.MAIN_MENU, false); menu.setGroupEnabled(R.id.MAIN_MENU, false); menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false); } break; default: if (mCurrentMenuState != mMenuState) { menu.setGroupVisible(R.id.MAIN_MENU, true); menu.setGroupEnabled(R.id.MAIN_MENU, true); menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true); } final WebView w = getTopWindow(); boolean canGoBack = false; boolean canGoForward = false; boolean isHome = false; if (w != null) { canGoBack = w.canGoBack(); canGoForward = w.canGoForward(); isHome = mSettings.getHomePage().equals(w.getUrl()); } final MenuItem back = menu.findItem(R.id.back_menu_id); back.setEnabled(canGoBack); final MenuItem home = menu.findItem(R.id.homepage_menu_id); home.setEnabled(!isHome); menu.findItem(R.id.forward_menu_id) .setEnabled(canGoForward); menu.findItem(R.id.new_tab_menu_id).setEnabled( mTabControl.getTabCount() < TabControl.MAX_TABS); // decide whether to show the share link option PackageManager pm = getPackageManager(); Intent send = new Intent(Intent.ACTION_SEND); send.setType("text/plain"); ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY); menu.findItem(R.id.share_page_menu_id).setVisible(ri != null); boolean isNavDump = mSettings.isNavDump(); final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id); nav.setVisible(isNavDump); nav.setEnabled(isNavDump); break; } mCurrentMenuState = mMenuState; return true; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { WebView webview = (WebView) v; WebView.HitTestResult result = webview.getHitTestResult(); if (result == null) { return; } int type = result.getType(); if (type == WebView.HitTestResult.UNKNOWN_TYPE) { Log.w(LOGTAG, "We should not show context menu when nothing is touched"); return; } if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) { // let TextView handles context menu return; } // Note, http://b/issue?id=1106666 is requesting that // an inflated menu can be used again. This is not available // yet, so inflate each time (yuk!) MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.browsercontext, menu); // Show the correct menu group String extra = result.getExtra(); menu.setGroupVisible(R.id.PHONE_MENU, type == WebView.HitTestResult.PHONE_TYPE); menu.setGroupVisible(R.id.EMAIL_MENU, type == WebView.HitTestResult.EMAIL_TYPE); menu.setGroupVisible(R.id.GEO_MENU, type == WebView.HitTestResult.GEO_TYPE); menu.setGroupVisible(R.id.IMAGE_MENU, type == WebView.HitTestResult.IMAGE_TYPE || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE); menu.setGroupVisible(R.id.ANCHOR_MENU, type == WebView.HitTestResult.SRC_ANCHOR_TYPE || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE); // Setup custom handling depending on the type switch (type) { case WebView.HitTestResult.PHONE_TYPE: menu.setHeaderTitle(Uri.decode(extra)); menu.findItem(R.id.dial_context_menu_id).setIntent( new Intent(Intent.ACTION_VIEW, Uri .parse(WebView.SCHEME_TEL + extra))); Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT); addIntent.putExtra(Insert.PHONE, Uri.decode(extra)); addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE); menu.findItem(R.id.add_contact_context_menu_id).setIntent( addIntent); menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener( new Copy(extra)); break; case WebView.HitTestResult.EMAIL_TYPE: menu.setHeaderTitle(extra); menu.findItem(R.id.email_context_menu_id).setIntent( new Intent(Intent.ACTION_VIEW, Uri .parse(WebView.SCHEME_MAILTO + extra))); menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener( new Copy(extra)); break; case WebView.HitTestResult.GEO_TYPE: menu.setHeaderTitle(extra); menu.findItem(R.id.map_context_menu_id).setIntent( new Intent(Intent.ACTION_VIEW, Uri .parse(WebView.SCHEME_GEO + URLEncoder.encode(extra)))); menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener( new Copy(extra)); break; case WebView.HitTestResult.SRC_ANCHOR_TYPE: case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE: TextView titleView = (TextView) LayoutInflater.from(this) .inflate(android.R.layout.browser_link_context_header, null); titleView.setText(extra); menu.setHeaderView(titleView); // decide whether to show the open link in new tab option menu.findItem(R.id.open_newtab_context_menu_id).setVisible( mTabControl.getTabCount() < TabControl.MAX_TABS); PackageManager pm = getPackageManager(); Intent send = new Intent(Intent.ACTION_SEND); send.setType("text/plain"); ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY); menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null); if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) { break; } // otherwise fall through to handle image part case WebView.HitTestResult.IMAGE_TYPE: if (type == WebView.HitTestResult.IMAGE_TYPE) { menu.setHeaderTitle(extra); } menu.findItem(R.id.view_image_context_menu_id).setIntent( new Intent(Intent.ACTION_VIEW, Uri.parse(extra))); menu.findItem(R.id.download_context_menu_id). setOnMenuItemClickListener(new Download(extra)); break; default: Log.w(LOGTAG, "We should not get here."); break; } } // Attach the given tab to the content view. // this should only be called for the current tab. private void attachTabToContentView(TabControl.Tab t) { // Attach the container that contains the main WebView and any other UI // associated with the tab. t.attachTabToContentView(mContentView); if (mShouldShowErrorConsole) { ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true); if (errorConsole.numberOfErrors() == 0) { errorConsole.showConsole(ErrorConsoleView.SHOW_NONE); } else { errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED); } mErrorConsoleContainer.addView(errorConsole, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } setLockIconType(t.getLockIconType()); setPrevLockType(t.getPrevLockIconType()); // this is to match the code in removeTabFromContentView() if (!mPageStarted && t.getTopWindow().getProgress() < 100) { mPageStarted = true; } WebView view = t.getWebView(); view.setEmbeddedTitleBar(mTitleBar); // Request focus on the top window. t.getTopWindow().requestFocus(); } // Attach a sub window to the main WebView of the given tab. private void attachSubWindow(TabControl.Tab t) { t.attachSubWindow(mContentView); getTopWindow().requestFocus(); } // Remove the given tab from the content view. private void removeTabFromContentView(TabControl.Tab t) { // Remove the container that contains the main WebView. t.removeTabFromContentView(mContentView); if (mTabControl.getCurrentErrorConsole(false) != null) { mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false)); } WebView view = t.getWebView(); if (view != null) { view.setEmbeddedTitleBar(null); } // unlike attachTabToContentView(), removeTabFromContentView() can be // called for the non-current tab. Need to add the check. if (t == mTabControl.getCurrentTab()) { t.setLockIconType(getLockIconType()); t.setPrevLockIconType(getPrevLockType()); // this is not a perfect solution. But currently there is one // WebViewClient for all the WebView. if user switches from an // in-load window to an already loaded window, mPageStarted will not // be set to false. If user leaves the Browser, pauseWebViewTimers() // won't do anything and leaves the timer running even Browser is in // the background. if (mPageStarted) { mPageStarted = false; } } } // Remove the sub window if it exists. Also called by TabControl when the // user clicks the 'X' to dismiss a sub window. /* package */ void dismissSubWindow(TabControl.Tab t) { t.removeSubWindow(mContentView); // Tell the TabControl to dismiss the subwindow. This will destroy // the WebView. mTabControl.dismissSubWindow(t); getTopWindow().requestFocus(); } // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)} // that accepts url as string. private TabControl.Tab openTabAndShow(String url, boolean closeOnExit, String appId) { return openTabAndShow(new UrlData(url), closeOnExit, appId); } // This method does a ton of stuff. It will attempt to create a new tab // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If // url isn't null, it will load the given url. /* package */ TabControl.Tab openTabAndShow(UrlData urlData, boolean closeOnExit, String appId) { final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS; final TabControl.Tab currentTab = mTabControl.getCurrentTab(); if (newTab) { final TabControl.Tab tab = mTabControl.createNewTab( closeOnExit, appId, urlData.mUrl); WebView webview = tab.getWebView(); // If the last tab was removed from the active tabs page, currentTab // will be null. if (currentTab != null) { removeTabFromContentView(currentTab); } // We must set the new tab as the current tab to reflect the old // animation behavior. mTabControl.setCurrentTab(tab); attachTabToContentView(tab); if (!urlData.isEmpty()) { urlData.loadIn(webview); } return tab; } else { // Get rid of the subwindow if it exists dismissSubWindow(currentTab); if (!urlData.isEmpty()) { // Load the given url. urlData.loadIn(currentTab.getWebView()); } } return currentTab; } private TabControl.Tab openTab(String url) { if (mSettings.openInBackground()) { TabControl.Tab t = mTabControl.createNewTab(); if (t != null) { WebView view = t.getWebView(); view.loadUrl(url); } return t; } else { return openTabAndShow(url, false, null); } } private class Copy implements OnMenuItemClickListener { private CharSequence mText; public boolean onMenuItemClick(MenuItem item) { copy(mText); return true; } public Copy(CharSequence toCopy) { mText = toCopy; } } private class Download implements OnMenuItemClickListener { private String mText; public boolean onMenuItemClick(MenuItem item) { onDownloadStartNoStream(mText, null, null, null, -1); return true; } public Download(String toDownload) { mText = toDownload; } } private void copy(CharSequence text) { try { IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard")); if (clip != null) { clip.setClipboardText(text); } } catch (android.os.RemoteException e) { Log.e(LOGTAG, "Copy failed", e); } } /** * Resets the browser title-view to whatever it must be * (for example, if we had a loading error) * When we have a new page, we call resetTitle, when we * have to reset the titlebar to whatever it used to be * (for example, if the user chose to stop loading), we * call resetTitleAndRevertLockIcon. */ /* package */ void resetTitleAndRevertLockIcon() { revertLockIcon(); resetTitleIconAndProgress(); } /** * Reset the title, favicon, and progress. */ private void resetTitleIconAndProgress() { WebView current = mTabControl.getCurrentWebView(); if (current == null) { return; } resetTitleAndIcon(current); int progress = current.getProgress(); mWebChromeClient.onProgressChanged(current, progress); } // Reset the title and the icon based on the given item. private void resetTitleAndIcon(WebView view) { WebHistoryItem item = view.copyBackForwardList().getCurrentItem(); if (item != null) { setUrlTitle(item.getUrl(), item.getTitle()); setFavicon(item.getFavicon()); } else { setUrlTitle(null, null); setFavicon(null); } } /** * Sets a title composed of the URL and the title string. * @param url The URL of the site being loaded. * @param title The title of the site being loaded. */ private void setUrlTitle(String url, String title) { mUrl = url; mTitle = title; mTitleBar.setTitleAndUrl(title, url); if (mFakeTitleBar != null) { mFakeTitleBar.setTitleAndUrl(title, url); } } /** * @param url The URL to build a title version of the URL from. * @return The title version of the URL or null if fails. * The title version of the URL can be either the URL hostname, * or the hostname with an "https://" prefix (for secure URLs), * or an empty string if, for example, the URL in question is a * file:// URL with no hostname. */ /* package */ static String buildTitleUrl(String url) { String titleUrl = null; if (url != null) { try { // parse the url string URL urlObj = new URL(url); if (urlObj != null) { titleUrl = ""; String protocol = urlObj.getProtocol(); String host = urlObj.getHost(); if (host != null && 0 < host.length()) { titleUrl = host; if (protocol != null) { // if a secure site, add an "https://" prefix! if (protocol.equalsIgnoreCase("https")) { titleUrl = protocol + "://" + host; } } } } } catch (MalformedURLException e) {} } return titleUrl; } // Set the favicon in the title bar. private void setFavicon(Bitmap icon) { mTitleBar.setFavicon(icon); if (mFakeTitleBar != null) { mFakeTitleBar.setFavicon(icon); } } /** * Saves the current lock-icon state before resetting * the lock icon. If we have an error, we may need to * roll back to the previous state. */ private void saveLockIcon() { mPrevLockType = mLockIconType; } /** * Reverts the lock-icon state to the last saved state, * for example, if we had an error, and need to cancel * the load. */ private void revertLockIcon() { mLockIconType = mPrevLockType; if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" + " revert lock icon to " + mLockIconType); } updateLockIconToLatest(); } /** * Close the tab, remove its associated title bar, and adjust mTabControl's * current tab to a valid value. */ /* package */ void closeTab(TabControl.Tab t) { int currentIndex = mTabControl.getCurrentIndex(); int removeIndex = mTabControl.getTabIndex(t); mTabControl.removeTab(t); if (currentIndex >= removeIndex && currentIndex != 0) { currentIndex--; } mTabControl.setCurrentTab(mTabControl.getTab(currentIndex)); resetTitleIconAndProgress(); } private void goBackOnePageOrQuit() { TabControl.Tab current = mTabControl.getCurrentTab(); if (current == null) { /* * Instead of finishing the activity, simply push this to the back * of the stack and let ActivityManager to choose the foreground * activity. As BrowserActivity is singleTask, it will be always the * root of the task. So we can use either true or false for * moveTaskToBack(). */ moveTaskToBack(true); return; } WebView w = current.getWebView(); if (w.canGoBack()) { w.goBack(); } else { // Check to see if we are closing a window that was created by // another window. If so, we switch back to that window. TabControl.Tab parent = current.getParentTab(); if (parent != null) { switchToTab(mTabControl.getTabIndex(parent)); // Now we close the other tab closeTab(current); } else { if (current.closeOnExit()) { // force mPageStarted to be false as we are going to either // finish the activity or remove the tab. This will ensure // pauseWebView() taking action. mPageStarted = false; if (mTabControl.getTabCount() == 1) { finish(); return; } // call pauseWebViewTimers() now, we won't be able to call // it in onPause() as the WebView won't be valid. // Temporarily change mActivityInPause to be true as // pauseWebViewTimers() will do nothing if mActivityInPause // is false. boolean savedState = mActivityInPause; if (savedState) { Log.e(LOGTAG, "BrowserActivity is already paused " + "while handing goBackOnePageOrQuit."); } mActivityInPause = true; pauseWebViewTimers(); mActivityInPause = savedState; removeTabFromContentView(current); mTabControl.removeTab(current); } /* * Instead of finishing the activity, simply push this to the back * of the stack and let ActivityManager to choose the foreground * activity. As BrowserActivity is singleTask, it will be always the * root of the task. So we can use either true or false for * moveTaskToBack(). */ moveTaskToBack(true); } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is // still down, we don't want to trigger the search. Pretend to consume // the key and do nothing. if (mMenuIsDown) return true; switch(keyCode) { case KeyEvent.KEYCODE_MENU: mMenuIsDown = true; break; case KeyEvent.KEYCODE_SPACE: // WebView/WebTextView handle the keys in the KeyDown. As // the Activity's shortcut keys are only handled when WebView // doesn't, have to do it in onKeyDown instead of onKeyUp. if (event.isShiftPressed()) { getTopWindow().pageUp(false); } else { getTopWindow().pageDown(false); } return true; case KeyEvent.KEYCODE_BACK: if (event.getRepeatCount() == 0) { event.startTracking(); return true; } else if (mCustomView == null && mActiveTabsPage == null && event.isLongPress()) { bookmarksOrHistoryPicker(true); return true; } break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode) { case KeyEvent.KEYCODE_MENU: mMenuIsDown = false; break; case KeyEvent.KEYCODE_BACK: if (event.isTracking() && !event.isCanceled()) { if (mCustomView != null) { // if a custom view is showing, hide it mWebChromeClient.onHideCustomView(); } else if (mActiveTabsPage != null) { // if tab page is showing, hide it removeActiveTabPage(true); } else { WebView subwindow = mTabControl.getCurrentSubWindow(); if (subwindow != null) { if (subwindow.canGoBack()) { subwindow.goBack(); } else { dismissSubWindow(mTabControl.getCurrentTab()); } } else { goBackOnePageOrQuit(); } } return true; } break; } return super.onKeyUp(keyCode, event); } /* package */ void stopLoading() { mDidStopLoad = true; resetTitleAndRevertLockIcon(); WebView w = getTopWindow(); w.stopLoading(); mWebViewClient.onPageFinished(w, w.getUrl()); cancelStopToast(); mStopToast = Toast .makeText(this, R.string.stopping, Toast.LENGTH_SHORT); mStopToast.show(); } private void cancelStopToast() { if (mStopToast != null) { mStopToast.cancel(); mStopToast = null; } } // called by a non-UI thread to post the message public void postMessage(int what, int arg1, int arg2, Object obj) { mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj)); } // public message ids public final static int LOAD_URL = 1001; public final static int STOP_LOAD = 1002; // Message Ids private static final int FOCUS_NODE_HREF = 102; private static final int CANCEL_CREDS_REQUEST = 103; private static final int RELEASE_WAKELOCK = 107; private static final int UPDATE_BOOKMARK_THUMBNAIL = 108; // Private handler for handling javascript and saving passwords private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case FOCUS_NODE_HREF: { String url = (String) msg.getData().get("url"); if (url == null || url.length() == 0) { break; } HashMap focusNodeMap = (HashMap) msg.obj; WebView view = (WebView) focusNodeMap.get("webview"); // Only apply the action if the top window did not change. if (getTopWindow() != view) { break; } switch (msg.arg1) { case R.id.open_context_menu_id: case R.id.view_image_context_menu_id: loadURL(getTopWindow(), url); break; case R.id.open_newtab_context_menu_id: final TabControl.Tab parent = mTabControl .getCurrentTab(); final TabControl.Tab newTab = openTab(url); if (newTab != parent) { parent.addChildTab(newTab); } break; case R.id.bookmark_context_menu_id: Intent intent = new Intent(BrowserActivity.this, AddBookmarkPage.class); intent.putExtra("url", url); startActivity(intent); break; case R.id.share_link_context_menu_id: Browser.sendString(BrowserActivity.this, url, getText(R.string.choosertitle_sharevia).toString()); break; case R.id.copy_link_context_menu_id: copy(url); break; case R.id.save_link_context_menu_id: case R.id.download_context_menu_id: onDownloadStartNoStream(url, null, null, null, -1); break; } break; } case LOAD_URL: loadURL(getTopWindow(), (String) msg.obj); break; case STOP_LOAD: stopLoading(); break; case CANCEL_CREDS_REQUEST: resumeAfterCredentials(); break; case RELEASE_WAKELOCK: if (mWakeLock.isHeld()) { mWakeLock.release(); } break; case UPDATE_BOOKMARK_THUMBNAIL: WebView view = (WebView) msg.obj; if (view != null) { updateScreenshot(view); } break; } } }; private void updateScreenshot(WebView view) { // If this is a bookmarked site, add a screenshot to the database. // FIXME: When should we update? Every time? // FIXME: Would like to make sure there is actually something to // draw, but the API for that (WebViewCore.pictureReady()) is not // currently accessible here. ContentResolver cr = getContentResolver(); final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl( cr, view.getOriginalUrl(), view.getUrl(), true); if (c != null) { boolean succeed = c.moveToFirst(); ContentValues values = null; while (succeed) { if (values == null) { final ByteArrayOutputStream os = new ByteArrayOutputStream(); Bitmap bm = createScreenshot(view); if (bm == null) { c.close(); return; } bm.compress(Bitmap.CompressFormat.PNG, 100, os); values = new ContentValues(); values.put(Browser.BookmarkColumns.THUMBNAIL, os.toByteArray()); } cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI, c.getInt(0)), values, null, null); succeed = c.moveToNext(); } c.close(); } } /** * Values for the size of the thumbnail created when taking a screenshot. * Lazily initialized. Instead of using these directly, use * getDesiredThumbnailWidth() or getDesiredThumbnailHeight(). */ private static int THUMBNAIL_WIDTH = 0; private static int THUMBNAIL_HEIGHT = 0; /** * Return the desired width for thumbnail screenshots, which are stored in * the database, and used on the bookmarks screen. * @param context Context for finding out the density of the screen. * @return int desired width for thumbnail screenshot. */ /* package */ static int getDesiredThumbnailWidth(Context context) { if (THUMBNAIL_WIDTH == 0) { float density = context.getResources().getDisplayMetrics().density; THUMBNAIL_WIDTH = (int) (90 * density); THUMBNAIL_HEIGHT = (int) (80 * density); } return THUMBNAIL_WIDTH; } /** * Return the desired height for thumbnail screenshots, which are stored in * the database, and used on the bookmarks screen. * @param context Context for finding out the density of the screen. * @return int desired height for thumbnail screenshot. */ /* package */ static int getDesiredThumbnailHeight(Context context) { // To ensure that they are both initialized. getDesiredThumbnailWidth(context); return THUMBNAIL_HEIGHT; } private Bitmap createScreenshot(WebView view) { Picture thumbnail = view.capturePicture(); if (thumbnail == null) { return null; } Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this), getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444); Canvas canvas = new Canvas(bm); // May need to tweak these values to determine what is the // best scale factor int thumbnailWidth = thumbnail.getWidth(); if (thumbnailWidth > 0) { float scaleFactor = (float) getDesiredThumbnailWidth(this) / (float)thumbnailWidth; canvas.scale(scaleFactor, scaleFactor); } thumbnail.draw(canvas); return bm; } // ------------------------------------------------------------------------- // WebViewClient implementation. //------------------------------------------------------------------------- // Use in overrideUrlLoading /* package */ final static String SCHEME_WTAI = "wtai://wp/"; /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;"; /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;"; /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;"; /* package */ WebViewClient getWebViewClient() { return mWebViewClient; } private void updateIcon(WebView view, Bitmap icon) { if (icon != null) { BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver, view.getOriginalUrl(), view.getUrl(), icon); } setFavicon(icon); } private void updateIcon(String url, Bitmap icon) { if (icon != null) { BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver, null, url, icon); } setFavicon(icon); } private final WebViewClient mWebViewClient = new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { resetLockIcon(url); setUrlTitle(url, null); // We've started to load a new page. If there was a pending message // to save a screenshot then we will now take the new page and // save an incorrect screenshot. Therefore, remove any pending // thumbnail messages from the queue. mHandler.removeMessages(UPDATE_BOOKMARK_THUMBNAIL); // If we start a touch icon load and then load a new page, we don't // want to cancel the current touch icon loader. But, we do want to // create a new one when the touch icon url is known. if (mTouchIconLoader != null) { mTouchIconLoader.mActivity = null; mTouchIconLoader = null; } ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false); if (errorConsole != null) { errorConsole.clearErrorMessages(); if (mShouldShowErrorConsole) { errorConsole.showConsole(ErrorConsoleView.SHOW_NONE); } } // Call updateIcon instead of setFavicon so the bookmark // database can be updated. updateIcon(url, favicon); if (mSettings.isTracing()) { String host; try { WebAddress uri = new WebAddress(url); host = uri.mHost; } catch (android.net.ParseException ex) { host = "browser"; } host = host.replace('.', '_'); host += ".trace"; mInTrace = true; Debug.startMethodTracing(host, 20 * 1024 * 1024); } // Performance probe if (false) { mStart = SystemClock.uptimeMillis(); mProcessStart = Process.getElapsedCpuTime(); long[] sysCpu = new long[7]; if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null, sysCpu, null)) { mUserStart = sysCpu[0] + sysCpu[1]; mSystemStart = sysCpu[2]; mIdleStart = sysCpu[3]; mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6]; } mUiStart = SystemClock.currentThreadTimeMillis(); } if (!mPageStarted) { mPageStarted = true; // if onResume() has been called, resumeWebViewTimers() does // nothing. resumeWebViewTimers(); } // reset sync timer to avoid sync starts during loading a page CookieSyncManager.getInstance().resetSync(); mInLoad = true; mDidStopLoad = false; showFakeTitleBar(); updateInLoadMenuItems(); if (!mIsNetworkUp) { createAndShowNetworkDialog(); if (view != null) { view.setNetworkAvailable(false); } } } @Override public void onPageFinished(WebView view, String url) { // Reset the title and icon in case we stopped a provisional // load. resetTitleAndIcon(view); if (!mDidStopLoad) { // Only update the bookmark screenshot if the user did not // cancel the load early. Message updateScreenshot = Message.obtain(mHandler, UPDATE_BOOKMARK_THUMBNAIL, view); mHandler.sendMessageDelayed(updateScreenshot, 500); } // Update the lock icon image only once we are done loading updateLockIconToLatest(); // Performance probe if (false) { long[] sysCpu = new long[7]; if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null, sysCpu, null)) { String uiInfo = "UI thread used " + (SystemClock.currentThreadTimeMillis() - mUiStart) + " ms"; if (LOGD_ENABLED) { Log.d(LOGTAG, uiInfo); } //The string that gets written to the log String performanceString = "It took total " + (SystemClock.uptimeMillis() - mStart) + " ms clock time to load the page." + "\nbrowser process used " + (Process.getElapsedCpuTime() - mProcessStart) + " ms, user processes used " + (sysCpu[0] + sysCpu[1] - mUserStart) * 10 + " ms, kernel used " + (sysCpu[2] - mSystemStart) * 10 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10 + " ms and irq took " + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart) * 10 + " ms, " + uiInfo; if (LOGD_ENABLED) { Log.d(LOGTAG, performanceString + "\nWebpage: " + url); } if (url != null) { // strip the url to maintain consistency String newUrl = new String(url); if (newUrl.startsWith("http://www.")) { newUrl = newUrl.substring(11); } else if (newUrl.startsWith("http://")) { newUrl = newUrl.substring(7); } else if (newUrl.startsWith("https://www.")) { newUrl = newUrl.substring(12); } else if (newUrl.startsWith("https://")) { newUrl = newUrl.substring(8); } if (LOGD_ENABLED) { Log.d(LOGTAG, newUrl + " loaded"); } /* if (sWhiteList.contains(newUrl)) { // The string that gets pushed to the statistcs // service performanceString = performanceString + "\nWebpage: " + newUrl + "\nCarrier: " + android.os.SystemProperties .get("gsm.sim.operator.alpha"); if (mWebView != null && mWebView.getContext() != null && mWebView.getContext().getSystemService( Context.CONNECTIVITY_SERVICE) != null) { ConnectivityManager cManager = (ConnectivityManager) mWebView .getContext().getSystemService( Context.CONNECTIVITY_SERVICE); NetworkInfo nInfo = cManager .getActiveNetworkInfo(); if (nInfo != null) { performanceString = performanceString + "\nNetwork Type: " + nInfo.getType().toString(); } } Checkin.logEvent(mResolver, Checkin.Events.Tag.WEBPAGE_LOAD, performanceString); Log.w(LOGTAG, "pushed to the statistics service"); } */ } } } if (mInTrace) { mInTrace = false; Debug.stopMethodTracing(); } if (mPageStarted) { mPageStarted = false; // pauseWebViewTimers() will do nothing and return false if // onPause() is not called yet. if (pauseWebViewTimers()) { if (mWakeLock.isHeld()) { mHandler.removeMessages(RELEASE_WAKELOCK); mWakeLock.release(); } } } } // return true if want to hijack the url to let another app to handle it @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith(SCHEME_WTAI)) { // wtai://wp/mc;number // number=string(phone-number) if (url.startsWith(SCHEME_WTAI_MC)) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(WebView.SCHEME_TEL + url.substring(SCHEME_WTAI_MC.length()))); startActivity(intent); return true; } // wtai://wp/sd;dtmf // dtmf=string(dialstring) if (url.startsWith(SCHEME_WTAI_SD)) { // TODO // only send when there is active voice connection return false; } // wtai://wp/ap;number;name // number=string(phone-number) // name=string if (url.startsWith(SCHEME_WTAI_AP)) { // TODO return false; } } // The "about:" schemes are internal to the browser; don't // want these to be dispatched to other apps. if (url.startsWith("about:")) { return false; } Intent intent; // perform generic parsing of the URI to turn it into an Intent. try { intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME); } catch (URISyntaxException ex) { Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage()); return false; } // check whether the intent can be resolved. If not, we will see // whether we can download it from the Market. if (getPackageManager().resolveActivity(intent, 0) == null) { String packagename = intent.getPackage(); if (packagename != null) { intent = new Intent(Intent.ACTION_VIEW, Uri .parse("market://search?q=pname:" + packagename)); intent.addCategory(Intent.CATEGORY_BROWSABLE); startActivity(intent); return true; } else { return false; } } // sanitize the Intent, ensuring web pages can not bypass browser // security (only access to BROWSABLE activities). intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setComponent(null); try { if (startActivityIfNeeded(intent, -1)) { return true; } } catch (ActivityNotFoundException ex) { // ignore the error. If no application can handle the URL, // eg about:blank, assume the browser can handle it. } if (mMenuIsDown) { openTab(url); closeOptionsMenu(); return true; } return false; } /** * Updates the lock icon. This method is called when we discover another * resource to be loaded for this page (for example, javascript). While * we update the icon type, we do not update the lock icon itself until * we are done loading, it is slightly more secure this way. */ @Override public void onLoadResource(WebView view, String url) { if (url != null && url.length() > 0) { // It is only if the page claims to be secure // that we may have to update the lock: if (mLockIconType == LOCK_ICON_SECURE) { // If NOT a 'safe' url, change the lock to mixed content! if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) { mLockIconType = LOCK_ICON_MIXED; if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" + " updated lock icon to " + mLockIconType + " due to " + url); } } } } } /** * Show the dialog, asking the user if they would like to continue after * an excessive number of HTTP redirects. */ @Override public void onTooManyRedirects(WebView view, final Message cancelMsg, final Message continueMsg) { new AlertDialog.Builder(BrowserActivity.this) .setTitle(R.string.browserFrameRedirect) .setMessage(R.string.browserFrame307Post) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { continueMsg.sendToTarget(); }}) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { cancelMsg.sendToTarget(); }}) .setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { cancelMsg.sendToTarget(); }}) .show(); } // Container class for the next error dialog that needs to be // displayed. class ErrorDialog { public final int mTitle; public final String mDescription; public final int mError; ErrorDialog(int title, String desc, int error) { mTitle = title; mDescription = desc; mError = error; } }; private void processNextError() { if (mQueuedErrors == null) { return; } // The first one is currently displayed so just remove it. mQueuedErrors.removeFirst(); if (mQueuedErrors.size() == 0) { mQueuedErrors = null; return; } showError(mQueuedErrors.getFirst()); } private DialogInterface.OnDismissListener mDialogListener = new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface d) { processNextError(); } }; private LinkedList<ErrorDialog> mQueuedErrors; private void queueError(int err, String desc) { if (mQueuedErrors == null) { mQueuedErrors = new LinkedList<ErrorDialog>(); } for (ErrorDialog d : mQueuedErrors) { if (d.mError == err) { // Already saw a similar error, ignore the new one. return; } } ErrorDialog errDialog = new ErrorDialog( err == WebViewClient.ERROR_FILE_NOT_FOUND ? R.string.browserFrameFileErrorLabel : R.string.browserFrameNetworkErrorLabel, desc, err); mQueuedErrors.addLast(errDialog); // Show the dialog now if the queue was empty. if (mQueuedErrors.size() == 1) { showError(errDialog); } } private void showError(ErrorDialog errDialog) { AlertDialog d = new AlertDialog.Builder(BrowserActivity.this) .setTitle(errDialog.mTitle) .setMessage(errDialog.mDescription) .setPositiveButton(R.string.ok, null) .create(); d.setOnDismissListener(mDialogListener); d.show(); } /** * Show a dialog informing the user of the network error reported by * WebCore. */ @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { if (errorCode != WebViewClient.ERROR_HOST_LOOKUP && errorCode != WebViewClient.ERROR_CONNECT && errorCode != WebViewClient.ERROR_BAD_URL && errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME && errorCode != WebViewClient.ERROR_FILE) { queueError(errorCode, description); } Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl + " " + description); // We need to reset the title after an error. resetTitleAndRevertLockIcon(); } /** * Check with the user if it is ok to resend POST data as the page they * are trying to navigate to is the result of a POST. */ @Override public void onFormResubmission(WebView view, final Message dontResend, final Message resend) { new AlertDialog.Builder(BrowserActivity.this) .setTitle(R.string.browserFrameFormResubmitLabel) .setMessage(R.string.browserFrameFormResubmitMessage) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { resend.sendToTarget(); }}) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dontResend.sendToTarget(); }}) .setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { dontResend.sendToTarget(); }}) .show(); } /** * Insert the url into the visited history database. * @param url The url to be inserted. * @param isReload True if this url is being reloaded. * FIXME: Not sure what to do when reloading the page. */ @Override public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { if (url.regionMatches(true, 0, "about:", 0, 6)) { return; } // remove "client" before updating it to the history so that it wont // show up in the auto-complete list. int index = url.indexOf("client=ms-"); if (index > 0 && url.contains(".google.")) { int end = url.indexOf('&', index); if (end > 0) { url = url.substring(0, index-1).concat(url.substring(end)); } else { url = url.substring(0, index-1); } } Browser.updateVisitedHistory(mResolver, url, true); WebIconDatabase.getInstance().retainIconForPageUrl(url); } /** * Displays SSL error(s) dialog to the user. */ @Override public void onReceivedSslError( final WebView view, final SslErrorHandler handler, final SslError error) { if (mSettings.showSecurityWarnings()) { final LayoutInflater factory = LayoutInflater.from(BrowserActivity.this); final View warningsView = factory.inflate(R.layout.ssl_warnings, null); final LinearLayout placeholder = (LinearLayout)warningsView.findViewById(R.id.placeholder); if (error.hasError(SslError.SSL_UNTRUSTED)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, null); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_untrusted); placeholder.addView(ll); } if (error.hasError(SslError.SSL_IDMISMATCH)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, null); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_mismatch); placeholder.addView(ll); } if (error.hasError(SslError.SSL_EXPIRED)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, null); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_expired); placeholder.addView(ll); } if (error.hasError(SslError.SSL_NOTYETVALID)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, null); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_not_yet_valid); placeholder.addView(ll); } new AlertDialog.Builder(BrowserActivity.this) .setTitle(R.string.security_warning) .setIcon(android.R.drawable.ic_dialog_alert) .setView(warningsView) .setPositiveButton(R.string.ssl_continue, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { handler.proceed(); } }) .setNeutralButton(R.string.view_certificate, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { showSSLCertificateOnError(view, handler, error); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { handler.cancel(); BrowserActivity.this.resetTitleAndRevertLockIcon(); } }) .setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { handler.cancel(); BrowserActivity.this.resetTitleAndRevertLockIcon(); } }) .show(); } else { handler.proceed(); } } /** * Handles an HTTP authentication request. * * @param handler The authentication handler * @param host The host * @param realm The realm */ @Override public void onReceivedHttpAuthRequest(WebView view, final HttpAuthHandler handler, final String host, final String realm) { String username = null; String password = null; boolean reuseHttpAuthUsernamePassword = handler.useHttpAuthUsernamePassword(); if (reuseHttpAuthUsernamePassword && (mTabControl.getCurrentWebView() != null)) { String[] credentials = mTabControl.getCurrentWebView() .getHttpAuthUsernamePassword(host, realm); if (credentials != null && credentials.length == 2) { username = credentials[0]; password = credentials[1]; } } if (username != null && password != null) { handler.proceed(username, password); } else { showHttpAuthentication(handler, host, realm, null, null, null, 0); } } @Override public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { if (mMenuIsDown) { // only check shortcut key when MENU is held return getWindow().isShortcutKey(event.getKeyCode(), event); } else { return false; } } @Override public void onUnhandledKeyEvent(WebView view, KeyEvent event) { if (view != mTabControl.getCurrentTopWebView()) { return; } if (event.isDown()) { BrowserActivity.this.onKeyDown(event.getKeyCode(), event); } else { BrowserActivity.this.onKeyUp(event.getKeyCode(), event); } } }; //-------------------------------------------------------------------------- // WebChromeClient implementation //-------------------------------------------------------------------------- /* package */ WebChromeClient getWebChromeClient() { return mWebChromeClient; } private final WebChromeClient mWebChromeClient = new WebChromeClient() { // Helper method to create a new tab or sub window. private void createWindow(final boolean dialog, final Message msg) { if (dialog) { mTabControl.createSubWindow(); final TabControl.Tab t = mTabControl.getCurrentTab(); attachSubWindow(t); WebView.WebViewTransport transport = (WebView.WebViewTransport) msg.obj; transport.setWebView(t.getSubWebView()); msg.sendToTarget(); } else { final TabControl.Tab parent = mTabControl.getCurrentTab(); final TabControl.Tab newTab = openTabAndShow(EMPTY_URL_DATA, false, null); if (newTab != parent) { parent.addChildTab(newTab); } WebView.WebViewTransport transport = (WebView.WebViewTransport) msg.obj; transport.setWebView(mTabControl.getCurrentWebView()); msg.sendToTarget(); } } @Override public boolean onCreateWindow(WebView view, final boolean dialog, final boolean userGesture, final Message resultMsg) { // Short-circuit if we can't create any more tabs or sub windows. if (dialog && mTabControl.getCurrentSubWindow() != null) { new AlertDialog.Builder(BrowserActivity.this) .setTitle(R.string.too_many_subwindows_dialog_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.too_many_subwindows_dialog_message) .setPositiveButton(R.string.ok, null) .show(); return false; } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) { new AlertDialog.Builder(BrowserActivity.this) .setTitle(R.string.too_many_windows_dialog_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.too_many_windows_dialog_message) .setPositiveButton(R.string.ok, null) .show(); return false; } // Short-circuit if this was a user gesture. if (userGesture) { createWindow(dialog, resultMsg); return true; } // Allow the popup and create the appropriate window. final AlertDialog.OnClickListener allowListener = new AlertDialog.OnClickListener() { public void onClick(DialogInterface d, int which) { createWindow(dialog, resultMsg); } }; // Block the popup by returning a null WebView. final AlertDialog.OnClickListener blockListener = new AlertDialog.OnClickListener() { public void onClick(DialogInterface d, int which) { resultMsg.sendToTarget(); } }; // Build a confirmation dialog to display to the user. final AlertDialog d = new AlertDialog.Builder(BrowserActivity.this) .setTitle(R.string.attention) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.popup_window_attempt) .setPositiveButton(R.string.allow, allowListener) .setNegativeButton(R.string.block, blockListener) .setCancelable(false) .create(); // Show the confirmation dialog. d.show(); return true; } @Override public void onCloseWindow(WebView window) { final TabControl.Tab current = mTabControl.getCurrentTab(); final TabControl.Tab parent = current.getParentTab(); if (parent != null) { // JavaScript can only close popup window. switchToTab(mTabControl.getTabIndex(parent)); // Now we need to close the window closeTab(current); } } @Override public void onProgressChanged(WebView view, int newProgress) { mTitleBar.setProgress(newProgress); if (mFakeTitleBar != null) { mFakeTitleBar.setProgress(newProgress); } if (newProgress == 100) { // onProgressChanged() may continue to be called after the main // frame has finished loading, as any remaining sub frames // continue to load. We'll only get called once though with // newProgress as 100 when everything is loaded. // (onPageFinished is called once when the main frame completes // loading regardless of the state of any sub frames so calls // to onProgressChanges may continue after onPageFinished has // executed) // sync cookies and cache promptly here. CookieSyncManager.getInstance().sync(); if (mInLoad) { mInLoad = false; updateInLoadMenuItems(); // If the options menu is open, leave the title bar if (!mOptionsMenuOpen || !mIconView) { hideFakeTitleBar(); } } } else if (!mInLoad) { // onPageFinished may have already been called but a subframe // is still loading and updating the progress. Reset mInLoad // and update the menu items. mInLoad = true; updateInLoadMenuItems(); if (!mOptionsMenuOpen || mIconView) { // This page has begun to load, so show the title bar showFakeTitleBar(); } } } @Override public void onReceivedTitle(WebView view, String title) { String url = view.getUrl(); // here, if url is null, we want to reset the title setUrlTitle(url, title); if (url == null || url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) { return; } // See if we can find the current url in our history database and // add the new title to it. if (url.startsWith("http://www.")) { url = url.substring(11); } else if (url.startsWith("http://")) { url = url.substring(4); } try { url = "%" + url; String [] selArgs = new String[] { url }; String where = Browser.BookmarkColumns.URL + " LIKE ? AND " + Browser.BookmarkColumns.BOOKMARK + " = 0"; Cursor c = mResolver.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, where, selArgs, null); if (c.moveToFirst()) { // Current implementation of database only has one entry per // url. ContentValues map = new ContentValues(); map.put(Browser.BookmarkColumns.TITLE, title); mResolver.update(Browser.BOOKMARKS_URI, map, "_id = " + c.getInt(0), null); } c.close(); } catch (IllegalStateException e) { Log.e(LOGTAG, "BrowserActivity onReceived title", e); } catch (SQLiteException ex) { Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex); } } @Override public void onReceivedIcon(WebView view, Bitmap icon) { updateIcon(view, icon); } @Override public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) { final ContentResolver cr = getContentResolver(); final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(cr, view.getOriginalUrl(), view.getUrl(), true); if (c != null) { if (c.getCount() > 0) { // Let precomposed icons take precedence over non-composed // icons. if (precomposed && mTouchIconLoader != null) { mTouchIconLoader.cancel(false); mTouchIconLoader = null; } // Have only one async task at a time. if (mTouchIconLoader == null) { mTouchIconLoader = new DownloadTouchIcon( BrowserActivity.this, cr, c, view); mTouchIconLoader.execute(url); } } else { c.close(); } } } @Override public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) { if (mCustomView != null) return; // Add the custom view to its container. mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER); mCustomView = view; mCustomViewCallback = callback; // Save the menu state and set it to empty while the custom // view is showing. mOldMenuState = mMenuState; mMenuState = EMPTY_MENU; // Hide the content view. mContentView.setVisibility(View.GONE); // Finally show the custom view container. mCustomViewContainer.setVisibility(View.VISIBLE); mCustomViewContainer.bringToFront(); } @Override public void onHideCustomView() { if (mCustomView == null) return; // Hide the custom view. mCustomView.setVisibility(View.GONE); // Remove the custom view from its container. mCustomViewContainer.removeView(mCustomView); mCustomView = null; // Reset the old menu state. mMenuState = mOldMenuState; mOldMenuState = EMPTY_MENU; mCustomViewContainer.setVisibility(View.GONE); mCustomViewCallback.onCustomViewHidden(); // Show the content view. mContentView.setVisibility(View.VISIBLE); } /** * The origin has exceeded its database quota. * @param url the URL that exceeded the quota * @param databaseIdentifier the identifier of the database on * which the transaction that caused the quota overflow was run * @param currentQuota the current quota for the origin. * @param estimatedSize the estimated size of the database. * @param totalUsedQuota is the sum of all origins' quota. * @param quotaUpdater The callback to run when a decision to allow or * deny quota has been made. Don't forget to call this! */ @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { mSettings.getWebStorageSizeManager().onExceededDatabaseQuota( url, databaseIdentifier, currentQuota, estimatedSize, totalUsedQuota, quotaUpdater); } /** * The Application Cache has exceeded its max size. * @param spaceNeeded is the amount of disk space that would be needed * in order for the last appcache operation to succeed. * @param totalUsedQuota is the sum of all origins' quota. * @param quotaUpdater A callback to inform the WebCore thread that a new * app cache size is available. This callback must always be executed at * some point to ensure that the sleeping WebCore thread is woken up. */ @Override public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize( spaceNeeded, totalUsedQuota, quotaUpdater); } /** * Instructs the browser to show a prompt to ask the user to set the * Geolocation permission state for the specified origin. * @param origin The origin for which Geolocation permissions are * requested. * @param callback The callback to call once the user has set the * Geolocation permission state. */ @Override public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show( origin, callback); } /** * Instructs the browser to hide the Geolocation permissions prompt. */ @Override public void onGeolocationPermissionsHidePrompt() { mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide(); } /* Adds a JavaScript error message to the system log. * @param message The error message to report. * @param lineNumber The line number of the error. * @param sourceID The name of the source file that caused the error. */ @Override public void addMessageToConsole(String message, int lineNumber, String sourceID) { ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true); errorConsole.addErrorMessage(message, sourceID, lineNumber); if (mShouldShowErrorConsole && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) { errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED); } Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber); } /** * Ask the browser for an icon to represent a <video> element. * This icon will be used if the Web page did not specify a poster attribute. * * @return Bitmap The icon or null if no such icon is available. * @hide pending API Council approval */ @Override public Bitmap getDefaultVideoPoster() { if (mDefaultVideoPoster == null) { mDefaultVideoPoster = BitmapFactory.decodeResource( getResources(), R.drawable.default_video_poster); } return mDefaultVideoPoster; } /** * Ask the host application for a custom progress view to show while * a <video> is loading. * * @return View The progress view. * @hide pending API Council approval */ @Override public View getVideoLoadingProgressView() { if (mVideoProgressView == null) { LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this); mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null); } return mVideoProgressView; } }; /** * Notify the host application a download should be done, or that * the data should be streamed if a streaming viewer is available. * @param url The full url to the content that should be downloaded * @param contentDisposition Content-disposition http header, if * present. * @param mimetype The mimetype of the content reported by the server * @param contentLength The file size reported by the server */ public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { // if we're dealing wih A/V content that's not explicitly marked // for download, check if it's streamable. if (contentDisposition == null || !contentDisposition.regionMatches( true, 0, "attachment", 0, 10)) { // query the package manager to see if there's a registered handler // that matches. Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse(url), mimetype); ResolveInfo info = getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY); if (info != null) { ComponentName myName = getComponentName(); // If we resolved to ourselves, we don't want to attempt to // load the url only to try and download it again. if (!myName.getPackageName().equals( info.activityInfo.packageName) || !myName.getClassName().equals( info.activityInfo.name)) { // someone (other than us) knows how to handle this mime // type with this scheme, don't download. try { startActivity(intent); return; } catch (ActivityNotFoundException ex) { if (LOGD_ENABLED) { Log.d(LOGTAG, "activity not found for " + mimetype + " over " + Uri.parse(url).getScheme(), ex); } // Best behavior is to fall back to a download in this // case } } } } onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength); } /** * Notify the host application a download should be done, even if there * is a streaming viewer available for thise type. * @param url The full url to the content that should be downloaded * @param contentDisposition Content-disposition http header, if * present. * @param mimetype The mimetype of the content reported by the server * @param contentLength The file size reported by the server */ /*package */ void onDownloadStartNoStream(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); // Check to see if we have an SDCard String status = Environment.getExternalStorageState(); if (!status.equals(Environment.MEDIA_MOUNTED)) { int title; String msg; // Check to see if the SDCard is busy, same as the music app if (status.equals(Environment.MEDIA_SHARED)) { msg = getString(R.string.download_sdcard_busy_dlg_msg); title = R.string.download_sdcard_busy_dlg_title; } else { msg = getString(R.string.download_no_sdcard_dlg_msg, filename); title = R.string.download_no_sdcard_dlg_title; } new AlertDialog.Builder(this) .setTitle(title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(msg) .setPositiveButton(R.string.ok, null) .show(); return; } // java.net.URI is a lot stricter than KURL so we have to undo // KURL's percent-encoding and redo the encoding using java.net.URI. URI uri = null; try { // Undo the percent-encoding that KURL may have done. String newUrl = new String(URLUtil.decode(url.getBytes())); // Parse the url into pieces WebAddress w = new WebAddress(newUrl); String frag = null; String query = null; String path = w.mPath; // Break the path into path, query, and fragment if (path.length() > 0) { // Strip the fragment int idx = path.lastIndexOf('#'); if (idx != -1) { frag = path.substring(idx + 1); path = path.substring(0, idx); } idx = path.lastIndexOf('?'); if (idx != -1) { query = path.substring(idx + 1); path = path.substring(0, idx); } } uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path, query, frag); } catch (Exception e) { Log.e(LOGTAG, "Could not parse url for download: " + url, e); return; } // XXX: Have to use the old url since the cookies were stored using the // old percent-encoded url. String cookies = CookieManager.getInstance().getCookie(url); ContentValues values = new ContentValues(); values.put(Downloads.COLUMN_URI, uri.toString()); values.put(Downloads.COLUMN_COOKIE_DATA, cookies); values.put(Downloads.COLUMN_USER_AGENT, userAgent); values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE, getPackageName()); values.put(Downloads.COLUMN_NOTIFICATION_CLASS, BrowserDownloadPage.class.getCanonicalName()); values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); values.put(Downloads.COLUMN_MIME_TYPE, mimetype); values.put(Downloads.COLUMN_FILE_NAME_HINT, filename); values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost()); if (contentLength > 0) { values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength); } if (mimetype == null) { // We must have long pressed on a link or image to download it. We // are not sure of the mimetype in this case, so do a head request new FetchUrlMimeType(this).execute(values); } else { final Uri contentUri = getContentResolver().insert(Downloads.CONTENT_URI, values); viewDownloads(contentUri); } } /** * Resets the lock icon. This method is called when we start a new load and * know the url to be loaded. */ private void resetLockIcon(String url) { // Save the lock-icon state (we revert to it if the load gets cancelled) saveLockIcon(); mLockIconType = LOCK_ICON_UNSECURE; if (URLUtil.isHttpsUrl(url)) { mLockIconType = LOCK_ICON_SECURE; if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" + " reset lock icon to " + mLockIconType); } } updateLockIconImage(LOCK_ICON_UNSECURE); } /* package */ void setLockIconType(int type) { mLockIconType = type; } /* package */ int getLockIconType() { return mLockIconType; } /* package */ void setPrevLockType(int type) { mPrevLockType = type; } /* package */ int getPrevLockType() { return mPrevLockType; } /** * Update the lock icon to correspond to our latest state. */ /* package */ void updateLockIconToLatest() { updateLockIconImage(mLockIconType); } /** * Updates the lock-icon image in the title-bar. */ private void updateLockIconImage(int lockIconType) { Drawable d = null; if (lockIconType == LOCK_ICON_SECURE) { d = mSecLockIcon; } else if (lockIconType == LOCK_ICON_MIXED) { d = mMixLockIcon; } mTitleBar.setLock(d); if (mFakeTitleBar != null) { mFakeTitleBar.setLock(d); } } /** * Displays a page-info dialog. * @param tab The tab to show info about * @param fromShowSSLCertificateOnError The flag that indicates whether * this dialog was opened from the SSL-certificate-on-error dialog or * not. This is important, since we need to know whether to return to * the parent dialog or simply dismiss. */ private void showPageInfo(final TabControl.Tab tab, final boolean fromShowSSLCertificateOnError) { final LayoutInflater factory = LayoutInflater .from(this); final View pageInfoView = factory.inflate(R.layout.page_info, null); final WebView view = tab.getWebView(); String url = null; String title = null; if (view == null) { url = tab.getUrl(); title = tab.getTitle(); } else if (view == mTabControl.getCurrentWebView()) { // Use the cached title and url if this is the current WebView url = mUrl; title = mTitle; } else { url = view.getUrl(); title = view.getTitle(); } if (url == null) { url = ""; } if (title == null) { title = ""; } ((TextView) pageInfoView.findViewById(R.id.address)).setText(url); ((TextView) pageInfoView.findViewById(R.id.title)).setText(title); mPageInfoView = tab; mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this) .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info) .setView(pageInfoView) .setPositiveButton( R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mPageInfoDialog = null; mPageInfoView = null; mPageInfoFromShowSSLCertificateOnError = null; // if we came here from the SSL error dialog if (fromShowSSLCertificateOnError) { // go back to the SSL error dialog showSSLCertificateOnError( mSSLCertificateOnErrorView, mSSLCertificateOnErrorHandler, mSSLCertificateOnErrorError); } } }) .setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mPageInfoDialog = null; mPageInfoView = null; mPageInfoFromShowSSLCertificateOnError = null; // if we came here from the SSL error dialog if (fromShowSSLCertificateOnError) { // go back to the SSL error dialog showSSLCertificateOnError( mSSLCertificateOnErrorView, mSSLCertificateOnErrorHandler, mSSLCertificateOnErrorError); } } }); // if we have a main top-level page SSL certificate set or a certificate // error if (fromShowSSLCertificateOnError || (view != null && view.getCertificate() != null)) { // add a 'View Certificate' button alertDialogBuilder.setNeutralButton( R.string.view_certificate, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mPageInfoDialog = null; mPageInfoView = null; mPageInfoFromShowSSLCertificateOnError = null; // if we came here from the SSL error dialog if (fromShowSSLCertificateOnError) { // go back to the SSL error dialog showSSLCertificateOnError( mSSLCertificateOnErrorView, mSSLCertificateOnErrorHandler, mSSLCertificateOnErrorError); } else { // otherwise, display the top-most certificate from // the chain if (view.getCertificate() != null) { showSSLCertificate(tab); } } } }); } mPageInfoDialog = alertDialogBuilder.show(); } /** * Displays the main top-level page SSL certificate dialog * (accessible from the Page-Info dialog). * @param tab The tab to show certificate for. */ private void showSSLCertificate(final TabControl.Tab tab) { final View certificateView = inflateCertificateView(tab.getWebView().getCertificate()); if (certificateView == null) { return; } LayoutInflater factory = LayoutInflater.from(this); final LinearLayout placeholder = (LinearLayout)certificateView.findViewById(R.id.placeholder); LinearLayout ll = (LinearLayout) factory.inflate( R.layout.ssl_success, placeholder); ((TextView)ll.findViewById(R.id.success)) .setText(R.string.ssl_certificate_is_valid); mSSLCertificateView = tab; mSSLCertificateDialog = new AlertDialog.Builder(this) .setTitle(R.string.ssl_certificate).setIcon( R.drawable.ic_dialog_browser_certificate_secure) .setView(certificateView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mSSLCertificateDialog = null; mSSLCertificateView = null; showPageInfo(tab, false); } }) .setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mSSLCertificateDialog = null; mSSLCertificateView = null; showPageInfo(tab, false); } }) .show(); } /** * Displays the SSL error certificate dialog. * @param view The target web-view. * @param handler The SSL error handler responsible for cancelling the * connection that resulted in an SSL error or proceeding per user request. * @param error The SSL error object. */ private void showSSLCertificateOnError( final WebView view, final SslErrorHandler handler, final SslError error) { final View certificateView = inflateCertificateView(error.getCertificate()); if (certificateView == null) { return; } LayoutInflater factory = LayoutInflater.from(this); final LinearLayout placeholder = (LinearLayout)certificateView.findViewById(R.id.placeholder); if (error.hasError(SslError.SSL_UNTRUSTED)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, placeholder); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_untrusted); } if (error.hasError(SslError.SSL_IDMISMATCH)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, placeholder); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_mismatch); } if (error.hasError(SslError.SSL_EXPIRED)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, placeholder); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_expired); } if (error.hasError(SslError.SSL_NOTYETVALID)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, placeholder); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_not_yet_valid); } mSSLCertificateOnErrorHandler = handler; mSSLCertificateOnErrorView = view; mSSLCertificateOnErrorError = error; mSSLCertificateOnErrorDialog = new AlertDialog.Builder(this) .setTitle(R.string.ssl_certificate).setIcon( R.drawable.ic_dialog_browser_certificate_partially_secure) .setView(certificateView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mSSLCertificateOnErrorDialog = null; mSSLCertificateOnErrorView = null; mSSLCertificateOnErrorHandler = null; mSSLCertificateOnErrorError = null; mWebViewClient.onReceivedSslError( view, handler, error); } }) .setNeutralButton(R.string.page_info_view, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mSSLCertificateOnErrorDialog = null; // do not clear the dialog state: we will // need to show the dialog again once the // user is done exploring the page-info details showPageInfo(mTabControl.getTabFromView(view), true); } }) .setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mSSLCertificateOnErrorDialog = null; mSSLCertificateOnErrorView = null; mSSLCertificateOnErrorHandler = null; mSSLCertificateOnErrorError = null; mWebViewClient.onReceivedSslError( view, handler, error); } }) .show(); } /** * Inflates the SSL certificate view (helper method). * @param certificate The SSL certificate. * @return The resultant certificate view with issued-to, issued-by, * issued-on, expires-on, and possibly other fields set. * If the input certificate is null, returns null. */ private View inflateCertificateView(SslCertificate certificate) { if (certificate == null) { return null; } LayoutInflater factory = LayoutInflater.from(this); View certificateView = factory.inflate( R.layout.ssl_certificate, null); // issued to: SslCertificate.DName issuedTo = certificate.getIssuedTo(); if (issuedTo != null) { ((TextView) certificateView.findViewById(R.id.to_common)) .setText(issuedTo.getCName()); ((TextView) certificateView.findViewById(R.id.to_org)) .setText(issuedTo.getOName()); ((TextView) certificateView.findViewById(R.id.to_org_unit)) .setText(issuedTo.getUName()); } // issued by: SslCertificate.DName issuedBy = certificate.getIssuedBy(); if (issuedBy != null) { ((TextView) certificateView.findViewById(R.id.by_common)) .setText(issuedBy.getCName()); ((TextView) certificateView.findViewById(R.id.by_org)) .setText(issuedBy.getOName()); ((TextView) certificateView.findViewById(R.id.by_org_unit)) .setText(issuedBy.getUName()); } // issued on: String issuedOn = reformatCertificateDate( certificate.getValidNotBefore()); ((TextView) certificateView.findViewById(R.id.issued_on)) .setText(issuedOn); // expires on: String expiresOn = reformatCertificateDate( certificate.getValidNotAfter()); ((TextView) certificateView.findViewById(R.id.expires_on)) .setText(expiresOn); return certificateView; } /** * Re-formats the certificate date (Date.toString()) string to * a properly localized date string. * @return Properly localized version of the certificate date string and * the original certificate date string if fails to localize. * If the original string is null, returns an empty string "". */ private String reformatCertificateDate(String certificateDate) { String reformattedDate = null; if (certificateDate != null) { Date date = null; try { date = java.text.DateFormat.getInstance().parse(certificateDate); } catch (ParseException e) { date = null; } if (date != null) { reformattedDate = DateFormat.getDateFormat(this).format(date); } } return reformattedDate != null ? reformattedDate : (certificateDate != null ? certificateDate : ""); } /** * Displays an http-authentication dialog. */ private void showHttpAuthentication(final HttpAuthHandler handler, final String host, final String realm, final String title, final String name, final String password, int focusId) { LayoutInflater factory = LayoutInflater.from(this); final View v = factory .inflate(R.layout.http_authentication, null); if (name != null) { ((EditText) v.findViewById(R.id.username_edit)).setText(name); } if (password != null) { ((EditText) v.findViewById(R.id.password_edit)).setText(password); } String titleText = title; if (titleText == null) { titleText = getText(R.string.sign_in_to).toString().replace( "%s1", host).replace("%s2", realm); } mHttpAuthHandler = handler; AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(titleText) .setIcon(android.R.drawable.ic_dialog_alert) .setView(v) .setPositiveButton(R.string.action, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String nm = ((EditText) v .findViewById(R.id.username_edit)) .getText().toString(); String pw = ((EditText) v .findViewById(R.id.password_edit)) .getText().toString(); BrowserActivity.this.setHttpAuthUsernamePassword (host, realm, nm, pw); handler.proceed(nm, pw); mHttpAuthenticationDialog = null; mHttpAuthHandler = null; }}) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { handler.cancel(); BrowserActivity.this.resetTitleAndRevertLockIcon(); mHttpAuthenticationDialog = null; mHttpAuthHandler = null; }}) .setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { handler.cancel(); BrowserActivity.this.resetTitleAndRevertLockIcon(); mHttpAuthenticationDialog = null; mHttpAuthHandler = null; }}) .create(); // Make the IME appear when the dialog is displayed if applicable. dialog.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); dialog.show(); if (focusId != 0) { dialog.findViewById(focusId).requestFocus(); } else { v.findViewById(R.id.username_edit).requestFocus(); } mHttpAuthenticationDialog = dialog; } public int getProgress() { WebView w = mTabControl.getCurrentWebView(); if (w != null) { return w.getProgress(); } else { return 100; } } /** * Set HTTP authentication password. * * @param host The host for the password * @param realm The realm for the password * @param username The username for the password. If it is null, it means * password can't be saved. * @param password The password */ public void setHttpAuthUsernamePassword(String host, String realm, String username, String password) { WebView w = mTabControl.getCurrentWebView(); if (w != null) { w.setHttpAuthUsernamePassword(host, realm, username, password); } } /** * connectivity manager says net has come or gone... inform the user * @param up true if net has come up, false if net has gone down */ public void onNetworkToggle(boolean up) { if (up == mIsNetworkUp) { return; } else if (up) { mIsNetworkUp = true; if (mAlertDialog != null) { mAlertDialog.cancel(); mAlertDialog = null; } } else { mIsNetworkUp = false; if (mInLoad) { createAndShowNetworkDialog(); } } WebView w = mTabControl.getCurrentWebView(); if (w != null) { w.setNetworkAvailable(up); } } // This method shows the network dialog alerting the user that the net is // down. It will only show the dialog if mAlertDialog is null. private void createAndShowNetworkDialog() { if (mAlertDialog == null) { mAlertDialog = new AlertDialog.Builder(this) .setTitle(R.string.loadSuspendedTitle) .setMessage(R.string.loadSuspended) .setPositiveButton(R.string.ok, null) .show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { switch (requestCode) { case COMBO_PAGE: if (resultCode == RESULT_OK && intent != null) { String data = intent.getAction(); Bundle extras = intent.getExtras(); if (extras != null && extras.getBoolean("new_window", false)) { openTab(data); } else { final TabControl.Tab currentTab = mTabControl.getCurrentTab(); dismissSubWindow(currentTab); if (data != null && data.length() != 0) { getTopWindow().loadUrl(data); } } } break; default: break; } getTopWindow().requestFocus(); } /* * This method is called as a result of the user selecting the options * menu to see the download window, or when a download changes state. It * shows the download window ontop of the current window. */ /* package */ void viewDownloads(Uri downloadRecord) { Intent intent = new Intent(this, BrowserDownloadPage.class); intent.setData(downloadRecord); startActivityForResult(intent, this.DOWNLOAD_PAGE); } /** * Open the Go page. * @param startWithHistory If true, open starting on the history tab. * Otherwise, start with the bookmarks tab. */ /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) { WebView current = mTabControl.getCurrentWebView(); if (current == null) { return; } Intent intent = new Intent(this, CombinedBookmarkHistoryActivity.class); String title = current.getTitle(); String url = current.getUrl(); Bitmap thumbnail = createScreenshot(current); // Just in case the user opens bookmarks before a page finishes loading // so the current history item, and therefore the page, is null. if (null == url) { url = mLastEnteredUrl; // This can happen. if (null == url) { url = mSettings.getHomePage(); } } // In case the web page has not yet received its associated title. if (title == null) { title = url; } intent.putExtra("title", title); intent.putExtra("url", url); intent.putExtra("thumbnail", thumbnail); // Disable opening in a new window if we have maxed out the windows intent.putExtra("disable_new_window", mTabControl.getTabCount() >= TabControl.MAX_TABS); intent.putExtra("touch_icon_url", current.getTouchIconUrl()); if (startWithHistory) { intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB, CombinedBookmarkHistoryActivity.HISTORY_TAB); } startActivityForResult(intent, COMBO_PAGE); } // Called when loading from context menu or LOAD_URL message private void loadURL(WebView view, String url) { // In case the user enters nothing. if (url != null && url.length() != 0 && view != null) { url = smartUrlFilter(url); if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) { view.loadUrl(url); } } } private String smartUrlFilter(Uri inUri) { if (inUri != null) { return smartUrlFilter(inUri.toString()); } return null; } // get window count int getWindowCount(){ if(mTabControl != null){ return mTabControl.getTabCount(); } return 0; } protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile( "(?i)" + // switch on case insensitive matching "(" + // begin group for schema "(?:http|https|file):\\/\\/" + "|(?:inline|data|about|content|javascript):" + ")" + "(.*)" ); /** * Attempts to determine whether user input is a URL or search * terms. Anything with a space is passed to search. * * Converts to lowercase any mistakenly uppercased schema (i.e., * "Http://" converts to "http://" * * @return Original or modified URL * */ String smartUrlFilter(String url) { String inUrl = url.trim(); boolean hasSpace = inUrl.indexOf(' ') != -1; Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl); if (matcher.matches()) { // force scheme to lowercase String scheme = matcher.group(1); String lcScheme = scheme.toLowerCase(); if (!lcScheme.equals(scheme)) { inUrl = lcScheme + matcher.group(2); } if (hasSpace) { inUrl = inUrl.replace(" ", "%20"); } return inUrl; } if (hasSpace) { // FIXME: Is this the correct place to add to searches? // what if someone else calls this function? int shortcut = parseUrlShortcut(inUrl); if (shortcut != SHORTCUT_INVALID) { Browser.addSearchUrl(mResolver, inUrl); String query = inUrl.substring(2); switch (shortcut) { case SHORTCUT_GOOGLE_SEARCH: return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER); case SHORTCUT_WIKIPEDIA_SEARCH: return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER); case SHORTCUT_DICTIONARY_SEARCH: return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER); case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH: // FIXME: we need location in this case return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER); } } } else { if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) { return URLUtil.guessUrl(inUrl); } } Browser.addSearchUrl(mResolver, inUrl); return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER); } /* package */ void setShouldShowErrorConsole(boolean flag) { if (flag == mShouldShowErrorConsole) { // Nothing to do. return; } mShouldShowErrorConsole = flag; ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true); if (flag) { // Setting the show state of the console will cause it's the layout to be inflated. if (errorConsole.numberOfErrors() > 0) { errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED); } else { errorConsole.showConsole(ErrorConsoleView.SHOW_NONE); } // Now we can add it to the main view. mErrorConsoleContainer.addView(errorConsole, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } else { mErrorConsoleContainer.removeView(errorConsole); } } final static int LOCK_ICON_UNSECURE = 0; final static int LOCK_ICON_SECURE = 1; final static int LOCK_ICON_MIXED = 2; private int mLockIconType = LOCK_ICON_UNSECURE; private int mPrevLockType = LOCK_ICON_UNSECURE; private BrowserSettings mSettings; private TabControl mTabControl; private ContentResolver mResolver; private FrameLayout mContentView; private View mCustomView; private FrameLayout mCustomViewContainer; private WebChromeClient.CustomViewCallback mCustomViewCallback; // FIXME, temp address onPrepareMenu performance problem. When we move everything out of // view, we should rewrite this. private int mCurrentMenuState = 0; private int mMenuState = R.id.MAIN_MENU; private int mOldMenuState = EMPTY_MENU; private static final int EMPTY_MENU = -1; private Menu mMenu; private FindDialog mFindDialog; // Used to prevent chording to result in firing two shortcuts immediately // one after another. Fixes bug 1211714. boolean mCanChord; private boolean mInLoad; private boolean mIsNetworkUp; private boolean mDidStopLoad; private boolean mPageStarted; private boolean mActivityInPause = true; private boolean mMenuIsDown; private static boolean mInTrace; // Performance probe private static final int[] SYSTEM_CPU_FORMAT = new int[] { Process.PROC_SPACE_TERM | Process.PROC_COMBINE, Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time }; private long mStart; private long mProcessStart; private long mUserStart; private long mSystemStart; private long mIdleStart; private long mIrqStart; private long mUiStart; private Drawable mMixLockIcon; private Drawable mSecLockIcon; /* hold a ref so we can auto-cancel if necessary */ private AlertDialog mAlertDialog; // Wait for credentials before loading google.com private ProgressDialog mCredsDlg; // The up-to-date URL and title (these can be different from those stored // in WebView, since it takes some time for the information in WebView to // get updated) private String mUrl; private String mTitle; // As PageInfo has different style for landscape / portrait, we have // to re-open it when configuration changed private AlertDialog mPageInfoDialog; private TabControl.Tab mPageInfoView; // If the Page-Info dialog is launched from the SSL-certificate-on-error // dialog, we should not just dismiss it, but should get back to the // SSL-certificate-on-error dialog. This flag is used to store this state private Boolean mPageInfoFromShowSSLCertificateOnError; // as SSLCertificateOnError has different style for landscape / portrait, // we have to re-open it when configuration changed private AlertDialog mSSLCertificateOnErrorDialog; private WebView mSSLCertificateOnErrorView; private SslErrorHandler mSSLCertificateOnErrorHandler; private SslError mSSLCertificateOnErrorError; // as SSLCertificate has different style for landscape / portrait, we // have to re-open it when configuration changed private AlertDialog mSSLCertificateDialog; private TabControl.Tab mSSLCertificateView; // as HttpAuthentication has different style for landscape / portrait, we // have to re-open it when configuration changed private AlertDialog mHttpAuthenticationDialog; private HttpAuthHandler mHttpAuthHandler; /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, Gravity.CENTER); // Google search final static String QuickSearch_G = "http://www.google.com/m?q=%s"; // Wikipedia search final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go"; // Dictionary search final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s"; // Google Mobile Local search final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view"; final static String QUERY_PLACE_HOLDER = "%s"; // "source" parameter for Google search through search key final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key"; // "source" parameter for Google search through goto menu final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto"; // "source" parameter for Google search through simplily type final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type"; // "source" parameter for Google search suggested by the browser final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest"; // "source" parameter for Google search from unknown source final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown"; private final static String LOGTAG = "browser"; private String mLastEnteredUrl; private PowerManager.WakeLock mWakeLock; private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes private Toast mStopToast; private TitleBar mTitleBar; private LinearLayout mErrorConsoleContainer = null; private boolean mShouldShowErrorConsole = false; // As the ids are dynamically created, we can't guarantee that they will // be in sequence, so this static array maps ids to a window number. final static private int[] WINDOW_SHORTCUT_ID_ARRAY = { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id, R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id, R.id.window_seven_menu_id, R.id.window_eight_menu_id }; // monitor platform changes private IntentFilter mNetworkStateChangedFilter; private BroadcastReceiver mNetworkStateIntentReceiver; private BroadcastReceiver mPackageInstallationReceiver; // AsyncTask for downloading touch icons /* package */ DownloadTouchIcon mTouchIconLoader; // activity requestCode final static int COMBO_PAGE = 1; final static int DOWNLOAD_PAGE = 2; final static int PREFERENCES_PAGE = 3; // the default <video> poster private Bitmap mDefaultVideoPoster; // the video progress view private View mVideoProgressView; /** * A UrlData class to abstract how the content will be set to WebView. * This base class uses loadUrl to show the content. */ private static class UrlData { String mUrl; byte[] mPostData; UrlData(String url) { this.mUrl = url; } void setPostData(byte[] postData) { mPostData = postData; } boolean isEmpty() { return mUrl == null || mUrl.length() == 0; } public void loadIn(WebView webView) { if (mPostData != null) { webView.postUrl(mUrl, mPostData); } else { webView.loadUrl(mUrl); } } }; /** * A subclass of UrlData class that can display inlined content using * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}. */ private static class InlinedUrlData extends UrlData { InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) { super(failUrl); mInlined = inlined; mMimeType = mimeType; mEncoding = encoding; } String mMimeType; String mInlined; String mEncoding; @Override boolean isEmpty() { return mInlined == null || mInlined.length() == 0 || super.isEmpty(); } @Override public void loadIn(WebView webView) { webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl); } } /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null); }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
226081225f56dfcad9664748c2fda47874a7a441
13d091100555a7933bc2b735351d2d3cee28b609
/src/test/java/utils/Driver.java
7645605fdeb951c8f42ef3e94184d7e91f30f85b
[]
no_license
Renas63/Renas63-VersacePOM
f4193a1be3f0e69a8870b24018bdeabf50b3bc54
f81898ccc00dfd723229e99faf814185e5404b93
refs/heads/master
2023-03-08T23:16:43.145724
2021-03-16T23:37:37
2021-03-16T23:37:37
348,519,248
0
0
null
null
null
null
UTF-8
Java
false
false
1,162
java
package utils; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class Driver { private static WebDriver driver; // PRIVATE CONSTRUCTOR FOR Singleton design pattern private Driver() { // thi sis singleton design pattern } public static WebDriver getDriver() { if (driver == null) { switch (ConfiguReader.getProperty("browser")) { case "chrome": WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); break; case "firefox": WebDriverManager.firefoxdriver().setup(); driver= new FirefoxDriver(); break; } } driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); return driver; } }
[ "75856707+Renas63@users.noreply.github.com" ]
75856707+Renas63@users.noreply.github.com
31118a596cfbf8133d646475dfdbfa2d3808570d
baf92ba93866109168d8e63964ba0cad926d182c
/toolsetmanager-34/src/com/byrobingames/manager/utils/UpdateToolset.java
addef25d7b52fc2709296645954651b24739ad89
[ "MIT" ]
permissive
byrobingames/byrobintoolsetmanager
6e1cc20a4c59fa90f4562863ffe2ba31084c410a
b80af9b5fa8e44bfd0856586a8dfd5531cf6ce27
refs/heads/master
2020-04-09T03:33:07.866899
2019-01-16T21:51:13
2019-01-16T21:51:13
159,987,026
0
0
null
null
null
null
UTF-8
Java
false
false
4,739
java
package com.byrobingames.manager.utils; import java.io.File; import java.util.ArrayList; import org.apache.commons.io.FilenameUtils; import com.byrobingames.manager.ByRobinGameExtension; import com.byrobingames.manager.reader.ReadGithubApi; import com.byrobingames.manager.utils.dialog.DialogBox; import stencyl.core.lib.Game; import stencyl.sw.SW; import stencyl.sw.app.TaskManager; import stencyl.sw.app.tasks.StencylWorker; import stencyl.sw.editors.game.advanced.ExtensionInstance; import stencyl.sw.util.FileHelper; import stencyl.sw.util.Locations; import stencyl.sw.util.MultiFileDownloader; import stencyl.sw.util.MultiFileDownloader.FileToDownload; public class UpdateToolset { private static final String repos_id ="byrobintoolsetmanager"; public static void downloadToolset(String name) { SW.get().getApp().saveGame(null); final String exRoot = Locations.getExtensionsLocation(); final File exRootFile = new File(exRoot); exRootFile.mkdirs(); FileHelper.makeFileWritable(exRootFile); final String downloadURL = ReadGithubApi.getDownloadURL(repos_id); final String fileName = FilenameUtils.getName(downloadURL); final String extensionLocation = exRoot + fileName; ArrayList<FileToDownload> files = new ArrayList<FileToDownload>(); files.add(new FileToDownload(downloadURL, name, extensionLocation)); Runnable r = new Runnable() { @Override public void run() { final TaskManager t = SW.get().getApp().getTaskManager(); t.run(new StencylWorker() { @Override public Integer doInBackground() { if(downloadURL.equals("null")){ //failed to download stop code and delete null.zip and return return 0; } t.showProgress("Installing "+ name + "..."); FileHelper.unzip(new File(extensionLocation), exRootFile); return 0; } @Override public void done(boolean status) { super.done(status); if(downloadURL.equals("null")){ //failed to download stop code and delete null.zip and return FileHelper.delete(new File(Locations.getPath(Locations.getExtensionsLocation(), fileName))); return; } t.hideProgress(); FileHelper.delete(new File(Locations.getPath(Locations.getExtensionsLocation(), fileName))); DialogBox.showGenericDialog( "Success", "<html>The " + name + " has been installed.<br>" + "Please restart Stencyl</html>"); } }); } }; MultiFileDownloader.downloadFiles("Downloading " + name + "...", files, r); } public static void renameExFolder(String repos_id){ Runnable mainTask = new Runnable() { public void run() { DialogBox.showErrorDialog("", "Wrong Foldername", "<html>It seems that the foldername of extension is nog correct.<br>" + "For correct working the extension foldername must be renamed<br> " + "from foldername: <strong>" + repos_id + "-master</strong> to foldername: <strong>" + repos_id + "</strong>.<br><br>" + "When you press ok i will rename the folder for you.</html>", true ); } }; Runnable onFinish = new Runnable() { public void run() { if(DialogBox.okIsPressed){ DialogBox.okIsPressed = false; final String sourceName = repos_id+"-master"; final String engineExRoot = Locations.getGameExtensionsLocation(); final File sourceLocation = new File(engineExRoot + sourceName); final File targetLocation = new File(engineExRoot + repos_id); boolean isEnabled; if(DownloadEngineEx.checkIfEnabled(sourceName)){ isEnabled = true; final ExtensionInstance instMaster = Game.getGame().getExtensions().get(sourceName); SW.get().getEngineExtensionManager().disableExtension(sourceName); SW.get().getExtensionDependencyManager().disable(instMaster.getExtension()); }else{ isEnabled = false; } FileHelper.copyDirectory(sourceLocation, targetLocation); FileHelper.delete(sourceLocation); SW.get().getEngineExtensionManager().reload(); SW.get().getApp().saveGame(null); try{ if(isEnabled){ final ExtensionInstance inst = Game.getGame().getExtensions().get(repos_id); SW.get().getEngineExtensionManager().enableExtension(repos_id); SW.get().getExtensionDependencyManager().enable(inst.getExtension()); } }catch (Exception e){ e.printStackTrace(); } } } }; ByRobinGameExtension.doLongTask(mainTask, onFinish); } }
[ "robinschaafsma@ziggo.nl" ]
robinschaafsma@ziggo.nl
e9fd06863ca03d6049d0487675c13ab6c1d7d2fb
7df5c211b5081594fb24be7433a354e830e7222c
/interfaces/src/main/java/com/zcl/interfaces/InterfacesApplication.java
2033e57c65723620d7b1862457b17014b3af71f7
[]
no_license
pianozcl/dubbo
3f8b122cada460ca58067bbbd87c9f2a7216d917
c0da78c847d236019afb7bf44027489a4b90629a
refs/heads/main
2023-03-29T19:26:47.348764
2021-04-10T08:28:41
2021-04-10T08:28:41
354,883,898
0
0
null
null
null
null
UTF-8
Java
false
false
331
java
package com.zcl.interfaces; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class InterfacesApplication { public static void main(String[] args) { SpringApplication.run(InterfacesApplication.class, args); } }
[ "pianozcl@gmail.com" ]
pianozcl@gmail.com
2592898a8302a7ebae85529ae30380983da75e14
672a84dde8739120516422ff71fa2e2028d74c30
/service-common/src/main/java/com/cloud/zhuwj/common/event/ApplicationFailedEventListener.java
20839ae08e67967dfa9ed97c5826780195cc665d
[]
no_license
HYXBio/spring-cloud-framework
90de4cab199cf4e2baa1746ab8eb0a03f1bddd09
2a9c801204240596e48e0302803c49f2b4e0d194
refs/heads/master
2022-02-27T13:41:59.727193
2019-08-11T09:30:49
2019-08-11T09:30:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
712
java
package com.cloud.zhuwj.common.event; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.event.ApplicationFailedEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; /** * @author zhuwj * @Description: 系统启动失败事件 * @date 2018/5/23 17:06 */ @Component public class ApplicationFailedEventListener implements ApplicationListener<ApplicationFailedEvent> { private static Logger logger = LoggerFactory.getLogger(ApplicationFailedEventListener.class); @Override public void onApplicationEvent(ApplicationFailedEvent event) { logger.info("系统启动失败......"); } }
[ "774623096@qq.com" ]
774623096@qq.com
f48ee6daa608a9005b52654151f86150d48e44d2
057f0ed61d5a158ea2d95be9e4faa216d586f140
/src/com/sfzt/copy/service/MultiMediaStoreHelper.java
21ee0d037a209c201aff9c9fe2a73c9dbe450680
[]
no_license
wlznzx/CopyTools
0068f385ad6a22a3e1048b8499787696154467e8
f734de7c2223cc2d69b670a7d2d00f3c188850c9
refs/heads/master
2021-01-19T23:49:08.103512
2017-04-22T06:58:29
2017-04-22T06:58:29
89,034,666
0
0
null
null
null
null
UTF-8
Java
false
false
3,977
java
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ package com.sfzt.copy.service; import java.util.ArrayList; import java.util.List; public abstract class MultiMediaStoreHelper { protected final List<String> mPathList = new ArrayList<String>(); private static final int NEED_UPDATE = 200; protected final MediaStoreHelper mMediaStoreHelper; public MultiMediaStoreHelper(MediaStoreHelper mediaStoreHelper) { if (mediaStoreHelper == null) { throw new IllegalArgumentException("mediaStoreHelper has not been initialized."); } mMediaStoreHelper = mediaStoreHelper; } public void addRecord(String path) { mPathList.add(path); if (mPathList.size() > NEED_UPDATE) { updateRecords(); } } public void updateRecords() { mPathList.clear(); } /** * Set dstfolder to scan with folder. * * @param dstFolder */ public void setDstFolder(String dstFolder) { mMediaStoreHelper.setDstFolder(dstFolder); } public static class PasteMediaStoreHelper extends MultiMediaStoreHelper { public PasteMediaStoreHelper(MediaStoreHelper mediaStoreHelper) { super(mediaStoreHelper); } @Override public void updateRecords() { mMediaStoreHelper.scanPathforMediaStore(mPathList); super.updateRecords(); } } public static class DeleteMediaStoreHelper extends MultiMediaStoreHelper { public DeleteMediaStoreHelper(MediaStoreHelper mediaStoreHelper) { super(mediaStoreHelper); } @Override public void updateRecords() { mMediaStoreHelper.deleteFileInMediaStore(mPathList); super.updateRecords(); } } }
[ "wl_znzx@163.com" ]
wl_znzx@163.com
090227e0ab5a9bc823c4372519bd1c988313640e
221af5419a54abb96b67f6fc0fd78b62ce685b0a
/src/notes/SimpleNotes.java
6a0baa9b52de127eb7b39242a46be8cfa5e28c68
[]
no_license
sahwar/SimpleNotes
afc2244c3d172957ca193eb10e8d141e5de13e51
76159001f47bce3c58c07f9660d7b721d736bfdd
refs/heads/master
2021-06-17T06:18:04.296619
2017-06-04T06:31:52
2017-06-04T06:31:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
11,613
java
package notes; import java.io.IOException; import java.util.Enumeration; import java.util.Vector; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.AlertType; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.List; import javax.microedition.midlet.*; import javax.microedition.rms.RecordEnumeration; import javax.microedition.rms.RecordStore; import javax.microedition.rms.RecordStoreException; import javax.microedition.rms.RecordStoreNotOpenException; /** * SimpleNotes midlet application. * * @author skoro */ public class SimpleNotes extends MIDlet implements CommandListener { private final String RECORD_STORE_NAME = "SimpleNotes"; private boolean midletPaused = false; /** * Notes container. */ private Vector list; /** * Form elements. */ private List mainForm; private Command exitCommand; private Command newNoteCommand; private Command clearCommand; private EditForm editForm; private RecordStore recordStore; public SimpleNotes() { super(); list = new Vector(); } /** * Called when MIDlet is started. Checks whether the MIDlet have been * already started and initialize/starts or resumes the MIDlet. */ public void startApp() { if (midletPaused) { // TODO: resume midlet. } else { try { openRecordStore(); readNotesFromRecordStore(); switchDisplayable(null, getMainForm()); } catch (Exception e) { e.printStackTrace(); getDisplay().setCurrent(new Alert("Error", e.getMessage(), null, AlertType.ERROR)); } } midletPaused = false; } /** * Called when MIDlet is paused. */ public void pauseApp() { midletPaused = true; } /** * Exits MIDlet. */ public void exitMIDlet() throws RecordStoreException { recordStore.closeRecordStore(); switchDisplayable(null, null); destroyApp(true); notifyDestroyed(); } /** * Called to signal the MIDlet to terminate. * * @param unconditional if true, then the MIDlet has to be unconditionally * terminated and all resources has to be released. */ public void destroyApp(boolean unconditional) { } /** * Returns a display instance. * * @return the display instance. */ public Display getDisplay() { return Display.getDisplay(this); } /** * Switches a current displayable in a display. The <code>display</code> * instance is taken from <code>getDisplay</code> method. This method is * used by all actions in the design for switching displayable. * * @param alert the Alert which is temporarily set to the display; if * <code>null</code>, then <code>nextDisplayable</code> is set immediately * @param nextDisplayable the Displayable to be set */ public void switchDisplayable(Alert alert, Displayable nextDisplayable) { Display display = getDisplay(); if (alert == null) { display.setCurrent(nextDisplayable); } else { display.setCurrent(alert, nextDisplayable); } } public List getMainForm() { if (mainForm == null) { mainForm = new List("Simple notes", List.IMPLICIT); mainForm.addCommand(getExitCommand()); mainForm.addCommand(getNewNoteCommand()); mainForm.addCommand(getClearCommand()); mainForm.setCommandListener(this); } return mainForm; } public Command getExitCommand() { if (exitCommand == null) { exitCommand = new Command("Exit", Command.EXIT, 0); } return exitCommand; } public Command getNewNoteCommand() { if (newNoteCommand == null) { newNoteCommand = new Command("New note", Command.SCREEN, 0); } return newNoteCommand; } public Command getClearCommand() { if (clearCommand == null) { clearCommand = new Command("Clear", Command.SCREEN, 0); } return clearCommand; } /** * Called by a system to indicated that a command has been invoked on a * particular displayable. * * @param command the Command that was invoked * @param displayable the Displayable where the command was invoked */ public void commandAction(Command command, Displayable displayable) { try { if (displayable == mainForm) { if (command == exitCommand) { exitMIDlet(); } else if (command == newNoteCommand) { editForm = EditForm.createNew("Add note", this); switchDisplayable(null, editForm); } else if (command == clearCommand) { Alert alert = null; if (mainForm.size() == 0) { alert = new Alert("No notes", "There are no notes.", null, AlertType.WARNING); } else { Confirm confirm = new Confirm("Clear all notes", "Are you sure to clear ALL notes ?"); confirm.setConfirmedListener(new Confirm.ConfirmedListener() { public void confirmedAction(Confirm c) { if (c.isConfirmed()) { clearNotes(); } // Return to main form after any action. switchDisplayable(null, mainForm); } }); alert = confirm.getAlert(); } switchDisplayable(alert, mainForm); } else if (command == List.SELECT_COMMAND) { editNote(mainForm.getSelectedIndex()); } } else if (displayable == editForm) { Alert alert = null; // Confirm dialog. if (command == editForm.getOkCommand()) { setNote(editForm.getString(), mainForm.getSelectedIndex()); } else if (command == editForm.getAddCommand()) { addNote(editForm.getString()); } else if (command == editForm.getDeleteCommand()) { Confirm confirm = new Confirm("Delete note", "Are you sure to delete note ?"); confirm.setConfirmedListener(new Confirm.ConfirmedListener() { public void confirmedAction(Confirm c) { if (c.isConfirmed()) { deleteNote(mainForm.getSelectedIndex()); } // Return to main form after any action. switchDisplayable(null, mainForm); } }); alert = confirm.getAlert(); } switchDisplayable(alert, mainForm); editForm = null; } } catch (Exception e) { e.printStackTrace(); switchDisplayable(new Alert("Error", e.getMessage(), null, AlertType.ERROR), mainForm); } } public Model addNote(String text) throws RecordStoreException, EmptyStringException { Note note = null; note = new Note(text); list.addElement(note); mainForm.append(note.getTitle(), null); return recordInsert(note); } public void editNote(int index) { if (index == -1) { return; } try { Note note = (Note) list.elementAt(index); editForm = EditForm.createFromNote(note, this); switchDisplayable(null, editForm); } catch (Exception e) { e.printStackTrace(); } } public void setNote(String text, int index) { if (index == -1) { return; } try { Note note = (Note) list.elementAt(index); note.setText(text); note.setTitle(""); mainForm.set(index, note.getTitle(), null); recordUpdate(note); } catch (Exception e) { e.printStackTrace(); } } public void deleteNote(int index) { if (index == -1) { return; } try { Note note = (Note) list.elementAt(index); list.removeElementAt(index); mainForm.delete(index); recordDelete(note); } catch (Exception e) { e.printStackTrace(); } } public void clearNotes() { try { Enumeration e = list.elements(); while (e.hasMoreElements()) { Model m = (Model) e.nextElement(); if (!m.isNew()) { recordStore.deleteRecord(m.getId()); } } list.removeAllElements(); mainForm.deleteAll(); } catch (Exception e) { e.printStackTrace(); } } protected void openRecordStore() throws RecordStoreException { if (recordStore != null) { return; // Already initialized. } recordStore = RecordStore.openRecordStore(RECORD_STORE_NAME, true); } protected Model recordInsert(Model model) throws RecordStoreException { byte[] data = model.toBytes(); model.setId(recordStore.addRecord(data, 0, data.length)); return model; } protected void recordUpdate(Model model) throws RecordStoreException { if (model.isNew()) { return; } byte[] data = model.toBytes(); recordStore.setRecord(model.getId(), data, 0, data.length); } private void readNotesFromRecordStore() throws RecordStoreNotOpenException, RecordStoreException { List form = getMainForm(); RecordEnumeration re = recordStore.enumerateRecords(null, null, false); if (re.numRecords() > 0) { while (re.hasNextElement()) { int id = re.nextRecordId(); try { Note note = (Note) Note.createFromBytes(recordStore.getRecord(id)); note.setId(id); list.addElement(note); form.append(note.getTitle(), null); } catch (EmptyStringException e) { // TODO: delete such records ? } } } } protected void recordDelete(Model model) throws RecordStoreException { if (model.isNew()) { return; } recordStore.deleteRecord(model.getId()); } }
[ "skorobogatko.oleksii@gmail.com" ]
skorobogatko.oleksii@gmail.com
ea6a1665e0de558103dfe04ed468cb4d8170c705
d56b26efa1a92cd91464163fc9f9709e1ebf30f5
/malldemo/oomall/src/main/java/xmu/oomall/dao/OrderDAO.java
c36705cea821f7275d89ce360d2d005963738624
[]
no_license
ziqi-zhu/SpringDemo
46a058df0b372485803f92fc54e444df41daf81e
8c17975743ea71949d3793d815b341aec277d480
refs/heads/master
2020-09-04T12:53:55.936314
2019-11-05T09:14:29
2019-11-05T09:14:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
497
java
package xmu.oomall.dao; import xmu.oomall.domain.CartItem; import xmu.oomall.domain.Order; import java.util.List; /** * @Author: Ming Qiu * @Description: * @Date: Created in 17:02 2019/11/5 * @Modified By: **/ public class OrderDAO { /** * 将购物车中物品加入订单 * @param cartItems 购物车物品 * @param order 订单 */ public void addCartToOrder(List<CartItem> cartItems, Order order){ for (CartItem item: cartItems){ } } }
[ "mingqiu@xmu.edu.cn" ]
mingqiu@xmu.edu.cn
79a4b63c1e7f3fbd2eeb247bfe3f27d55e22e3f5
6738f74a5c2d1ec2912a58b52e12ce4632a99331
/src/main/java/com/jfinal/config/Plugins.java
08d231f0793664e0f9d27fd9175c786e62322406
[ "Apache-2.0" ]
permissive
cokolin/JFinal-Servlet3
f5947c9541c112a0f1ea48424591d319533b73aa
b22593a084045f6a9736fdd4f28f6e01bbaed73d
refs/heads/master
2021-01-10T13:15:42.547390
2016-01-03T09:08:07
2016-01-03T09:08:07
47,909,457
0
0
null
null
null
null
UTF-8
Java
false
false
1,084
java
/** * Copyright (c) 2011-2015, James Zhan 詹波 (jfinal@126.com). * * 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.jfinal.config; import java.util.ArrayList; import java.util.List; import com.jfinal.plugin.IPlugin; /** * Plugins. */ public final class Plugins { private final List<IPlugin> pluginList = new ArrayList<IPlugin>(); public Plugins add(IPlugin plugin) { if (plugin != null) this.pluginList.add(plugin); return this; } public List<IPlugin> getPluginList() { return pluginList; } }
[ "cokolin@126.com" ]
cokolin@126.com
c8e8c399a0f3d8ed50fc86165e05755edabac2f1
d6f532da80f4e91f0c8d13940892c664da175a07
/src/bingo_client/views/server/ServerDispatcher.java
3e61d72cf46ab4604c5c1aa1604ad32375e6349f
[ "MIT" ]
permissive
luisvillara/bingo
1eda3cc8d0f15121491c8fdb2b964ee436907086
1d89f9861c77ee96bc3841fa3c72137cd6be6a0a
refs/heads/master
2021-01-12T13:56:59.652277
2015-04-12T15:33:22
2015-04-12T15:33:22
32,418,060
0
0
null
null
null
null
UTF-8
Java
false
false
3,729
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package bingo_client.views.server; import bingo_client.gui.ClientFrameDelegate; import bingo_ws.lib.ServerDelegate; import bingo_ws.views.Request; import java.net.Socket; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import org.json.JSONException; import org.json.JSONObject; /** * * @author Luis */ public class ServerDispatcher extends Thread { private Vector mMessageQueue = new Vector(); private String senderIP; private Vector mClients = new Vector(); private ServerDelegate delegate; public ServerDispatcher(ServerDelegate delegate){ this.delegate = delegate; } /** * Adds given client to the server's client list. */ public synchronized void addClient(ClientInfo aClientInfo) { mClients.add(aClientInfo); } /** * Deletes given client from the server's client list * if the client is in the list. */ public synchronized void deleteClient(ClientInfo aClientInfo) { int clientIndex = mClients.indexOf(aClientInfo); if (clientIndex != -1) mClients.removeElementAt(clientIndex); } /** * Adds given message to the dispatcher's message queue and notifies this * thread to wake up the message queue reader (getNextMessageFromQueue method). * dispatchMessage method is called by other threads (ClientListener) when * a message is arrived. */ public synchronized void dispatchMessage(ClientInfo aClientInfo, String aMessage) { Socket socket = aClientInfo.mSocket; senderIP = socket.getInetAddress().getHostAddress(); String senderPort = "" + socket.getPort(); //aMessage = senderIP + ":" + senderPort + " : " + aMessage; mMessageQueue.add(aMessage); notify(); } /** * @return and deletes the next message from the message queue. If there is no * messages in the queue, falls in sleep until notified by dispatchMessage method. */ private synchronized String getNextMessageFromQueue() throws InterruptedException { while (mMessageQueue.size()==0) wait(); String message = (String) mMessageQueue.get(0); mMessageQueue.removeElementAt(0); return message; } /** * Sends given message to all clients in the client list. Actually the * message is added to the client sender thread's message queue and this * client sender thread is notified. */ private synchronized void sendMessageToAllClients(String aMessage) { for (int i=0; i<mClients.size(); i++) { ClientInfo clientInfo = (ClientInfo) mClients.get(i); clientInfo.mClientSender.sendMessage(aMessage); } } /** * Infinitely reads messages from the queue and dispatch them * to all clients connected to the server. */ public void run() { try { while (true) { String message = getNextMessageFromQueue(); System.out.println(message); JSONObject msg = new JSONObject(message); this.delegate.process_message(senderIP, msg, msg.getInt("COD")); } } catch (InterruptedException ie) { // Thread interrupted. Stop its execution } catch (JSONException ex) { Logger.getLogger(ServerDispatcher.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "Error al leer mensaje JSON", "Error", JOptionPane.ERROR_MESSAGE); } } }
[ "alfredovillalobo@gmail.com" ]
alfredovillalobo@gmail.com
96df6836b84729cd75b2104071530cafb02a33fe
68fc17db528a7632e112313112ded5c7d52f981a
/src/Ders2_Kodlama/io/Course.java
e9cd6dd080f6c4bb064d46bbdce3a96f8f90f78d
[]
no_license
omerserbetci/JavaKampOdevler
6cc9b25fe81dbdcc03d7f55599466e2974abdcef
a85f4ba3b62b106b394141293c20709b202f9393
refs/heads/master
2023-04-20T06:59:09.454797
2021-05-08T11:58:35
2021-05-08T11:58:35
361,539,608
1
0
null
null
null
null
UTF-8
Java
false
false
934
java
package Ders2_Kodlama.io; public class Course { int courseId; String courseName; String courseDetail; Student student; public Course() { System.out.println("Course constructor worked."); } public Course(int id, String name, String detail, Student student) { this(); setCourseId(id); setCourseName(name); setCourseDetail(detail); setStudent(student); } public int getCourseId() { return courseId; } public void setCourseId(int courseId) { this.courseId = courseId; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseDetail() { return courseDetail; } public void setCourseDetail(String courseDetail) { this.courseDetail = courseDetail; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } }
[ "omer.serbetci@etiya.com" ]
omer.serbetci@etiya.com
2bcf2050f5a43178d27e926fdf6f045772f2942c
8b309faf55ae7e396bd1e00a179baf09c695461d
/src/main/java/sample/bikes/Bike.java
33016e01afff001ff595f38f6db7b744caaf2a3c
[ "Apache-2.0" ]
permissive
laliluna/explore-languages
61e73f0d2974ffeb8af51c34a4ce50b73339b529
0d18bf5e689941e24b78a840201bad8bf9c7bc28
refs/heads/master
2020-05-14T15:10:11.904007
2019-04-17T09:33:27
2019-04-17T09:33:27
181,847,123
0
0
null
null
null
null
UTF-8
Java
false
false
450
java
package sample.bikes; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import java.util.Random; @Entity @Table(name = "bikes") public class Bike { @Id @GeneratedValue Integer id; String name; public Bike() { } public Bike(String name) { this.name = name; } public String getName() { return name; } public Integer getId() { return id; } }
[ "usenet@laliluna.de" ]
usenet@laliluna.de
0b785f44840cb6a07daddf073548a7bb475e4a61
c9d643b29358e7eb5ed847510d8fe13b46953830
/src/test/java/kr/or/ddit/user/repository/UserDaoTest.java
c7e472eb7e784327d0796b33b1769bfd3bb9f75a
[]
no_license
rlagPdls123/jsProject
52aa1669f219e3f028f78333421f78060b06bf23
b736195cdce7e1ccbc2475bb090837570070610b
refs/heads/master
2021-06-17T14:48:14.586841
2019-08-19T07:46:08
2019-08-19T07:46:08
199,803,257
0
0
null
2021-04-22T18:30:43
2019-07-31T07:27:57
Java
UTF-8
Java
false
false
863
java
package kr.or.ddit.user.repository; import static org.junit.Assert.*; import java.util.List; import org.junit.Test; import kr.or.ddit.user.model.User; public class UserDaoTest { /** * * Method : getUserListTest * 작성자 : PC-25 * 변경이력 : * Method 설명 : getUserList 테스트 */ @Test public void getUserListTest() { /***Given***/ IUserDao userDao = new UserDao(); /***When***/ List<User> userList = userDao.getUserList(); /***Then***/ assertEquals(5, userList.size()); } @Test public void getUserTest() { /***Given***/ String userId = "brown"; IUserDao userDao = new UserDao(); /***When***/ User userVo = userDao.getUser(userId); /***Then***/ assertEquals("브라운", userVo.getUserNm()); assertEquals("brown1234", userVo.getPass()); } }
[ "sexyik@naver.com" ]
sexyik@naver.com
4c426d9c60ef6f3e4fcb855b9c8064ec1d47cec8
112bd08378041ad3451f1e30c812d3defe38746f
/app/src/androidTest/java/com/coolweather/android/util/HttpUtilTest.java
d7202c6439b7f9ac3997786fd91ff5128a1bf16f
[]
no_license
Aisw/kuWeather
e7e81e861d800103c75546bfe762921425809743
f26c90b7d428e123c71b5409a89dd438e723548e
refs/heads/main
2023-02-02T01:18:07.647505
2020-12-21T08:29:25
2020-12-21T08:29:25
323,274,061
0
0
null
null
null
null
UTF-8
Java
false
false
560
java
package com.coolweather.android.util; import org.junit.Test; import java.io.IOException; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import static org.junit.Assert.*; public class HttpUtilTest { @Test public void sendOKHttpRequest() throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://guolin.tech/api/china").build(); Response response = client.newCall(request).execute(); System.out.println(response.body()); } }
[ "1493881416@qq.com" ]
1493881416@qq.com
662a3ac3bde23b1768c0018b7678ce130b590436
ae5188951cce9a02934bd6f975d568cb69c9aa5f
/base/src/main/java/org/hpdroid/base/view/expandablelayout/ExpandableLinearLayout.java
7533f4be8529f085570ca2b7c8ee047d0342dc42
[]
no_license
marryperry/Common
46793b7cf5cc143dfa63900d15fcf398c3d38643
b27ad2d69551d02139443339d7d6928ba634fc86
refs/heads/master
2020-06-12T16:35:20.706042
2016-12-26T10:10:29
2016-12-26T10:10:29
75,793,600
1
0
null
2016-12-07T05:55:02
2016-12-07T03:02:06
Java
UTF-8
Java
false
false
10,111
java
package org.hpdroid.base.view.expandablelayout; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Configuration; import android.content.res.TypedArray; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.animation.Interpolator; import android.widget.LinearLayout; import com.hpdroid.base.R; import org.hpdroid.base.view.expandablelayout.util.FastOutSlowInInterpolator; import java.util.ArrayList; import java.util.List; public class ExpandableLinearLayout extends LinearLayout { public static final String KEY_SUPER_STATE = "super_state"; public static final String KEY_EXPANDED = "expanded"; private static final int DEFAULT_DURATION = 300; private int wms; private int hms; private List<View> expandableViews; private int duration = DEFAULT_DURATION; private boolean expanded = false; private Interpolator interpolator = new FastOutSlowInInterpolator(); private AnimatorSet animatorSet; private OnExpansionUpdateListener listener; public ExpandableLinearLayout(Context context) { super(context); init(null); } public ExpandableLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public ExpandableLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public ExpandableLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(attrs); } private void init(AttributeSet attrs) { if (attrs != null) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ExpandableLayout); duration = a.getInt(R.styleable.ExpandableLayout_el_duration, DEFAULT_DURATION); expanded = a.getBoolean(R.styleable.ExpandableLayout_el_expanded, false); a.recycle(); } expandableViews = new ArrayList<>(); } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); Bundle bundle = new Bundle(); bundle.putBoolean(KEY_EXPANDED, expanded); bundle.putParcelable(KEY_SUPER_STATE, superState); return bundle; } @Override protected void onRestoreInstanceState(Parcelable state) { Bundle bundle = (Bundle) state; expanded = bundle.getBoolean(KEY_EXPANDED); Parcelable superState = bundle.getParcelable(KEY_SUPER_STATE); for (View expandableView : expandableViews) { expandableView.setVisibility(expanded ? VISIBLE : GONE); } super.onRestoreInstanceState(superState); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { LayoutParams lp = (LayoutParams) params; if (lp.expandable) { expandableViews.add(child); child.setVisibility(expanded ? VISIBLE : GONE); } super.addView(child, index, params); } @Override public void removeView(View child) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.expandable) { expandableViews.remove(child); } super.removeView(child); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); wms = widthMeasureSpec; hms = heightMeasureSpec; } @Override public LinearLayout.LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } @Override protected void onConfigurationChanged(Configuration newConfig) { if (animatorSet != null) { animatorSet.cancel(); } super.onConfigurationChanged(newConfig); } public boolean isExpanded() { return expanded; } public void toggle() { toggle(true); } public void toggle(boolean animate) { if (expanded) { collapse(animate); } else { expand(animate); } } public void expand() { expand(true); } @SuppressLint("WrongCall") public void expand(boolean animate) { if (expanded) { return; } if (animatorSet != null) { animatorSet.cancel(); animatorSet = null; } expanded = true; for (View expandableView : expandableViews) { LayoutParams lp = (LayoutParams) expandableView.getLayoutParams(); // Calculate view's original height expandableView.setVisibility(View.VISIBLE); lp.width = lp.originalWidth; lp.height = lp.originalHeight; lp.weight = lp.originalWeight; super.onMeasure(wms, hms); } for (View expandableView : expandableViews) { int targetSize = getOrientation() == HORIZONTAL ? expandableView.getMeasuredWidth() : expandableView.getMeasuredHeight(); if (animate) { animateSize(expandableView, targetSize); } else { setSize(expandableView, targetSize); } } if (animatorSet != null && animate) { animatorSet.start(); } } public void collapse() { collapse(true); } public void collapse(boolean animate) { if (!expanded) { return; } if (animatorSet != null) { animatorSet.cancel(); animatorSet = null; } expanded = false; for (View expandableView : expandableViews) { if (animate) { animateSize(expandableView, 0); } else { setSize(expandableView, 0); } } if (animatorSet != null && animate) { animatorSet.start(); } } public void setOnExpansionUpdateListener(OnExpansionUpdateListener listener) { this.listener = listener; } private void animateSize(final View view, final int targetSize) { if (animatorSet == null) { animatorSet = new AnimatorSet(); animatorSet.setInterpolator(interpolator); animatorSet.setDuration(duration); } final LayoutParams lp = (LayoutParams) view.getLayoutParams(); lp.weight = 0; int currentSize; if (getOrientation() == HORIZONTAL) { currentSize = view.getWidth(); } else { currentSize = view.getHeight(); } ValueAnimator animator = ValueAnimator.ofInt(currentSize, targetSize); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { if (getOrientation() == HORIZONTAL) { view.getLayoutParams().width = (Integer) valueAnimator.getAnimatedValue(); } else { view.getLayoutParams().height = (Integer) valueAnimator.getAnimatedValue(); } view.requestLayout(); if (listener != null) { float fraction = targetSize == 0 ? 1 - valueAnimator.getAnimatedFraction() : valueAnimator.getAnimatedFraction(); listener.onExpansionUpdate(fraction); } } }); animator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { view.setVisibility(View.VISIBLE); } @Override public void onAnimationEnd(Animator animator) { if (targetSize == 0) { view.setVisibility(GONE); } else { lp.width = lp.originalWidth; lp.height = lp.originalHeight; lp.weight = lp.originalWeight; } } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); animatorSet.playTogether(animator); } private void setSize(View view, int targetSize) { LayoutParams lp = (LayoutParams) view.getLayoutParams(); if (targetSize == 0) { view.setVisibility(GONE); } else { lp.width = lp.originalWidth; lp.height = lp.originalHeight; lp.weight = lp.originalWeight; view.requestLayout(); } if (listener != null) { listener.onExpansionUpdate(targetSize == 0 ? 0f : 1f); } } public static class LayoutParams extends LinearLayout.LayoutParams { private final boolean expandable; private final int originalWidth; private final int originalHeight; private final float originalWeight; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ExpandableLayout); expandable = a.getBoolean(R.styleable.ExpandableLayout_layout_expandable, false); originalWidth = this.width; originalHeight = this.height; originalWeight = this.weight; a.recycle(); } } public interface OnExpansionUpdateListener { void onExpansionUpdate(float expansionFraction); } }
[ "huangpg@59store.com" ]
huangpg@59store.com
6d69bdc513067f1804308763315302d162b6f716
0192ccdbd35b0a43d4d933fe7d29097b56fdef2e
/webservice-restfull/src/com/ibanheiz/expose/ClienteResource.java
1d732849498baaa63ec030ad0498c880b77102ed
[]
no_license
MarcosToledo/treinamento-web-service
5e719d93afd934923618f2332cb3ad0e1c26d054
ee7a2e6da67fa6b643f89b6550bf3de0cd5c7a53
refs/heads/master
2021-01-17T22:13:34.953842
2015-10-03T18:53:37
2015-10-03T18:53:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,840
java
package com.ibanheiz.expose; import java.io.Serializable; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import com.ibanheiz.cliente.Cliente; import com.ibanheiz.cliente.ClienteService; @Path("/clientes") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Singleton public class ClienteResource implements Serializable { private static final long serialVersionUID = -6997135368312026507L; @Inject private ClienteService clienteService; @GET public Response buscarTodos() { List<Cliente> clientes = clienteService.buscarTodos(); return Response.ok(clientes.toArray(new Cliente[clientes.size()])).build(); } @POST public Response salvar(Cliente cliente) { try { System.out.println(cliente); // clienteService.salvar(cliente); } catch (Exception e) { e.printStackTrace(); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } return Response.ok(cliente).build(); } @PUT @Path("{id}") public Response alterar(@PathParam("id") String id, Cliente cliente) { cliente.setId(Integer.parseInt(id)); try { clienteService.alterar(cliente); } catch (Exception e) { e.printStackTrace(); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } return Response.ok(cliente).build(); } @DELETE @Path("{id}") public Response remover(@PathParam("id") String id) { return Response.status(Status.NOT_IMPLEMENTED).build(); } }
[ "nicolas.ibanheiz@gmail.com" ]
nicolas.ibanheiz@gmail.com
0d96f911f1f29ee6397ba34ae107fb90ecaf2546
85dfa29b10cf4fcc15e8ac45922e56eb72a40a85
/products/src/main/java/se/telenor/products/dto/ResponseWrapper.java
f01a565d4e08d62f79e54adb32c848f2080b9728
[]
no_license
nemethsamusandor/telenor
cc73d9ecc2642b49e1626a5ec0754525d2437d75
8435a3f3dcaeb4a5db782974d4ca50b481b17af2
refs/heads/master
2022-12-19T21:18:58.717698
2020-09-21T05:38:12
2020-09-21T05:38:12
295,996,793
0
0
null
null
null
null
UTF-8
Java
false
false
349
java
package se.telenor.products.dto; import java.util.List; /** * @author Sandor Nemeth * @version 1.00 * @date 16.09.2020 */ public class ResponseWrapper { private List<Payload> data; public List<Payload> getData() { return data; } public void setData(List<Payload> data) { this.data = data; } }
[ "extern.sandor.nemeth@porscheinformatik.com" ]
extern.sandor.nemeth@porscheinformatik.com
c97d140049a8a60e177a84b379c491bfbd71732e
da074b8fe10c215055f47f33a60804e3f781d788
/app/src/main/java/com/manturf/manturf/Fragments/TopTimeLine.java
cfafe7e85f134b03f86d898c63eaf35cb567115d
[]
no_license
wakwak3125/Manturf
e92ec5b23fb3801df0d5545c1cc1da5139314015
121e70bfcc0c8c27ba6f93db53405b3a5645c17a
refs/heads/master
2016-09-06T16:41:31.506343
2015-01-26T06:28:06
2015-01-26T06:28:06
28,717,284
0
0
null
null
null
null
UTF-8
Java
false
false
5,467
java
package com.manturf.manturf.Fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.manturf.manturf.AppController; import com.manturf.manturf.Item.NomikaiList; import com.manturf.manturf.R; import com.manturf.manturf.adapter.TopTimeLineAdapter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class TopTimeLine extends Fragment { private TopTimeLineAdapter mAdapter; public static final String TAG = TopTimeLine.class.getSimpleName(); /* public static TopTimeLine newInstance() { TopTimeLine fragment = new TopTimeLine(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } */ public TopTimeLine() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_top_time_line, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mAdapter = new TopTimeLineAdapter(getActivity()); ListView listView = (ListView)getView().findViewById(R.id.list1); listView.setAdapter(mAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ListView listView = (ListView)parent; NomikaiList nomikaiList = (NomikaiList)listView.getItemAtPosition(position); Log.i(TAG,"onItemClick:"); Log.i(TAG,"position = " + position); Log.i(TAG,"id = " + id); Log.i(TAG,"Api側のid = " + nomikaiList.getId()); Log.i(TAG,"飲み会タイトル = " + nomikaiList.getTitle()); Log.i(TAG,"業界 = " + nomikaiList.getContent()); Log.i(TAG,"場所 = " + nomikaiList.getPlace()); Log.i(TAG,"日時 = " + nomikaiList.getDate()); Log.i(TAG,"時間 = " + nomikaiList.getTime()); } }); fetch(); } private void fetch(){ JsonObjectRequest request = new JsonObjectRequest( "http://manturf2.herokuapp.com/api/v1/events", null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { // TODO:Jsonパースやで! try { List<NomikaiList> nomikaiLists = parse(jsonObject); mAdapter.swapNomikaiList(nomikaiLists); } catch (JSONException e){ Toast.makeText(getActivity(),"フェッチできないね。"+e.getMessage(), Toast.LENGTH_SHORT).show(); Log.d("tag","フェッチできないね。"+ e.getMessage()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getActivity(), "パースできませんでした" + error.getMessage(), Toast.LENGTH_SHORT).show(); //Log.d("tag","パースできませんでした" + error.getMessage()); } } ); AppController.getInstance().getRequestQueue().add(request); } private List<NomikaiList> parse(JSONObject json)throws JSONException{ ArrayList<NomikaiList> records = new ArrayList<>(); JSONArray jsonimages = json.getJSONArray("all_events"); for (int i=0; i<jsonimages.length();i++){ JSONObject jsonimage = jsonimages.getJSONObject(i); int id = jsonimage.getInt("id"); String title = jsonimage.getString("title"); String content = jsonimage.getString("content"); String place = jsonimage.getString("place"); String time = jsonimage.getString("time"); String occupation = jsonimage.getString("occupation"); String date = jsonimage.getString("date"); NomikaiList record = new NomikaiList(id,title,content,place,time,occupation,date); records.add(record); } return records; } public interface OnFragmentInteractionListener { // TODO: Update argument type and name // public void onFragmentInteraction(Uri uri); } }
[ "rsakaguchi3125@gmail.com" ]
rsakaguchi3125@gmail.com
8131a7d9459cc96fe20242a129df9f44abf3495a
4f1d4025ec27f8c24008776a7608bd245944a829
/icode/src/test/java/com/example/icode/ExampleUnitTest.java
9a5203e0674ded5946c422c99ce3e2ffe27e5954
[]
no_license
allencall1234/AsDemos
ff0d04a00bd0e328caabed2d26f8f6ef3e460e35
edfc22cbfd36fb43b635bb55fea184bf8d51f06a
refs/heads/master
2021-01-20T01:18:12.607872
2018-02-09T10:17:34
2018-02-09T10:17:34
101,282,867
0
0
null
null
null
null
UTF-8
Java
false
false
395
java
package com.example.icode; 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); } }
[ "zhulanting@dafycredit.com" ]
zhulanting@dafycredit.com
bef688b62a5286b1cb3a07e81170a2f4fe46d1c9
63f23757f2f1aae86e4a07f6ea9c2efd3131392b
/domain-api/src/main/java/org/dfm/piggyurl/domain/common/ShortUrlLevel.java
f03a02476377288e9718c9f96114e5cac248e6f5
[ "MIT" ]
permissive
er-ashishraj/piggyurl
e9abb4efd3b85df1b08bb0251b1d48a3d00963dc
6b0d6b8aa985afa29adc5d1cdfbceac2b969343f
refs/heads/master
2023-01-04T22:54:57.727901
2022-12-20T09:57:05
2022-12-20T09:57:05
294,021,760
0
0
MIT
2020-09-18T16:57:17
2020-09-09T06:21:27
Java
UTF-8
Java
false
false
343
java
package org.dfm.piggyurl.domain.common; public enum ShortUrlLevel { NONE("NONE"), USER("USER"), TRIBE("TRIBE"), FEATURE_TEAM("FEATURE_TEAM"); private String shortUrlLevel; ShortUrlLevel(final String shortUrlLevel) { this.shortUrlLevel = shortUrlLevel; } public String getShortUrlLevel() { return this.shortUrlLevel; } }
[ "er.ashishraj2010@gmail.com" ]
er.ashishraj2010@gmail.com
3c14638df33ac883126e9399b4173407c2311474
c9c989fc5a4450176e679d22bea6a7656b917ad6
/PrebidMobile/API1.0Demo/src/androidTest/java/org/prebid/mobile/app/MoPubBannerTest.java
e08cb73cb57ef49b6e7df9f17226df42aaecaca6
[ "Apache-2.0" ]
permissive
AntoineJac/prebid-mobile-android
6fddd90c1735fba5933fbf339851e0904855978e
846365a3847cab16c7643b825fd9caf4db3aa10c
refs/heads/master
2020-05-02T02:45:12.180290
2019-03-26T06:18:55
2019-03-26T06:18:55
142,245,930
0
1
Apache-2.0
2019-03-26T03:47:17
2018-07-25T04:08:24
Java
UTF-8
Java
false
false
5,246
java
/* * Copyright 2018-2019 Prebid.org, Inc. * * 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.prebid.mobile.app; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.prebid.mobile.ResultCode; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.rule.ActivityTestRule; import static androidx.test.espresso.Espresso.onData; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.action.ViewActions.typeText; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.web.assertion.WebViewAssertions.webContent; import static androidx.test.espresso.web.assertion.WebViewAssertions.webMatches; import static androidx.test.espresso.web.matcher.DomMatchers.containingTextInBody; import static androidx.test.espresso.web.model.Atoms.getCurrentUrl; import static androidx.test.espresso.web.sugar.Web.onWebView; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.core.AllOf.allOf; import static org.junit.Assert.assertEquals; @RunWith(AndroidJUnit4.class) public class MoPubBannerTest { @Rule public ActivityTestRule<MainActivity> m = new ActivityTestRule<>(MainActivity.class); @Test public void testMoPubWithoutAutoRefreshAndSize300x250() throws Exception { onView(withId(R.id.adServerSpinner)).perform(click()); onData(allOf(is(instanceOf(String.class)), is("MoPub"))).perform(click()); onView(withId(R.id.autoRefreshInput)).perform(typeText("0")); onView(withId(R.id.showAd)).perform(click()); Thread.sleep(10000); assertEquals(ResultCode.SUCCESS, ((DemoActivity) TestUtil.getCurrentActivity()).resultCode); onView(withId(R.id.adFrame)).check(matches(isDisplayed())); onWebView().check(webMatches(getCurrentUrl(), containsString("ads.mopub.com"))); onWebView().check(webContent(containingTextInBody("ucTag.renderAd"))); assertEquals(1, ((DemoActivity) TestUtil.getCurrentActivity()).refreshCount); Thread.sleep(120000); assertEquals(1, ((DemoActivity) TestUtil.getCurrentActivity()).refreshCount); } @Test public void testMoPubWithoutAutoRefreshAndSize320x50() throws Exception { onView(withId(R.id.adServerSpinner)).perform(click()); onData(allOf(is(instanceOf(String.class)), is("MoPub"))).perform(click()); onView(withId(R.id.adSizeSpinner)).perform(click()); onData(allOf(is(instanceOf(String.class)), is("320x50"))).perform(click()); onView(withId(R.id.autoRefreshInput)).perform(typeText("15000")); onView(withId(R.id.showAd)).perform(click()); Thread.sleep(10000); assertEquals(ResultCode.SUCCESS, ((DemoActivity) TestUtil.getCurrentActivity()).resultCode); onView(withId(R.id.adFrame)).check(matches(isDisplayed())); onWebView().check(webMatches(getCurrentUrl(), containsString("ads.mopub.com"))); onWebView().check(webContent(containingTextInBody("pbm.showAdFromCacheId"))); assertEquals(1, ((DemoActivity) TestUtil.getCurrentActivity()).refreshCount); Thread.sleep(120000); assertEquals(1, ((DemoActivity) TestUtil.getCurrentActivity()).refreshCount); } @Test public void testMoPubWithAutoRefreshAndSize300x250() throws Exception { onView(withId(R.id.adServerSpinner)).perform(click()); onData(allOf(is(instanceOf(String.class)), is("MoPub"))).perform(click()); onView(withId(R.id.autoRefreshInput)).perform(typeText("30000")); onView(withId(R.id.showAd)).perform(click()); Thread.sleep(10000); assertEquals(ResultCode.SUCCESS, ((DemoActivity) TestUtil.getCurrentActivity()).resultCode); onView(withId(R.id.adFrame)).check(matches(isDisplayed())); onWebView().check(webMatches(getCurrentUrl(), containsString("ads.mopub.com"))); onWebView().check(webContent(containingTextInBody("ucTag.renderAd"))); assertEquals(1, ((DemoActivity) TestUtil.getCurrentActivity()).refreshCount); Thread.sleep(120000); assertEquals(5, ((DemoActivity) TestUtil.getCurrentActivity()).refreshCount); ((DemoActivity) TestUtil.getCurrentActivity()).stopAutoRefresh(); Thread.sleep(120000); assertEquals(5, ((DemoActivity) TestUtil.getCurrentActivity()).refreshCount); } }
[ "noreply@github.com" ]
noreply@github.com
54fa3fc08271ad321713cf5cccfb46ce7d4bf394
a8d433f451696cd019337b6b986496e464cd0210
/dalarm/dalarm-flink/src/main/java/org/enast/hummer/stream/flink/JSONKeyValueDeserializationSchemaTest.java
d196423b4d76580988673f9011cfca328bf50b92
[ "Apache-2.0" ]
permissive
lideen999/dalarm
6f2dcef5080c3a3c711f1dc8584a3ead350891b0
2adc37889beac04c4085b979fb8219ea2056ee84
refs/heads/master
2022-12-29T12:38:01.887013
2020-07-14T03:30:40
2020-07-14T03:30:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,405
java
package org.enast.hummer.stream.flink; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011; import org.apache.flink.streaming.util.serialization.JSONKeyValueDeserializationSchema; import org.enast.hummer.stream.flink.utils.ExecutionEnvUtil; import java.util.Properties; import static org.enast.hummer.stream.flink.utils.KafkaConfigUtil.buildKafkaProps; /** * Desc: 该 Schema 可以反序列化 JSON 成对象,并包含数据的元数据信息 */ public class JSONKeyValueDeserializationSchemaTest { public static void main(String[] args) throws Exception { final ParameterTool parameterTool = ExecutionEnvUtil.createParameterTool(args); StreamExecutionEnvironment env = ExecutionEnvUtil.prepare(parameterTool); Properties props = buildKafkaProps(parameterTool); //可以控制是否需要元数据字段 FlinkKafkaConsumer011<ObjectNode> kafkaConsumer = new FlinkKafkaConsumer011<>("test", new JSONKeyValueDeserializationSchema(true), props); env.addSource(kafkaConsumer).print(); //读取到的数据在 value 字段中,对应的元数据在 metadata 字段中 env.execute(); } }
[ "154903157@qq.com" ]
154903157@qq.com