hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
d2da576bbb69ebc498721b2d798f1a1732b09806 | 3,630 | package core.document.graph;
import com.sun.javafx.collections.ObservableListWrapper;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
public class FilteredNetworkGraph extends LogicalGraph {
protected final NetworkGraph<LogicalNode, LogicalEdge> root;
private final ObservableListWrapper<LogicalNode> nodesHidden;
public FilteredNetworkGraph(LogicalGraph root) {
super(root.getCidrList());
this.root = root;
nodesHidden = new ObservableListWrapper<>(new LinkedList<>());
root.nodesObservable.addListener(this::Handle_NodeListChanged);
root.edgesObservable.addListener(this::Handle_EdgeListChanged);
nodesHidden.addListener(this::Handle_HiddenListChanged);
}
public void initialize() {
addNodes(root.nodesObservable);
updateEdges();
refresh();
}
@Override
protected void createSubnets(final List<LogicalNode> nodesNew) {
//Do not create subnets from a FilteredNetworkGraph
}
private void Handle_NodeListChanged(ListChangeListener.Change<? extends LogicalNode> change) {
LinkedList<LogicalNode> nodesRemoved = new LinkedList<>();
LinkedList<LogicalNode> nodesAdded = new LinkedList<>();
while(change.next()) {
nodesRemoved.addAll(change.getRemoved());
nodesAdded.addAll(change.getAddedSubList());
}
removeNodes(nodesRemoved);
addNodes(nodesAdded);
updateEdges();
refresh();
}
private void Handle_HiddenListChanged(ListChangeListener.Change<? extends LogicalNode> change) {
LinkedList<LogicalNode> nodesRemoved = new LinkedList<>();
LinkedList<LogicalNode> nodesAdded = new LinkedList<>();
while(change.next()) {
nodesAdded.addAll(change.getRemoved());
nodesRemoved.addAll(change.getAddedSubList());
}
removeNodes(nodesRemoved);
addNodes(nodesAdded);
updateEdges();
refresh();
}
private void Handle_EdgeListChanged(ListChangeListener.Change<? extends LogicalEdge> change) {
updateEdges();
refresh();
}
protected void updateEdges() {
//Only use edges committed in the root, but check against uncommitted nodes.
List<LogicalEdge> edgesAll = new LinkedList<>(root.edgesObservable);
List<LogicalEdge> edgesFiltered = edgesAll.stream().filter(edge -> nodes.containsKey(edge.getSource()) && nodes.containsKey(edge.getDestination())).collect(Collectors.toList());
List<LogicalEdge> edgesRemoved = new LinkedList<>(edges.keySet());
edgesRemoved.removeAll(edgesFiltered);
List<LogicalEdge> edgesAdded = new LinkedList<>(edgesFiltered);
edgesAdded.removeAll(edges.keySet());
addEdges(edgesAdded);
removeEdges(edgesRemoved);
}
@Override
public void clearTopology() {
//We don't call the superclass implementation since the superclass clears the node lists and we will propagate that from the ObservableLists in root.
nodesHidden.clear();
}
@Override
public int indexOf(LogicalNode node) {
return this.root.indexOf(node);
}
@Override
public int indexOf(LogicalEdge edge) {
return this.root.indexOf(edge);
}
@Override
public List<LogicalNode> getRawNodeList() {
return this.root.getRawNodeList();
}
public ObservableList<LogicalNode> getHiddenNodes() {
return nodesHidden;
}
}
| 32.410714 | 185 | 0.684298 |
963a358181c0010d4967db9ca5051463beef5a2b | 750 | package Loops.Exercises4;
import java.util.Scanner;
public class LoopExercises4 {
public static void main(String[] args) {
int n;
int r;
int sumn=1;
int sumr=1;
int com=1;
int result=0;
try (Scanner input = new Scanner(System.in)) {
System.out.print("Please give a n:");
n =input.nextInt();
System.out.print("Please give a r:");
r =input.nextInt();
}
for(int i=1; i<=n; i++){
sumn=sumn*i;
}
for(int i=1; i<=r; i++){
sumr=sumr*i;
}
for(int i=1; i<=(n-r); i++){
com=com*i;
}
result=sumn/(sumr*com);
System.out.println("Result is "+result);
}
}
| 24.193548 | 53 | 0.474667 |
78d3a5ae589e51ba6ac467232fffcc72ea398dbd | 304 | package Java2;
public class Rectangle {
private double length;
private double width;
public Rectangle(double length, double width){this.length=length;this.width=width;}
public double getPerimeter() {return length * 2 + width * 2;}
public double getArea() {return length * width;}
} | 27.636364 | 87 | 0.710526 |
8305eedbc1a86a1b9854583b79b81dcf45aeaeda | 3,765 | package com.jspxcms.ext.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import com.jspxcms.core.domain.Site;
/**
* Friendlink
*
* @author yangxing
*
*/
@Entity
@Table(name = "cms_friendlink")
public class Friendlink implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* 已审核
*/
public static final int AUDITED = 0;
/**
* 未审核
*/
public static final int SAVED = 1;
public void applyDefaultValue() {
if (getSeq() == null) {
setSeq(Integer.MAX_VALUE);
}
if(getStatus()==null){
setStatus(AUDITED);
}
}
private Integer id;
private FriendlinkType type;
private Site site;
private String name;
private String url;
private Integer seq;
private String logo;
private String description;
private String email;
private Boolean recommend;
private Integer status;
private Boolean withLogo;
@Id
@Column(name = "f_friendlink_id", unique = true, nullable = false)
@TableGenerator(name = "tg_cms_friendlink", pkColumnValue = "cms_friendlink", table = "t_id_table", pkColumnName = "f_table", valueColumnName = "f_id_value", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "tg_cms_friendlink")
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "f_friendlinktype_id", nullable = false)
public FriendlinkType getType() {
return this.type;
}
public void setType(FriendlinkType type) {
this.type = type;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "f_site_id",nullable =false)
public Site getSite() {
return this.site;
}
public void setSite(Site site) {
this.site = site;
}
@Column(name = "f_name", nullable = false, length = 100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "f_url", nullable = false)
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
@Column(name = "f_seq", nullable = false)
public Integer getSeq() {
return this.seq;
}
public void setSeq(Integer seq) {
this.seq = seq;
}
@Column(name = "f_logo")
public String getLogo() {
return this.logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
@Column(name = "f_description")
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name = "f_email", length = 100)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name = "f_is_recommend", nullable = false, length = 1)
public Boolean getRecommend() {
return this.recommend;
}
public void setRecommend(Boolean recommend) {
this.recommend = recommend;
}
@Column(name = "f_status", nullable = false, length = 1)
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Column(name = "f_is_with_logo", nullable = false, length = 1)
public Boolean getWithLogo() {
return withLogo;
}
public void setWithLogo(Boolean withLogo) {
this.withLogo = withLogo;
}
}
| 21.889535 | 197 | 0.67676 |
86c6596b45372291e683bc571e09c43cda85a4b2 | 453 | package eta.runtime.thunk;
import eta.runtime.stg.StgClosure;
import eta.runtime.stg.StgContext;
import eta.runtime.stg.StgConstr;
import eta.runtime.apply.Apply;
public class SelectorNNoUpd extends SelectorNoUpd {
public SelectorNNoUpd(int i, StgClosure p) {
super(i, p);
}
@Override
public void enter(StgContext context) {
super.enter(context);
context.I(1, ((StgConstr) context.R(1)).getN(index));
}
}
| 22.65 | 61 | 0.693157 |
42aee5a4ef134b3cb917d9a26bc8b17daecf1f89 | 1,334 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.facebook;
import android.content.*;
// Referenced classes of package com.facebook:
// AccessTokenManager
public final class CurrentAccessTokenExpirationBroadcastReceiver extends BroadcastReceiver
{
public CurrentAccessTokenExpirationBroadcastReceiver()
{
// 0 0:aload_0
// 1 1:invokespecial #8 <Method void BroadcastReceiver()>
// 2 4:return
}
public void onReceive(Context context, Intent intent)
{
if("com.facebook.sdk.ACTION_CURRENT_ACCESS_TOKEN_CHANGED".equals(((Object) (intent.getAction()))))
//* 0 0:ldc1 #13 <String "com.facebook.sdk.ACTION_CURRENT_ACCESS_TOKEN_CHANGED">
//* 1 2:aload_2
//* 2 3:invokevirtual #19 <Method String Intent.getAction()>
//* 3 6:invokevirtual #25 <Method boolean String.equals(Object)>
//* 4 9:ifeq 18
AccessTokenManager.getInstance().currentAccessTokenChanged();
// 5 12:invokestatic #31 <Method AccessTokenManager AccessTokenManager.getInstance()>
// 6 15:invokevirtual #34 <Method void AccessTokenManager.currentAccessTokenChanged()>
// 7 18:return
}
}
| 37.055556 | 100 | 0.682159 |
87b2095c0e06f0521b782eda5e9c859b88760081 | 1,562 | package com.opalfire.foodorder.models;
public class RecommendedDish {
String avaialable;
String category;
String description;
String imgUrl;
Boolean isVeg;
String name;
String price;
public RecommendedDish(String str, String str2, String str3, Boolean bool, String str4, String str5, String str6) {
this.name = str;
this.category = str2;
this.price = str3;
this.isVeg = bool;
this.imgUrl = str4;
this.description = str5;
this.avaialable = str6;
}
public String getAvaialable() {
return this.avaialable;
}
public void setAvaialable(String str) {
this.avaialable = str;
}
public String getName() {
return this.name;
}
public void setName(String str) {
this.name = str;
}
public String getCategory() {
return this.category;
}
public void setCategory(String str) {
this.category = str;
}
public String getPrice() {
return this.price;
}
public void setPrice(String str) {
this.price = str;
}
public Boolean getIsVeg() {
return this.isVeg;
}
public void setIsVeg(Boolean bool) {
this.isVeg = bool;
}
public String getImgUrl() {
return this.imgUrl;
}
public void setImgUrl(String str) {
this.imgUrl = str;
}
public String getDescription() {
return this.description;
}
public void setDescription(String str) {
this.description = str;
}
}
| 20.025641 | 119 | 0.591549 |
3193793cb87197e8086508055f4b1300d278e623 | 3,281 | package com.u8.server.sdk.liebao;
import com.u8.server.data.UChannel;
import com.u8.server.data.UOrder;
import com.u8.server.data.UUser;
import com.u8.server.log.Log;
import com.u8.server.sdk.*;
import com.u8.server.utils.EncryptUtils;
import net.sf.json.JSONObject;
import java.util.*;
/**
* 猎宝游戏
* Created by lizhong on 2017/09/18.
*/
public class LiebaoSDK implements ISDKScript{
private String gameid;
private String username;
private String logintime;
private String sign;
@Override
public void verify(final UChannel channel, String extension, final ISDKVerifyListener callback) {
try{
JSONObject json = JSONObject.fromObject(extension);
username = json.getString("username");
logintime = json.getString("logintime");
gameid = channel.getCpID();
Map<String,String> params = new LinkedHashMap<String, String>();
params.put("gameid",gameid);
params.put("username",username);
params.put("logintime",logintime);
sign = generateSign(params,channel);
params.put("sign",sign);
UHttpAgent httpClient = UHttpAgent.getInstance();
httpClient.post(channel.getChannelAuthUrl(), params, new UHttpFutureCallback() {
@Override
public void completed(String result) {
JSONObject json = JSONObject.fromObject(result);
String code = json.getString("code");
boolean status = json.getBoolean("status");
String msg = json.getString("msg");
if("200".equals(code)&&status){
callback.onSuccess(new SDKVerifyResult(true,username,username,username,msg));
return;
}
callback.onFailed(channel.getMaster().getSdkName() + " verify failed. the post result is " + result);
}
@Override
public void failed(String err) {
callback.onFailed(channel.getMaster().getSdkName() + " verify failed. " + err);
}
});
}catch (Exception e){
e.printStackTrace();
callback.onFailed(channel.getMaster().getSdkName() + " verify execute failed. the exception is "+e.getMessage());
}
}
@Override
public void onGetOrderID(UUser user, UOrder order, ISDKOrderListener callback) {
if(callback != null){
callback.onSuccess("");
}
}
public static String generateSign(Map<String, String> params,UChannel channel) {
List<String> keys = new ArrayList<String>(params.keySet());
StringBuilder postdatasb = new StringBuilder();
for (int i = 0; i < keys.size(); i++) {
String k = keys.get(i);
String v = String.valueOf(params.get(k));
postdatasb.append(k + "=" + v + "&");
}
postdatasb.append("appkey=").append(channel.getCpAppKey());
//postdatasb.deleteCharAt(postdatasb.length() - 1);
//对排序后的参数附加开发商签名密钥
return EncryptUtils.md5(postdatasb.toString()).toLowerCase();
}
}
| 40.506173 | 126 | 0.576349 |
5509cf7197f66ead7137fab64cb62c188947ad5b | 3,146 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2007, 2009, 2010, 2011, 2013, 2014, 2016 Synacor, Inc.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software Foundation,
* version 2 of the License.
*
* 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 <https://www.gnu.org/licenses/>.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.account.callback;
import java.util.Map;
import com.zimbra.common.service.ServiceException;
import com.zimbra.cs.account.AttributeCallback;
import com.zimbra.cs.account.Domain;
import com.zimbra.cs.account.Entry;
import com.zimbra.cs.account.Provisioning;
public class DomainStatus extends AttributeCallback {
@Override
public void preModify(CallbackContext context, String attrName, Object value,
Map attrsToModify, Entry entry)
throws ServiceException {
if (!(value instanceof String))
throw ServiceException.INVALID_REQUEST(Provisioning.A_zimbraDomainStatus+" is a single-valued attribute", null);
String status = (String) value;
if (status.equals(Provisioning.DOMAIN_STATUS_SHUTDOWN)) {
throw ServiceException.INVALID_REQUEST("Setting " + Provisioning.A_zimbraDomainStatus + " to " + Provisioning.DOMAIN_STATUS_SHUTDOWN + " is not allowed. It is an internal status and can only be set by server", null);
} else if (status.equals(Provisioning.DOMAIN_STATUS_CLOSED)) {
attrsToModify.put(Provisioning.A_zimbraMailStatus, Provisioning.MAIL_STATUS_DISABLED);
} else {
if (entry != null) {
Domain domain = (Domain)entry;
if (domain.beingRenamed())
throw ServiceException.INVALID_REQUEST("domain " + domain.getName() + " is being renamed, cannot change " + Provisioning.A_zimbraDomainStatus, null);
}
String alsoModifyingMailStatus = (String)attrsToModify.get(Provisioning.A_zimbraMailStatus);
if (alsoModifyingMailStatus == null) {
if (entry != null) {
String curMailStatus = entry.getAttr(Provisioning.A_zimbraMailStatus);
if (status.equals(Provisioning.DOMAIN_STATUS_SUSPENDED) &&
curMailStatus != null &&
curMailStatus.equals(Provisioning.MAIL_STATUS_DISABLED))
return;
}
attrsToModify.put(Provisioning.A_zimbraMailStatus, Provisioning.MAIL_STATUS_ENABLED);
}
}
}
@Override
public void postModify(CallbackContext context, String attrName, Entry entry) {
}
}
| 43.09589 | 229 | 0.661157 |
b2c25036582997aed73036e8c632dd2ec5238ead | 195 | package com.automaton.accessories;
import java.util.concurrent.CompletableFuture;
public interface BatteryAccessory extends Accessory {
CompletableFuture<Integer> getBatteryLevelState();
}
| 24.375 | 54 | 0.830769 |
d9caa12ec3aa117d0fcc06666e5437f324dc74ee | 815 | package com.hdw.enterprise.dto;
import com.hdw.common.mybatis.base.dto.CommonDTO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @Description com.hdw.enterprise.param
* @Author TuMingLong
* @Date 2019/11/7 10:36
*/
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel("查询消息类型参数对象")
public class EnterpriseJobDTO extends CommonDTO {
@ApiModelProperty("主键ID")
private String id;
@ApiModelProperty("企业ID")
private String enterpriseId;
@ApiModelProperty("职位代码")
private String jobCode;
@ApiModelProperty("职位名称")
private String jobName;
@ApiModelProperty("部门ID")
private String departmentId;
@ApiModelProperty(value = "用户ID", hidden = true)
private Long userId;
}
| 25.46875 | 52 | 0.741104 |
0d9b1be412cb70cba6765f63e613e97de73c3a26 | 891 | package com.savorgames.api.v1;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import com.savorgames.api.v1.resp.BaseResEntity;
import com.savorgames.api.v1.resp.ResValidFailEntity;
public class BaseApiController {
protected BaseResEntity baseResEntity = new BaseResEntity();
/**
* 判断错误 如果有错误返回一个ResponseValidError类型
* @param result
* @return
*/
protected ResValidFailEntity validHasErrors(BindingResult result) {
if(result.hasErrors()){
ResValidFailEntity resve = new ResValidFailEntity();
Map<String, String> es = new HashMap<>();
List<FieldError> lserror = result.getFieldErrors();
for(FieldError e : lserror){
es.put(e.getField(), e.getDefaultMessage());
}
resve.setErrors(es);
return resve;
}
return null;
}
}
| 24.75 | 68 | 0.748597 |
72b69e2827b13bf1411fa81c12322b1f9ce9028d | 1,346 | package codeforces;
import java.util.Scanner;
/**
* Created by sherxon on 12/25/16.
*/
public class Voting {
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
int n=in.nextInt();
in.nextLine();
char[] s=in.nextLine().toCharArray();
int d=-1;
int r=-1;
for (int k = 0; k <s.length; k++) {
if(s[k]=='D' && d==-1){
d=k;
}else if(s[k]=='R' && r==-1){
r=k;
}
if(r>-1 && d>-1)break;
}
char c=0;
for (int i = 0; i < s.length; i++) {
if(s[i]=='D'){
if(i<d)continue;
int j = r+1;
for (; j<s.length; j++)
if(s[i]=='R') break;
if(j==s.length){
c='D';
break;
}
r=j;
}else{
if(i<r)continue;
int j = d+1;
for (; j <s.length; j++)
if(s[i]=='D') break;
if(j==s.length) {
c='R';
break;
}
d=j;
}
}
if(c>0) System.out.println(c);
else{
System.out.println(r + " " + d);
}
}
}
| 24.472727 | 45 | 0.325409 |
770450434c388f21c5c69df8388d562091c75819 | 4,843 | package li.strolch.execution;
import static li.strolch.model.StrolchModelConstants.BAG_PARAMETERS;
import static li.strolch.model.StrolchModelConstants.PolicyConstants.PARAM_RESERVED;
import static org.junit.Assert.*;
import java.io.File;
import li.strolch.execution.service.StartActivityExecutionService;
import li.strolch.model.Locator;
import li.strolch.model.Resource;
import li.strolch.model.State;
import li.strolch.model.Tags;
import li.strolch.model.activity.Action;
import li.strolch.model.activity.Activity;
import li.strolch.model.parameter.BooleanParameter;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.privilege.model.Certificate;
import li.strolch.service.LocatorArgument;
import li.strolch.service.parameter.SetParameterService;
import li.strolch.service.parameter.SetParameterService.SetParameterArg;
import li.strolch.testbase.runtime.RuntimeMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ReservationExecutionTest extends RuntimeMock {
private static final Logger logger = LoggerFactory.getLogger(ReservationExecutionTest.class);
@Before
public void before() {
mockRuntime(new File("target/" + ReservationExecutionTest.class.getName()),
new File("src/test/resources/executiontest"));
startContainer();
}
@After
public void after() {
destroyRuntime();
}
@Test
public void shouldNotExecuteWhenReserved() throws InterruptedException {
Locator activityLoc = Locator.valueOf(Tags.ACTIVITY, "ToStock", "produceMachine1");
Certificate cert = loginTest();
// before we execute, we reserve, so execution can't be done
SetParameterService setParamSvc = new SetParameterService();
SetParameterArg setParamArg = new SetParameterArg();
setParamArg.locator = Locator
.valueOf(Tags.RESOURCE, "Machine", "machine1", Tags.BAG, BAG_PARAMETERS, PARAM_RESERVED);
setParamArg.valueAsString = "true";
doServiceAssertResult(cert, setParamSvc, setParamArg);
// now we try to start the execution of the activity
StartActivityExecutionService svc = new StartActivityExecutionService();
LocatorArgument arg = new LocatorArgument();
arg.realm = "execution";
arg.locator = activityLoc;
doServiceAssertResult(cert, svc, arg);
// and verify that the activity is still created as the
// first element tries to reserve the machine, which fail
// as we previously reserved it manually
try (StrolchTransaction tx = getRealm("execution").openTx(cert, ReservationExecutionTest.class, true)) {
Action action = tx.findElement(activityLoc.append("produce"));
assertEquals(State.CREATED, action.getState());
}
}
@Test
public void shouldExecuteWhenNotReserved() throws InterruptedException {
Locator activityLoc = Locator.valueOf(Tags.ACTIVITY, "ToStock", "produceMachine2");
Certificate cert = loginTest();
try (StrolchTransaction tx = getRealm("execution").openTx(cert, ReservationExecutionTest.class, true)) {
// verify that the machine is not reserved
Resource machine = tx.getResourceBy("Machine", "machine1");
BooleanParameter reservedP = machine.getParameter(BAG_PARAMETERS, PARAM_RESERVED);
logger.info("Checking machine is not reserved initially");
assertFalse(reservedP.getValue());
}
// start the execution of the activity
StartActivityExecutionService svc = new StartActivityExecutionService();
LocatorArgument arg = new LocatorArgument();
arg.realm = "execution";
arg.locator = activityLoc;
doServiceAssertResult(cert, svc, arg);
Thread.sleep(50L);
try (StrolchTransaction tx = getRealm("execution").openTx(cert, ReservationExecutionTest.class, true)) {
// and verify that the activity is in execution
Action action = tx.findElement(activityLoc.append("reserve"));
assertEquals(State.EXECUTED, action.getState());
// verify that the machine is reserved
Resource machine = tx.getResourceBy("Machine", "machine1");
BooleanParameter reservedP = machine.getParameter(BAG_PARAMETERS, PARAM_RESERVED);
logger.info("Checking machine is reserved, after reserve action is executed.");
assertTrue(reservedP.getValue());
}
// now wait till execution should be finished
Thread.sleep(300L);
try (StrolchTransaction tx = getRealm("execution").openTx(cert, ReservationExecutionTest.class, true)) {
// and now verify is executed
Activity activity = tx.findElement(activityLoc);
assertEquals(State.EXECUTED, activity.getState());
// verify that the machine is not reserved anymore
Resource machine = tx.getResourceBy("Machine", "machine1");
BooleanParameter reservedP = machine.getParameter(BAG_PARAMETERS, PARAM_RESERVED);
logger.info("Checking machine is released, after release action is executed.");
assertFalse(reservedP.getValue());
}
}
}
| 36.141791 | 106 | 0.772868 |
566bcfa1cc583236249a27fef864bb92c2759eb1 | 149 | package soar.cluster.instance;
/**
* FailFastCluster
*
* @author xiuyuhang [xiuyuhang]
* @since 2018-03-29
*/
public class FailFastCluster {
}
| 13.545455 | 32 | 0.697987 |
0dcb16f8e0f575046f989dcb006e22fe28696fad | 17,426 | /**
* Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.ntask.core.impl.remote;
import org.apache.axis2.clustering.ClusteringAgent;
import org.apache.axis2.clustering.ClusteringCommand;
import org.apache.axis2.clustering.ClusteringFault;
import org.apache.axis2.clustering.ClusteringMessage;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.ntask.common.TaskException;
import org.wso2.carbon.ntask.common.TaskException.Code;
import org.wso2.carbon.ntask.core.Task;
import org.wso2.carbon.ntask.core.TaskInfo;
import org.wso2.carbon.ntask.core.TaskManager;
import org.wso2.carbon.ntask.core.TaskRepository;
import org.wso2.carbon.ntask.core.impl.RegistryBasedTaskRepository;
import org.wso2.carbon.ntask.core.internal.TasksDSComponent;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.remotetasks.stub.admin.common.RemoteTaskAdmin;
import org.wso2.carbon.remotetasks.stub.admin.common.xsd.DeployedTaskInformation;
import org.wso2.carbon.utils.ConfigurationContextService;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* This class represents a remote task manager implementation.
*/
public class RemoteTaskManager implements TaskManager {
private static final Log log = LogFactory.getLog(RemoteTaskManager.class);
public static final String REMOTE_TASK_SERVER_ADDRESS = "task.server.remote.address";
public static final String REMOTE_TASK_SERVER_USERNAME = "task.server.remote.username";
public static final String REMOTE_TASK_SERVER_PASSWORD = "task.server.remote.password";
public static final String TASK_CLIENT_DISPATCH_ADDRESS = "task.client.dispatch.address";
public static final String REMOTE_TASK_ID_REPO_PROP = "REMOTE_TASK_ID_REPO_PROP";
private TaskRepository taskRepository;
private RemoteTaskAdmin remoteTaskAdmin;
private static Map<String, Integer> runningTasksMap = new ConcurrentHashMap<String, Integer>();
public RemoteTaskManager(TaskRepository taskRepository, RemoteTaskAdmin remoteTaskAdmin) {
this.taskRepository = taskRepository;
this.remoteTaskAdmin = remoteTaskAdmin;
}
public RemoteTaskAdmin getRemoteTaskAdmin() {
return remoteTaskAdmin;
}
public TaskRepository getTaskRepository() {
return taskRepository;
}
public int getTenantId() {
return this.getTaskRepository().getTenantId();
}
public String getTaskType() {
return this.getTaskRepository().getTasksType();
}
@Override
public void initStartupTasks() throws TaskException {
for (TaskInfo taskInfo : this.getAllTasks()) {
try {
this.scheduleTask(taskInfo.getName());
} catch (Exception e) {
log.error("Error in scheduling task '" + taskInfo.getName()
+ "': " + e.getMessage(), e);
}
}
}
private void setRemoteTaskIdForTask(String taskName, String remoteTaskId) throws TaskException {
this.getTaskRepository().setTaskMetadataProp(taskName, REMOTE_TASK_ID_REPO_PROP,
remoteTaskId);
}
@Override
public void scheduleTask(String taskName) throws TaskException {
Registry registry = RegistryBasedTaskRepository.getRegistry();
try {
registry.beginTransaction();
String remoteTaskId = RemoteTaskUtils.createRemoteTaskMapping(this.getTenantId(),
this.getTaskType(), taskName);
this.setRemoteTaskIdForTask(taskName, remoteTaskId);
TaskInfo taskInfo = this.getTaskRepository().getTask(taskName);
registry.commitTransaction();
try {
this.getRemoteTaskAdmin().addRemoteSystemTask(
RemoteTaskUtils.convert(taskInfo, this.getTaskType(), remoteTaskId,
this.getTenantId()), this.getTenantId());
} catch (Exception e) {
throw new TaskException(e.getMessage(), Code.UNKNOWN, e);
}
} catch (RegistryException e) {
log.error("Error in retrieving registry : " + e.getMessage(), e);
}
}
@Override
public void rescheduleTask(String taskName) throws TaskException {
this.deleteTask(taskName, false);
this.scheduleTask(taskName);
}
@Override
public boolean deleteTask(String taskName) throws TaskException {
return this.deleteTask(taskName, true);
}
private String getRemoteTaskId(String taskName) throws TaskException {
return this.getTaskRepository().getTaskMetadataProp(taskName, REMOTE_TASK_ID_REPO_PROP);
}
private boolean deleteTask(String taskName, boolean removeFromRepo) throws TaskException {
try {
boolean result = this.getRemoteTaskAdmin().deleteRemoteSystemTask(
RemoteTaskUtils.remoteTaskNameFromTaskInfo(this.getTaskType(), taskName),
this.getTenantId());
Registry registry = RegistryBasedTaskRepository.getRegistry();
registry.beginTransaction();
/* remove the remote task id mapping */
String remoteTaskId = this.getRemoteTaskId(taskName);
if (remoteTaskId != null) {
RemoteTaskUtils.removeRemoteTaskMapping(remoteTaskId);
}
if (removeFromRepo) {
result &= this.getTaskRepository().deleteTask(taskName);
}
registry.commitTransaction();
return result;
} catch (Exception e) {
throw new TaskException(e.getMessage(), Code.UNKNOWN, e);
}
}
@Override
public void pauseTask(String taskName) throws TaskException {
try {
this.getRemoteTaskAdmin().pauseRemoteSystemTask(
RemoteTaskUtils.remoteTaskNameFromTaskInfo(this.getTaskType(), taskName),
this.getTenantId());
} catch (Exception e) {
throw new TaskException(e.getMessage(), Code.UNKNOWN, e);
}
}
@Override
public void resumeTask(String taskName) throws TaskException {
try {
this.getRemoteTaskAdmin().resumeRemoteSystemTask(
RemoteTaskUtils.remoteTaskNameFromTaskInfo(this.getTaskType(), taskName),
this.getTenantId());
} catch (Exception e) {
throw new TaskException(e.getMessage(), Code.UNKNOWN, e);
}
}
@Override
public void registerTask(TaskInfo taskInfo) throws TaskException {
String taskName = taskInfo.getName();
/*
* get the remote task id if the task is already existing, because this
* id will be overridden when the task is updated
*/
String remoteTaskId = this.getRemoteTaskId(taskName);
this.getTaskRepository().addTask(taskInfo);
if (remoteTaskId != null) {
/* restore the remote task id */
this.setRemoteTaskIdForTask(taskName, remoteTaskId);
}
}
public TaskState getTaskStateRemote(String taskName) throws TaskException {
try {
DeployedTaskInformation depTaskInfo = this.getRemoteTaskAdmin().getRemoteSystemTask(
RemoteTaskUtils.remoteTaskNameFromTaskInfo(this.getTaskType(), taskName),
this.getTenantId());
if (depTaskInfo == null) {
return TaskState.NONE;
}
TaskState ts = TaskState.valueOf(depTaskInfo.getStatus());
return ts;
} catch (Exception e) {
throw new TaskException(e.getMessage(), Code.UNKNOWN, e);
}
}
private ClusteringAgent getClusteringAgent() throws TaskException {
ConfigurationContextService configCtxService = TasksDSComponent
.getConfigurationContextService();
if (configCtxService == null) {
throw new TaskException("ConfigurationContextService not available "
+ "for notifying the cluster", Code.UNKNOWN);
}
ConfigurationContext configCtx = configCtxService.getServerConfigContext();
ClusteringAgent agent = configCtx.getAxisConfiguration().getClusteringAgent();
if (log.isDebugEnabled()) {
log.debug("Clustering Agent: " + agent);
}
return agent;
}
private TaskState getTaskStateFromLocalCluster(String taskName) throws TaskException {
/* first check local server */
if (this.isTaskRunning(taskName)) {
return TaskState.BLOCKED;
}
ClusteringAgent agent = this.getClusteringAgent();
if (agent == null) {
return TaskState.UNKNOWN;
}
TaskStatusMessage msg = new TaskStatusMessage();
msg.setTaskName(taskName);
msg.setTaskType(this.getTaskType());
msg.setTenantId(this.getTenantId());
try {
List<ClusteringCommand> result = agent.sendMessage(msg, true);
TaskStatusResult status;
for (ClusteringCommand entry : result) {
status = (TaskStatusResult) entry;
if (status.isRunning()) {
return TaskState.BLOCKED;
}
}
return TaskState.NORMAL;
} catch (ClusteringFault e) {
throw new TaskException(e.getMessage(), Code.UNKNOWN, e);
}
}
@Override
public TaskState getTaskState(String taskName) throws TaskException {
TaskState taskState = this.getTaskStateRemote(taskName);
if (taskState == TaskState.NORMAL) {
taskState = this.getTaskStateFromLocalCluster(taskName);
}
return taskState;
}
@Override
public TaskInfo getTask(String taskName) throws TaskException {
return this.getTaskRepository().getTask(taskName);
}
@Override
public List<TaskInfo> getAllTasks() throws TaskException {
return this.getTaskRepository().getAllTasks();
}
@Override
public boolean isTaskScheduled(String taskName) throws TaskException {
return this.getTaskState(taskName) != TaskState.NONE;
}
private boolean isMyTaskTypeRegistered() {
return TasksDSComponent.getTaskService().getRegisteredTaskTypes().contains(this.getTaskType());
}
public void runTask(String taskName) throws TaskException {
if (this.isMyTaskTypeRegistered()) {
TasksDSComponent.executeTask(new TaskExecution(taskName));
} else {
throw new TaskException("Task type: '" + this.getTaskType() +
"' is not registered in the current task node", Code.TASK_NODE_NOT_AVAILABLE);
}
}
public static void addRunningTask(String runningTaskId) {
synchronized (runningTasksMap) {
Integer value = runningTasksMap.get(runningTaskId);
if (value != null) {
value++;
} else {
value = 1;
}
runningTasksMap.put(runningTaskId, value);
}
}
public static void removeRunningTask(String runningTaskId) {
synchronized (runningTasksMap) {
Integer value = runningTasksMap.get(runningTaskId);
if (value != null) {
value--;
if (value <= 0) {
runningTasksMap.remove(runningTaskId);
} else {
runningTasksMap.put(runningTaskId, value);
}
}
}
}
public static boolean isRunningTaskExist(String runningTaskId) {
return runningTasksMap.containsKey(runningTaskId);
}
public boolean isTaskRunning(String taskName) throws TaskException {
return isRunningTaskExist(this.generateRunningTaskId(taskName));
}
private String generateRunningTaskId(String taskName) {
return this.getTenantId() + "#" + this.getTaskType() + "#" + taskName;
}
private class TaskExecution implements Runnable {
private String taskName;
public TaskExecution(String taskName) {
this.taskName = taskName;
}
public String getTaskName() {
return taskName;
}
private boolean isTaskRunningInCluster() throws TaskException {
return getTaskStateFromLocalCluster(this.getTaskName()) == TaskState.BLOCKED;
}
@Override
public void run() {
String runningTaskId = generateRunningTaskId(this.getTaskName());
/*
* the try/catch/finally ordering is there for a reason, do not mess
* with it!
*/
try {
TaskInfo taskInfo = getTaskRepository().getTask(this.getTaskName());
if (taskInfo.getTriggerInfo().isDisallowConcurrentExecution()
&& this.isTaskRunningInCluster()) {
/*
* this check is done here instead of outside is because,
* the repository lookup is anyway happens here and it is
* expensive for it to be done again
*/
return;
}
try {
addRunningTask(runningTaskId);
Task task = (Task) Class.forName(taskInfo.getTaskClass()).newInstance();
task.setProperties(taskInfo.getProperties());
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(
getTenantId(), true);
task.init();
task.execute();
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
} finally {
removeRunningTask(runningTaskId);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
/**
* This class represents the cluster message for retrieving a task status.
*/
public static class TaskStatusMessage extends ClusteringMessage {
private static final long serialVersionUID = 8904018070655665868L;
private int tenantId;
private String taskType;
private String taskName;
private TaskStatusResult result;
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
public String getTaskType() {
return taskType;
}
public void setTaskType(String taskType) {
this.taskType = taskType;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
@Override
public ClusteringCommand getResponse() {
return this.result;
}
@Override
public void execute(ConfigurationContext ctx) throws ClusteringFault {
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(this.getTenantId(), true);
TaskManager tm = TasksDSComponent.getTaskService().getTaskManager(
this.getTaskType());
if (tm instanceof RemoteTaskManager) {
this.result = new TaskStatusResult();
this.result.setRunning(((RemoteTaskManager) tm).isTaskRunning(this
.getTaskName()));
}
} catch (Exception e) {
throw new ClusteringFault(e.getMessage(), e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
/**
* This class represents a clustering message result for task statuses.
*/
public static class TaskStatusResult extends ClusteringCommand {
private static final long serialVersionUID = 4982249263193601405L;
private boolean running;
public boolean isRunning() {
return running;
}
public void setRunning(boolean running) {
this.running = running;
}
@Override
public void execute(ConfigurationContext ctx) throws ClusteringFault {
}
}
}
| 36.304167 | 108 | 0.623666 |
9f3aa255aaa198eebebaa9075ae66f626c850bd0 | 8,887 | package edu.maranatha.pbol.view;
import edu.maranatha.pbol.utils.BackgroundExecutor;
import edu.maranatha.pbol.utils.Timer;
import edu.maranatha.pbol.utils.Utils;
import javax.swing.*;
import java.awt.*;
import java.util.concurrent.Executor;
public class WaveformParallelFrame extends JFrame {
private int WIDTH = 450;
private int HEIGHT = 100;
private int N_TASK = 2;
private int NTOTLINES = 0;
private int DISCARD_FACTOR = 4; //must be %2=0 ( < 8 )
private WaveformPanel wfp;
private int[] polyliney, polylinex; //contains positions for the polyline
//Executor/Other
Executor executor = BackgroundExecutor.get();
boolean updatedOnScreen = true;
private boolean canWriteOnScreen = false;
//Icons
ImageIcon frameIcon = new ImageIcon(getClass().getResource("/res/waveicon.png"));
//Check correctness/performance
int taskCount = 0;
Timer timer = new Timer(); //timer for max/min drawtime
public WaveformParallelFrame() {
super();
setIconImage(frameIcon.getImage());
setSize(WIDTH, HEIGHT + 20);
setTitle("Waveform Frame");
setName("Main FRAME");
wfp = new WaveformPanel();
wfp.setSize(WIDTH, HEIGHT);
wfp.setName("Waveform PANEL");
wfp.setDoubleBuffered(false);
add(wfp);
setLocationRelativeTo(null);
}
public void updateWave(byte[] pcmdata) {
wfp.updateWave(pcmdata);
}
/**
* This panel gets a signal with updateWave and each time
* he can (not busy), he asks the executor to run
* N_TASK tasks that calculate the absolute position of the
* polyline relative to part of the signal (that is pcmdata)
*
* @author Pierluigi
*/
class WaveformPanel extends JPanel {
byte[] pcmdata = null;
Label cdtlmx; //Label per il drawtime massimo
Label cdtlmn; //Label per il drawtime minimo
Label cdtlavg; //Label per il drawtime medio
public WaveformPanel() {
super();
setLayout(null);
cdtlmx = new Label("DrawTime max");
cdtlmx.setBounds(0, 0, 80, 10);
add(cdtlmx);
cdtlmn = new Label("DrawTime min");
cdtlmn.setBounds(0, 10, 80, 10);
add(cdtlmn);
cdtlavg = new Label("DrawTime avg");
cdtlavg.setBounds(160, 0, 80, 10);
add(cdtlavg);
}
/**
* Refresh the wave every times a new pcmdata arrives
*/
public void updateWave(byte[] pcmdata) {
//ignore all other pcmdata until we draw something
//repaint();
synchronized (wfp) {
if (!updatedOnScreen)
return;
updatedOnScreen = false;
}
this.pcmdata = pcmdata;
callTask();
}
/**
* This makes the executor run some task
* each task calculate position for part of the signal
*/
private void callTask() {
timer.start();
int numLines = pcmdata.length / 4; // half because 2 points = 1 line, other half because we use 16 bit samples
numLines /= DISCARD_FACTOR; //Discard other lines for performance (no quality but speed).
//Instantiate the array if the number of total lines changes
//This might happen due to different pcm lenght from song to song
if (NTOTLINES != numLines) {
NTOTLINES = numLines;
instantiateEmptyLinesArray();
log("Lines we are drawing: " + numLines);
}
//Let multiple task do the math
int diff = pcmdata.length / N_TASK;
for (int i = 0; i < N_TASK; i++)
executor.execute(new WaveformTask(getWidth(), getHeight(), i * diff, (i + 1) * diff, i));
}
/**
* Handle the refresh of the waveform
*
* @param g
*/
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
if (pcmdata == null) {
int HEIGHT = getHeight();
int WIDTH = getWidth();
//Render a straight line
g2d.drawLine(0, HEIGHT / 2, WIDTH, HEIGHT / 2);
return;
}
//Let swing handle the drawing
if (polylinex != null) {
drawLines(g2d);
}
}
/**
* This task calculates part of the polyline, relative to a portion
* of the signal (pcmdata.lenght/N_TASK)
*
* @author Pierluigi
*/
class WaveformTask implements Runnable {
int HEIGHT;
int WIDTH;
int from;
int to;
int N;
public WaveformTask(int width, int height, int from, int to, int n) {
HEIGHT = height;
WIDTH = width;
this.to = to;
this.from = from;
this.N = n;
}
@Override
public void run() {
//log("Task " + N + " inizia l'esecuzione");
calcLine2d();
//The last thread synch with the drawing arrays
//log("Task " + N + " ha completato l'esecuzione");
synchronized (polylinex) {
taskCount++;
if (taskCount == N_TASK) {
taskCount = 0;
canWriteOnScreen = true;
repaint(); //If I'm the last one, then repaint
}
}
}
void calcLine2d() {
float scale = (float) HEIGHT / 65536; //h/2^16
int npoints = (to - from) / (2 * DISCARD_FACTOR); //16bit, half gone
//log( "from: " + from + " to: " + to);
float pwidth = (float) WIDTH / N_TASK;
float dx = (pwidth) * N;
int dy = HEIGHT / 2;
float lineLen = (float) pwidth / npoints;
int ix = 0; //relative x position
int absi; //absolute index of the arrays
int inc = DISCARD_FACTOR * 2;
for (int i = from; i < to; i += inc) {
int sample0 = Utils.getSixteenBitSample(pcmdata[i + 1], pcmdata[i]);
int val0 = (int) (sample0 * scale) + dy;
int diffx0 = Math.round(lineLen * ix + dx);
absi = ix + (N * npoints);
WaveformParallelFrame.this.polylinex[absi] = diffx0;
WaveformParallelFrame.this.polyliney[absi] = val0;
ix++;
//log("x vals: " + diffx0 + " --" + nlines + " from: " + from + " to: " + to+ " DX: " + dx);
//log("Updated GUI ( " + sumData + ") " + lineLen + " " + WIDTH + " " + HEIGHT + " nlines: " +nlines + " Scale: "+scale );
}
}
}
//TASK DEFINITION END
/**
* This should draw lines
*
* @param g2d
*/
void drawLines(Graphics2D g2d) {
assert (polylinex != null); //Was everything instantiated with success ?
assert (taskCount == 0); //Have all the task processed their wave for the cycle?
if (canWriteOnScreen) { //repaint() might be called from something else (window resize, etc)
//log("Inizio a disegnare...");
g2d.drawPolyline(polylinex, polyliney, polylinex.length);
g2d.dispose();
timer.stop();
//log("Disegno eseguito.");
synchronized (wfp) {
canWriteOnScreen = false;
updatedOnScreen = true; //sync with pcmdata input
}
}
}
/**
* Called each time the UI is rendered
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
cdtlmx.setText(timer.getMax() + "");
cdtlmn.setText(timer.getMin() + "");
cdtlavg.setText(timer.getAvg() + "");
}
/**
* Initialize arrays
*/
private void instantiateEmptyLinesArray() {
polylinex = new int[NTOTLINES * 2];
polyliney = new int[NTOTLINES * 2];
for (int i = 0; i < NTOTLINES * 2; i++) {
polylinex[i] = 0;
polyliney[i] = 0;
}
}
}
/// END OF JPANEL CLASS
private void log(String line) {
System.out.println("WF out] " + line);
}
}
| 34.85098 | 143 | 0.509171 |
2d70344cb26ee583cd58d4811d9fe2de691fb081 | 2,137 | /**
*
* mysite - Static Site Generator
* Copyright (c) 2012, myJerry Developers
*
* 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.myjerry.mysite.util;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.MicrosoftConditionalCommentTagTypes;
import net.htmlparser.jericho.Source;
import net.htmlparser.jericho.SourceFormatter;
import org.myjerry.mysite.model.ProjectFile;
/**
*
* @author sangupta
* @since 2 Jan 2012
*/
public class HtmlSource {
static {
MicrosoftConditionalCommentTagTypes.register();
}
private ProjectFile projectFile;
private Source source;
public HtmlSource(ProjectFile file) {
this.projectFile = file;
String contents = this.projectFile.getContents();
source = new Source(contents);
}
public void tidyHtml() {
try {
StringWriter writer = new StringWriter();
new SourceFormatter(source).setIndentString(" ").setTidyTags(true).writeTo(writer);
writer.close();
this.projectFile.setContents(writer.toString());
} catch(Exception e) {
System.out.println("Unable to prettify HTML for file: " + this.projectFile.getPath());
}
}
public List<String> extractAllHyperLinks() {
List<String> links = new ArrayList<String>();
List<Element> elements = source.getAllElements(HTMLElementName.A);
if(elements != null && elements.size() > 0) {
for(Element element : elements) {
String href = element.getAttributeValue("href");
links.add(href);
}
}
return links;
}
}
| 26.060976 | 89 | 0.728591 |
65870bb2d8498effe9bde190ff135dd8440ef3a3 | 628 | /******************************************************************
*
* CyberVRML97 for Java
*
* Copyright (C) Satoshi Konno 1997-1998
*
* File : NodeList.java
*
******************************************************************/
package org.cybergarage.x3d.node;
import org.cybergarage.x3d.util.*;
public class NodeList extends LinkedList {
public NodeList() {
RootNode rootNode = new RootNode();
setRootNode(rootNode);
}
public void removeNodes() {
LinkedListNode rootNode = getRootNode();
while (rootNode.getNextNode() != null) {
Node nextNode = (Node)rootNode.getNextNode();
nextNode.remove();
}
}
} | 21.655172 | 67 | 0.550955 |
cf8ae7741ff98e180ea9138ac6773881d116d4c5 | 1,656 | package com.im.alg.code;
import java.util.HashMap;
import java.util.Map;
/**
* 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
* <p>
* 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
* <p>
* 给定 nums = [2, 7, 11, 15], target = 9
* <p>
* 因为 nums[0] + nums[1] = 2 + 7 = 9
* 所以返回 [0, 1]
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/two-sum
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class Lesson1 {
/**
* O(n^2)
*
* @param nums
* @param target
* @return
*/
public int[] twoSum(int[] nums, int target) {
if (nums.length <= 1 || nums == null) throw new IllegalArgumentException();
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
throw new IllegalArgumentException("没有符合条件的俩数之和");
}
/**
* 利用map 降低时间复杂度 k -存储元素, v -存储索引
* 判断map中是否存入目标元素,没有放入map中,有返回下标索引
* O(n)
* @param ints
* @param target
* @return
*/
public int[] twoSum2(int[] ints, int target) {
if (ints.length <= 1 || ints == null) throw new IllegalArgumentException();
Map<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < ints.length; i++) {
int n = target - ints[i];
if (hashMap.containsKey(n)) {
return new int[]{i, hashMap.get(n)};
} else {
hashMap.put(ints[i], i);
}
}
throw new IllegalArgumentException("没有符合条件的俩数之和");
}
}
| 25.875 | 83 | 0.515097 |
18ef543d80dc19a28e88c355ed1817e12c488fe1 | 2,738 | package com.alexis.tarotapp.api.repository;
import com.alexis.tarotapp.api.entities.Category;
import com.alexis.tarotapp.api.general.result.Result;
import com.alexis.tarotapp.api.repository.listing.CategoryListingResult;
import com.alexis.tarotapp.api.repository.pagination.PaginationParams;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.List;
/**
* Created by alzayon on 8/1/2017.
*/
public class CategoryDao implements ICategoryDao {
@Override
public Result<Category> add(Session session, Category category) {
session.save(category);
return new Result<>(category);
}
@Override
public Result<Category> update(Session session, Category category) {
final Category reattachedCategory = (Category)session.merge(category);
session.save(reattachedCategory);
return new Result<>(reattachedCategory);
}
@Override
public Result<CategoryListingResult> list(Session session, PaginationParams paginationParams) {
try {
final Query query = session.createQuery("from Category");
query.setFirstResult(paginationParams.getStart());
query.setMaxResults(paginationParams.getLimit());
String countQ = "Select count (c.id) from Category c";
Query countQuery = session.createQuery(countQ);
Long countResults = (Long) countQuery.uniqueResult();
final List<Category> categories = query.list();
final CategoryListingResult categoryListingResult = new CategoryListingResult(countResults, categories);
return new Result<>(categoryListingResult);
} catch (HibernateException ex) {
final Result<CategoryListingResult> result = new Result<>(null, ex);
return result;
}
}
@Override
public Result<Category> fetch(Session session, int id) {
//https://stackoverflow.com/questions/11089599/hibernate-get-entity-by-id
final Category category = (Category) session.get(Category.class, id);
return new Result<>(category);
}
@Override
public Result<Boolean> delete(Session session, int id) {
//http://www.codejava.net/frameworks/hibernate/hibernate-basics-3-ways-to-delete-an-entity-from-the-datastore
//https://www.mkyong.com/hibernate/hibernate-cascade-example-save-update-delete-and-delete-orphan/
final Category category = (Category) session.get(Category.class, id);
boolean outcome = false;
if (category != null) {
session.delete(category);
outcome = true;
}
return new Result<>(outcome);
}
}
| 37.506849 | 117 | 0.689189 |
1ece875993f4b10a3fbe3ee6c9016c43b70e894b | 2,337 | /**
*
*/
package com.mtit.utils;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.mtit.entity.TitleMappingDao;
import com.mtit.process.SyncException;
/**
* Class that provides functionality to map MYOB fields.
*
* @author Mei
*
*/
public class MYOBUtils {
// Unit of measure descriptions
private static final String EACH="Ea";
private static final String KILOGRAM="kg";
private static final String GRAM="g";
private static final String POUND="lb";
private static final String OUNCE="oz";
private static final String LITRE="l";
private static final String MILLILITRE="ml";
// Title Mapping list
private static Map<String, String> titleMap = null;
/**
* Helper utility to convert MYOB unit of measure to a string to be
* used with WebWidget.
*
* @param myobUom
* @return
*/
public static String getUnitOfMeasure(int myobUom) {
String uom = null;
switch (myobUom) {
case 0:
uom = EACH;
break;
case 1:
uom = KILOGRAM;
break;
case 2:
uom = GRAM;
break;
case 3:
uom = POUND;
break;
case 4:
uom = OUNCE;
break;
case 5:
uom = LITRE;
break;
case 6:
uom = MILLILITRE;
break;
default:
break;
}
return uom;
}
/**
* Returns the title based on what has been set in the Title Mapping xml file.
*
* @param description
* @return
* @throws SyncException
*/
public static String transformTitle(String myobDesc) throws SyncException {
String returnString = myobDesc;
if (titleMap == null) {
titleMap = TitleMappingDao.getTitleMappingString();
}
for (Iterator<Entry<String, String>> itr=titleMap.entrySet().iterator(); itr.hasNext(); ) {
Entry<String, String> entry = itr.next();
if (myobDesc.contains(entry.getKey())) {
// Form the string to be replaced first.
String key = entry.getKey();
// Replace all punctuation
key = key.replaceAll("\\p{Punct}", "\\\\p{Punct}");
if ( !entry.getKey().matches("\\W\\w+\\W")) {
key = "\\b" + key + "\\b";
}
if ("del".equals(entry.getValue())) {
returnString = returnString.replaceAll(key, "");
} else {
returnString = returnString.replaceAll(key, entry.getValue());
}
}
}
returnString = returnString.replaceAll("\\s\\s", " ");
return returnString;
}
}
| 21.054054 | 93 | 0.643988 |
cfdc5133dedf8cf130bc479ce05633cefb95c4c1 | 3,147 | package vn.edu.uit.owleditor.view.window;
import com.vaadin.event.ShortcutAction;
import com.vaadin.server.Sizeable;
import com.vaadin.ui.*;
import com.vaadin.ui.themes.ValoTheme;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.SWRLRule;
import uk.ac.manchester.cs.owl.explanation.ordering.ExplanationTree;
import uk.ac.manchester.cs.owl.explanation.ordering.Tree;
import vn.edu.uit.owleditor.OWLEditorUI;
import vn.edu.uit.owleditor.core.OWLEditorKitImpl;
/**
* @author Chuong Dang, University of Information and Technology, HCMC Vietnam,
* Faculty of Computer Network and Telecomunication created on 12/15/14.
*/
public class ExplanationWindow extends Window {
private final VerticalLayout root = new VerticalLayout();
private final VerticalLayout body = new VerticalLayout();
public ExplanationWindow(ExplanationTree explanationTree) {
initialize();
printIndented(explanationTree, "");
}
private void printIndented(Tree<OWLAxiom> node, String indent) {
OWLAxiom axiom = node.getUserObject();
body.addComponent(new ExplanationLabel(axiom));
if (!node.isLeaf()) {
for (Tree<OWLAxiom> child : node.getChildren()) {
printIndented(child, indent + " ");
}
}
}
private void initialize() {
setModal(true);
setClosable(false);
setResizable(false);
setWidth(700.0f, Unit.PIXELS);
setHeight(500.0f, Unit.PIXELS);
setContent(buildContent());
}
private Component buildContent() {
body.setMargin(true);
body.setSpacing(true);
body.setWidth("100%");
root.addStyleName(ValoTheme.LAYOUT_CARD);
root.addComponent(body);
root.addComponent(buildFooter());
root.setExpandRatio(body, 1.0f);
root.setSizeFull();
return root;
}
private Component buildFooter() {
HorizontalLayout footer = new HorizontalLayout();
footer.setSpacing(true);
footer.addStyleName(ValoTheme.WINDOW_BOTTOM_TOOLBAR);
footer.setWidth(100.0f, Sizeable.Unit.PERCENTAGE);
Button cancel = new Button("OK");
cancel.addClickListener(event -> close());
cancel.setClickShortcut(ShortcutAction.KeyCode.ESCAPE, null);
footer.addComponents(cancel);
footer.setComponentAlignment(cancel, Alignment.BOTTOM_RIGHT);
return footer;
}
protected class ExplanationLabel extends Panel {
private final Label label = new Label();
public ExplanationLabel(OWLAxiom axiom) {
if (axiom instanceof SWRLRule)
label.setValue(OWLEditorUI.getEditorKit().getRuleRenderer().renderSWRLRule((SWRLRule) axiom));
else
label.setValue(OWLEditorKitImpl.render(axiom));
label.addStyleName(ValoTheme.LABEL_COLORED);
label.addStyleName(ValoTheme.LABEL_NO_MARGIN);
label.setSizeUndefined();
addStyleName(ValoTheme.PANEL_BORDERLESS);
setContent(label);
setWidth("100%");
}
}
}
| 31.787879 | 110 | 0.663489 |
7a01963968dda7e4da5b8b8f291dd1ecc92817e7 | 1,208 | package com.googlecode.gwt.test.uibinder;
import com.google.gwt.user.client.ui.Grid;
import com.googlecode.gwt.test.GwtTestTest;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class UiBinderWithGridTest extends GwtTestTest {
@Test
public void instanciation() {
// When
UiBinderWithGrid uiBinderGrid = new UiBinderWithGrid();
Grid grid = uiBinderGrid.getGrid();
// Then
assertThat(grid.getRowCount()).isEqualTo(2);
assertThat(grid.getWidget(0, 0)).isSameAs(uiBinderGrid.myLabel);
assertThat(grid.getWidget(0, 1)).isSameAs(uiBinderGrid.myHTML);
assertThat(grid.getCellFormatter().getElement(1, 0).getInnerHTML()).isEqualTo(uiBinderGrid.myDiv.toString());
assertThat(grid.getCellFormatter().getElement(1, 1).getInnerHTML()).isEqualTo(uiBinderGrid.mySpan.toString());
// styles
assertThat(grid.getRowFormatter().getStyleName(0)).isEqualTo("optionalHeaderStyle");
assertThat(grid.getCellFormatter().getStyleName(0, 0)).isEqualTo("optionalFooCellStyle");
assertThat(grid.getCellFormatter().getStyleName(1, 1)).isEqualTo("optionalSpanCellStyle");
}
}
| 38.967742 | 118 | 0.719371 |
53c6a8ac4556566ba0e6a8a22f1f72595f96c5c8 | 1,937 | package com.seeker.smartcalendar;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import com.seeker.calendar.CalendarDay;
import com.seeker.calendar.controller.EventController;
import com.seeker.calendar.utils.CalendarUtils;
import java.util.Random;
/**
* @author Seeker
* @date 2018/12/22/022 9:31
* @describe TODO
*/
public class HorizontalActivity extends BaseActivity {
Random random = new Random();
@Override
public int contentViewLayId() {
return R.layout.activity_horizontal;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final EventController<Person> eventController = smartCalendarView.getEventController();
findViewById(R.id.addEvent).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
eventController.removeEvent(calendarDay);
calendarDay.day = nextDay();
Person person = new Person("Seeker",30);
eventController.addEvent(calendarDay,person);
smartCalendarView.refreshUI();
makeToast(person.toString());
}
});
findViewById(R.id.getEvent).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Person person = eventController.getEvent(calendarDay);
makeToast(person.toString());
}
});
findViewById(R.id.removeEvent).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
eventController.removeEvent(calendarDay);
smartCalendarView.refreshUI();
}
});
}
private int nextDay(){
return random.nextInt(28)+1;
}
}
| 28.485294 | 95 | 0.632421 |
65bfbc26400b9c3684159dd8a961165e2bb80ee8 | 4,642 | package com.example.parstagram.fragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.parstagram.EndlessRecyclerViewScrollListener;
import com.example.parstagram.Post;
import com.example.parstagram.PostsAdapter;
import com.example.parstagram.R;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class PostsFragment extends Fragment {
RecyclerView rvPosts;
public static final String TAG = "PostsFragment";
protected List<Post> allPosts;
protected PostsAdapter adapter;
private EndlessRecyclerViewScrollListener endlessRecyclerViewScrollListener;
public PostsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_posts, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
rvPosts = view.findViewById(R.id.rvPosts);
allPosts = new ArrayList<>();
adapter = new PostsAdapter(getContext(), allPosts);
// set adapter and layout manager for RV
rvPosts.setAdapter(adapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
rvPosts.setLayoutManager(linearLayoutManager);
endlessRecyclerViewScrollListener = new EndlessRecyclerViewScrollListener(linearLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
Date createdAt = allPosts.get(allPosts.size()-1).getCreatedAt();
loadNextDataFromApi(createdAt);
}
};
rvPosts.addOnScrollListener(endlessRecyclerViewScrollListener);
queryPosts(0);
}
private void queryPosts(int page) {
// specify we want to query Post.class
ParseQuery<Post> query = ParseQuery.getQuery(Post.class);
// include data referred by userkey
query.include(Post.KEY_USER);
// limit num posts to latest 20
query.setLimit(5);
// order by newest first
query.addDescendingOrder("createdAt");
// start async call for posts
query.findInBackground(new FindCallback<Post>() {
@Override
public void done(List<Post> posts, ParseException e) {
if (e != null) {
Log.e(TAG, "issue with getting posts", e);
return;
}
// to debug - print every post description
for (Post post : posts) {
Log.i(TAG, "Posts: " + post.getDescription() + ", username " + post.getUser());
}
// save received posts to allPosts and notify adapter of new data
allPosts.addAll(posts);
adapter.notifyDataSetChanged();
}
});
}
private void loadNextDataFromApi(Date createdAt) {
ParseQuery<Post> query = ParseQuery.getQuery(Post.class);
// skips already loaded posts
query.include(Post.KEY_USER);
query.addDescendingOrder("createdAt");
query.setLimit(5);
query.whereLessThan("createdAt", createdAt);
query.findInBackground(new FindCallback<Post>() {
@Override
public void done(List<Post> posts, ParseException e) {
if (e != null) {
Log.e(TAG, "issue with getting posts", e);
return;
}
// to debug - print every post description
for (Post post : posts) {
Log.i(TAG, "Posts: " + post.getDescription() + ", username " + post.getUser());
}
// save received posts to allPosts and notify adapter of new data
allPosts.addAll(posts);
adapter.notifyDataSetChanged();
// endlessRecyclerViewScrollListener.resetState();
}
});
}
} | 35.984496 | 104 | 0.635717 |
56d8f7d6e8a1eece2f16a293496cecdb763c22f9 | 3,846 | package com.maoface.ueditor.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
/**
* @author zhuxuchao
* @date 2020-04-02 10:46
*/
@EnableConfigurationProperties({
UploadImageProperties.class,
UploadVideoProperties.class,
UploadFileProperties.class,
UploadSnapscreenProperties.class,
UploadCatcherProperties.class,
UploadScrawlProperties.class,
FileManagerProperties.class,
ImageManagerProperties.class
})
@ConfigurationProperties(prefix = "ueditor.config")
public class UeditorProperties {
/**
* Ueditor后端服务映射地址
*/
private String requestMappingPath = "/baidu/ueditor/action";
/**
* 上传图片配置项
*/
@Autowired
private UploadImageProperties uploadImageConfig;
/**
* 上传视频配置项
*/
@Autowired
private UploadVideoProperties uploadVideoConfig;
/**
* 上传附件配置项
*/
@Autowired
private UploadFileProperties uploadFileConfig;
/**
* 上传涂鸦图片配置项
*/
@Autowired
private UploadScrawlProperties uploadScrawlConfig;
/**
* 上传抓取远程图片配置项
*/
@Autowired
private UploadCatcherProperties uploadCatcherConfig;
/**
* 上传截图配置项
*/
@Autowired
private UploadSnapscreenProperties uploadSnapscreenConfig;
/**
* 列出指定目录下的图片
*/
@Autowired
private ImageManagerProperties imageManagerConfig;
/**
* 列出指定目录下的文件
*/
@Autowired
private FileManagerProperties fileManagerConfig;
public String getRequestMappingPath() {
return requestMappingPath;
}
public void setRequestMappingPath(String requestMappingPath) {
this.requestMappingPath = requestMappingPath;
}
public UploadImageProperties getUploadImageConfig() {
return uploadImageConfig;
}
public void setUploadImageConfig(UploadImageProperties uploadImageConfig) {
this.uploadImageConfig = uploadImageConfig;
}
public UploadVideoProperties getUploadVideoConfig() {
return uploadVideoConfig;
}
public void setUploadVideoConfig(UploadVideoProperties uploadVideoConfig) {
this.uploadVideoConfig = uploadVideoConfig;
}
public UploadFileProperties getUploadFileConfig() {
return uploadFileConfig;
}
public void setUploadFileConfig(UploadFileProperties uploadFileConfig) {
this.uploadFileConfig = uploadFileConfig;
}
public UploadScrawlProperties getUploadScrawlConfig() {
return uploadScrawlConfig;
}
public void setUploadScrawlConfig(UploadScrawlProperties uploadScrawlConfig) {
this.uploadScrawlConfig = uploadScrawlConfig;
}
public UploadCatcherProperties getUploadCatcherConfig() {
return uploadCatcherConfig;
}
public void setUploadCatcherConfig(UploadCatcherProperties uploadCatcherConfig) {
this.uploadCatcherConfig = uploadCatcherConfig;
}
public UploadSnapscreenProperties getUploadSnapscreenConfig() {
return uploadSnapscreenConfig;
}
public void setUploadSnapscreenConfig(UploadSnapscreenProperties uploadSnapscreenConfig) {
this.uploadSnapscreenConfig = uploadSnapscreenConfig;
}
public ImageManagerProperties getImageManagerConfig() {
return imageManagerConfig;
}
public void setImageManagerConfig(ImageManagerProperties imageManagerConfig) {
this.imageManagerConfig = imageManagerConfig;
}
public FileManagerProperties getFileManagerConfig() {
return fileManagerConfig;
}
public void setFileManagerConfig(FileManagerProperties fileManagerConfig) {
this.fileManagerConfig = fileManagerConfig;
}
}
| 27.471429 | 94 | 0.722049 |
395f60193ddd65ee6cdceeefcfd8325f7bb614df | 1,824 | class Deque {
int start;
int end;
int size;
int[] deque;
int n;
Deque(int size) {
this.size = size;
end = size - 1;
deque = new int[size];
}
boolean isEmpty () {
return (n == 0);
}
boolean isFull() {
return (n == size);
}
void inStart(int value) {
if (!isFull()) {
if (start == size) {
deque[start - 1] = value;
start = 0;
n++;
} else {
deque[start++] = value;
n++;
}
}
}
void inEnd(int value) {
if (!isFull()) {
if (end == 0) {
deque[end] = value;
end = size - 1;
n++;
} else {
deque[end--] = value;
n++;
}
}
}
int outStart() {
if (!isEmpty()) {
if (start == 0) {
start = size - 1;
int ret = deque[start];
deque[start] = 0;
n--;
return ret;
} else {
int ret = deque[--start];
deque[start] = 0;
n--;
return ret;
}
}
return 0;
}
int outEnd() {
if (!isEmpty()) {
if (end == size - 1) {
end = 0;
int ret = deque[end];
deque[end] = 0;
n--;
return ret;
} else {
int ret = deque[++end];
deque[end] = 0;
n--;
return ret;
}
}
return 0;
}
} | 21.975904 | 55 | 0.285088 |
c5655cf6194e007e9cf2971cced065e3ae20cf02 | 15,191 | package com.perforce.common.node;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.perforce.common.ConverterException;
import com.perforce.common.Stats;
import com.perforce.common.StatsType;
import com.perforce.common.asset.AssetWriter;
import com.perforce.common.asset.ContentType;
import com.perforce.common.asset.TranslateCharsetType;
import com.perforce.common.depot.DepotConvert;
import com.perforce.config.CFG;
import com.perforce.config.Config;
import com.perforce.config.ConfigException;
import com.perforce.svn.change.ChangeConvert;
import com.perforce.svn.history.ChangeAction;
import com.perforce.svn.history.RevisionTree;
import com.perforce.svn.history.RevisionTree.NodeType;
import com.perforce.svn.parser.Content;
import com.perforce.svn.parser.Property;
import com.perforce.svn.parser.RecordStateTrace;
import com.perforce.svn.process.MergeInfo;
import com.perforce.svn.process.MergeSource;
import com.perforce.svn.query.QueryHistory;
import com.perforce.svn.query.QueryInterface;
public class NodeConvert implements NodeInterface {
private Logger logger = LoggerFactory.getLogger(NodeConvert.class);
private ChangeConvert changelist;
private DepotConvert depot;
private RevisionTree tree;
private String toPath;
private long toChange;
private ArrayList<MergeSource> fromList;
private Property property;
private Content content;
private boolean pendingBlock;
/**
* Constructor
*
* @param nodePath
* @param nodeChange
* @param nodeAction
*/
public NodeConvert(ChangeConvert cl, DepotConvert nodeDepot,
RevisionTree nodeTree, boolean subBlock) {
changelist = cl;
depot = nodeDepot;
tree = nodeTree;
pendingBlock = subBlock;
}
@Override
public void setTo(String path, long change) {
toPath = path;
toChange = change;
}
@Override
public void setFrom(ArrayList<MergeSource> from) {
// Copy mergeinfo sources into new ChangeAction list
fromList = from;
}
@Override
public void action(Action nodeAction, NodeType type, boolean caseRename)
throws Exception {
switch (type) {
case FILE:
fileAction(nodeAction);
break;
case DIR:
dirAction(nodeAction);
break;
default:
throw new ConverterException("unknown NodeType(" + type + ")");
}
}
private void fileAction(Action nodeAction) throws Exception {
QueryInterface query = new QueryHistory(tree);
ChangeAction act = null;
// ChangeAction from = null;
// get type and properties from last revision
ChangeAction lastAction = query.findLastAction(toPath, toChange);
switch (nodeAction) {
case ADD:
case EDIT:
act = tree.add(toPath, toChange, nodeAction, content,
NodeType.FILE, pendingBlock);
break;
case UPDATE:
fileAction(Action.REMOVE);
if (lastAction != null
&& !lastAction.getAction().equals(Action.REMOVE)) {
act = tree.add(toPath, toChange, Action.EDIT, content,
NodeType.FILE, pendingBlock);
} else {
act = tree.add(toPath, toChange, Action.ADD, content,
NodeType.FILE, pendingBlock);
}
break;
case REMOVE:
// Remove action should have no real content
if (!content.isBlob()) {
if (lastAction != null) {
content.setType(lastAction.getType());
content.setProps(lastAction.getProps());
} else {
StringBuffer msg = new StringBuffer();
msg.append("SKIPPING: cannot delete a non-existant revision.\n");
logger.warn(msg.toString());
Stats.inc(StatsType.warningCount);
return;
}
if (logger.isTraceEnabled()) {
StringBuffer sb = new StringBuffer();
sb.append("no content: ");
sb.append("action: ");
sb.append("(" + lastAction.getAction() + ") ");
sb.append(content.getType());
logger.trace(sb.toString());
}
}
act = tree.add(toPath, toChange, nodeAction, content,
NodeType.FILE, pendingBlock);
break;
case COPY:
case BRANCH:
if (fromList != null && fromList.size() == 1) {
ChangeAction from = fromList.get(0).getFromNode();
if (isCopy(toPath, from)) {
// Use from Type and Properties if no real content
if (!content.isBlob()) {
content.setType(from.getType());
content.setProps(from.getProps());
}
// determine branch type and add action to tree
act = processBranch(depot, from, toPath, toChange, content);
} else {
// Can't get here unless case-sensitivity issue job053572
StringBuffer msg = new StringBuffer();
msg.append("SKIPPING: cannot branch a deleted revision to");
msg.append(" a non-existant or deleted target.\n");
logger.warn(msg.toString());
Stats.inc(StatsType.warningCount);
return;
}
} else {
throw new ConverterException("Unexpected number of sources");
}
break;
case MERGE:
if (fromList != null && !fromList.isEmpty()) {
// determine branch type and add action to tree
act = tree.add(toPath, toChange, nodeAction, content,
NodeType.FILE, pendingBlock);
} else {
throw new ConverterException("Expected one or more sources");
}
break;
case LABEL:
return;
default:
throw new ConverterException("Node-action(" + nodeAction + ")");
}
if (act != null && act.getAction() != null) {
// add action to changelist
changelist.addRevision(act, fromList);
} else {
RecordStateTrace.dump();
StringBuffer msg = new StringBuffer();
msg.append("Unknown issue:\n");
msg.append("\tPlease send log files and report the issue to Support.\n");
msg.append("\t support@perforce.com and CC:pallen@perforce.com\n\n");
logger.error(msg.toString());
throw new RuntimeException(msg.toString());
}
// Create archive if node has content
if (content.isBlob()) {
AssetWriter archive = new AssetWriter(depot, act);
archive.write(content);
}
}
private void dirAction(Action nodeAction) throws Exception {
QueryInterface query = new QueryHistory(tree);
// Pseudo content
Content content = new Content();
switch (nodeAction) {
case ADD:
case EDIT:
// find properties
processDirProperty(content);
break;
case UPDATE:
dirAction(Action.REMOVE);
// find properties
processDirProperty(content);
break;
case COPY:
dirAction(Action.REMOVE);
dirAction(Action.BRANCH);
// find properties
processDirProperty(content);
break;
case REMOVE:
List<ChangeAction> removeActions = query.listLastActions(toPath,
toChange);
for (ChangeAction remove : removeActions) {
if (remove.getAction() != Action.REMOVE) {
String removePath = remove.getPath();
// get type and properties from last revision
ChangeAction lastAction = query.findLastAction(removePath,
toChange);
if (lastAction != null) {
content.setType(lastAction.getType());
content.setProps(lastAction.getProps());
}
if (logger.isTraceEnabled()) {
StringBuffer sb = new StringBuffer();
sb.append("remove: " + remove.getPath());
if (lastAction != null) {
sb.append("(" + lastAction.getAction() + ") ");
} else {
sb.append("(null) ");
}
sb.append("type: " + remove.getType());
logger.trace(sb.toString());
}
// add action to tree
ChangeAction act = tree
.add(removePath, toChange, Action.REMOVE, content,
NodeType.FILE, pendingBlock);
// add action to changelist
changelist.addRevision(act, null);
}
}
break;
case BRANCH:
// Trap condition when more than one source is detected, could be a
// strange 'unsupported' mergeinfo case.
if (fromList.size() != 1) {
StringBuffer sb = new StringBuffer();
sb.append("fromList has more than one source:");
sb.append(fromList.toString());
throw new ConverterException(sb.toString());
}
String fromPath = fromList.get(0).getFromPath();
long fromSvnRev = fromList.get(0).getEndFromSvnRev();
List<ChangeAction> fromActions = query.listLastActions(fromPath,
fromSvnRev);
for (ChangeAction from : fromActions) {
// wrap from change action into list for changelist
ArrayList<MergeSource> copyActs = new ArrayList<MergeSource>();
MergeSource mergeFrom = new MergeSource(from.getPath(),
from.getStartChange(), from.getEndChange());
mergeFrom.setFromNode(from);
copyActs.add(mergeFrom);
// get 'to' action using branch source and target
String toFilePath = NodeHelper.remap(fromPath, toPath,
from.getPath());
// build new ChangeAction
if (isCopy(toFilePath, from)) {
// Use from Type and Properties as there is no content
content.setType(from.getType());
content.setProps(from.getProps());
if (logger.isTraceEnabled()) {
StringBuffer sb = new StringBuffer();
sb.append("copy: " + from.getPath());
sb.append("(" + from.getAction() + ") ");
sb.append("to " + toFilePath + "\n");
sb.append("Content type: " + content.getType());
logger.trace(sb.toString());
}
ChangeAction act = processBranch(depot, from, toFilePath,
toChange, content);
// add action to changelist
changelist.addRevision(act, copyActs);
}
}
// find properties
processDirProperty(content);
break;
case LABEL:
return;
default:
throw new ConverterException("Node-action(" + nodeAction + ")");
}
}
/**
* Helper method to check if branch action is a copy (prevents population of
* deleted revisions if there is no existing target.
*
* @param toPath
* @param from
* @return
* @throws Exception
*/
private boolean isCopy(String toPath, ChangeAction from) throws Exception {
QueryInterface query = new QueryHistory(tree);
// check if target exists
ChangeAction lastToAction = query.findLastAction(toPath, toChange - 1);
// copy all non deleted source actions, but if target exists and
// is not deleted then copy delete.
if (from.getAction() != Action.REMOVE) {
return true;
} else {
if (lastToAction != null) {
if (lastToAction.getAction() != Action.REMOVE) {
return true;
}
}
}
return false;
}
/**
* Creates a versioned file containing the directories properties
*
* @param content
* @throws Exception
*/
private void processDirProperty(Content content) throws Exception {
if (!(Boolean) Config.get(CFG.SVN_PROP_ENABLED) || property == null)
return;
// Property file path
String propPath = toPath;
if (!toPath.isEmpty()) {
propPath += "/";
}
propPath += Config.get(CFG.SVN_PROP_NAME);
// Create attributes content and node
NodeAttributes attributes = new NodeAttributes(property);
content.setAttributes(attributes);
Action action = null;
ChangeAction act = null;
QueryInterface query = new QueryHistory(tree);
ChangeAction lastAction = query.findLastAction(propPath, toChange);
if (!property.isEmpty()) {
if ((lastAction != null)
&& (lastAction.getAction() != Action.REMOVE)) {
action = Action.EDIT;
} else {
action = Action.ADD;
}
act = tree.add(propPath, toChange, action, content, NodeType.FILE,
pendingBlock);
AssetWriter archiveProperty = new AssetWriter(depot, act);
content.getAttributes().setHeader(act.getPath(),
act.getEndChange(), act.getEndRev());
archiveProperty.write(content);
} else {
if ((lastAction != null)
&& (lastAction.getAction() != Action.REMOVE)) {
action = Action.REMOVE;
act = tree.add(propPath, toChange, action, content,
NodeType.FILE, pendingBlock);
}
}
if (act != null) {
changelist.addRevision(act, null);
}
}
/**
* Handles per-file branching and will up/down grade as required
*
* has content -> ADD or INTEG same to/from path -> ADD or EDIT from is
* REMOVE -> target is REMOVE
*
* Returns a modified ChangeAction
*
* @param depot
* @param from
* @param to
* @param nodeChange
* @param content
* @return
* @throws Exception
*/
private ChangeAction processBranch(DepotConvert depot, ChangeAction from,
String toPath, long nodeChange, Content content) throws Exception {
Action action = null;
ChangeAction act = null;
if (from.getAction() != Action.REMOVE) {
QueryInterface query = new QueryHistory(tree);
ChangeAction lastTo = query.findLastAction(toPath, nodeChange - 1);
// Branch or Integ
if (lastTo == null || lastTo.getAction() == Action.REMOVE) {
action = Action.BRANCH;
} else {
action = Action.INTEG;
}
// CornerCase: if content, downgrade Action
if (content != null && content.isBlob()) {
// ADD action: if no previous rev or a REMOVE action
if (lastTo == null || lastTo.getAction() == Action.REMOVE) {
action = Action.ADD;
} else {
action = Action.INTEG;
}
if (logger.isTraceEnabled()) {
logger.trace("Dirty edit action to " + action);
}
}
// CornerCase: if same file, downgrade Action
if (from.getPath().equalsIgnoreCase(toPath) && !pendingBlock) {
// ADD action: if no previous rev or a REMOVE action
if (lastTo == null || lastTo.getAction() == Action.REMOVE) {
action = Action.ADD;
} else {
action = Action.EDIT;
}
if (logger.isTraceEnabled()) {
logger.trace("Downgrading action to " + action);
}
}
// Add branch details to RevisionTree
act = tree.branch(from.getPath(), from.getEndChange(), toPath,
nodeChange, action, content, NodeType.FILE, pendingBlock);
// If no content then check lazy copy has an archive file
if (content.isBlob() == false) {
AssetWriter archive = new AssetWriter(depot, act);
archive.check(act.getLazyCopy());
}
}
// Propagate REMOVE action by deleting target
else {
act = tree.branch(from.getPath(), from.getEndChange(), toPath,
nodeChange, Action.REMOVE, content, NodeType.FILE,
pendingBlock);
}
return act;
}
@Override
public void setContent(Content c) throws Exception {
content = c;
downgradeTypes();
}
@Override
public void setProperty(Property property) {
this.property = property;
}
/**
* Down grade content type for non unicode servers from utf8 to text or
* utf32 to binary, this MUST occur before the ChangeAction is added to the
* revision tree.
*
* @throws ConfigException
*/
private void downgradeTypes() throws ConfigException {
if ((Boolean) Config.get(CFG.P4_UNICODE) == false && content != null) {
if ((content.getType() == ContentType.UTF_32BE)
|| (content.getType() == ContentType.UTF_32LE)) {
if (logger.isInfoEnabled()) {
logger.info("Non-unicode server, downgrading utf32 file to binary");
}
content.setType(ContentType.P4_BINARY);
}
if (content.getType().getP4Type() == TranslateCharsetType.UTF8) {
if (logger.isInfoEnabled()) {
logger.info("Non-unicode server, downgrading file to text");
}
content.setType(ContentType.P4_TEXT);
}
}
}
@Override
public void setMergeInfo(MergeInfo merge, String path) {
RevisionTree node = tree.create(path, NodeType.NULL);
node.setMergeInfo(merge);
if (logger.isDebugEnabled()) {
logger.debug("setMergeInfo on : " + path);
logger.debug("... " + merge);
}
}
}
| 27.371171 | 77 | 0.676058 |
d619e40698f582dc6dbbea95af93080ea5671f17 | 5,169 | package textgen;
import java.util.AbstractList;
/** A class that implements a doubly linked list
*
* @author UC San Diego Intermediate Programming MOOC team
*
* @param <E> The type of the elements stored in the list
*/
public class MyLinkedList<E> extends AbstractList<E> {
LLNode<E> head;
LLNode<E> tail;
int size;
/** Create a new empty LinkedList */
public MyLinkedList() {
// TODO: Implement this method
// sentinel nodes are not used
head = tail = null;
size = 0;
}
/**
* Appends an element to the end of the list
* @param element The element to add
*/
public boolean add(E element )
{
// TODO: Implement this method
this.add(size, element);
return true;
}
/** Get the element at position index
* @throws IndexOutOfBoundsException if the index is out of bounds. */
public E get(int index)
{
// TODO: Implement this method.
if(index >= size || index < 0) {
throw new IndexOutOfBoundsException("List does not contain the given index");
}
return getNodeAtIndex(index).data;
}
/**
* Add an element to the list at the specified index
* @param The index where the element should be added
* @param element The element to add
*/
public void add(int index, E element ) {
if (index > size || index < 0) {
throw new IndexOutOfBoundsException("List does not contain the given index");
}
if (element == null) {
throw new NullPointerException("Tried to insert null element to the list");
}
LLNode<E> node = new LLNode<E>(element);
if (size == 0) {
head = tail = new LLNode<E>(element);
}
else if (index == 0) { //insert at head
node.next = head;
head.prev = node;
head = node;
}
else if (index == size) { // insert at tail
tail.next = node;
node.prev = tail;
tail = node;
}
else {
LLNode<E> current = getNodeAtIndex(index);
node.next = current;
node.prev = current.prev;
node.prev.next = node;
current.prev = node;
}
size += 1;
}
private LLNode<E> getNodeAtIndex (int index) {
// Helper method
// For get when size >= 1
// For add at index when size > 0 and 0 < index < size
// For remove at index when size > 1 and 0 < index < size - 1
// For set at index when size > 1 and 0 <= index <= size - 1
LLNode<E> current = null;
if (index <= size / 2) { // if insertion index is closer to head, iterate forwards starting from head
current = head;
for (int i = 0; i < index; i++) {
current = current.next;
}
} else { // if insertion index is closer to tail, iterate backwards starting from tail
current = tail;
for (int i = size - 1; i > index; i--) {
current = current.prev;
}
}
return current;
}
/** Return the size of the list */
public int size()
{
// TODO: Implement this method
return size;
}
/** Remove a node at the specified index and return its data element.
* @param index The index of the element to remove
* @return The data element removed
* @throws IndexOutOfBoundsException If index is outside the bounds of the list
*
*/
public E remove(int index)
{
// TODO: Implement this method
if(index >= size || index < 0) {
throw new IndexOutOfBoundsException("List does not contain the given index");
}
LLNode<E> toBeRemoved = null;
if(size == 1) {
toBeRemoved = head;
head = tail = null;
} else if(index == 0) {
toBeRemoved = head;
head = head.next;
head.prev = null;
} else if(index == size - 1 ) {
toBeRemoved = tail;
tail = tail.prev;
tail.next = null;
} else {
toBeRemoved = getNodeAtIndex(index);
toBeRemoved.prev.next = toBeRemoved.next;
toBeRemoved.next.prev = toBeRemoved.prev;
}
size -= 1;
return toBeRemoved.data;
}
/**
* Set an index position in the list to a new element
* @param index The index of the element to change
* @param element The new element
* @return The element that was replaced
* @throws IndexOutOfBoundsException if the index is out of bounds.
*/
public E set(int index, E element)
{
// TODO: Implement this method
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("List does not contain the given index");
}
if(element == null) {
throw new NullPointerException("Tried to insert null element to the list");
}
LLNode<E> current = getNodeAtIndex(index);
E oldData = current.data;
current.data = element;
return oldData;
}
public String toString() {
StringBuilder sb = new StringBuilder();
LLNode<E> current = head;
while(current != null) {
sb.append(current.toString() + ", ");
current = current.next;
}
return sb.subSequence(0, sb.length() - 2).toString();
}
}
class LLNode<E>
{
LLNode<E> prev;
LLNode<E> next;
E data;
// TODO: Add any other methods you think are useful here
// E.g. you might want to add another constructor
public LLNode(E e)
{
this.data = e;
this.prev = null;
this.next = null;
}
public String toString() {
return this.data + "";
}
}
| 25.716418 | 104 | 0.623912 |
54587d85c540929dcb9efd362d90369058e83cb2 | 2,462 | package com.qiju.game.car.config;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import com.qiju.game.car.config.bean.DataType;
import com.qiju.game.car.db.dao.ConfigDao;
import com.qiju.game.car.util.ClassUtil;
/**
* 负责配置文件的初始化和检测更新
*
* @author qintingyin
*
*/
public class ConfigInitializeManager {
private static String base_dir = null;
static {
String path = getBaseDir() + "log4j.xml";
DOMConfigurator.configureAndWatch(path, 1000);
}
protected static final Logger logger = Logger.getLogger(ConfigInitializeManager.class);
private static ConfigInitializeManager instance = new ConfigInitializeManager();
private Map<String, ConfigLoader> hotMap = new HashMap<String, ConfigLoader>();
public static ConfigInitializeManager getInstance() {
return instance;
}
private ConfigInitializeManager() {
init();
}
private void init() {
try {
List<Class<?>> list = ClassUtil.getAllAssignedClass(ConfigLoader.class);
for (Class<?> clazz : list) {
DataType type = clazz.getAnnotation(DataType.class);
ConfigLoader loader = (ConfigLoader) clazz.newInstance();
loader.load();
if (type != null && type.type().equals(DataType.Type.Hot)) {
hotMap.put(clazz.getSimpleName(), loader);
}
}
} catch (Exception e) {
logger.error("error at init ConfigInitializeManager..", e);
}
// 配置更新检测线程,定期读取数据库config表,根据结果判断需要更新的配置并更新
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
ConfigDao dao = new ConfigDao();
List<String> names = dao.queryAllChanges();
if (names.size() > 0) {
dao.resetChanges();
for (String key : names) {
try {
hotMap.get(key).load();
} catch (Exception e) {
logger.error("配置[" + key + "]热更新出错...", e);
}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "configCheckThread").start();
}
public static String getBaseDir() {
if (base_dir == null) {
String dev_dir = "/src/main/resources/";
File file = new File(System.getProperty("user.dir") + dev_dir);
if (file.exists() && file.isDirectory()) {
base_dir = System.getProperty("user.dir") + dev_dir;
} else {
base_dir = System.getProperty("user.dir") + "/resource/";
}
}
return base_dir;
}
}
| 25.915789 | 88 | 0.662876 |
a935ff2719f88b8fd575d3f7e1dd3c9ec5a776a1 | 4,664 | package com.qypt.just_syn_asis_version1_0.activity;
import com.qypt.just_syn_asis_version1_0.model.EventBussMessage;
import com.qypt.just_syn_asis_version1_0.model.TaskBean;
import com.qypt.just_syn_asis_version1_0.utils.DialogUtils;
import de.greenrobot.event.EventBus;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
*
* @author Administrator justson
*
*/
public class AccountActivity extends SynActivity implements OnClickListener,
android.content.DialogInterface.OnClickListener {
private TextView account_phone_phone_textview;
private TextView account_name_name_textview;
private Button out_account_button;
public static final int ACCOUNTACTIVITY = 1099;
private MyHandler mMyHandler;
private String name;
@Override
protected void initView() {
EventBus.getDefault().register(this);
overridePendingTransition(R.anim.bottom_out_alp_fade_in, 0);
setContentView(R.layout.activity_account);
ImageView comeback_account = (ImageView) findViewById(R.id.comeback_account);
comeback_account.setOnClickListener(this);
account_phone_phone_textview = (TextView) findViewById(R.id.account_phone_phone_textview);
account_name_name_textview = (TextView) findViewById(R.id.account_name_name_textview);
out_account_button = (Button) findViewById(R.id.out_account_button);
out_account_button.setOnClickListener(this);
mMyHandler = new MyHandler(Looper.getMainLooper());
LinearLayout operation_account_linearlayout = (LinearLayout) findViewById(R.id.operation_account_linearlayout);
operation_account_linearlayout.setOnClickListener(this);
}
@Override
protected void initViewData() {
Intent mIntent = getIntent();
String phone = mIntent.getStringExtra("phone");
name = mIntent.getStringExtra("name");
account_name_name_textview.setText(name);
account_phone_phone_textview.setText(phone);
}
@Override
protected void onPause() {
overridePendingTransition(0, R.anim.top_out_fade_out);
super.onPause();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.comeback_account:
this.finish();
break;
case R.id.out_account_button:
drop_Out_account();
break;
case R.id.operation_account_linearlayout:
Intent mIntent = new Intent(this, OperationActivity.class);
mIntent.putExtra("userName",name );
startActivity(mIntent);
break;
}
}
/**
* 提示用户, 确定便退出
*/
private void drop_Out_account() {
Log.i("Info", "show dialog");
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(this, 2);
mAlertDialog.setTitle("提示");
mAlertDialog.setMessage("确定退出账号吗?");
mAlertDialog.setNegativeButton("取消", null);
mAlertDialog.setPositiveButton("确定", this);
mAlertDialog.show();
}
/**
* 跳转到登录界面
*/
@Override
public void onClick(DialogInterface dialog, int which) {
DialogUtils.moreColorProgress(this);
Message mMessage = mMyHandler.obtainMessage(0x99);
mMyHandler.sendMessageDelayed(mMessage, 2000);
}
private void NotifyMainActivity() {
EventBussMessage.Builder builder = new EventBussMessage.Builder();
builder.setSubscriber(ACCOUNTACTIVITY);
builder.setMessage("用户退出了啦~");
EventBussMessage mEventBussMessage = builder.build();
EventBus.getDefault().post(mEventBussMessage);
}
/**
* 用handler做一个延迟的效果
*
* @author Administrator
*
*/
final class MyHandler extends Handler {
public MyHandler(Looper mLooper) {
super(mLooper);
}
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x99) {
clearRecord();
NotifyMainActivity();// 通知主界面,退出账号了
Intent mIntent = new Intent(AccountActivity.this,
LoginActivity.class);
startActivityForResult(mIntent,0);
DialogUtils.moreColorDismiss();
AccountActivity.this.finish();
}
}
}
/**
* 清楚sharePreference里面的文件
*/
private void clearRecord() {
SharedPreferences mSharedPreferences = this.getSharedPreferences(
"account", this.MODE_PRIVATE);
Editor mEditor = mSharedPreferences.edit();
mEditor.clear();
mEditor.commit();
}
public void onEventMainThread(EventBussMessage mEventBussMessage) {
}
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}
| 26.202247 | 113 | 0.766081 |
4018c8f919c52a7fc897372d7644b44041396fab | 17,644 | package com.honyum.elevatorMan.activity.maintenance;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.baidu.navisdk.util.common.StringUtils;
import com.honyum.elevatorMan.R;
import com.honyum.elevatorMan.activity.workOrder.MaintenanceFinishActivity;
import com.honyum.elevatorMan.base.BaseFragmentActivity;
import com.honyum.elevatorMan.net.MaintenanceServiceFinishRequest;
import com.honyum.elevatorMan.net.UploadImageRequest;
import com.honyum.elevatorMan.net.UploadImageResponse;
import com.honyum.elevatorMan.net.base.NetConstant;
import com.honyum.elevatorMan.net.base.NetTask;
import com.honyum.elevatorMan.net.base.NewRequestHead;
import com.honyum.elevatorMan.net.base.RequestBean;
import com.honyum.elevatorMan.net.base.Response;
import com.honyum.elevatorMan.utils.ImageNode;
import com.honyum.elevatorMan.utils.UploadImageManager;
import com.honyum.elevatorMan.utils.Utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by Star on 2017/6/10.
*/
public class MaintenanceTaskFinishActivity extends BaseFragmentActivity {
private ImageView mImageView1;
private ImageView mImageView2;
private ImageView mImageView3;
private String currId = "";
private TextView tv_fix_complete;
private String bi = "";
private String ai = "";
private String ci = "";
private String mPublicPath = "";
//临时文件,处理照片的压缩
private String mTempFile = "";
private EditText et_remark;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maint_result);
initPublicPath();
initTitle();
initView();
}
/**
* 初始化照片存储路径
*
* @param
*/
private void initPublicPath() {
Intent it = getIntent();
currId = it.getStringExtra("Id");
String sdPath = Utils.getSdPath();
if (null == sdPath) {
return;
}
//LiftInfo liftInfo = (LiftInfo) intent.getSerializableExtra("lift");
mPublicPath = sdPath + "/chorstar/maintenancetask/" + currId + "/";
}
/**
* 初始化标题
*/
private void initTitle() {
initTitleBar("维保结果", R.id.title_service_result,
R.drawable.back_normal, backClickListener);
}
/**
* 调用系统相机之后返回
*
* @param requestCode
* @param resultCode
* @param data
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
if (StringUtils.isEmpty(mPublicPath)) {
showToast("请检查SD卡");
return;
}
String dirPath = mPublicPath + requestCode + "/";
ImageView imageView = null;
Button delButton = null;
if (1 == requestCode) {
imageView = mImageView1;
delButton = (Button) findViewById(R.id.btn_del_1);
delButton.setTag(requestCode);
showImage(dirPath, imageView, delButton);
String imgPath1 = (String) mImageView1.getTag(R.id.file_path);
Log.e("TAG", "onActivityResult: " + imgPath1);
ai = imgPath1;
saveImageData("1"+currId+getConfig().getUserId(), imgPath1);
//requestUploadImage(imgPath1, imgPath1,requestCode);
} else if (2 == requestCode) {
imageView = mImageView2;
delButton = (Button) findViewById(R.id.btn_del_2);
delButton.setTag(requestCode);
showImage(dirPath, imageView, delButton);
String imgPath2 = (String) mImageView2.getTag(R.id.file_path);
Log.e("TAG", "onActivityResult: " + imgPath2);
bi = imgPath2;
saveImageData("2"+currId+getConfig().getUserId(), imgPath2);
///requestUploadImage(imgPath2,imgPath2, requestCode);
}
else if (3 == requestCode) {
imageView = mImageView3;
delButton = (Button) findViewById(R.id.btn_del_3);
delButton.setTag(requestCode);
showImage(dirPath, imageView, delButton);
String imgPath3 = (String) mImageView3.getTag(R.id.file_path);
Log.e("TAG", "onActivityResult: " + imgPath3);
ci = imgPath3;
saveImageData("3"+currId+getConfig().getUserId(), imgPath3);
//requestUploadImage(imgPath3,imgPath3, requestCode);
}
}
private void requestMaintOrderProcessWorkerFinish(ImageNode head) {
NetTask task = new NetTask(getConfig().getServer() + NetConstant.URL_MAINT_TASK_FINISH,
getRequestBean(getConfig().getUserId(), getConfig().getToken(),head)) {
@Override
protected void onResponse(NetTask task, String result) {
Response response = Response.getResponse(result);
if (response.getHead() != null&&response.getHead().getRspCode().equals("0")) {
showAppToast(getString(R.string.sucess));
finish();
}
//Log.e("!!!!!!!!!!!!!!", "onResponse: "+ msInfoList.get(0).getMainttypeId());
}
//Log.e("!!!!!!!!!!!!!!", "onResponse: "+ msInfoList.get(0).getMainttypeId());;
};
addTask(task);
}
private RequestBean getRequestBean(String userId, String token,ImageNode head) {
ai = head.getUrl();
if (head.hasNext()&& !TextUtils.isEmpty(head.getNext().getUrl())) {
head = head.getNext();
bi = head.getUrl();
}
if (head.hasNext()&& !TextUtils.isEmpty(head.getNext().getUrl())) {
head = head.getNext();
ci = head.getUrl();
}
MaintenanceServiceFinishRequest request = new MaintenanceServiceFinishRequest();
request.setHead(new NewRequestHead().setaccessToken(token).setuserId(userId));
request.setBody(request.new MaintenanceServiceFinishBody().setMaintOrderProcessId(currId).setMaintUserFeedback(et_remark.getText().toString().trim()).setAfterImg(ai).setBeforeImg(bi).setAfterImg1(ci));
return request;
}
/**
* 显示拍摄的照片并
*
* @param dirPath
* @param imageView
* @param delButton
*/
private void showImage(String dirPath, final ImageView imageView,
final Button delButton) {
Bitmap bitmap = Utils.getBitmapBySize(mTempFile, 600, 800);
//清理临时目录
initTempFile();
FileOutputStream outputStream = null;
File dirFile = new File(dirPath);
//如果目录存在,则删除,重新创建,保证同一个电梯在同一时间同一个照片位置只有一个照片目录
if (dirFile.exists()) {
Utils.deleteFiles(dirFile);
} else {
dirFile.mkdirs();
}
String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg";
final String filePath = dirPath + fileName;
try {
outputStream = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 30, outputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Bitmap showImage = Utils.getBitmapBySize(filePath, 120, 160);
imageView.setImageBitmap(showImage);
imageView.setTag(R.id.file_path, filePath);
imageView.setOnClickListener(overViewClickListener);
delButton.setVisibility(View.VISIBLE);
delButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File file = new File(filePath);
file.delete();
delButton.setVisibility(View.GONE);
if ((int)delButton.getTag(R.id.index) == 1) {
ai = "";
saveImageData(imageView.getTag(R.id.file_path).toString(), "");
} else if ((int)delButton.getTag(R.id.index) == 2) {
bi = "";
saveImageData(imageView.getTag(R.id.file_path).toString(), "");
}
else if ((int)delButton.getTag(R.id.index) == 3) {
ci = "";
saveImageData(imageView.getTag(R.id.file_path).toString(), "");
}
imageView.setTag(R.id.file_path, "");
imageView.setImageResource(R.drawable.defaut_image);
imageView.setOnClickListener(imageViewClickListener);
}
});
}
/**
* 将图片转换成BASE64
*
* @param imgPath
* @return
*/
public static String imgToStrByBase64(String imgPath) {
if (StringUtils.isEmpty(imgPath)) {
return "";
}
File file = new File(imgPath);
if (!file.exists()) {
return "";
}
Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
return Utils.imgToStrByBase64(bitmap);
}
UploadImageManager imager ;
ImageNode first;
ImageNode sec;
ImageNode thir;
/**
* 初始化view
*/
private void initView() {
mImageView1 = (ImageView) findViewById(R.id.iv_image1);
mImageView2 = (ImageView) findViewById(R.id.iv_image2);
mImageView3 = (ImageView) findViewById(R.id.iv_image3);
mImageView1.setOnClickListener(imageViewClickListener);
mImageView2.setOnClickListener(imageViewClickListener);
mImageView3.setOnClickListener(imageViewClickListener);
mImageView1.setTag(R.id.index, 1);
mImageView2.setTag(R.id.index, 2);
mImageView3.setTag(R.id.index, 3);
et_remark = (EditText) findViewById(R.id.et_remark);
Button button1 = (Button) findViewById(R.id.btn_del_1);
Button button2 = (Button) findViewById(R.id.btn_del_2);
Button button3 = (Button) findViewById(R.id.btn_del_3);
button1.setTag(R.id.index,1);
button2.setTag(R.id.index,2);
button3.setTag(R.id.index,3);
String path1 = getImageData("1"+currId+getConfig().getUserId());
String path2 = getImageData("2"+currId+getConfig().getUserId());
String path3 = getImageData("3"+currId+getConfig().getUserId());
first = new ImageNode();
sec = new ImageNode();
thir = new ImageNode();
first.setNext(sec);
sec.setNext(thir);
imager = new UploadImageManager();
if (path1!=null)
loadPicture(path1, mImageView1, button1);
if (path2!=null)
loadPicture(path2, mImageView2, button2);
if (path3!=null)
loadPicture(path3, mImageView3, button3);
tv_fix_complete = (TextView) findViewById(R.id.tv_fix_complete);
tv_fix_complete.setOnClickListener(new View.OnClickListener(
) {
@Override
public void onClick(View v) {
if (ai.equals("") || bi.equals("")||"".equals(ci)) {
showAppToast("请拍摄完整的图片!");
return;
}
imager.getImages(MaintenanceTaskFinishActivity.this,first,(datas)->{
requestMaintOrderProcessWorkerFinish(datas);
return null;
});
}
});
}
/**
* 加载之前拍摄的照片
*
* @param filePath
* @param imageView
* @param delButton
*/
private void loadPicture(String filePath, final ImageView imageView, final Button delButton) {
Bitmap bitmap = Utils.getBitmapBySize(filePath, 60, 80);
imageView.setImageBitmap(bitmap);
imageView.setTag(R.id.file_path, filePath);
if ((int)imageView.getTag(R.id.index) == 1) {
ai = filePath;
first.setImg(Utils.imgToStrByBase64(filePath));
} else if ((int)imageView.getTag(R.id.index) == 2) {
bi = filePath;
sec.setImg(Utils.imgToStrByBase64(filePath));
}
else if ((int)imageView.getTag(R.id.index) == 3) {
ci = filePath;
thir.setImg(Utils.imgToStrByBase64(filePath));
}
imageView.setOnClickListener(overViewClickListener);
delButton.setVisibility(View.VISIBLE);
delButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File file = new File(filePath);
file.delete();
delButton.setVisibility(View.GONE);
if ((int)delButton.getTag(R.id.index) == 1) {
ai = "";
deleteImageData("1"+currId+getConfig().getUserId());
} else if ((int)delButton.getTag(R.id.index) == 2) {
bi = "";
deleteImageData("2"+currId+getConfig().getUserId());
}
else if ((int)delButton.getTag(R.id.index) == 3) {
ci = "";
deleteImageData("3"+currId+getConfig().getUserId());
}
imageView.setImageResource(R.drawable.defaut_image);
imageView.setOnClickListener(imageViewClickListener);
}
});
}
/**
* 拍照之后点击照片查看照片预览
*/
private View.OnClickListener overViewClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v instanceof ImageView) {
String filePath = (String) v.getTag(R.id.file_path);
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
((ImageView) findViewById(R.id.iv_overview)).setImageBitmap(bitmap);
final LinearLayout llFullScreen = (LinearLayout) findViewById(R.id.ll_full_screen);
llFullScreen.setVisibility(View.VISIBLE);
llFullScreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
llFullScreen.setVisibility(View.GONE);
}
});
}
}
};
/**
* 初始化临时文件
*/
private void initTempFile() {
String sdPath = Utils.getSdPath();
if (null == sdPath) {
return;
}
String tempPath = sdPath + "/chorstar/maintenancetask/temp/";
mTempFile = tempPath + "original.jpg";
File tempFile = new File(mTempFile);
//文件存在,删除
if (tempFile.exists()) {
tempFile.delete();
return;
}
//目录不存在,创建目录
File pathFile = new File(tempPath);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
}
/**
* 点击照片位置时进行拍照
*/
private View.OnClickListener imageViewClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
//初始化临时目录
initTempFile();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File out = new File(mTempFile);
Uri uri = Uri.fromFile(out);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, (Integer) v.getTag(R.id.index));
}
};
private RequestBean getImageRequestBean(String userId, String token, String path) {
UploadImageRequest request = new UploadImageRequest();
request.setHead(new NewRequestHead().setuserId(userId).setaccessToken(token));
request.setBody(request.new UploadImageBody().setImg(path));
return request;
}
private void requestUploadImage(final String path, final String realPath, final int request) {
NetTask task = new NetTask(getConfig().getServer() + NetConstant.UP_LOAD_IMG,
getImageRequestBean(getConfig().getUserId(), getConfig().getToken(), path)) {
@Override
protected void onResponse(NetTask task, String result) {
UploadImageResponse response = UploadImageResponse.getUploadImageResponse(result);
if (response.getHead() != null && response.getHead().getRspCode().equals("0")) {
String url = response.getBody().getUrl();
showAppToast(getString(R.string.sucess));
if (request == 1) {
ai = url;
saveImageData(realPath, url);
} else if (request == 2) {
saveImageData(realPath, url);
bi = url;
}
else if (request == 3) {
saveImageData(realPath, url);
ci = url;
}
}
//Log.e("!!!!!!!!!!!!!!", "onResponse: "+ msInfoList.get(0).getMainttypeId());
}
};
addTask(task);
}
}
| 33.353497 | 209 | 0.584278 |
e2218425ee739f34e078cd41356f55b5af8f34fd | 768 | package cn.az.mall;
import cn.az.mall.entity.PmsBrand;
import cn.az.mall.service.IPmsBrandService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
@SpringBootTest
public class LittleMallApplicationTests {
@Resource
private IPmsBrandService pmsBrandService;
@Test
public void contextLoads() {
pmsBrandService.page(new Page<>(1, 5),
Wrappers.<PmsBrand>lambdaQuery().orderByAsc(PmsBrand::getId))
.getRecords().forEach(System.out::println);
pmsBrandService.listMaps().forEach(System.out::println);
}
}
| 28.444444 | 73 | 0.748698 |
ee9b9bf797387ef6dc08a8196bdb987eeda7bf65 | 3,135 | /*
* This file was automatically generated by EvoSuite
* Tue Jul 31 22:50:15 GMT 2018
*/
package org.mozilla.javascript.tools.debugger;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
import org.mozilla.javascript.tools.debugger.RunProxy;
import org.mozilla.javascript.tools.debugger.SwingGui;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class RunProxy_ESTest extends RunProxy_ESTest_scaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
RunProxy runProxy0 = new RunProxy((SwingGui) null, 2163);
// Undeclared exception!
try {
runProxy0.run();
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// 2163
//
verifyException("org.mozilla.javascript.tools.debugger.RunProxy", e);
}
}
@Test(timeout = 4000)
public void test1() throws Throwable {
RunProxy runProxy0 = new RunProxy((SwingGui) null, 4);
// Undeclared exception!
try {
runProxy0.run();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.mozilla.javascript.tools.debugger.RunProxy", e);
}
}
@Test(timeout = 4000)
public void test2() throws Throwable {
RunProxy runProxy0 = new RunProxy((SwingGui) null, 3);
// Undeclared exception!
try {
runProxy0.run();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.mozilla.javascript.tools.debugger.RunProxy", e);
}
}
@Test(timeout = 4000)
public void test3() throws Throwable {
RunProxy runProxy0 = new RunProxy((SwingGui) null, 2);
// Undeclared exception!
try {
runProxy0.run();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.mozilla.javascript.tools.debugger.MessageDialogWrapper", e);
}
}
@Test(timeout = 4000)
public void test4() throws Throwable {
RunProxy runProxy0 = new RunProxy((SwingGui) null, 1);
// Undeclared exception!
try {
runProxy0.run();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.mozilla.javascript.tools.debugger.MessageDialogWrapper", e);
}
}
}
| 31.35 | 176 | 0.644019 |
7984296a53e883e51a95dc06878fb3ea5b93894e | 2,606 | /*
* Copyright 2017 Ecole des Mines de Saint-Etienne.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.thesmartenergy.sparql.generate.jena.graph;
import com.github.thesmartenergy.sparql.generate.jena.expr.E_URIParam;
import java.util.List;
import java.util.UUID;
import org.apache.jena.graph.NodeVisitor;
import org.apache.jena.sparql.expr.Expr;
/**
* The class of expression nodes of type {@code <text{<expr>}> }, or any other
* IRI with embedded expressions.
*
* @author maxime.lefrancois
*/
public class Node_ExtendedURI extends Node_ExprList {
/**
*
* @param components list of NodeValueString or Expressions
*/
private Node_ExtendedURI(List<Expr> components) {
super(UUID.randomUUID().toString().substring(0,8), components);
}
/**
* Builder of immutable Node_ExtendedURI
*/
public static class Builder extends Node_ExprList.Builder {
@Override
public Node_ExtendedURI build() {
return new Node_ExtendedURI(components);
}
@Override
public void add(Expr e){
components.add(new E_URIParam(e));
}
}
/**
* {@inheritDoc }
*/
@Override
public Object visitWith(NodeVisitor v) {
if (v instanceof SPARQLGenerateNodeVisitor) {
((SPARQLGenerateNodeVisitor) v).visit(this);
}
return null;
}
/**
* {@inheritDoc }
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Node_ExtendedURI)) {
return false;
}
Node_ExtendedURI on = (Node_ExtendedURI) o;
if (components.size() != on.components.size()) {
return false;
}
for (int i = 0; i < components.size(); i++) {
if (!components.get(i).equals(on.components.get(i))) {
return false;
}
}
return true;
}
}
| 28.955556 | 79 | 0.600153 |
aae0447d9c98de073187f2303d80c9d05fdbd773 | 215 |
public class Match extends Thread
{
Logic logic;
public Match(Logic log)
{
this.logic = log;
this.setPriority(MAX_PRIORITY);
}
public void run()
{
logic.run = true;
logic.newGame(AI.BOTPLY);
}
}
| 11.944444 | 33 | 0.660465 |
d59ff69d1e08c3d9534545ef8ab318a284b1da67 | 818 | package by.danila.tictactoe.display;
import by.danila.tictactoe.core.Cell;
/**
* @author Andrei Zhemaituk
*/
class CurrentMove {
private static Object monitor = new Object();
static Cell current;
static void set(Cell cell) {
synchronized (monitor) {
current = cell;
monitor.notify();
}
}
static Cell get() {
synchronized (monitor) {
while (true) {
if (current != null) {
Cell result = current;
current = null;
return result;
}
try {
monitor.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
| 20.974359 | 50 | 0.457213 |
17e15f1b5ca3e6c3fd9efbf6c1d20ed072c9787a | 3,462 | /*
* 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.camel.example.azurestorageblob;
import com.azure.storage.blob.BlobServiceClientBuilder;
import com.azure.storage.blob.models.ListBlobsOptions;
import com.azure.storage.common.StorageSharedKeyCredential;
import java.util.Iterator;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
/**
* A basic example of list large azure blob storage.
*/
public final class Application {
private static final String ACCOUNT = "ENTER_YOUR_ACCOUNT";
private static final String ACCESS_KEY = "ACCESS_KEY";
private static final String BLOB_CONTAINER_NAME = "CONTAINER";
public static void main(String[] args) throws Exception {
// create a CamelContext
try (CamelContext camel = new DefaultCamelContext()) {
// add routes which can be inlined as anonymous inner class
// (to keep all code in a single java file for this basic example)
camel.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("timer://runOnce?repeatCount=1&delay=0")
.routeId("listBlobs")
.process(exchange -> exchange.getIn()
.setBody(
new BlobServiceClientBuilder()
.endpoint(String.format("https://%s.blob.core.windows.net", ACCOUNT))
.credential(new StorageSharedKeyCredential(ACCOUNT, ACCESS_KEY))
.buildClient()
.getBlobContainerClient(BLOB_CONTAINER_NAME)
.listBlobs(
new ListBlobsOptions().setMaxResultsPerPage(1),
null
)
)
)
.loopDoWhile(exchange ->
exchange.getIn().getBody(Iterator.class).hasNext()
)
.process(exchange ->
exchange.getIn().setBody(exchange.getIn().getBody(Iterator.class).next())
)
.log("${body.name}")
.end();
}
});
// start is not blocking
camel.start();
// so run for 10 seconds
Thread.sleep(10_000);
// and then stop nicely
camel.stop();
}
}
}
| 42.740741 | 105 | 0.571346 |
bad79bfdc4e7475e3f9cdb698f75c2cc7f787830 | 1,462 | /*
* Copyright 2016 Prowave Consulting, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package io.prowave.chargify.webhook.bean;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class DunningStepReached extends Payload {
private Dunner dunner;
@JsonProperty("current_step")
private CurrentStep currentStep;
@JsonProperty("next_step")
private NextStep nextStep;
public Dunner getDunner() {
return dunner;
}
public void setDunner(Dunner dunner) {
this.dunner = dunner;
}
public CurrentStep getCurrentStep() {
return currentStep;
}
public void setCurrentStep(CurrentStep currentStep) {
this.currentStep = currentStep;
}
public NextStep getNextStep() {
return nextStep;
}
public void setNextStep(NextStep nextStep) {
this.nextStep = nextStep;
}
}
| 25.206897 | 75 | 0.757182 |
ff5132d5ed275f17072fde1a4380bfda3a8ba01a | 3,721 | package org.sonatype.guice.bean.reflect;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
final class ResourceEnumeration
implements Enumeration<URL>
{
private static final Iterator<String> NO_ENTRIES = Collections.emptyList().iterator();
private final Iterator<URL> urls;
private final String subPath;
private final GlobberStrategy globber;
private final Object globPattern;
private final boolean recurse;
private URL currentURL;
private boolean isFolder;
private Iterator<String> entryNames = NO_ENTRIES;
private String nextEntryName;
ResourceEnumeration(String subPath, String glob, boolean recurse, URL[] urls)
{
this.subPath = normalizeSearchPath(subPath);
globber = selectGlobberStrategy(glob);
globPattern = globber.compile(glob);
this.recurse = recurse;
this.urls = Arrays.asList(urls).iterator();
}
public boolean hasMoreElements()
{
while (null == nextEntryName)
{
if (entryNames.hasNext())
{
String name = (String)entryNames.next();
if (matchesRequest(name))
{
nextEntryName = name;
}
}
else if (urls.hasNext())
{
currentURL = ((URL)urls.next());
entryNames = scan(currentURL);
}
else
{
return false;
}
}
return true;
}
public URL nextElement()
{
if (hasMoreElements())
{
String name = nextEntryName;
nextEntryName = null;
try
{
return isFolder ? new URL(currentURL, name) : new URL("jar:" + currentURL + "!/" + name);
}
catch (MalformedURLException e)
{
throw new IllegalStateException(e.toString());
}
}
throw new NoSuchElementException();
}
private static String normalizeSearchPath(String path)
{
if ((null == path) || ("/".equals(path)))
{
return "";
}
boolean echoSlash = false;
StringBuilder buf = new StringBuilder();
int i = 0; for (int length = path.length(); i < length; i++)
{
char c = path.charAt(i);
boolean isNotSlash = '/' != c;
if ((echoSlash) || (isNotSlash))
{
echoSlash = isNotSlash;
buf.append(c);
}
}
if (echoSlash)
{
buf.append('/');
}
return buf.toString();
}
private static GlobberStrategy selectGlobberStrategy(String glob)
{
if ((null == glob) || ("*".equals(glob)))
{
return GlobberStrategy.ANYTHING;
}
int firstWildcard = glob.indexOf('*');
if (firstWildcard < 0)
{
return GlobberStrategy.EXACT;
}
int lastWildcard = glob.lastIndexOf('*');
if (firstWildcard == lastWildcard)
{
if (firstWildcard == 0)
{
return GlobberStrategy.SUFFIX;
}
if (lastWildcard == glob.length() - 1)
{
return GlobberStrategy.PREFIX;
}
}
return GlobberStrategy.PATTERN;
}
private Iterator<String> scan(URL url)
{
isFolder = url.getPath().endsWith("/");
return isFolder ? new FileEntryIterator(url, subPath, recurse) : new ZipEntryIterator(url);
}
private boolean matchesRequest(String entryName)
{
if ((entryName.endsWith("/")) || (!entryName.startsWith(subPath)))
{
return false;
}
if ((!recurse) && (entryName.indexOf('/', subPath.length()) > 0))
{
return false;
}
return globber.match(globPattern, entryName);
}
}
| 16.178261 | 97 | 0.598226 |
8252791c6ab6d3748205e8fc6f01c5cb94bfe29c | 472 | package yte.intern.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import yte.intern.model.UserLogin;
import yte.intern.model.UserProfile;
import java.util.List;
import java.util.Optional;
public interface UserLoginRepository extends JpaRepository<UserLogin, Long> {
Optional<UserLogin> findByUsername(String username);
List<UserLogin> findAllByUserProfile(UserProfile userProfile);
Boolean existsByUsername(String username);
} | 26.222222 | 77 | 0.813559 |
c4b7e30ad3c079d12af67cf3bac23c2859da93ea | 109 | package com.bdoemu.gameserver.model.misc.enums;
public enum EAttackType {
MELEE,
RANGED,
MAGIC
} | 15.571429 | 47 | 0.706422 |
80d0992ea37f46c061e986c133f22761a500a118 | 255 | package zetra.iocshark.exceptions;
public class InstanceNotRegisteredException extends IocStoreException {
public InstanceNotRegisteredException(Class instanceClass) {
super("No registered instance for: " + instanceClass.getName());
}
}
| 28.333333 | 72 | 0.772549 |
7736216345119e242477790db252cd0bf44c4a99 | 1,315 | package com.abed.assignment.controller;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class DataManager {
private final ApiHelper mApiHelper;
private final SharedPrefHelper mSharedPrefHelper;
private final EventBusHelper mEventBusHelper;
private final LocalFileHelper mLocalFileHelper;
private final DatabaseHelper mDatabaseHelper;
@Inject
public DataManager(SharedPrefHelper sharedPrefHelper,
EventBusHelper eventBusHelper,
ApiHelper apiHelper,
DatabaseHelper databaseHelper,
LocalFileHelper localFileHelper) {
mSharedPrefHelper = sharedPrefHelper;
mEventBusHelper = eventBusHelper;
mApiHelper = apiHelper;
mLocalFileHelper = localFileHelper;
this.mDatabaseHelper = databaseHelper;
}
public EventBusHelper getEventBusHelper() {
return mEventBusHelper;
}
public ApiHelper getApiHelper() {
return mApiHelper;
}
public SharedPrefHelper getSharedPrefHelper() {
return mSharedPrefHelper;
}
public LocalFileHelper getLocalFileHelper() {
return mLocalFileHelper;
}
public DatabaseHelper getDatabaseHelper() {
return mDatabaseHelper;
}
}
| 27.395833 | 57 | 0.686692 |
053a9331fabe779c793ad11463b26dde0ea7c7d5 | 390 | package org.prebid.server.deals.proto;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Value;
/**
* Defines the contract for lineItems[].frequencyCap.
*/
@Builder
@Value
public class FrequencyCap {
@JsonProperty("fcapId")
String fcapId;
Long count;
Integer periods;
@JsonProperty("periodType")
String periodType;
}
| 16.25 | 53 | 0.725641 |
8d3161d7dc35e9252f4079f471b9132fa9615318 | 1,629 | package com.onchain.tademo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;
import java.nio.charset.Charset;
import java.util.UUID;
/**
* @author zhouq
* @date 2017/11/23
*/
@Slf4j
@Component
public class Helper {
/**
* check param whether is null or ''
*
* @param params
* @return boolean
*/
public static Boolean isEmptyOrNull(Object... params) {
if (params != null) {
for (Object val : params) {
if ("".equals(val) || val == null) {
return true;
}
}
return false;
}
return true;
}
public static Boolean isNotEmptyAndNull(Object...params){
return !isEmptyOrNull(params);
}
/**
* get current method name
*
* @return
*/
public static String currentMethod() {
return new Exception("").getStackTrace()[1].getMethodName();
}
public static String getBasicAuthHeader(String username, String password) {
String auth = username + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String(encodedAuth);
log.info("header authorization:{}",authHeader);
return authHeader;
}
public static String generateRequestId(){
return UUID.randomUUID().toString();
}
public static String generateUnPassClaimId(){
return "unpass"+UUID.randomUUID().toString().replace("-","");
}
}
| 22.625 | 93 | 0.596071 |
466652ccca9f12cf0a86206a390321eb9c1b75dd | 1,015 | package com.wedian.site.modules.cms.web;
import com.wedian.site.common.mapper.JsonMapper;
import com.wedian.site.common.web.BaseController;
import com.wedian.site.modules.sys.entity.User;
import com.wedian.site.modules.sys.utils.UserUtils;
import com.wedian.site.common.web.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by Administrator on 2015/5/12.
*/
@Controller
public class IndexController extends BaseController {
@RequestMapping(value="/index",method = RequestMethod.GET)
public String index(ModelMap model){
User currentUser = UserUtils.getUser();
System.out.println("index----------------------"+ JsonMapper.toJsonString(currentUser));
model.addAttribute("user", currentUser);
return "index.ftl";
}
}
| 35 | 96 | 0.757635 |
68ffce5ec600244368cf6e137c7c7f19766a3cd3 | 4,906 | package io.github.mightguy.spellcheck.symspell;
import io.github.mightguy.spellcheck.symspell.api.DataHolder;
import io.github.mightguy.spellcheck.symspell.common.DictionaryItem;
import io.github.mightguy.spellcheck.symspell.common.Murmur3HashFunction;
import io.github.mightguy.spellcheck.symspell.common.QwertzDistance;
import io.github.mightguy.spellcheck.symspell.common.SpellCheckSettings;
import io.github.mightguy.spellcheck.symspell.common.SuggestionItem;
import io.github.mightguy.spellcheck.symspell.common.Verbosity;
import io.github.mightguy.spellcheck.symspell.common.WeightedDamerauLevenshteinDistance;
import io.github.mightguy.spellcheck.symspell.exception.SpellCheckException;
import io.github.mightguy.spellcheck.symspell.impl.InMemoryDataHolder;
import io.github.mightguy.spellcheck.symspell.impl.SymSpellCheck;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class GermanLangSpellChecker {
static DataHolder dataHolder1;
static DataHolder dataHolder2;
static SymSpellCheck symSpellCheck;
static SymSpellCheck qwertzSymSpellCheck;
static WeightedDamerauLevenshteinDistance weightedDamerauLevenshteinDistance;
static WeightedDamerauLevenshteinDistance qwertzWeightedDamerauLevenshteinDistance;
@BeforeClass
public static void setup() throws IOException, SpellCheckException {
ClassLoader classLoader = SymSpellTest.class.getClassLoader();
SpellCheckSettings spellCheckSettings = SpellCheckSettings.builder()
.countThreshold(1)
.deletionWeight(1)
.insertionWeight(1)
.replaceWeight(1)
.maxEditDistance(2)
.transpositionWeight(1)
.topK(5)
.prefixLength(10)
.verbosity(Verbosity.ALL).build();
weightedDamerauLevenshteinDistance =
new WeightedDamerauLevenshteinDistance(spellCheckSettings.getDeletionWeight(),
spellCheckSettings.getInsertionWeight(), spellCheckSettings.getReplaceWeight(),
spellCheckSettings.getTranspositionWeight(), null);
qwertzWeightedDamerauLevenshteinDistance =
new WeightedDamerauLevenshteinDistance(spellCheckSettings.getDeletionWeight(),
spellCheckSettings.getInsertionWeight(), spellCheckSettings.getReplaceWeight(),
spellCheckSettings.getTranspositionWeight(), new QwertzDistance());
dataHolder1 = new InMemoryDataHolder(spellCheckSettings, new Murmur3HashFunction());
dataHolder2 = new InMemoryDataHolder(spellCheckSettings, new Murmur3HashFunction());
symSpellCheck = new SymSpellCheck(dataHolder1, weightedDamerauLevenshteinDistance,
spellCheckSettings);
qwertzSymSpellCheck = new SymSpellCheck(dataHolder2, qwertzWeightedDamerauLevenshteinDistance,
spellCheckSettings);
List<String> result = new ArrayList<>();
loadUniGramFile(
new File(classLoader.getResource("de-100k.txt").getFile()));
}
private static void loadUniGramFile(File file) throws IOException, SpellCheckException {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
String[] arr = line.split("\\s+");
dataHolder1.addItem(new DictionaryItem(arr[0], Double.parseDouble(arr[1]), -1.0));
dataHolder2.addItem(new DictionaryItem(arr[0], Double.parseDouble(arr[1]), -1.0));
}
}
@Test
public void testMultiWordCorrection() throws SpellCheckException {
assertTypoAndCorrected(symSpellCheck,
"entwick lung".toLowerCase(),
"entwicklung".toLowerCase(),
2);
assertTypoEdAndCorrected(symSpellCheck,
"nömlich".toLowerCase(),
"nämlich".toLowerCase(),
2, 1);
assertTypoEdAndCorrected(qwertzSymSpellCheck,
"nömlich".toLowerCase(),
"nämlich".toLowerCase(),
2, 0.10);
}
public static void assertTypoAndCorrected(SymSpellCheck spellCheck, String typo, String correct,
double maxEd) throws SpellCheckException {
List<SuggestionItem> suggestionItems = spellCheck
.lookupCompound(typo.toLowerCase().trim(), maxEd);
Assert.assertTrue(suggestionItems.size() > 0);
Assert.assertEquals(correct.toLowerCase().trim(), suggestionItems.get(0).getTerm().trim());
}
public static void assertTypoEdAndCorrected(SymSpellCheck spellCheck, String typo, String correct,
double maxEd, double expED) throws SpellCheckException {
List<SuggestionItem> suggestionItems = spellCheck
.lookupCompound(typo.toLowerCase().trim(), maxEd);
Assert.assertTrue(suggestionItems.size() > 0);
Assert.assertEquals(correct.toLowerCase().trim(), suggestionItems.get(0).getTerm().trim());
Assert.assertEquals(suggestionItems.get(0).getDistance(), expED, 0.12);
}
}
| 40.545455 | 100 | 0.758663 |
042970cd4449733d9ecbf13ef71f9dac5491f29d | 2,897 | package com.sciatta.java.example.collection;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by yangxiaoyu on 2019-04-19<br>
* All Rights Reserved(C) 2017 - 2019 SCIATTA<br><p/>
* SetTests
*/
public class SetTests {
@Test
public void testHashSet() {
Collection<String> src = Arrays.asList("h", "e", "l", "l", "o");
// 无序,去重
Set<String> c = new HashSet<>(src);
assertEquals(4, c.size());
assertEquals(new HashSet<>(Arrays.asList("h", "e", "l", "o")), c);
}
@Test
public void testSetOperation() {
Set<Integer> c1;
Set<Integer> c2;
// 并集union,两个集合中的全部元素
c1 = new HashSet<>(Arrays.asList(1, 2, 5, 7, 6));
c2 = new HashSet<>(Arrays.asList(3, 5, 1, 4, 9));
c1.addAll(c2);
assertEquals(new HashSet<>(Arrays.asList(1, 2, 5, 7, 6, 3, 4, 9)), c1);
// 交集intersect,两个集合的公共元素
c1 = new HashSet<>(Arrays.asList(1, 2, 5, 7, 6));
c2 = new HashSet<>(Arrays.asList(3, 5, 1, 4, 9));
c1.retainAll(c2);
assertEquals(new HashSet<>(Arrays.asList(1, 5)), c1);
// 差集difference,集合c1相对于c2的差集,即元素在c1中,不在c2中
c1 = new HashSet<>(Arrays.asList(1, 2, 5, 7, 6));
c2 = new HashSet<>(Arrays.asList(3, 5, 1, 4, 9));
c1.removeAll(c2);
assertEquals(new HashSet<>(Arrays.asList(2, 7, 6)), c1);
// 对称差集symmetricDiff,集合c1和c2的并集,减去集合c1和c2的交集
c1 = new HashSet<>(Arrays.asList(1, 2, 5, 7, 6));
c2 = new HashSet<>(Arrays.asList(3, 5, 1, 4, 9));
Set<Integer> symmetricDiff = new HashSet<>(c1);
symmetricDiff.addAll(c2);
Set<Integer> temp = new HashSet<>(c1);
temp.retainAll(c2);
symmetricDiff.removeAll(temp);
assertEquals(new HashSet<>(Arrays.asList(2, 7, 6, 3, 4, 9)), symmetricDiff);
}
@Test
public void testToArray() {
Set<Integer> c1;
c1 = new HashSet<>(Collections.singletonList(1000));
Integer data = c1.iterator().next();
// 返回的是一个新数组,集合不负责维护这个数组。
Object[] os = c1.toArray();
Object test = os[0];
// 数组中的元素和集合中的元素相同。
assertEquals(data, test);
// 可以自由修改数组,而不影响原集合
os[0] = null;
assertEquals(1000, (int) c1.iterator().next());
}
@Test
public void testEnumSet() {
EnumSet<Color> colors = EnumSet.noneOf(Color.class);
assertEquals(0, colors.size());
colors.add(Color.RED);
assertEquals(1, colors.size());
colors = EnumSet.allOf(Color.class);
assertEquals(3, colors.size());
assertTrue(colors.contains(Color.BLUE));
assertTrue(colors.contains(Color.RED));
assertTrue(colors.contains(Color.GREEN));
}
enum Color {
RED,
GREEN,
BLUE
}
}
| 28.97 | 84 | 0.571626 |
125c28bf4c0bb84a679ee2c8af385f98d4d2eb0b | 1,366 | package frc.robot.autonomous.commands;
import com.ctre.phoenix.motorcontrol.ControlMode;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.vision.Limelight;
import frc.robot.subsystems.Shooter;
import frc.robot.subsystems.Drivebase;
public class DriveToGoal extends CommandBase {
private Drivebase m_drive;
private Shooter m_shooter;
private Limelight m_limelight;
private double targetDist;
private double kPDist = 0.1;
public DriveToGoal(Drivebase drive, Shooter shooter, Limelight limelight, double targetDist) {
m_drive = drive;
m_limelight = limelight;
this.targetDist = targetDist;
addRequirements(drive, limelight);
}
@Override
public void initialize() {
}
@Override
public void execute() {
double distError = targetDist - m_shooter.getDistToTarget(m_limelight.getDegVerticalToTarget());
double driveCorrect = kPDist * distError;
double leftPow =+ driveCorrect;
double rightPow =+ driveCorrect;
m_drive.getLeftMaster().set(ControlMode.PercentOutput, leftPow);
m_drive.getRightMaster().set(ControlMode.PercentOutput, rightPow);
}
@Override
public void end(boolean interrupted) {
m_drive.stop();
}
@Override
public boolean isFinished() {
return false;
}
} | 24.836364 | 104 | 0.698389 |
892a5aca34b20206ca700697ae62c864845c868d | 139 | package br.ufmg.dcc.labsoft.interfaces;
public interface Interface1Renamed {
public void process();
public void save(String code);
}
| 15.444444 | 39 | 0.76259 |
383399ad30cf034f25691ea28589da52137aaf83 | 7,787 | /*
* [New BSD License]
* Copyright (c) 2011-2012, Brackit Project Team <info@brackit.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Brackit Project Team nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.brackit.xquery.util.path;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.brackit.xquery.atomic.QNm;
import org.junit.Test;
/**
*
* @author Sebastian Baechle, Max Bechtold
*
*/
public class PathTest {
@Test
public void testSimplePath() throws Exception {
Path<QNm> expected = (new Path<QNm>()).child(new QNm("tag"));
Path<QNm> parsed = (new PathParser(expected.toString())).parse();
assertEquals("Path parsed correctly", expected, parsed);
}
@Test
public void testSimplePath2() throws Exception {
Path<QNm> expected = (new Path<QNm>()).child(new QNm("tag"))
.child(new QNm("hallo")).descendant(new QNm("aha"));
Path<QNm> parsed = (new PathParser(expected.toString())).parse();
assertEquals("Path parsed correctly", expected, parsed);
}
@Test
public void testSimplePath3() throws Exception {
Path<QNm> expected = (new Path<QNm>()).self().child(new QNm("tag"))
.child(new QNm("hallo")).descendant(new QNm("aha"));
Path<QNm> parsed = (new PathParser(expected.toString())).parse();
assertEquals("Path parsed correctly", expected, parsed);
}
@Test
public void testSimplePath4() throws Exception {
Path<QNm> expected = (new Path<QNm>()).self().child(new QNm("tag"))
.child(new QNm("hallo")).descendant(new QNm("aha"));
String implicitSelfPath = expected.toString().substring(2);
Path<QNm> parsed = (new PathParser(implicitSelfPath)).parse();
assertEquals("Path parsed correctly", expected, parsed);
}
@Test
public void testSelfPath4() throws Exception {
Path<QNm> expected = (new Path<QNm>()).self().self().descendant(
new QNm("aha"));
Path<QNm> parsed = (new PathParser(expected.toString())).parse();
assertEquals("Path parsed correctly", expected, parsed);
}
@Test
public void testQualifiedPath() throws Exception {
Path<QNm> expected = (new Path<QNm>()).child(new QNm(null, "foo", "tag"));
Path<QNm> parsed = (new PathParser(expected.toString())).parse();
assertEquals("Path parsed correctly", expected, parsed);
}
@Test
public void testQualifiedPathPreamble() throws Exception {
Path<QNm> expected = (new Path<QNm>()).child(
new QNm("http://brackit.org/ns/bit", "bit", "tag"));
String path = "namespace foo = 'localhost'; " +
"namespace bit = 'http://brackit.org/ns/bit'; " + expected.toString();
Path<QNm> parsed = (new PathParser(path)).parse();
assertEquals("Path parsed correctly", expected, parsed);
}
@Test
public void testQualifiedPathMalformedPreamble() throws Exception {
Path<QNm> expected = (new Path<QNm>()).child(
new QNm("http://brackit.org/ns/bit", "bit", "tag"));
String path = "namespace foo = 'localhost'" + expected.toString();
try {
Path<QNm> parsed = (new PathParser(path)).parse();
assertTrue("Malformed preamble recognized", false);
} catch (PathException e) {
}
}
@Test
public void testQualifiedPathUndefinedPrefix() throws Exception {
Path<QNm> expected = (new Path<QNm>()).child(
new QNm("http://brackit.org/ns/bit", "xzibit", "tag"));
String path = "namespace foo = 'localhost'; " + expected.toString();
try {
Path<QNm> parsed = (new PathParser(path)).parse();
assertTrue("Missing namespace declaration recognized", false);
} catch (PathException e) {
}
}
@Test
public void testFilePath() throws Exception {
Path<QNm> parsed = (new PathParser("/test.xml")).parse();
assertEquals("Path parsed correctly", new Path<QNm>()
.child(new QNm("test.xml")), parsed);
}
@Test
public void testFile2Path() throws Exception {
Path<QNm> parsed = (new PathParser("_test.xml")).parse();
assertEquals("Path parsed correctly", new Path<QNm>().self().child(
new QNm("_test.xml")), parsed);
}
@Test
public void testFilePath2() throws Exception {
Path<QNm> parsed = (new PathParser("../conf.d//test.xml")).parse();
assertEquals("Path parsed correctly", new Path<QNm>().parent()
.child(new QNm("conf.d")).descendant(new QNm("test.xml")), parsed);
}
@Test
public void testInvalidPath1() throws Exception {
try {
Path<QNm> parsed = (new PathParser("/a/..b/c")).parse();
fail("Parser accepted invalid input");
} catch (PathException e) {
// expected
}
}
@Test
public void testMatchWithBacktracking() throws Exception {
Path<QNm> pattern = (new PathParser("//a/b//c")).parse();
Path<QNm> path = (new PathParser("/e/a/b/b/f/b/e/c")).parse();
assertTrue("Pattern matches path", pattern.matches(path));
}
@Test
public void testMatchWithDoubleTwoStagedBacktracking() throws Exception {
Path<QNm> pattern = (new PathParser("//a/b/c//d")).parse();
Path<QNm> path = (new PathParser("/a/b/c/a/b/b/c/f/b/c/e/d"))
.parse();
assertTrue("Pattern does match path", pattern.matches(path));
}
@Test
public void testNoMatchWithBacktrackingButNoDescendantStartAxis()
throws Exception {
Path<QNm> pattern = (new PathParser("/a/b//c")).parse();
Path<QNm> path = (new PathParser("/e/a/b/b/f/b/e/c")).parse();
assertFalse("Pattern matches path", pattern.matches(path));
}
@Test
public void testNoMatchWithDoubleTwoStagedBacktracking() throws Exception {
Path<QNm> pattern = (new PathParser("//a/b/c//d")).parse();
Path<QNm> path = (new PathParser("/a/b/b/c/f/b/c/e/d")).parse();
assertFalse("Pattern does not match path", pattern.matches(path));
}
@Test
public void testNoMatchWithDoubleTwoStagedBacktrackingButNoDescendantStartAxis()
throws Exception {
Path<QNm> pattern = (new PathParser("/a/b/c//d")).parse();
Path<QNm> path = (new PathParser("/e/a/b/c/a/b/b/c/f/b/c/e/d"))
.parse();
assertFalse("Pattern does match path", pattern.matches(path));
}
@Test
public void testMatch() throws Exception {
Path<QNm> pattern = (new PathParser("//c")).parse();
Path<QNm> path = (new PathParser("//a/b/c")).parse();
assertTrue("Pattern does match path", pattern.matches(path));
}
@Test
public void testVerySimplePath() throws Exception {
Path<QNm> parsed = (new PathParser("l")).parse();
assertFalse(parsed.isEmpty());
}
}
| 37.4375 | 83 | 0.696802 |
ec6753c399120fdf1654fb1648a723c2ce4be9e2 | 7,620 | package com.moome;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MoomeServerConnector implements Runnable {
public static final int DEFAULT_PORT = 29798;
public static final String MINOR_SEP = "#l";
public static final String MAJOR_SEP = "#v";
public String ip = "localhost";
public int port = 29798;
public String name = System.getProperty("user.name");
public Socket socket = null;
public String token = "";
private BufferedReader in = null;
private PrintWriter out = null;
private MoomeServerEventListener listener = new MoomeServerEventListener(){@Override public void onDisconnect(String reason) {}@Override public void onConnect() {}};
public String csrf = "";
public MoomeServerConnector(String ip, int port, String name) {
this.ip = ip;
this.port = port;
this.name = name;
}
public void connect() throws MoomeServerException {
try {
this.socket = new Socket(this.ip, this.port);
} catch (IOException e) {
System.out.println(this.ip + ", " + this.port);
e.printStackTrace();
throw new MoomeServerException();
}
Thread t = new Thread(this);
t.start();
}
public void disconnect() {
this.build(1, "token=" + this.token); // No need to specify reason, the server knows the protocol.
this.running = false;
try {
this.socket.close();
} catch (IOException e) {
System.out.println("[ERROR]: IOException, failed to close port.");
e.printStackTrace();
}
}
public List<MoomeServerUser> usrdata = new ArrayList<>();
public boolean running = false;
public String version = "";
public boolean versionCompatable(String version) {
String[] split = version.split("\\.");
String[] split2 = this.version.split("\\.");
if(split[0].equals(split2[0]) && split[1].equals(split2[1]))
return true;
return false;
}
@Override
public void run() {
this.running = true;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
// Get token from server
this.build(3, "");
// Get motd from server
this.build(5, "");
while(running) {
String input = "";
try {
input = in.readLine();
} catch(Exception e) {
System.out.println("[ERROR]: Server closed.");
running = false;
try {
this.socket.close();
} catch (IOException e1) {
System.out.println("[ERROR]: IOException, failed to close port.");
}
ScreenManager.setScreen(1);
return;
}
final int index = input.indexOf('/');
final String type = input.substring(0, index); // ADD - 1 IF BUG!
final List<String> keys = new ArrayList<>();
final HashMap<String, String> pairZ = new HashMap<String, String>();
final String dataSplit = input.substring(index + 1); // The data without the type specs
final String[] pairs = dataSplit.split("#l");
for (final String pair : pairs) {
try {
final String[] split = pair.split("=");
keys.add(split[0].toLowerCase());
pairZ.put(split[0].toLowerCase(), split[1]);
} catch (final Exception e) {
System.out.println(pair);
}
}
// logic
switch(type) {
case "1":
this.getListener().onDisconnect(pairZ.get("reason")+ "");
this.running = false;
try {
this.socket.close();
} catch (IOException e) {
System.out.println("[ERROR]: IOException, failed to close port.");
e.printStackTrace();
}
break;
case "3":
this.token = pairZ.get("token");
this.csrf = pairZ.get("csrf");
System.out.println("[TOKEN]: " + token);
System.out.println("[CSRF]: " + csrf);
this.getListener().onConnect();
break;
case "0":
final List<MoomeServerUser> list = new ArrayList<>();
final String[] users = dataSplit.split("#v");
for(final String user : users) {
final String[] data = user.split("#l");
final MoomeServerUser u = new MoomeServerUser();
System.out.println(input);
for(final String s : data) {
final String[] ss = s.split("=");
switch(ss[0]) {
case "name":
u.name = ss[1];
break;
case "x":
u.x = ss[1];
break;
case "y":
u.y = ss[1];
break;
case "world":
u.world = ss[1];
break;
case "visible":
u.visible = ss[1];
break;
case "looks":
u.looks = ss[1];
break;
case "csrf":
u.csrf = ss[1];
break;
}
}
list.add(u);
}
this.usrdata = list;
System.out.println("Length: " + usrdata.size());
break;
case "5":
this.version = pairZ.get("version");
System.out.println("[MOTD FOUND]: Version is " + pairZ.get("version") + ", port is " + pairZ.get("port"));
break;
}
}
}
public void updateData() {
this.build(0, "token=" + this.token);
}
public void updateCoords(final int x, final int y, final int look) { // TODO: Make escape(name) a constant-- LAG UPDATE!
this.build(2, "name=" + escape(this.name) + "#llooks=" + look + "#lx=" + x + "#ly=" + y + "#ltoken=" + this.token);
}
private void build(final int type, final String args) {
if(out != null) {
out.println(type + "/" + args); // MUST stip special characters before running this function with escape(params...)
out.flush();
}
}
public static String escape(final String message) {
return message.replaceAll("#v", "v").replaceAll("#l", "l").replaceAll("=", "~");
}
public MoomeServerEventListener getListener() {
return this.listener;
}
public void setListener(MoomeServerEventListener listener) {
this.listener = listener;
}
}
| 36.285714 | 169 | 0.477953 |
4b96639de3bc538d5b9ff04ce4d230153e148055 | 357 | package com.example.recipes.user;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "User already exist")
public class UserAlreadyExistsException extends RuntimeException {
public UserAlreadyExistsException() {
super();
}
}
| 27.461538 | 78 | 0.784314 |
79e930bb403e0751bae501c4235148f8e172a599 | 4,015 | /**
*/
package org.sheepy.lily.vulkan.extra.model.nuklear.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.sheepy.lily.vulkan.extra.model.nuklear.FontImageProvider;
import org.sheepy.lily.vulkan.extra.model.nuklear.NuklearFont;
import org.sheepy.lily.vulkan.extra.model.nuklear.NuklearPackage;
import org.sheepy.lily.vulkan.model.vulkanresource.impl.ImageDataProviderImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Font Image Provider</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.sheepy.lily.vulkan.extra.model.nuklear.impl.FontImageProviderImpl#getNuklearFont <em>Nuklear Font</em>}</li>
* </ul>
*
* @generated
*/
public class FontImageProviderImpl extends ImageDataProviderImpl implements FontImageProvider
{
/**
* The cached value of the '{@link #getNuklearFont() <em>Nuklear Font</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNuklearFont()
* @generated
* @ordered
*/
protected NuklearFont nuklearFont;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected FontImageProviderImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return NuklearPackage.Literals.FONT_IMAGE_PROVIDER;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NuklearFont getNuklearFont()
{
if (nuklearFont != null && ((EObject)nuklearFont).eIsProxy())
{
InternalEObject oldNuklearFont = nuklearFont;
nuklearFont = (NuklearFont)eResolveProxy(oldNuklearFont);
if (nuklearFont != oldNuklearFont)
{
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, NuklearPackage.FONT_IMAGE_PROVIDER__NUKLEAR_FONT, oldNuklearFont, nuklearFont));
}
}
return nuklearFont;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NuklearFont basicGetNuklearFont()
{
return nuklearFont;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setNuklearFont(NuklearFont newNuklearFont)
{
NuklearFont oldNuklearFont = nuklearFont;
nuklearFont = newNuklearFont;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, NuklearPackage.FONT_IMAGE_PROVIDER__NUKLEAR_FONT, oldNuklearFont, nuklearFont));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case NuklearPackage.FONT_IMAGE_PROVIDER__NUKLEAR_FONT:
if (resolve) return getNuklearFont();
return basicGetNuklearFont();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case NuklearPackage.FONT_IMAGE_PROVIDER__NUKLEAR_FONT:
setNuklearFont((NuklearFont)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case NuklearPackage.FONT_IMAGE_PROVIDER__NUKLEAR_FONT:
setNuklearFont((NuklearFont)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case NuklearPackage.FONT_IMAGE_PROVIDER__NUKLEAR_FONT:
return nuklearFont != null;
}
return super.eIsSet(featureID);
}
} //FontImageProviderImpl
| 22.942857 | 143 | 0.680199 |
646fb8d6031376494144a0194b66b1c9a0ba475f | 3,478 | package controllers;
import com.avaje.ebean.Ebean;
import models.match.Match;
import models.tournament.MatchDay;
import models.tournament.Tournament;
import play.data.Form;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import java.util.List;
public class MatchDaysAPI extends Controller {
public Result get(Long tid, Integer n) {
final MatchDay matchday = findMatchDay(tid, n);
if (matchday == null) return badRequest();
else return ok(Json.toJson(matchday));
}
public Result list(Long tid) {
final List<MatchDay> matchdays = Ebean.find(MatchDay.class).where().eq("tournament_id", tid).findList();
if (matchdays == null || matchdays.isEmpty()) return badRequest();
else return ok(Json.toJson(matchdays));
}
public Result post(Long tid) {
final Tournament tournament = Ebean.find(Tournament.class, tid);
if (tournament == null) return notFound();
final Form<MatchDay> form = Form.form(MatchDay.class).bindFromRequest();
if (form.hasErrors()) {
return badRequest(form.errorsAsJson());
} else {
final MatchDay matchDay = form.get();
tournament.getMatchDays().add(matchDay);
tournament.update();
matchDay.save();
return ok(Json.toJson(matchDay));
}
}
public Result put(Long tid, Integer n) {
final MatchDay matchDay = findMatchDay(tid, n);
final Form<MatchDay> form = Form.form(MatchDay.class).bindFromRequest();
if (form.hasErrors()) return badRequest(form.errorsAsJson());
if (matchDay == null) return notFound();
else {
matchDay.setNumber(form.get().getNumber());
matchDay.update();
return ok(Json.toJson(matchDay));
}
}
private MatchDay findMatchDay(Long tid, Integer n) {
return Ebean.find(MatchDay.class).where().eq("tournament_id", tid).eq("number", n).findUnique();
}
public Result putMatch(Long tid, Integer n) {
final Form<Match> form = Form.form(Match.class).bindFromRequest();
final MatchDay matchday = findMatchDay(tid, n);
if (form.hasErrors()) return badRequest(form.errorsAsJson());
else {
final Match match = form.get();
matchday.getMatchList().add(match);
matchday.update();
match.save();
return ok(Json.toJson(match));
}
}
public Result getMatches(Long tid, Integer n) {
final MatchDay matchday = Ebean.find(MatchDay.class)
.select("matchList")
.where()
.eq("tournament_id", tid)
.eq("number", n)
.findUnique();
return ok(Json.toJson(matchday.getMatchList()));
}
public Result delete(Long tid, Integer n) {
try {
final MatchDay matchday = findMatchDay(tid, n);
if (matchday == null) return badRequest();
else {
final List<Match> matchList = matchday.getMatchList();
if (matchList != null) {
for (Match match : matchList) {
match.delete();
}
}
matchday.delete();
return ok();
}
} catch (Exception e) {
e.printStackTrace();
return badRequest(e.getMessage());
}
}
}
| 34.098039 | 112 | 0.577343 |
ad98c711796ef7cddbfe63798660c0e538555642 | 2,148 | /*
* (C) Copyright 2006-2014 Nuxeo SA (http://nuxeo.com/) and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* Florent Guillaume
*/
package org.nuxeo.ecm.core.opencmis.impl;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.RecoverableClientException;
import org.nuxeo.ecm.core.event.Event;
import org.nuxeo.ecm.core.event.EventListener;
import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
/**
* Throws an exception after creating a doc to test rollback behavior.
*/
public class ThrowExceptionListener implements EventListener {
public static final String CRASHME_NAME = "CRASHME";
public static final String AFTERCRASH_NAME = "AFTERCRASH";
@Override
public void handleEvent(Event event) {
DocumentEventContext ctx = (DocumentEventContext) event.getContext();
DocumentModel doc = ctx.getSourceDocument();
if (CRASHME_NAME.equals(doc.getName())) {
// create another doc so that we can check it'll be rolled back correctly
CoreSession session = doc.getCoreSession();
DocumentModel doc2 = session.createDocumentModel("/", AFTERCRASH_NAME, "File");
doc2 = session.createDocument(doc2);
session.save();
// now throw an exception
// make sure it's not swallowed by EventServiceImpl
event.markBubbleException();
// RecoverableClientException to avoid ERROR logging in EventServiceImpl
throw new RecoverableClientException("error", "error", null);
}
}
}
| 38.357143 | 91 | 0.707635 |
b20dc0ebeb4ee51e36c87da72ce785b666a418c6 | 1,828 | /**
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.mr4c.message;
import org.junit.*;
import static org.junit.Assert.*;
public class MessageTest {
private Message m_msg1a;
private Message m_msg1b;
private Message m_msg2; // different topic
private Message m_msg3; // different content
private Message m_msg4; // different content type
@Before public void setUp() {
m_msg1a = buildMessage1();
m_msg1b = buildMessage1();
m_msg2 = buildMessage2();
m_msg3 = buildMessage3();
m_msg4 = buildMessage4();
}
@Test public void testEquals() {
assertEquals(m_msg1a, m_msg1b);
}
@Test public void testNotEqualTopic() {
assertFalse(m_msg1a.equals(m_msg2));
}
@Test public void testNotEqualContent() {
assertFalse(m_msg1a.equals(m_msg3));
}
@Test public void testNotEqualContentType() {
assertFalse(m_msg1a.equals(m_msg4));
}
private Message buildMessage1() {
return new Message("topic1", "content1", "type1");
}
private Message buildMessage2() {
return new Message("topic2", "content1", "type1");
}
private Message buildMessage3() {
return new Message("topic1", "content2", "type1");
}
private Message buildMessage4() {
return new Message("topic1", "content1", "type2");
}
}
| 25.041096 | 76 | 0.712801 |
6b4e4d601b604d361db005fcd7499c96542c7bb8 | 568 | package com.android.internal.util;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
/**
* Hidden API Stub of class com.android.internal.util.XmlUtils.
* @author canyie
*/
public final class XmlUtils {
private XmlUtils() {
}
public static final HashMap<String, ?> readMapXml(InputStream in) throws XmlPullParserException, IOException {
throw new IllegalStateException("Hidden API Stub called: com.android.internal.util.XmlUtils#readMapXml(InputStream)");
}
}
| 27.047619 | 126 | 0.753521 |
2dce14e6a20b8052e7f9f8e4566810d50ac0f3e7 | 2,251 | package ru.job4j.tracker;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
/**
* TrackerSQLTest.
* @author Vovk Alexander (vovk.ag747@gmail.com)
* @version $Id$
* @since 0.1
*/
public class TrackerSQLTest {
private TrackerSQL sql;
@Before
public void setUp() throws SQLException {
sql = new TrackerSQL(ConnectionRollback.create(this.init()));
}
public Connection init() {
try (InputStream in = TrackerSQL.class.getClassLoader().getResourceAsStream("app.properties")) {
Properties config = new Properties();
config.load(in);
Class.forName(config.getProperty("driver-class-name"));
return DriverManager.getConnection(
config.getProperty("url"),
config.getProperty("username"),
config.getProperty("password")
);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
@Test
public void checkAdd() throws SQLException {
Item item = new Item("test1", "testDescription", 123L);
sql.add(item);
assertThat(sql.findByName("test1").size(), is(3));
}
@Test
public void checkReplace() {
Item newItem = new Item("test2", "testDescription2", 125L);
assertThat(sql.replace("2", newItem), is(true));
}
@Test
public void checkDelete() {
assertThat(sql.delete("2"), is(true));
}
@Test
public void checkFindAll() {
Item item = new Item("test3", "testDescription3", 123456L);
Item newItem = new Item("test4", "testDescription4", 125567L);
sql.add(item);
sql.add(newItem);
assertThat(sql.findAll().size(), is(6));
}
@Test
public void checkFindByName() {
assertThat(sql.findByName("test3").get(0).getId(), is("12"));
}
@Test
public void checkFindById() {
assertThat(sql.findById("12").getName(), is("test3"));
}
} | 30.835616 | 104 | 0.618836 |
145b17c579fcbfc5b1501651df40dbbd5fa1d16d | 13,532 | package au.com.crypto;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Iterator;
import java.util.zip.GZIPInputStream;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.bcpg.CompressionAlgorithmTags;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPEncryptedData;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataList;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPOnePassSignatureList;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory;
import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator;
import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator;
import org.bouncycastle.util.io.Streams;
/**
* A simple utility class that encrypts/decrypts public key based
* encryption files.
* <p>
* To encrypt a file: KeyBasedFileProcessor -e [-a|-ai] fileName publicKeyFile.<br>
* If -a is specified the output file will be "ascii-armored".
* If -i is specified the output file will be have integrity checking added.
* <p>
* To decrypt: KeyBasedFileProcessor -d fileName secretKeyFile passPhrase.
* <p>
* Note 1: this example will silently overwrite files, nor does it pay any attention to
* the specification of "_CONSOLE" in the filename. It also expects that a single pass phrase
* will have been used.
* <p>
* Note 2: if an empty file name has been specified in the literal data object contained in the
* encrypted packet a file with the name filename.out will be generated in the current working directory.
*/
public class KeyBasedFileProcessor {
static {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
public static void decryptFile(
String inputFileName,
String keyFileName,
char[] passwd,
String defaultFileName)
throws IOException, NoSuchProviderException {
InputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
InputStream keyIn = new BufferedInputStream(new FileInputStream(keyFileName));
decryptFile(in, keyIn, passwd, defaultFileName);
keyIn.close();
in.close();
}
public static void decryptGzipFile(
String inputFileName,
String keyFileName,
char[] passwd,
String defaultFileName)
throws IOException, NoSuchProviderException {
InputStream in = new GZIPInputStream(new FileInputStream(inputFileName));
InputStream keyIn = new BufferedInputStream(new FileInputStream(keyFileName));
decryptFile(in, keyIn, passwd, defaultFileName);
keyIn.close();
in.close();
}
/**
* decrypt the passed in message stream
*/
public static void decryptFile(
InputStream in,
InputStream keyIn,
char[] passwd,
String defaultFileName)
throws IOException, NoSuchProviderException {
in = PGPUtil.getDecoderStream(in);
try {
JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(in);
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
//
// the first object might be a PGP marker packet.
//
if (o instanceof PGPEncryptedDataList) {
enc = (PGPEncryptedDataList) o;
} else {
enc = (PGPEncryptedDataList) pgpF.nextObject();
}
//
// find the secret key
//
Iterator it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator());
while (sKey == null && it.hasNext()) {
pbe = (PGPPublicKeyEncryptedData) it.next();
sKey = PGPCryptoUtil.findSecretKey(pgpSec, pbe.getKeyID(), passwd);
}
if (sKey == null) {
throw new IllegalArgumentException("secret key for message not found.");
}
InputStream clear =
pbe.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey));
JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear);
Object message = plainFact.nextObject();
if (message instanceof PGPCompressedData) {
PGPCompressedData cData = (PGPCompressedData) message;
JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
message = pgpFact.nextObject();
}
if (message instanceof PGPLiteralData) {
PGPLiteralData ld = (PGPLiteralData) message;
String outFileName = ld.getFileName();
if (outFileName.length() == 0) {
outFileName = defaultFileName;
}
InputStream unc = ld.getInputStream();
OutputStream fOut = new BufferedOutputStream(new FileOutputStream(defaultFileName));
Streams.pipeAll(unc, fOut);
fOut.close();
} else if (message instanceof PGPOnePassSignatureList) {
throw new PGPException("encrypted message contains a signed message - not literal data.");
} else {
throw new PGPException("message is not a simple encrypted file - type unknown.");
}
if (pbe.isIntegrityProtected()) {
if (!pbe.verify()) {
System.err.println("message failed integrity check");
} else {
System.err.println("message integrity check passed");
}
} else {
System.err.println("no message integrity check");
}
} catch (PGPException e) {
System.err.println(e);
if (e.getUnderlyingException() != null) {
e.getUnderlyingException().printStackTrace();
}
}
}
/**
* decrypt the passed in message stream
*/
public static InputStream decryptFile(
InputStream in,
InputStream keyIn,
char[] passwd)
throws IOException, NoSuchProviderException {
in = PGPUtil.getDecoderStream(in);
InputStream unc = null;
try {
JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(in);
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
//
// the first object might be a PGP marker packet.
//
if (o instanceof PGPEncryptedDataList) {
enc = (PGPEncryptedDataList) o;
} else {
enc = (PGPEncryptedDataList) pgpF.nextObject();
}
//
// find the secret key
//
Iterator it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator());
while (sKey == null && it.hasNext()) {
pbe = (PGPPublicKeyEncryptedData) it.next();
sKey = PGPCryptoUtil.findSecretKey(pgpSec, pbe.getKeyID(), passwd);
}
if (sKey == null) {
throw new IllegalArgumentException("secret key for message not found.");
}
InputStream clear =
pbe.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey));
JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear);
Object message = plainFact.nextObject();
if (message instanceof PGPCompressedData) {
PGPCompressedData cData = (PGPCompressedData) message;
JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
message = pgpFact.nextObject();
}
if (message instanceof PGPLiteralData) {
PGPLiteralData ld = (PGPLiteralData) message;
// String outFileName = ld.getFileName();
// if (outFileName.length() == 0) {
// outFileName = defaultFileName;
// }
unc = ld.getInputStream();
// OutputStream fOut = new BufferedOutputStream(new FileOutputStream(defaultFileName));
// Streams.pipeAll(unc, fOut);
//
// fOut.close();
} else if (message instanceof PGPOnePassSignatureList) {
throw new PGPException("encrypted message contains a signed message - not literal data.");
} else {
throw new PGPException("message is not a simple encrypted file - type unknown.");
}
// if (pbe.isIntegrityProtected()) {
// if (!pbe.verify()) {
// System.err.println("message failed integrity check");
// } else {
// System.err.println("message integrity check passed");
// }
// } else {
// System.err.println("no message integrity check");
// }
} catch (PGPException e) {
System.err.println(e);
if (e.getUnderlyingException() != null) {
e.getUnderlyingException().printStackTrace();
}
}
return unc;
}
public static void encryptFile(
String outputFileName,
String inputFileName,
String encKeyFileName,
boolean armor,
boolean withIntegrityCheck)
throws IOException, NoSuchProviderException, PGPException {
OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFileName));
PGPPublicKey encKey = PGPCryptoUtil.readPublicKey(encKeyFileName);
encryptFile(out, inputFileName, encKey, armor, withIntegrityCheck);
out.close();
}
private static void encryptFile(
OutputStream out,
String fileName,
PGPPublicKey encKey,
boolean armor,
boolean withIntegrityCheck)
throws IOException, NoSuchProviderException {
if (armor) {
out = new ArmoredOutputStream(out);
}
try {
byte[] bytes = PGPCryptoUtil.compressFile(fileName, CompressionAlgorithmTags.ZIP);
PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5).setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom()).setProvider("BC"));
encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider("BC"));
OutputStream cOut = encGen.open(out, bytes.length);
cOut.write(bytes);
cOut.close();
if (armor) {
out.close();
}
} catch (PGPException e) {
System.err.println(e);
if (e.getUnderlyingException() != null) {
e.getUnderlyingException().printStackTrace();
}
}
}
public static void main(
String[] args)
throws Exception {
Security.addProvider(new BouncyCastleProvider());
if (args.length == 0) {
System.err.println("usage: KeyBasedFileProcessor -e|-d [-a|ai] file [secretKeyFile passPhrase|pubKeyFile]");
return;
}
if (args[0].equals("-e")) {
if (args[1].equals("-a") || args[1].equals("-ai") || args[1].equals("-ia")) {
encryptFile(args[2] + ".asc", args[2], args[3], true, (args[1].indexOf('i') > 0));
} else if (args[1].equals("-i")) {
encryptFile(args[2] + ".bpg", args[2], args[3], false, true);
} else {
encryptFile(args[1] + ".bpg", args[1], args[2], false, false);
}
} else if (args[0].equals("-d")) {
decryptFile(args[1], args[2], args[3].toCharArray(), new File(args[1]).getName() + ".out");
} else {
System.err.println("usage: KeyBasedFileProcessor -d|-e [-a|ai] file [secretKeyFile passPhrase|pubKeyFile]");
}
}
}
| 38.334278 | 173 | 0.610701 |
811995ba0fc78355b6ed8958a212aed86f6c1224 | 1,148 | package com.batis.application.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
@Aspect
public class WebAspect {
private final static Logger LOGGER = LoggerFactory.getLogger(WebAspect.class);
@Before("com.batis.application.aspect.point.CommonPointcuts.onWebRequest()")
public void onWebRequest(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
if (LOGGER.isInfoEnabled()) {
LOGGER.info("\n" + "Declaring Type: " + methodSignature.getDeclaringTypeName() + "\n" +
"Return Type: " + methodSignature.getReturnType().getName() + "\n" +
"Name: " + methodSignature.getName() + "\n" +
"ParamterNames: " + Arrays.toString(methodSignature.getParameterNames()) + "\n");
}
}
}
| 37.032258 | 101 | 0.692509 |
81e017b197fff8b7772597a77d62af4263768776 | 3,815 | package com.wilutions.jsfs;
/*
*
* THIS FILE HAS BEEN GENERATED BY class byps.gen.j.GenRegistry DO NOT MODIFY.
*/
import byps.*;
public class BRegistry_JSFS extends BRegistry {
public BRegistry_JSFS() {
super(BBinaryModel.MEDIUM);
}
private static BRegisteredSerializer[] serializers = new BRegisteredSerializer[] {
new BRegisteredSerializer(9906860, "com.wilutions.jsfs.BSerializer_9906860"),
new BRegisteredSerializer(145996442, "com.wilutions.jsfs.BSerializer_145996442"),
new BRegisteredSerializer(169662220, "com.wilutions.jsfs.BSerializer_169662220"),
new BRegisteredSerializer(240503306, "com.wilutions.jsfs.BSerializer_240503306"),
new BRegisteredSerializer(481066845, "com.wilutions.jsfs.BSerializer_481066845"),
new BRegisteredSerializer(544795964, "com.wilutions.jsfs.BSerializer_544795964"),
new BRegisteredSerializer(566696346, "com.wilutions.jsfs.BSerializer_566696346"),
new BRegisteredSerializer(575037953, "com.wilutions.jsfs.BSerializer_575037953"),
new BRegisteredSerializer(665368294, "com.wilutions.jsfs.BSerializer_665368294"),
new BRegisteredSerializer(706034600, "com.wilutions.jsfs.BSerializer_706034600"),
new BRegisteredSerializer(744806851, "com.wilutions.jsfs.BSerializer_744806851"),
new BRegisteredSerializer(964561591, "com.wilutions.jsfs.BSerializer_964561591"),
new BRegisteredSerializer(964561595, "com.wilutions.jsfs.BSerializer_964561595"),
new BRegisteredSerializer(964561600, "com.wilutions.jsfs.BSerializer_964561600"),
new BRegisteredSerializer(979378962, "com.wilutions.jsfs.BSerializer_979378962"),
new BRegisteredSerializer(1032737639, "com.wilutions.jsfs.BSerializer_1032737639"),
new BRegisteredSerializer(1078989294, "com.wilutions.jsfs.BSerializer_1078989294"),
new BRegisteredSerializer(1090607752, "com.wilutions.jsfs.BSerializer_1090607752"),
new BRegisteredSerializer(1092766252, "com.wilutions.jsfs.BSerializer_1092766252"),
new BRegisteredSerializer(1100528120, "com.wilutions.jsfs.BSerializer_1100528120"),
new BRegisteredSerializer(1124739608, "com.wilutions.jsfs.BSerializer_1124739608"),
new BRegisteredSerializer(1131301080, "com.wilutions.jsfs.BSerializer_1131301080"),
new BRegisteredSerializer(1153231042, "com.wilutions.jsfs.BSerializer_1153231042"),
new BRegisteredSerializer(1274131736, "com.wilutions.jsfs.BSerializer_1274131736"),
new BRegisteredSerializer(1354059712, "com.wilutions.jsfs.BSerializer_1354059712"),
new BRegisteredSerializer(1366717454, "com.wilutions.jsfs.BSerializer_1366717454"),
new BRegisteredSerializer(1374008726, "com.wilutions.jsfs.BSerializer_1374008726"),
new BRegisteredSerializer(1381128722, "com.wilutions.jsfs.BSerializer_1381128722"),
new BRegisteredSerializer(1439246415, "com.wilutions.jsfs.BSerializer_1439246415"),
new BRegisteredSerializer(1542825705, "com.wilutions.jsfs.BSerializer_1542825705"),
new BRegisteredSerializer(1609273478, "com.wilutions.jsfs.BSerializer_1609273478"),
new BRegisteredSerializer(1733426638, "com.wilutions.jsfs.BSerializer_1733426638"),
new BRegisteredSerializer(1762179110, "com.wilutions.jsfs.BSerializer_1762179110"),
new BRegisteredSerializer(1815527676, "com.wilutions.jsfs.BSerializer_1815527676"),
new BRegisteredSerializer(1824869366, "com.wilutions.jsfs.BSerializer_1824869366"),
new BRegisteredSerializer(1833696176, "com.wilutions.jsfs.BSerializer_1833696176"),
new BRegisteredSerializer(1849102471, "com.wilutions.jsfs.BSerializer_1849102471"),
new BRegisteredSerializer(1888107655, "com.wilutions.jsfs.BSerializer_1888107655"),
new BRegisteredSerializer(1925305675, "com.wilutions.jsfs.BSerializer_1925305675"),
};
@Override
protected BRegisteredSerializer[] getSortedSerializers() {
return serializers;
}
}
| 61.532258 | 86 | 0.811533 |
5ffdc9d9c18683e1ebac8627bddc68fa6a1c52fa | 449 | package com.michaelfotiadis.shpparser.containers.ergo.geometry;
public enum ErgoShapefileGeometryType {
POINT("Point"), POLYLINE("Polyline"), POLYGON("Polygon"),
MULTI_LINE_STRING("MultiLineString"), MULTI_POLYGON("MultiPolygon");
private final String description;
private ErgoShapefileGeometryType(final String description) {
this.description = description;
}
@Override
public String toString() {
return this.description;
}
}
| 23.631579 | 69 | 0.770601 |
6650af295b2ecb01020457f02478267bfc8ca4ef | 4,726 | package com.example.gongxingheng.spider;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TextView;
import java.util.ArrayList;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
public class ContentActivity extends AppCompatActivity {
private TextView title;
private String tit;
private TextView content;
private static final int SHOW_RESPONSE = 0;
private String url="";
private Handler handler = new Handler(){
public void handleMessage(Message msg){
switch (msg.what){
case SHOW_RESPONSE:
ArrayList<String> t= (ArrayList<String>)msg.obj;
String c="";
tit = t.get(0);
title.setText(t.get(0));
for(int i =1;i<t.size();i++){
c += t.get(i)+"\n\n";
}
content.setText(c);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
Transition fade = TransitionInflater.from(this).inflateTransition(R.transition.fade);
//退出时使用
getWindow().setExitTransition(fade);
//第一次进入时使用
getWindow().setEnterTransition(fade);
//再次进入时使用
getWindow().setReenterTransition(fade);
setContentView(R.layout.activity_content);
ShareSDK.initSDK(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.content_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
title =(TextView)findViewById(R.id.title);
content = (TextView)findViewById(R.id.content);
sendRequestWithHttpURLConnection();
Intent intent = getIntent();
url = intent.getStringExtra("url");
}
@Override
public boolean onSupportNavigateUp() {
finish();
return super.onSupportNavigateUp();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.content_bar, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_share:
//TODO search
showShare();
break;
}
return super.onOptionsItemSelected(item);
}
private void sendRequestWithHttpURLConnection(){
new Thread(new Runnable() {
@Override
public void run() {
try{
MyContext c = new MyContext();
//stitle = c.getContent(url);
Message msg = Message.obtain();
msg.obj = c.getContent(url);
msg.what = SHOW_RESPONSE;
handler.sendMessage(msg);
}catch (Exception e){
Intent intent = new Intent(ContentActivity.this,ErrorActivity.class);
intent.putExtra("s","fda");
startActivity(intent);
e.printStackTrace();
}
}
}).start();
}
private void showShare() {
OnekeyShare oks = new OnekeyShare();
//关闭sso授权
oks.disableSSOWhenAuthorize();
// title标题,印象笔记、邮箱、信息、微信、人人网、QQ和QQ空间使用
oks.setTitle("东大新闻");
// titleUrl是标题的网络链接,仅在Linked-in,QQ和QQ空间使用
oks.setTitleUrl(url);
// text是分享文本,所有平台都需要这个字段
oks.setText("《"+tit+"》"+" 这篇文章不错");
//分享网络图片,新浪微博分享网络图片需要通过审核后申请高级写入接口,否则请注释掉测试新浪微博
//oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
// imagePath是图片的本地路径,Linked-In以外的平台都支持此参数
//oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
// url仅在微信(包括好友和朋友圈)中使用
oks.setUrl(url);
// comment是我对这条分享的评论,仅在人人网和QQ空间使用
//oks.setComment("我是测试评论文本");
// site是分享此内容的网站名称,仅在QQ空间使用
oks.setSite("ShareSDK");
// siteUrl是分享此内容的网站地址,仅在QQ空间使用
oks.setSiteUrl(url);
// 启动分享GUI
oks.show(this);
}
}
| 33.048951 | 93 | 0.602412 |
4e5ace040c55eb5125d21a9936813da60f4ac6ec | 2,254 |
package org.opentele.server.dgks.monitoringdataset.version1_0_1.generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ProducerOfLabResultType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ProducerOfLabResultType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Identifier" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="IdentifierCode" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ProducerOfLabResultType", propOrder = {
"identifier",
"identifierCode"
})
public class ProducerOfLabResultType {
@XmlElement(name = "Identifier", required = true)
protected String identifier;
@XmlElement(name = "IdentifierCode", required = true)
protected String identifierCode;
/**
* Gets the value of the identifier property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIdentifier() {
return identifier;
}
/**
* Sets the value of the identifier property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIdentifier(String value) {
this.identifier = value;
}
/**
* Gets the value of the identifierCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIdentifierCode() {
return identifierCode;
}
/**
* Sets the value of the identifierCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIdentifierCode(String value) {
this.identifierCode = value;
}
}
| 24.769231 | 95 | 0.617125 |
5177564cc562bde1db22015eab7b8f9f7bf341e3 | 3,585 | package mc.carlton.freerpg.serverInfo;
import mc.carlton.freerpg.FreeRPG;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class PlacedBlocksManager {
private static HashSet<Location> blocks = new HashSet<>(); //The set of all tracked blocks on the server
private static HashSet<Location> temporaryBlocks = new HashSet<>(); //Temporary blocks to be added to blocks later, but are still checked to see if tracked
private static boolean isFileMangerMakingCopy = false;
private static int copiesBeingMade = 0;
public boolean isBlockTracked(Block block) {
Location location = block.getLocation();
return isLocationTracked(location);
}
public boolean isLocationTracked(Location location) {
return blocks.contains(location) || temporaryBlocks.contains(location); //If it is in EITHER list
}
public HashSet<Location> getBlocks() {
isFileMangerMakingCopy = true; //Let all classes know a copy is being made
copiesBeingMade += 1; //Add to to total number of copies currently being made
HashSet<Location> blocksCopy = new HashSet<>(blocks);
copiesBeingMade -= 1; //Copy is made, reduce the number of total copies currently being made by one
if (copiesBeingMade <= 0) { //If there are no copies being made (It can be the case that multiple calls to getBlocksMap() were made around the same time
isFileMangerMakingCopy = false; // we can say tell all classes that no copies are being made
}
return blocksCopy;
}
public void setBlocksMap(HashSet<Location> newblocks) {
this.blocks = newblocks;
}
public void addBlock(Block block) {
Location location = block.getLocation();
addLocation(location);
}
public void addLocation(Location location) {
temporaryBlocks.add(location); //Adds the location to a temporary list (NEVER saved to file or iterated through)
if (!isFileMangerMakingCopy) { //If we are making a copy
blocks.add(location); //add the location to the main list of block
temporaryBlocks.remove(location); //Remove from the secondary list
} else { //If we're not making a copy
Plugin plugin = FreeRPG.getPlugin(FreeRPG.class);
new BukkitRunnable() { //Try again in 1 tick (0.05 s)
@Override
public void run() {
addLocation(location);
}
}.runTaskLater(plugin, 1).getTaskId();
}
}
public void removeBlock(Block block) {
Location location = block.getLocation();
removeLocation(location);
}
public void removeLocation(Location location) {
if (!isFileMangerMakingCopy) { //If we are not currently making a copy, remove the block
if (blocks.contains(location)) {
blocks.remove(location);
}
} else { //If we are currently making a copy, wait a tick to try to remove the location again
Plugin plugin = FreeRPG.getPlugin(FreeRPG.class);
new BukkitRunnable() {
@Override
public void run() {
removeLocation(location);
}
}.runTaskLater(plugin, 1).getTaskId();
}
}
}
| 40.738636 | 160 | 0.656346 |
a8b48a8aec5cb91768ae348e2a2f0475d2e44d20 | 16,098 | /**
* Copyright (c) 2009-2013, Lukas Eder, lukas.eder@gmail.com
* Christopher Deckers, chrriis@gmail.com
* All rights reserved.
*
* This software is licensed to you under the Apache License, Version 2.0
* (the "License"); You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name "jOOQ" nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.jooq.debug.console;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Dialog.ModalityType;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.font.TextAttribute;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.jooq.debug.DatabaseDescriptor;
import org.jooq.debug.Debugger;
import org.jooq.debug.console.misc.JSedRegExBuilder;
import org.jooq.debug.impl.DebuggerFactory;
/**
* @author Christopher Deckers
*/
@SuppressWarnings({"serial", "hiding"})
public class Console extends JFrame {
private Debugger debugger;
private JTabbedPane mainTabbedPane;
private EditorsPane editorsPane;
public Console(DatabaseDescriptor editorDatabaseDescriptor, boolean isShowingLoggingTab, boolean isShowingDebugger) {
debugger = DebuggerFactory.localDebugger(editorDatabaseDescriptor);
// Local debugger registration is managed by the console since it hides the debugger.
addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
debugger.close();
}
});
init(isShowingLoggingTab, isShowingDebugger);
}
public Console(final Debugger debugger, boolean isShowingLoggingTab, boolean isShowingDebugger) {
this.debugger = debugger;
// Local debugger registration is handled externally if needed (e.g.: remote client must not be registered).
init(isShowingLoggingTab, isShowingDebugger);
}
private void init(boolean isShowingLoggingTab, boolean isShowingDebugger) {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
JMenuItem regExpEditorMenuItem = new JMenuItem("Reg. Exp. Editor");
regExpEditorMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog(Console.this, "Reg. Exp Editor");
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.add(new JSedRegExBuilder("/foo/bar/gi", "axFooax\nbxfoobx"), BorderLayout.CENTER);
dialog.add(contentPane, BorderLayout.CENTER);
dialog.setSize(600, 400);
dialog.setVisible(true);
dialog.setLocationRelativeTo(Console.this);
}
});
fileMenu.add(regExpEditorMenuItem);
JMenuItem exitMenuItem = new JMenuItem("Exit");
exitMenuItem.setMnemonic('x');
exitMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
performCleanup();
} catch(Exception ex) {
ex.printStackTrace();
}
switch(getDefaultCloseOperation()) {
case HIDE_ON_CLOSE:
setVisible(false);
break;
case DISPOSE_ON_CLOSE:
dispose();
break;
case EXIT_ON_CLOSE:
System.exit(0);
break;
case DO_NOTHING_ON_CLOSE:
default:
break;
}
}
});
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
JMenuItem aboutMenuItem = new JMenuItem("About");
aboutMenuItem.setMnemonic('A');
aboutMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final JDialog aboutDialog = new JDialog(Console.this, "About jOOQ Console", ModalityType.APPLICATION_MODAL);
aboutDialog.setResizable(false);
Container contentPane = aboutDialog.getContentPane();
JTabbedPane tabbedPane = new JTabbedPane();
JPanel aboutPane = new JPanel(new GridBagLayout());
aboutPane.setOpaque(false);
aboutPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
aboutPane.add(new JLabel("jOOQ library: "), new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
aboutPane.add(new JLabel("Lukas Eder"), new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
aboutPane.add(new JLabel("jOOQ Console: "), new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 0, 0), 0, 0));
aboutPane.add(new JLabel("Christopher Deckers"), new GridBagConstraints(1, 1, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 0, 0), 0, 0));
aboutPane.add(new JLabel("License: "), new GridBagConstraints(0, 2, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 0, 0), 0, 0));
aboutPane.add(new JLabel("Apache License, Version 2.0"), new GridBagConstraints(1, 2, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 0, 0), 0, 0));
aboutPane.add(new JLabel("Web site: "), new GridBagConstraints(0, 3, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 0, 0), 0, 0));
JLabel siteLabel = new JLabel("http://www.jooq.org");
siteLabel.setForeground(Color.BLUE);
Map<TextAttribute, Object> attributeMap = new HashMap<TextAttribute, Object>();
attributeMap.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_ONE_PIXEL);
siteLabel.setFont(siteLabel.getFont().deriveFont(attributeMap));
siteLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
siteLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
try {
Desktop.getDesktop().browse(new URI("http://www.jooq.org"));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
aboutPane.add(siteLabel, new GridBagConstraints(1, 3, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 0, 0), 0, 0));
tabbedPane.addTab("About", aboutPane);
JPanel disclaimerPane = new JPanel(new BorderLayout());
disclaimerPane.setBorder(BorderFactory.createEmptyBorder(2, 5, 5, 5));
disclaimerPane.setOpaque(false);
JTextArea textArea = new JTextArea(
"This software is provided by the copyright holders and contributors \"as is\"" +
" and any express or implied warranties, including, but not limited to, the" +
" implied warranties of merchantability and fitness for a particular purpose" +
" are disclaimed. In no event shall the copyright owner or contributors be" +
" liable for any direct, indirect, incidental, special, exemplary, or" +
" consequential damages (including, but not limited to, procurement of" +
" substitute goods or services; loss of use, data, or profits; or business" +
" interruption) however caused and on any theory of liability, whether in" +
" contract, strict liability, or tort (including negligence or otherwise)" +
" arising in any way out of the use of this software, even if advised of the" +
" possibility of such damage."
);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
disclaimerPane.add(new JScrollPane(textArea));
tabbedPane.addTab("Disclaimer", disclaimerPane);
contentPane.add(tabbedPane, BorderLayout.CENTER);
JPanel southPane = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
aboutDialog.dispose();
}
});
southPane.add(okButton);
contentPane.add(southPane, BorderLayout.SOUTH);
aboutDialog.setSize(500, 400);
aboutDialog.setLocationRelativeTo(Console.this);
aboutDialog.setVisible(true);
}
});
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
mainTabbedPane = new JTabbedPane();
String title = "jOOQ Console";
// if(editorDatabaseDescriptor != null) {
// String schemaName = editorDatabaseDescriptor.getSchema().getName();
// if(schemaName != null && schemaName.length() != 0) {
// title += " - " + schemaName;
// }
// }
setTitle(title);
// TODO: use context names to have on screen selector.
String[] executionContextNames = debugger.getExecutionContextNames();
boolean isExecutionSupported = executionContextNames.length > 0;
if(isExecutionSupported) {
addEditorTab();
}
if(isShowingLoggingTab) {
addLoggerTab();
}
if(isShowingDebugger) {
addDebuggerTab();
}
contentPane.add(mainTabbedPane, BorderLayout.CENTER);
setLocationByPlatform(true);
setSize(800, 600);
addNotify();
if(isExecutionSupported) {
editorsPane.adjustDefaultFocus();
}
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
try {
performCleanup();
} catch(Exception ex) {
ex.printStackTrace();
}
}
});
setContentPane(contentPane);
}
private void performCleanup() {
if(sqlLoggerPane != null) {
sqlLoggerPane.setLogging(false);
}
if(editorsPane != null) {
editorsPane.performCleanup();
}
}
private DebuggerPane sqlDebuggerPane;
private void addDebuggerTab() {
sqlDebuggerPane = new DebuggerPane(debugger);
mainTabbedPane.addTab("Debugger", sqlDebuggerPane);
}
private LoggerPane sqlLoggerPane;
private void addLoggerTab() {
sqlLoggerPane = new LoggerPane(debugger);
mainTabbedPane.addTab("Logger", sqlLoggerPane);
}
public static void openConsole(DatabaseDescriptor databaseDescriptor, boolean isLoggingActive) {
Console sqlConsoleFrame = new Console(databaseDescriptor, true, true);
sqlConsoleFrame.setLoggingActive(isLoggingActive);
sqlConsoleFrame.setVisible(true);
}
public void setLoggingActive(boolean isLoggingActive) {
if(sqlLoggerPane != null) {
sqlLoggerPane.setLogging(isLoggingActive);
// Logger is the last tab.
mainTabbedPane.setSelectedIndex(mainTabbedPane.getTabCount() - 1);
}
}
private void addEditorTab() {
editorsPane = new EditorsPane(debugger, true);
editorsPane.setBorder(BorderFactory.createEmptyBorder(2, 5, 5, 5));
mainTabbedPane.addTab("Editor", editorsPane);
}
public static void main(String[] args) {
if(args.length < 2) {
System.out.println("Please specify IP and port of a running Server");
System.out.println("Usage: Console <ip> <port>");
return;
}
final Debugger debugger;
try {
debugger = DebuggerFactory.remoteDebugger(args[0], Integer.parseInt(args[1]));
} catch(Exception e) {
e.printStackTrace();
return;
}
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Console sqlConsoleFrame = new Console(debugger, true, true);
sqlConsoleFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
sqlConsoleFrame.setVisible(true);
}
});
}
}
| 45.603399 | 204 | 0.618027 |
493eaa2c748d4d09b16ff798190bd0f7e958ab2e | 8,151 | package com.hs.controller;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.hs.model.AlarmExcelModel;
import com.hs.request.BatchAlarmsRequest;
import com.hs.request.GetTotalChartRequest;
import com.hs.request.GetWarnListRequest;
import com.hs.response.ResultResponse;
import com.hs.response.ResultUtil;
import com.hs.service.AlarmService;
import com.hs.service.WarnService;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
* @desc: 用户管理
* @author: kpchen
* @createTime: 2019年7月20日 下午1:25:36
* @history:
* @version: v1.0
*/
@Api
@RestController
@RequestMapping("/warn")
public class WarnController {
@Autowired
private WarnService warnService;
@Autowired
private AlarmService alarmService;
/**
* @author: 报警列表
* @createTime: 2019年7月20日 下午2:53:50
* @history:
* @param httpServletRequest
* @param httpServletResponse
* @param request
* @return ResultResponse
*/
@ApiOperation(value="报警列表", notes="报警列表")
@GetMapping("getWarnList")
public ResultResponse getWarnList(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,
GetWarnListRequest request) {
return warnService.getWarnList(request);
}
/**
* @desc: 处理告警
* @author: kpchen
* @createTime: 2019年8月18日 上午11:53:56
* @history:
* @param httpServletRequest
* @param httpServletResponse
* @param id
* @return ResultResponse
*/
@GetMapping("dealAlarmById")
public ResultResponse dealAlarmById(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,Integer id) {
return warnService.dealAlarmById(id);
}
/**
* @desc: 批量删除
* @author: kpchen
* @createTime: 2019年8月18日 上午11:54:32
* @history:
* @param httpServletRequest
* @param httpServletResponse
* @param id
* @return ResultResponse
*/
@RequestMapping("batchAlarms")
public ResultResponse batchAlarms(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,
@RequestBody BatchAlarmsRequest request) {
return warnService.batchAlarms(request);
}
/**
* @desc: 获取报警名称列表
* @author: kpchen
* @createTime: 2019年8月20日 下午10:34:06
* @history:
* @param httpServletRequest
* @param httpServletResponse
* @return ResultResponse
*/
@RequestMapping("getAlarmList")
public ResultResponse getAlarmList(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) {
return warnService.getAlarmList();
}
/**
* @desc: 获取报警列表
* @author: kpchen
* @createTime: 2019年9月8日 上午11:35:01
* @history:
* @param httpServletRequest
* @param httpServletResponse
* @return ResultResponse
*/
@RequestMapping("getAlarmNameList")
public JSONObject getAlarmNameList(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) {
return warnService.getAlarmNameList();
}
/**
* @desc: 通过id查询alarm实体
* @author: kpchen
* @createTime: 2019年9月7日 下午12:23:23
* @history:
* @param httpServletRequest
* @param httpServletResponse
* @param alarmId
* @return ResultResponse
*/
@RequestMapping("getEchartsByAid")
public ResultResponse getEchartsByAid(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String alarmId) {
return warnService.getEchartsByAid(alarmId);
}
/**
* @desc: 获取当日统计数据
* @author: kpchen
* @createTime: 2019年11月24日 下午5:03:24
* @history:
* @param httpServletRequest
* @param httpServletResponse
* @param alarmId
* @return ResultResponse
*/
@RequestMapping("getTotalByAid")
public ResultResponse getTotalByAid(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String alarmId) {
return warnService.getTotalByAid(alarmId);
}
/**
* @desc: 获取综合数据
* @author: kpchen
* @createTime: 2019年9月7日 下午12:23:10
* @history:
* @param httpServletRequest
* @param httpServletResponse
* @param request
* @return ResultResponse
*/
@RequestMapping("getTotalChart")
public ResultResponse getTotalChart(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,
GetTotalChartRequest request) {
return warnService.getTotalChart(request);
}
/**
* @desc: 处理今天数据
* @author: kpchen
* @createTime: 2019年9月7日 下午12:24:54
* @history:
* @param httpServletRequest
* @param httpServletResponse
* @return ResultResponse
*/
@RequestMapping("dealWithToday")
public ResultResponse dealWithToday(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) {
alarmService.parseData();
return ResultUtil.success();
}
@RequestMapping("dealWithSomeDay")
public ResultResponse dealWithToday(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String day) {
if (StringUtils.isBlank(day)) {
return ResultUtil.error("day 参数为空");
}
return alarmService.parseDataSomeday(day);
}
/**
* @desc: 获取今天的定时任务是否有异常
* @author: kpchen
* @createTime: 2019年9月15日 下午7:09:15
* @history:
* @param httpServletRequest
* @param httpServletResponse
* @return ResultResponse
*/
@RequestMapping("getErrorLog")
public ResultResponse getErrorLog(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) {
return alarmService.getErrorLog();
}
/**
* @desc: 删除报警日志
* @author: kpchen
* @createTime: 2019年9月15日 下午7:43:32
* @history:
* @param httpServletRequest
* @param httpServletResponse
* @return ResultResponse
*/
@RequestMapping("deleteErrorLog")
public ResultResponse deleteErrorLog(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) {
return alarmService.deleteErrorLog();
}
/**
* @desc: 导出
* @author: kpchen
* @createTime: 2019年9月8日 下午3:26:01
* @history:
* @param httpServletRequest
* @param httpServletResponse
* @param request
* @throws Exception void
*/
@RequestMapping("downloadAlarm")
public void downloadAlarm(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,
GetWarnListRequest request) throws Exception {
String realPath = httpServletRequest.getServletContext().getRealPath("/");
realPath = realPath + "upload" + File.separator + "excel" + File.separator;
List<AlarmExcelModel> alarmExcelModels = warnService.getAllWarnList(request, realPath);
ExportParams params = new ExportParams("极视智能报警详情","报警详情");
Map<String, Object> data = new HashMap<String, Object>();
data.put("date", new Date());//导出一般都要日期
data.put("list", alarmExcelModels);//导出list集合
Workbook book = ExcelExportUtil.exportExcel(params,AlarmExcelModel.class, alarmExcelModels);
export(httpServletResponse, book, "极视智能报警详情");
}
/**
* export导出请求头设置
*
* @param response
* @param workbook
* @param fileName
* @throws Exception
*/
private static void export(HttpServletResponse response, Workbook workbook, String fileName) throws Exception {
response.reset();
response.setContentType("application/x-msdownload");
fileName = fileName + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("gb2312"), "ISO-8859-1") + ".xls");
ServletOutputStream outStream = null;
try {
outStream = response.getOutputStream();
workbook.write(outStream);
} finally {
outStream.close();
}
}
}
| 30.414179 | 140 | 0.753282 |
2b184f22ac0519c3520b3551f415090f07a5a8ca | 660 | package org.radarbase.schema.specification.active;
import static org.radarbase.schema.util.SchemaUtils.expandClass;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
import org.radarbase.schema.specification.AppDataTopic;
public class AppActiveSource extends ActiveSource<AppDataTopic> {
@JsonProperty("app_provider")
private String appProvider;
@JsonSetter
@SuppressWarnings("PMD.UnusedPrivateMethod")
private void setAppProvider(String provider) {
this.appProvider = expandClass(provider);
}
public String getAppProvider() {
return appProvider;
}
}
| 28.695652 | 65 | 0.772727 |
847d89e44ea5860872f34fc61fbdd068d36d8b51 | 2,264 | package com.example.client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class MinaClient {
public static void main(String[] args) {
MinaClient minaClient = new MinaClient();
minaClient.start();
}
public void start() {
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
Socket socket = null;
try {
socket = new Socket("127.0.0.1", 9898);
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String str=null;
startServerReplyListener(socket);
int num=0;
while ((str = bufferedReader.readLine()) != null) {
System.out.println(str);
bufferedWriter.write(str);
if(num%2==0){
bufferedWriter.write("\n");
}
num++;
bufferedWriter.flush();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (bufferedWriter != null) {
bufferedWriter.close();
}
if (socket != null) {
socket.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void startServerReplyListener(Socket socket){
new Thread(new Runnable(){
@Override
public void run() {
BufferedReader bufferedReader=null;
try {
bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str=null;
while((str=bufferedReader.readLine())!=null){
System.out.println(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}).start();
}
}
| 23.340206 | 89 | 0.658569 |
9059cc68561e5d3ab124399c890a95e7f2fb3f8b | 21,603 | /*
* 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.
*/
// THIS CODE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
package org.apache.kafka.common.message;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;
import org.apache.kafka.common.errors.UnsupportedVersionException;
import org.apache.kafka.common.protocol.ApiMessage;
import org.apache.kafka.common.protocol.MessageUtil;
import org.apache.kafka.common.protocol.ObjectSerializationCache;
import org.apache.kafka.common.protocol.Readable;
import org.apache.kafka.common.protocol.Writable;
import org.apache.kafka.common.protocol.types.Field;
import org.apache.kafka.common.protocol.types.RawTaggedField;
import org.apache.kafka.common.protocol.types.RawTaggedFieldWriter;
import org.apache.kafka.common.protocol.types.Schema;
import org.apache.kafka.common.protocol.types.Struct;
import org.apache.kafka.common.protocol.types.Type;
import org.apache.kafka.common.utils.ByteUtils;
import static java.util.Map.Entry;
import static org.apache.kafka.common.protocol.types.Field.TaggedFieldsSection;
public class DescribeAclsRequestData implements ApiMessage {
byte resourceTypeFilter;
String resourceNameFilter;
byte patternTypeFilter;
String principalFilter;
String hostFilter;
byte operation;
byte permissionType;
private List<RawTaggedField> _unknownTaggedFields;
public static final Schema SCHEMA_0 =
new Schema(
new Field("resource_type_filter", Type.INT8, "The resource type."),
new Field("resource_name_filter", Type.NULLABLE_STRING, "The resource name, or null to match any resource name."),
new Field("principal_filter", Type.NULLABLE_STRING, "The principal to match, or null to match any principal."),
new Field("host_filter", Type.NULLABLE_STRING, "The host to match, or null to match any host."),
new Field("operation", Type.INT8, "The operation to match."),
new Field("permission_type", Type.INT8, "The permission type to match.")
);
public static final Schema SCHEMA_1 =
new Schema(
new Field("resource_type_filter", Type.INT8, "The resource type."),
new Field("resource_name_filter", Type.NULLABLE_STRING, "The resource name, or null to match any resource name."),
new Field("pattern_type_filter", Type.INT8, "The resource pattern to match."),
new Field("principal_filter", Type.NULLABLE_STRING, "The principal to match, or null to match any principal."),
new Field("host_filter", Type.NULLABLE_STRING, "The host to match, or null to match any host."),
new Field("operation", Type.INT8, "The operation to match."),
new Field("permission_type", Type.INT8, "The permission type to match.")
);
public static final Schema SCHEMA_2 =
new Schema(
new Field("resource_type_filter", Type.INT8, "The resource type."),
new Field("resource_name_filter", Type.COMPACT_NULLABLE_STRING, "The resource name, or null to match any resource name."),
new Field("pattern_type_filter", Type.INT8, "The resource pattern to match."),
new Field("principal_filter", Type.COMPACT_NULLABLE_STRING, "The principal to match, or null to match any principal."),
new Field("host_filter", Type.COMPACT_NULLABLE_STRING, "The host to match, or null to match any host."),
new Field("operation", Type.INT8, "The operation to match."),
new Field("permission_type", Type.INT8, "The permission type to match."),
TaggedFieldsSection.of(
)
);
public static final Schema[] SCHEMAS = new Schema[] {
SCHEMA_0,
SCHEMA_1,
SCHEMA_2
};
public static final short LOWEST_SUPPORTED_VERSION = 0;
public static final short HIGHEST_SUPPORTED_VERSION = 2;
public DescribeAclsRequestData(Readable _readable, short _version) {
read(_readable, _version);
}
public DescribeAclsRequestData(Struct _struct, short _version) {
fromStruct(_struct, _version);
}
public DescribeAclsRequestData() {
this.resourceTypeFilter = (byte) 0;
this.resourceNameFilter = "";
this.patternTypeFilter = (byte) 3;
this.principalFilter = "";
this.hostFilter = "";
this.operation = (byte) 0;
this.permissionType = (byte) 0;
}
@Override
public short apiKey() {
return 29;
}
@Override
public short lowestSupportedVersion() {
return 0;
}
@Override
public short highestSupportedVersion() {
return 2;
}
@Override
public void read(Readable _readable, short _version) {
this.resourceTypeFilter = _readable.readByte();
{
int length;
if (_version >= 2) {
length = _readable.readUnsignedVarint() - 1;
} else {
length = _readable.readShort();
}
if (length < 0) {
this.resourceNameFilter = null;
} else if (length > 0x7fff) {
throw new RuntimeException("string field resourceNameFilter had invalid length " + length);
} else {
this.resourceNameFilter = _readable.readString(length);
}
}
if (_version >= 1) {
this.patternTypeFilter = _readable.readByte();
} else {
this.patternTypeFilter = (byte) 3;
}
{
int length;
if (_version >= 2) {
length = _readable.readUnsignedVarint() - 1;
} else {
length = _readable.readShort();
}
if (length < 0) {
this.principalFilter = null;
} else if (length > 0x7fff) {
throw new RuntimeException("string field principalFilter had invalid length " + length);
} else {
this.principalFilter = _readable.readString(length);
}
}
{
int length;
if (_version >= 2) {
length = _readable.readUnsignedVarint() - 1;
} else {
length = _readable.readShort();
}
if (length < 0) {
this.hostFilter = null;
} else if (length > 0x7fff) {
throw new RuntimeException("string field hostFilter had invalid length " + length);
} else {
this.hostFilter = _readable.readString(length);
}
}
this.operation = _readable.readByte();
this.permissionType = _readable.readByte();
this._unknownTaggedFields = null;
if (_version >= 2) {
int _numTaggedFields = _readable.readUnsignedVarint();
for (int _i = 0; _i < _numTaggedFields; _i++) {
int _tag = _readable.readUnsignedVarint();
int _size = _readable.readUnsignedVarint();
switch (_tag) {
default:
this._unknownTaggedFields = _readable.readUnknownTaggedField(this._unknownTaggedFields, _tag, _size);
break;
}
}
}
}
@Override
public void write(Writable _writable, ObjectSerializationCache _cache, short _version) {
int _numTaggedFields = 0;
_writable.writeByte(resourceTypeFilter);
if (resourceNameFilter == null) {
if (_version >= 2) {
_writable.writeUnsignedVarint(0);
} else {
_writable.writeShort((short) -1);
}
} else {
byte[] _stringBytes = _cache.getSerializedValue(resourceNameFilter);
if (_version >= 2) {
_writable.writeUnsignedVarint(_stringBytes.length + 1);
} else {
_writable.writeShort((short) _stringBytes.length);
}
_writable.writeByteArray(_stringBytes);
}
if (_version >= 1) {
_writable.writeByte(patternTypeFilter);
} else {
if (this.patternTypeFilter != (byte) 3) {
throw new UnsupportedVersionException("Attempted to write a non-default patternTypeFilter at version " + _version);
}
}
if (principalFilter == null) {
if (_version >= 2) {
_writable.writeUnsignedVarint(0);
} else {
_writable.writeShort((short) -1);
}
} else {
byte[] _stringBytes = _cache.getSerializedValue(principalFilter);
if (_version >= 2) {
_writable.writeUnsignedVarint(_stringBytes.length + 1);
} else {
_writable.writeShort((short) _stringBytes.length);
}
_writable.writeByteArray(_stringBytes);
}
if (hostFilter == null) {
if (_version >= 2) {
_writable.writeUnsignedVarint(0);
} else {
_writable.writeShort((short) -1);
}
} else {
byte[] _stringBytes = _cache.getSerializedValue(hostFilter);
if (_version >= 2) {
_writable.writeUnsignedVarint(_stringBytes.length + 1);
} else {
_writable.writeShort((short) _stringBytes.length);
}
_writable.writeByteArray(_stringBytes);
}
_writable.writeByte(operation);
_writable.writeByte(permissionType);
RawTaggedFieldWriter _rawWriter = RawTaggedFieldWriter.forFields(_unknownTaggedFields);
_numTaggedFields += _rawWriter.numFields();
if (_version >= 2) {
_writable.writeUnsignedVarint(_numTaggedFields);
_rawWriter.writeRawTags(_writable, Integer.MAX_VALUE);
} else {
if (_numTaggedFields > 0) {
throw new UnsupportedVersionException("Tagged fields were set, but version " + _version + " of this message does not support them.");
}
}
}
@SuppressWarnings("unchecked")
@Override
public void fromStruct(Struct struct, short _version) {
NavigableMap<Integer, Object> _taggedFields = null;
this._unknownTaggedFields = null;
if (_version >= 2) {
_taggedFields = (NavigableMap<Integer, Object>) struct.get("_tagged_fields");
}
this.resourceTypeFilter = struct.getByte("resource_type_filter");
this.resourceNameFilter = struct.getString("resource_name_filter");
if (_version >= 1) {
this.patternTypeFilter = struct.getByte("pattern_type_filter");
} else {
this.patternTypeFilter = (byte) 3;
}
this.principalFilter = struct.getString("principal_filter");
this.hostFilter = struct.getString("host_filter");
this.operation = struct.getByte("operation");
this.permissionType = struct.getByte("permission_type");
if (_version >= 2) {
if (!_taggedFields.isEmpty()) {
this._unknownTaggedFields = new ArrayList<>(_taggedFields.size());
for (Entry<Integer, Object> entry : _taggedFields.entrySet()) {
this._unknownTaggedFields.add((RawTaggedField) entry.getValue());
}
}
}
}
@Override
public Struct toStruct(short _version) {
TreeMap<Integer, Object> _taggedFields = null;
if (_version >= 2) {
_taggedFields = new TreeMap<>();
}
Struct struct = new Struct(SCHEMAS[_version]);
struct.set("resource_type_filter", this.resourceTypeFilter);
struct.set("resource_name_filter", this.resourceNameFilter);
if (_version >= 1) {
struct.set("pattern_type_filter", this.patternTypeFilter);
} else {
if (this.patternTypeFilter != (byte) 3) {
throw new UnsupportedVersionException("Attempted to write a non-default patternTypeFilter at version " + _version);
}
}
struct.set("principal_filter", this.principalFilter);
struct.set("host_filter", this.hostFilter);
struct.set("operation", this.operation);
struct.set("permission_type", this.permissionType);
if (_version >= 2) {
struct.set("_tagged_fields", _taggedFields);
}
return struct;
}
@Override
public int size(ObjectSerializationCache _cache, short _version) {
int _size = 0, _numTaggedFields = 0;
_size += 1;
if (resourceNameFilter == null) {
if (_version >= 2) {
_size += 1;
} else {
_size += 2;
}
} else {
byte[] _stringBytes = resourceNameFilter.getBytes(StandardCharsets.UTF_8);
if (_stringBytes.length > 0x7fff) {
throw new RuntimeException("'resourceNameFilter' field is too long to be serialized");
}
_cache.cacheSerializedValue(resourceNameFilter, _stringBytes);
if (_version >= 2) {
_size += _stringBytes.length + ByteUtils.sizeOfUnsignedVarint(_stringBytes.length + 1);
} else {
_size += _stringBytes.length + 2;
}
}
if (_version >= 1) {
_size += 1;
}
if (principalFilter == null) {
if (_version >= 2) {
_size += 1;
} else {
_size += 2;
}
} else {
byte[] _stringBytes = principalFilter.getBytes(StandardCharsets.UTF_8);
if (_stringBytes.length > 0x7fff) {
throw new RuntimeException("'principalFilter' field is too long to be serialized");
}
_cache.cacheSerializedValue(principalFilter, _stringBytes);
if (_version >= 2) {
_size += _stringBytes.length + ByteUtils.sizeOfUnsignedVarint(_stringBytes.length + 1);
} else {
_size += _stringBytes.length + 2;
}
}
if (hostFilter == null) {
if (_version >= 2) {
_size += 1;
} else {
_size += 2;
}
} else {
byte[] _stringBytes = hostFilter.getBytes(StandardCharsets.UTF_8);
if (_stringBytes.length > 0x7fff) {
throw new RuntimeException("'hostFilter' field is too long to be serialized");
}
_cache.cacheSerializedValue(hostFilter, _stringBytes);
if (_version >= 2) {
_size += _stringBytes.length + ByteUtils.sizeOfUnsignedVarint(_stringBytes.length + 1);
} else {
_size += _stringBytes.length + 2;
}
}
_size += 1;
_size += 1;
if (_unknownTaggedFields != null) {
_numTaggedFields += _unknownTaggedFields.size();
for (RawTaggedField _field : _unknownTaggedFields) {
_size += ByteUtils.sizeOfUnsignedVarint(_field.tag());
_size += ByteUtils.sizeOfUnsignedVarint(_field.size());
_size += _field.size();
}
}
if (_version >= 2) {
_size += ByteUtils.sizeOfUnsignedVarint(_numTaggedFields);
} else {
if (_numTaggedFields > 0) {
throw new UnsupportedVersionException("Tagged fields were set, but version " + _version + " of this message does not support them.");
}
}
return _size;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof DescribeAclsRequestData)) return false;
DescribeAclsRequestData other = (DescribeAclsRequestData) obj;
if (resourceTypeFilter != other.resourceTypeFilter) return false;
if (this.resourceNameFilter == null) {
if (other.resourceNameFilter != null) return false;
} else {
if (!this.resourceNameFilter.equals(other.resourceNameFilter)) return false;
}
if (patternTypeFilter != other.patternTypeFilter) return false;
if (this.principalFilter == null) {
if (other.principalFilter != null) return false;
} else {
if (!this.principalFilter.equals(other.principalFilter)) return false;
}
if (this.hostFilter == null) {
if (other.hostFilter != null) return false;
} else {
if (!this.hostFilter.equals(other.hostFilter)) return false;
}
if (operation != other.operation) return false;
if (permissionType != other.permissionType) return false;
return MessageUtil.compareRawTaggedFields(_unknownTaggedFields, other._unknownTaggedFields);
}
@Override
public int hashCode() {
int hashCode = 0;
hashCode = 31 * hashCode + resourceTypeFilter;
hashCode = 31 * hashCode + (resourceNameFilter == null ? 0 : resourceNameFilter.hashCode());
hashCode = 31 * hashCode + patternTypeFilter;
hashCode = 31 * hashCode + (principalFilter == null ? 0 : principalFilter.hashCode());
hashCode = 31 * hashCode + (hostFilter == null ? 0 : hostFilter.hashCode());
hashCode = 31 * hashCode + operation;
hashCode = 31 * hashCode + permissionType;
return hashCode;
}
@Override
public DescribeAclsRequestData duplicate() {
DescribeAclsRequestData _duplicate = new DescribeAclsRequestData();
_duplicate.resourceTypeFilter = resourceTypeFilter;
if (resourceNameFilter == null) {
_duplicate.resourceNameFilter = null;
} else {
_duplicate.resourceNameFilter = resourceNameFilter;
}
_duplicate.patternTypeFilter = patternTypeFilter;
if (principalFilter == null) {
_duplicate.principalFilter = null;
} else {
_duplicate.principalFilter = principalFilter;
}
if (hostFilter == null) {
_duplicate.hostFilter = null;
} else {
_duplicate.hostFilter = hostFilter;
}
_duplicate.operation = operation;
_duplicate.permissionType = permissionType;
return _duplicate;
}
@Override
public String toString() {
return "DescribeAclsRequestData("
+ "resourceTypeFilter=" + resourceTypeFilter
+ ", resourceNameFilter=" + ((resourceNameFilter == null) ? "null" : "'" + resourceNameFilter.toString() + "'")
+ ", patternTypeFilter=" + patternTypeFilter
+ ", principalFilter=" + ((principalFilter == null) ? "null" : "'" + principalFilter.toString() + "'")
+ ", hostFilter=" + ((hostFilter == null) ? "null" : "'" + hostFilter.toString() + "'")
+ ", operation=" + operation
+ ", permissionType=" + permissionType
+ ")";
}
public byte resourceTypeFilter() {
return this.resourceTypeFilter;
}
public String resourceNameFilter() {
return this.resourceNameFilter;
}
public byte patternTypeFilter() {
return this.patternTypeFilter;
}
public String principalFilter() {
return this.principalFilter;
}
public String hostFilter() {
return this.hostFilter;
}
public byte operation() {
return this.operation;
}
public byte permissionType() {
return this.permissionType;
}
@Override
public List<RawTaggedField> unknownTaggedFields() {
if (_unknownTaggedFields == null) {
_unknownTaggedFields = new ArrayList<>(0);
}
return _unknownTaggedFields;
}
public DescribeAclsRequestData setResourceTypeFilter(byte v) {
this.resourceTypeFilter = v;
return this;
}
public DescribeAclsRequestData setResourceNameFilter(String v) {
this.resourceNameFilter = v;
return this;
}
public DescribeAclsRequestData setPatternTypeFilter(byte v) {
this.patternTypeFilter = v;
return this;
}
public DescribeAclsRequestData setPrincipalFilter(String v) {
this.principalFilter = v;
return this;
}
public DescribeAclsRequestData setHostFilter(String v) {
this.hostFilter = v;
return this;
}
public DescribeAclsRequestData setOperation(byte v) {
this.operation = v;
return this;
}
public DescribeAclsRequestData setPermissionType(byte v) {
this.permissionType = v;
return this;
}
}
| 38.924324 | 149 | 0.595751 |
6996329836731303c1f85774547bf43f567e2eb8 | 546 | package com.here.autonomous.driving.controller.strategies;
import com.here.autonomous.driving.model.BusAddresses;
public class StatCalculationStrategyFactory {
private final StatCalculationStrategy speedCalculationStrategy = new SpeedStatCalculationStrategy();
public StatCalculationStrategy getStatCalculationStrategy(BusAddresses busAddresses) {
switch (busAddresses) {
case SPEED_BUS_ADDRESS:
return speedCalculationStrategy;
default:
return null;
}
}
}
| 28.736842 | 104 | 0.721612 |
3a889def1b65e02d778ecf6a73e7509b18483630 | 1,525 | package jp.vmi.selenium.selenese.command;
import jp.vmi.selenium.selenese.Context;
import jp.vmi.selenium.selenese.FlowControlState;
import jp.vmi.selenium.selenese.result.Result;
import jp.vmi.selenium.selenese.result.Success;
import static jp.vmi.selenium.selenese.command.ArgumentType.*;
/**
* Command "while".
*/
public class While extends BlockStartImpl {
private static final int ARG_CONDITION = 0;
private static class WhileState implements FlowControlState {
private boolean isAlreadyFinished = false;
@Override
public boolean isAlreadyFinished() {
return isAlreadyFinished;
}
public void setAlreadyFinished(boolean isAlreadyFinished) {
this.isAlreadyFinished = isAlreadyFinished;
}
}
While(int index, String name, String... args) {
super(index, name, args, VALUE);
}
@Override
public boolean isLoopBlock() {
return true;
}
@Override
protected Result executeImpl(Context context, String... curArgs) {
WhileState state = context.getFlowControlState(this);
if (state == null) {
state = new WhileState();
context.setFlowControlState(this, state);
}
if (!context.isTrue(curArgs[ARG_CONDITION])) {
state.setAlreadyFinished(true);
context.getCommandListIterator().jumpTo(blockEnd);
return new Success("Break");
} else {
return new Success("Continue");
}
}
}
| 27.232143 | 70 | 0.64918 |
088296159e364efe0cbd778b9e9f3b00b71ada2c | 8,803 | /*
* 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.
*
* Copyright 2007-2014 SSAC(Systems of Social Accounting Consortium)
* <author> Yasunari Ishizuka (PieCake,Inc.)
* <author> Hiroshi Deguchi (TOKYO INSTITUTE OF TECHNOLOGY)
* <author> Yuji Onuki (Statistics Bureau)
* <author> Shungo Sakaki (Tokyo University of Technology)
* <author> Akira Sasaki (HOSEI UNIVERSITY)
* <author> Hideki Tanuma (TOKYO INSTITUTE OF TECHNOLOGY)
*/
/*
* @(#)MacroFilterDefArgReferDialog.java 3.1.0 2014/05/16
* - modified by Y.Ishizuka(PieCake.inc,)
* @(#)MacroFilterDefArgReferDialog.java 2.0.0 2012/10/28
* - created by Y.Ishizuka(PieCake.inc,)
*/
package ssac.falconseed.module.swing;
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import ssac.aadl.common.CommonResources;
import ssac.falconseed.module.IModuleArgConfig;
import ssac.falconseed.module.ModuleArgConfig;
import ssac.falconseed.runner.ModuleRunner;
import ssac.falconseed.runner.RunnerMessages;
import ssac.falconseed.runner.setting.AppSettings;
import ssac.util.Strings;
import ssac.util.swing.AbBasicDialog;
/**
* マクロフィルタの定義引数から参照する引数を選択するダイアログ。
*
* @version 3.1.0 2014/05/16
* @since 2.0.0
*/
public class MacroFilterDefArgReferDialog extends AbBasicDialog
{
//------------------------------------------------------------
// Constants
//------------------------------------------------------------
private static final long serialVersionUID = 1L;
//------------------------------------------------------------
// Fields
//------------------------------------------------------------
private final MacroFilterEditModel _datamodel;
private final ModuleArgConfig _targetArg;
private JList _cList;
private IModuleArgConfig _selected = null;
/**
* 引数参照の前に付加する文字列のテキストボックス
* @since 3.1.0
*/
private JTextField _tfPrefix;
/**
* 引数参照の後に付加する文字列のテキストボックス
* @since 3.1.0
*/
private JTextField _tfSuffix;
//------------------------------------------------------------
// Constructions
//------------------------------------------------------------
public MacroFilterDefArgReferDialog(Frame owner, MacroFilterEditModel datamodel, ModuleArgConfig targetArg) {
super(owner, RunnerMessages.getInstance().MacroFilterDefArgReferDlg_Title, true);
if (datamodel == null)
throw new NullPointerException("'datamodel' is null.");
if (targetArg == null)
throw new NullPointerException("'targetArg' is null.");
if (targetArg.isFixedValue() || targetArg.getParameterType() == null)
throw new IllegalArgumentException("'targetArg' is fixed value!");
this._datamodel = datamodel;
this._targetArg = targetArg;
setConfiguration(AppSettings.MACROFILTERDEFARGREF_DLG, AppSettings.getInstance().getConfiguration());
}
public MacroFilterDefArgReferDialog(Dialog owner, MacroFilterEditModel datamodel, ModuleArgConfig targetArg) {
super(owner, RunnerMessages.getInstance().MacroFilterDefArgReferDlg_Title, true);
if (datamodel == null)
throw new NullPointerException("'datamodel' is null.");
if (targetArg == null)
throw new NullPointerException("'targetArg' is null.");
if (targetArg.isFixedValue() || targetArg.getParameterType() == null)
throw new IllegalArgumentException("'targetArg' is fixed value!");
this._datamodel = datamodel;
this._targetArg = targetArg;
setConfiguration(AppSettings.MACROFILTERDEFARGREF_DLG, AppSettings.getInstance().getConfiguration());
}
@Override
public void initialComponent() {
_cList = new JList(createListModel());
_cList.setCellRenderer(new ArgReferListRenderer());
_cList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Prefix/Suffix(@since 3.1.0)
_tfPrefix = new JTextField();
_tfSuffix = new JTextField();
Object targetArgValue = _targetArg.getValue();
if (targetArgValue instanceof FilterArgReferValueEditModel) {
FilterArgReferValueEditModel refValue = (FilterArgReferValueEditModel)targetArgValue;
_tfPrefix.setText(refValue.getPrefix());
_tfSuffix.setText(refValue.getSuffix());
targetArgValue = refValue.getReferencedArgument();
}
super.initialComponent();
restoreConfiguration();
// 参照を選択(@since 3.1.0)
if (targetArgValue != null) {
_cList.setSelectedValue(targetArgValue, true);
}
}
//------------------------------------------------------------
// Public interfaces
//------------------------------------------------------------
public IModuleArgConfig getSelectedArgument() {
return _selected;
}
//------------------------------------------------------------
// Internal methods
//------------------------------------------------------------
@Override
protected JButton createApplyButton() {
return null; // no [apply] button
}
@Override
protected boolean doOkAction() {
// 選択された定義引数を保存
if (_cList.isSelectionEmpty()) {
// no selection
ModuleRunner.showErrorMessage(this, RunnerMessages.getInstance().msgChooseReferArgument);
return false;
}
FilterArgEditModel selModel = (FilterArgEditModel)_cList.getSelectedValue();
// Check Prefix
String strPrefix = _tfPrefix.getText();
// Check Suffix
String strSuffix = _tfSuffix.getText();
// Prefix/Suffix があれば、固有のインスタンスを生成(@since 3.1.0)
if (!Strings.isNullOrEmpty(strPrefix) || !Strings.isNullOrEmpty(strSuffix)) {
// Prefix/Suffix の指定あり
_selected = new FilterArgReferValueEditModel(selModel, strPrefix, strSuffix);
} else {
// 単純な参照
_selected = selModel;
}
return super.doOkAction();
}
@Override
protected void setupActions() {
super.setupActions();
}
@Override
protected void setupDialogConditions() {
super.setupDialogConditions();
setResizable(true);
setKeepMinimumSize(true);
}
@Override
protected void setupMainContents() {
super.setupMainContents();
JScrollPane scList = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scList.setViewportView(this._cList);
JLabel lblTitle = new JLabel(RunnerMessages.getInstance().ArgReferDlg_Label_args);
JPanel pnlMain = new JPanel(new GridBagLayout());
pnlMain.setBorder(CommonResources.DIALOG_CONTENT_BORDER);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.gridheight = 1;
gbc.weightx = 0;
gbc.weighty = 0;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.NONE;
pnlMain.add(lblTitle, gbc);
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
pnlMain.add(scList, gbc);
// 付加する文字の入力コンポーネント
gbc.gridwidth = 1;
gbc.weighty = 0;
gbc.insets = new Insets(5, 0, 0, 0);
// 前に付加する文字
//--- ラベル
gbc.gridy++;
gbc.gridx = 0;
gbc.weightx = 0;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.NONE;
pnlMain.add(new JLabel(RunnerMessages.getInstance().ArgReferDlg_Label_prefix + " "), gbc);
//--- 入力フィールド
gbc.gridx = 1;
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
pnlMain.add(_tfPrefix, gbc);
// 後に付加する文字
//--- ラベル
gbc.gridy++;
gbc.gridx = 0;
gbc.weightx = 0;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.NONE;
pnlMain.add(new JLabel(RunnerMessages.getInstance().ArgReferDlg_Label_suffix + " "), gbc);
//--- 入力フィールド
gbc.gridx = 1;
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
pnlMain.add(_tfSuffix, gbc);
this.getContentPane().add(pnlMain, BorderLayout.CENTER);
}
protected ListModel createListModel() {
return _datamodel.getReferenceableMExecDefArguments(_targetArg);
}
@Override
protected Dimension getDefaultSize() {
return new Dimension(320,300);
}
//------------------------------------------------------------
// Inner classes
//------------------------------------------------------------
}
| 30.77972 | 119 | 0.676701 |
62d3914e0270d8085ca0b9c86217c99fcfd8decf | 2,069 | package core.ipc.repeatServer.processors;
import java.util.logging.Logger;
import utilities.ILoggable;
import argo.jdom.JsonNode;
import argo.jdom.JsonNodeFactories;
import core.ipc.repeatServer.MainMessageSender;
abstract class AbstractMessageProcessor implements ILoggable {
protected static final String SUCCESS_STATUS = "Success";
protected static final String FAILURE_STATUS = "Failure";
protected final MainMessageSender messageSender;
protected AbstractMessageProcessor(MainMessageSender messageSender) {
this.messageSender = messageSender;
}
public abstract boolean process(String type, long id, JsonNode content) throws InterruptedException;
protected abstract boolean verifyMessageContent(JsonNode content);
protected boolean verifyReplyContent(JsonNode content) {
return content.isStringValue("status") &&
content.isNode("message");
}
protected boolean success(String type, long id, String message) {
return messageSender.sendMessage(type, id, generateReply(SUCCESS_STATUS, message));
}
protected boolean success(String type, long id, JsonNode message) {
return messageSender.sendMessage(type, id, generateReply(SUCCESS_STATUS, message));
}
protected boolean success(String type, long id) {
return success(type, id, "");
}
protected boolean failure(String type, long id, String message) {
getLogger().warning(message);
messageSender.sendMessage(type, id, generateReply(FAILURE_STATUS, message));
return false;
}
protected JsonNode generateReply(String status, String message) {
return JsonNodeFactories.object(
JsonNodeFactories.field("status", JsonNodeFactories.string(status)),
JsonNodeFactories.field("message", JsonNodeFactories.string(message))
);
}
protected JsonNode generateReply(String status, JsonNode message) {
return JsonNodeFactories.object(
JsonNodeFactories.field("status", JsonNodeFactories.string(status)),
JsonNodeFactories.field("message", message)
);
}
@Override
public final Logger getLogger() {
return Logger.getLogger(getClass().getName());
}
}
| 31.348485 | 101 | 0.781537 |
8f5a5b9f38e6c65f7af2014ffebc9e5e8d3fcf8c | 848 | package it.unibz.inf.ontouml.vp.model.ontouml.serialization;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import it.unibz.inf.ontouml.vp.model.ontouml.view.GeneralizationSetView;
import java.io.IOException;
public class GeneralizationSetViewSerializer extends JsonSerializer<GeneralizationSetView> {
@Override
public void serialize(
GeneralizationSetView gsView, JsonGenerator jsonGen, SerializerProvider provider)
throws IOException {
jsonGen.writeStartObject();
serializeFields(gsView, jsonGen);
jsonGen.writeEndObject();
}
static void serializeFields(GeneralizationSetView gsView, JsonGenerator jsonGen)
throws IOException {
NodeViewSerializer.serializeFields(gsView, jsonGen);
}
}
| 35.333333 | 92 | 0.806604 |
95510a03d11335c55bf5199a9ba4415e36411cbb | 1,421 | /**
* Copyright 2013 52°North Initiative for Geospatial Open Source Software GmbH
*
* 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.n52.sir.ds.solr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
/**
* @author Yakoub
*
*/
public class SOLRDeleteSensorInfoDAO {
private static Logger log = LoggerFactory.getLogger(SOLRInsertSensorInfoDAO.class);
private SolrConnection connection;
@Inject
public SOLRDeleteSensorInfoDAO(SolrConnection c) {
this.connection = c;
log.debug("NEW {}", this);
}
public void deleteSensorById(String id) {
log.debug("Deleting sensor with id {}", id);
try {
this.connection.deleteSensorWithID(id);
}
catch (Exception e) {
log.error("Error on deleting sensor", e);
}
log.debug("Deleted {}", id);
}
}
| 26.314815 | 87 | 0.681914 |
11f89a1041aaab890530fcbe1242e9017db16335 | 3,196 | import java.util.Random;
public class Main {
private static void testEncodeLong64() {
Random r = new Random();
boolean success = true;
for (int i = 0; i < 100; i++) {
long x = r.nextLong();
long y = LongEncoder.encode64(x);
long z = LongEncoder.decode64(y);
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("testEncodeLong64 success");
} else {
System.out.println("testEncodeLong64 failed");
}
}
private static void testEncodeLong48() {
Random r = new Random();
boolean success = true;
for (int i = 0; i < 100; i++) {
long x = r.nextLong() >>> 16;
long y = LongEncoder.encode48(x);
long z = LongEncoder.decode48(y);
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("testEncodeLong48 success");
} else {
System.out.println("testEncodeLong48 failed");
}
}
private static void testBase62() {
Random r = new Random();
boolean success = true;
for (int i = 0; i < 100; i++) {
long x = r.nextLong();
String y = Base62.encode(LongEncoder.encode64(x));
long z = LongEncoder.decode64(Base62.decode(y));
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("testBase62 success");
} else {
System.out.println("testBase62 failed");
}
}
private static void testBase62ForShortLink(){
Random r = new Random();
boolean success = true;
for (int i = 0; i < 100; i++) {
long x = r.nextLong() >>> 16;
// 48bit的x, y的长度在1~9之间,长度为8居多
// 如果需要恒定8字节,则可以用Base64, Base64时6bit一个字节,正好8字节
// 如果又不想引入特殊字符('-','_'), 则x需要需要小于等于47bit,构造一个47bit的x(比较复杂)
String y = Base62.encodePositive(LongEncoder.encode48(x));
long z = LongEncoder.decode48(Base62.decodePositive(y));
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("testBase62ForShortLink success");
} else {
System.out.println("testBase62ForShortLink failed");
}
}
private static void testLong48ToHex() {
Random r = new Random();
long x = r.nextLong() >>> 16;
String y = HexUtil.long48ToHex(LongEncoder.encode48(x));
long z = LongEncoder.decode48(HexUtil.hexToLong48(y));
if (x == z) {
System.out.println("testLong48ToHex success");
} else {
System.out.println("testLong48ToHex failed");
}
System.out.println("y = " + y);
}
public static void main(String[] args) {
testEncodeLong64();
testEncodeLong48();
testBase62();
testBase62ForShortLink();
testLong48ToHex();
}
}
| 30.438095 | 70 | 0.498123 |
6c584035e67d4799d8f985bf000ba75c5d408bf0 | 2,362 | /*
* 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.dubbo.qos.textui;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
public class TKvTest {
@Test
public void test1() {
TKv tKv = new TKv(new TTable.ColumnDefine(TTable.Align.RIGHT), new TTable.ColumnDefine(10, false, TTable.Align.LEFT));
tKv.add("KEY-1", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
tKv.add("KEY-2", "1234567890");
tKv.add("KEY-3", "1234567890");
TTable tTable = new TTable(new TTable.ColumnDefine[]{
new TTable.ColumnDefine(),
new TTable.ColumnDefine(20, false, TTable.Align.LEFT)
});
String kv = tKv.rendering();
assertThat(kv, containsString("ABCDEFGHIJ" + System.lineSeparator()));
assertThat(kv, containsString("KLMNOPQRST" + System.lineSeparator()));
assertThat(kv, containsString("UVWXYZ" + System.lineSeparator()));
tTable.addRow("OPTIONS", kv);
String table = tTable.rendering();
assertThat(table, containsString("|OPTIONS|"));
assertThat(table, containsString("|KEY-3"));
System.out.println(table);
}
@Test
public void test2() throws Exception {
TKv tKv = new TKv();
tKv.add("KEY-1", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
tKv.add("KEY-2", "1234567890");
tKv.add("KEY-3", "1234567890");
String kv = tKv.rendering();
assertThat(kv, containsString("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
System.out.println(kv);
}
}
| 38.721311 | 126 | 0.676122 |
cbc36c532e2c5a0585b9a9866976589b8d3b4184 | 464 | /**
* Copyright (C) 2013 Alexander Szczuczko
*
* This file may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package ca.szc.keratin.core.event.message.interfaces;
public interface DirectlyReplyable
{
/**
* Reply to the event with some text by appending the sender to the reply message.
*
* @param reply Text to use in reply
*/
public void replyDirectly( String reply );
}
| 25.777778 | 86 | 0.696121 |
35ca3a428821708be77a509670a657d7371b57f6 | 1,456 | /*
* Copyright 2003-2009 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 com.jdon.jivejdon.domain.model.attachment;
import java.util.Collection;
/**
* upload files is a part of aggregation root.
*
* it should be load with messageVO.
*
* @author banq
*
*/
public class AttachmentsVO {
private final Long messageId;
// for upload files lazyload
private final Collection uploadFiles;
// for read or load
public AttachmentsVO( Long messageId, Collection<UploadFile> uploadFiles) {
super();
this.messageId = messageId;
this.uploadFiles = uploadFiles;
}
public Collection<UploadFile> getUploadFiles() {
return uploadFiles;
}
public void preloadUploadFileDatas() {
if (getUploadFiles() != null) {
// preload will cause memory expand
// for (Object o : uploadFiles) {
// UploadFile uploadFile = (UploadFile) o;
// uploadFile.preloadData();
// }
}
}
}
| 24.266667 | 77 | 0.714973 |
4b6ce04a517edb3df963e39bd6174dfb1982813c | 2,132 | package org.ff4j.services;
/*
* #%L
* ff4j-spring-services
* %%
* Copyright (C) 2013 - 2016 FF4J
* %%
* 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.
* #L%
*/
import org.ff4j.FF4j;
import org.ff4j.core.Feature;
import org.ff4j.services.domain.FeatureApiBean;
import org.ff4j.services.validator.FeatureValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author <a href="mailto:paul58914080@gmail.com">Paul Williams</a>
*/
@Service
public class GroupServices {
@Autowired
private FF4j ff4j;
@Autowired
private FeatureValidator featureValidator;
public Collection<FeatureApiBean> getFeaturesByGroup(String groupName) {
featureValidator.assertGroupExist(groupName);
Collection<Feature> features = ff4j.getFeatureStore().readGroup(groupName).values();
Collection<FeatureApiBean> featureApiBeans = new ArrayList<FeatureApiBean>();
if (!CollectionUtils.isEmpty(features)) {
for (Feature feature : features) {
featureApiBeans.add(new FeatureApiBean(feature));
}
}
return featureApiBeans;
}
public void enableGroup(String groupName) {
featureValidator.assertGroupExist(groupName);
ff4j.getFeatureStore().enableGroup(groupName);
}
public void disableGroup(String groupName) {
featureValidator.assertGroupExist(groupName);
ff4j.getFeatureStore().disableGroup(groupName);
}
}
| 32.30303 | 92 | 0.721388 |
c46efc13c08fc1f0912a2348c9332a14e82e7c11 | 2,092 | package edu.pdx.cs410J.prathik.ApptBookAndroid;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextClock;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int CREATE = 1;
private static final int SEARCH = 2;
private static final int ALL_APPOINTMENTS = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appt_book_main_menu);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
}
public void READMe(View view) {
Intent intent = new Intent(Intent.ACTION_VIEW, null, this, READMe.class);
startActivity(intent);
}
public void createNewAppointment(View view) {
Intent intent = new Intent(Intent.ACTION_VIEW, null, this, CreateAppointment.class);
startActivityForResult(intent, CREATE);
}
public void searchAppointments(View view) {
Intent intent = new Intent(Intent.ACTION_VIEW, null, this, SearchAppointments.class);
startActivityForResult(intent, SEARCH);
}
public void allAppointments(View view) {
Intent intent = new Intent(Intent.ACTION_VIEW, null, this, AllAppointments.class);
startActivityForResult(intent, ALL_APPOINTMENTS);
}
} | 24.045977 | 93 | 0.711281 |
7bb228e78adca6e623beacc740cbbc7cee7de349 | 19,159 | /*
* Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
*/
package org.ligoj.app.plugin.build.jenkins;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.transaction.Transactional;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.ligoj.app.AbstractServerTest;
import org.ligoj.app.api.SubscriptionStatusWithData;
import org.ligoj.app.iam.model.DelegateOrg;
import org.ligoj.app.model.Node;
import org.ligoj.app.model.Parameter;
import org.ligoj.app.model.ParameterValue;
import org.ligoj.app.model.Project;
import org.ligoj.app.model.Subscription;
import org.ligoj.app.plugin.build.BuildResource;
import org.ligoj.app.resource.node.ParameterValueResource;
import org.ligoj.app.resource.subscription.SubscriptionResource;
import org.ligoj.bootstrap.MatcherUtil;
import org.ligoj.bootstrap.core.resource.BusinessException;
import org.ligoj.bootstrap.core.validation.ValidationJsonException;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.xml.sax.SAXException;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.matching.UrlPattern;
/**
* Test class of {@link JenkinsPluginResource}
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = "classpath:/META-INF/spring/application-context-test.xml")
@Rollback
@Transactional
class JenkinsPluginResourceTest extends AbstractServerTest {
@Autowired
private JenkinsPluginResource resource;
@Autowired
private ParameterValueResource pvResource;
@Autowired
private SubscriptionResource subscriptionResource;
protected int subscription;
@BeforeEach
void prepareData() throws IOException {
// Only with Spring context
persistEntities("csv", new Class[] { Node.class, Parameter.class, Project.class, Subscription.class,
ParameterValue.class, DelegateOrg.class }, StandardCharsets.UTF_8.name());
this.subscription = getSubscription("gStack");
// Coverage only
resource.getKey();
}
/**
* Return the subscription identifier of the given project. Assumes there is only one subscription for a service.
*/
private int getSubscription(final String project) {
return getSubscription(project, BuildResource.SERVICE_KEY);
}
@Test
void deleteLocal() throws MalformedURLException, URISyntaxException {
resource.delete(subscription, false);
// nothing has been done. If remote delete is done, an exception will be
// thrown and this test will fail.
}
@Test
void deleteRemote() throws IOException, URISyntaxException {
addLoginAccess();
addAdminAccess();
// post delete
final UrlPattern deletePath = urlEqualTo("/job/ligoj-bootstrap/doDelete");
httpServer.stubFor(post(deletePath).willReturn(
aResponse().withHeader("location", "location").withStatus(HttpStatus.SC_MOVED_TEMPORARILY)));
httpServer.start();
resource.delete(subscription, true);
// check that server has been called.
httpServer.verify(1, WireMock.postRequestedFor(deletePath));
}
@Test
void deleteRemoteFailed() throws IOException {
addLoginAccess();
addAdminAccess();
// post delete
final UrlPattern deletePath = urlEqualTo("/job/ligoj-bootstrap/doDelete");
httpServer.stubFor(post(deletePath).willReturn(aResponse().withStatus(HttpStatus.SC_NOT_FOUND)));
httpServer.start();
Assertions.assertThrows(BusinessException.class, () -> {
resource.delete(subscription, true);
});
}
@Test
void getJenkinsResourceInvalidUrl() {
resource.getResource(new HashMap<>(), null);
}
@Test
void getVersion() throws Exception {
addAdminAccess();
httpServer.start();
final String version = resource.getVersion(subscription);
Assertions.assertEquals("1.574", version);
}
@Test
void getLastVersion() {
final String lastVersion = resource.getLastVersion();
Assertions.assertNotNull(lastVersion);
Assertions.assertTrue(lastVersion.compareTo("1.576") > 0);
}
@Test
void getLastVersionFailed() {
Assertions.assertNull(resource.getLastVersion("any:some"));
}
@Test
void validateJobNotFound() {
httpServer.stubFor(get(urlEqualTo("/job/ligoj-bootstrap/config.xml"))
.willReturn(aResponse().withStatus(HttpStatus.SC_NOT_FOUND)));
httpServer.start();
final Map<String, String> parameters = pvResource.getNodeParameters("service:build:jenkins:bpr");
parameters.put(JenkinsPluginResource.PARAMETER_JOB, "ligoj-bootstrap");
MatcherUtil.assertThrows(Assertions.assertThrows(ValidationJsonException.class, () -> {
resource.validateJob(parameters);
}), JenkinsPluginResource.PARAMETER_JOB, "jenkins-job");
}
@Test
void link() throws IOException, URISyntaxException {
addLoginAccess();
addAdminAccess();
addJobAccess();
httpServer.start();
// Attach the Jenkins project identifier
final Parameter parameter = new Parameter();
parameter.setId(JenkinsPluginResource.PARAMETER_JOB);
final Subscription subscription = new Subscription();
final Subscription source = em.find(Subscription.class, this.subscription);
subscription.setProject(source.getProject());
subscription.setNode(source.getNode());
em.persist(subscription);
final ParameterValue parameterValue = new ParameterValue();
parameterValue.setParameter(parameter);
parameterValue.setData("ligoj-bootstrap");
parameterValue.setSubscription(subscription);
em.persist(parameterValue);
em.flush();
// Invoke create for an already created entity, since for now, there is
// nothing but validation pour jenkins
resource.link(subscription.getId());
// Nothing to validate for now...
}
@Test
void validateJob() throws IOException, URISyntaxException {
addJobAccess();
httpServer.start();
final Map<String, String> parameters = pvResource.getNodeParameters("service:build:jenkins:bpr");
parameters.put(JenkinsPluginResource.PARAMETER_JOB, "ligoj-bootstrap");
checkJob(resource.validateJob(parameters), false);
}
@Test
void validateJobSimple() throws IOException, URISyntaxException {
httpServer.stubFor(get(urlEqualTo(
"/api/xml?depth=1&tree=jobs[displayName,name,color]&xpath=hudson/job[name='ligoj-bootstrap']&wrapper=hudson"))
.willReturn(aResponse().withStatus(HttpStatus.SC_OK)
.withBody(IOUtils.toString(new ClassPathResource(
"mock-server/jenkins/jenkins-ligoj-bootstrap-config-simple.xml").getInputStream(),
StandardCharsets.UTF_8))));
httpServer.start();
final Map<String, String> parameters = pvResource.getNodeParameters("service:build:jenkins:bpr");
parameters.put(JenkinsPluginResource.PARAMETER_JOB, "ligoj-bootstrap");
final Job job = resource.validateJob(parameters);
Assertions.assertEquals("ligoj-bootstrap", job.getId());
Assertions.assertNull(job.getName());
Assertions.assertNull(job.getDescription());
Assertions.assertEquals("disabled", job.getStatus());
Assertions.assertFalse(job.isBuilding());
}
@Test
void validateJobBuilding() throws IOException, URISyntaxException {
addJobAccessBuilding();
httpServer.start();
final Map<String, String> parameters = pvResource.getNodeParameters("service:build:jenkins:bpr");
parameters.put(JenkinsPluginResource.PARAMETER_JOB, "ligoj-bootstrap");
checkJob(resource.validateJob(parameters), true);
}
private void checkJob(final Job job, final boolean building) {
Assertions.assertEquals("ligoj-bootstrap", job.getId());
Assertions.assertEquals("Ligoj - Bootstrap", job.getName());
Assertions.assertEquals("Any description", job.getDescription());
Assertions.assertEquals("yellow", job.getStatus());
Assertions.assertEquals(building, job.isBuilding());
}
@Test
void checkStatus() throws IOException {
addLoginAccess();
addAdminAccess();
httpServer.start();
final Map<String, String> parametersNoCheck = subscriptionResource.getParametersNoCheck(subscription);
parametersNoCheck.remove(JenkinsPluginResource.PARAMETER_JOB);
Assertions.assertTrue(resource.checkStatus(parametersNoCheck));
}
@Test
void checkSubscriptionStatus() throws IOException, URISyntaxException {
addJobAccess();
httpServer.start();
final SubscriptionStatusWithData nodeStatusWithData = resource
.checkSubscriptionStatus(subscriptionResource.getParametersNoCheck(subscription));
Assertions.assertTrue(nodeStatusWithData.getStatus().isUp());
checkJob((Job) nodeStatusWithData.getData().get("job"), false);
}
private void addJobAccess() throws IOException {
httpServer.stubFor(get(urlEqualTo(
"/api/xml?depth=1&tree=jobs[displayName,name,color]&xpath=hudson/job[name='ligoj-bootstrap']&wrapper=hudson"))
.willReturn(aResponse().withStatus(HttpStatus.SC_OK)
.withBody(IOUtils.toString(
new ClassPathResource("mock-server/jenkins/jenkins-ligoj-bootstrap-config.xml")
.getInputStream(),
StandardCharsets.UTF_8))));
}
private void addJobAccessBuilding() throws IOException {
httpServer.stubFor(get(urlEqualTo(
"/api/xml?depth=1&tree=jobs[displayName,name,color]&xpath=hudson/job[name='ligoj-bootstrap']&wrapper=hudson"))
.willReturn(aResponse().withStatus(HttpStatus.SC_OK).withBody(IOUtils.toString(
new ClassPathResource("mock-server/jenkins/jenkins-ligoj-bootstrap-config-building.xml")
.getInputStream(),
StandardCharsets.UTF_8))));
}
@Test
void validateAdminAccess() throws IOException {
addLoginAccess();
addAdminAccess();
addJobAccess();
httpServer.start();
final String version = resource.validateAdminAccess(pvResource.getNodeParameters("service:build:jenkins:bpr"));
Assertions.assertEquals("1.574", version);
}
private void addAdminAccess() throws IOException {
httpServer.stubFor(get(urlEqualTo("/api/json?tree=numExecutors"))
.willReturn(aResponse().withStatus(HttpStatus.SC_OK).withHeader("x-jenkins", "1.574")
.withBody(IOUtils.toString(
new ClassPathResource("mock-server/jenkins/jenkins-version.json").getInputStream(),
StandardCharsets.UTF_8))));
}
@Test
void validateAdminAccessConnectivityFail() {
httpServer.stubFor(get(urlEqualTo("/login")).willReturn(aResponse().withStatus(HttpStatus.SC_BAD_GATEWAY)));
httpServer.start();
MatcherUtil.assertThrows(Assertions.assertThrows(ValidationJsonException.class, () -> {
resource.validateAdminAccess(pvResource.getNodeParameters("service:build:jenkins:bpr"));
}), JenkinsPluginResource.PARAMETER_URL, "jenkins-connection");
}
@Test
void validateAdminAccessLoginFail() {
httpServer.stubFor(get(urlEqualTo("/login")).willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
httpServer.stubFor(get(urlEqualTo("/api/xml")).willReturn(aResponse().withStatus(HttpStatus.SC_BAD_GATEWAY)));
httpServer.start();
MatcherUtil.assertThrows(Assertions.assertThrows(ValidationJsonException.class, () -> {
resource.validateAdminAccess(pvResource.getNodeParameters("service:build:jenkins:bpr"));
}), JenkinsPluginResource.PARAMETER_USER, "jenkins-login");
}
@Test
void validateAdminAccessNoRight() throws IOException {
addLoginAccess();
httpServer.stubFor(get(urlEqualTo("/computer/(master)/config.xml"))
.willReturn(aResponse().withStatus(HttpStatus.SC_BAD_GATEWAY)));
httpServer.start();
MatcherUtil.assertThrows(Assertions.assertThrows(ValidationJsonException.class, () -> {
resource.validateAdminAccess(pvResource.getNodeParameters("service:build:jenkins:bpr"));
}), JenkinsPluginResource.PARAMETER_USER, "jenkins-rights");
}
@Test
void findAllByName() throws IOException, SAXException, ParserConfigurationException {
httpServer.stubFor(get(urlPathEqualTo("/api/xml")).willReturn(aResponse().withStatus(HttpStatus.SC_OK)
.withBody(IOUtils.toString(
new ClassPathResource("mock-server/jenkins/jenkins-api-xml-tree.xml").getInputStream(),
StandardCharsets.UTF_8))));
httpServer.start();
final List<Job> jobs = resource.findAllByName("service:build:jenkins:bpr", "ligoj");
checkAll(jobs);
}
private void checkAll(final List<Job> jobs) {
Assertions.assertEquals(29, jobs.size());
Assertions.assertEquals("Ligoj - Cron - SSE", jobs.get(6).getName());
Assertions.assertEquals("CRON - Projet SSE", jobs.get(6).getDescription());
Assertions.assertEquals("ligoj-cron-sse", jobs.get(6).getId());
Assertions.assertEquals("disabled", jobs.get(6).getStatus());
}
@Test
void findAllTemplateByName() throws IOException, SAXException, ParserConfigurationException {
httpServer.stubFor(
get(urlPathEqualTo("/view/Templates/api/xml")).willReturn(aResponse().withStatus(HttpStatus.SC_OK)
.withBody(IOUtils.toString(
new ClassPathResource("mock-server/jenkins/jenkins-api-xml-tree.xml").getInputStream(),
StandardCharsets.UTF_8))));
httpServer.start();
final List<Job> jobs = resource.findAllTemplateByName("service:build:jenkins:bpr", "ligoj");
checkAll(jobs);
}
/**
* Bad credential
*/
@Test
void findAllByNameFailed() throws IOException, SAXException, ParserConfigurationException {
httpServer.stubFor(get(urlPathEqualTo("/api/xml"))
.willReturn(aResponse().withStatus(HttpStatus.SC_UNAUTHORIZED).withBody("<html>FORBIDDEN</html>")));
httpServer.start();
Assertions.assertEquals(0, resource.findAllByName("service:build:jenkins:bpr", "ligoj").size());
}
@Test
void findById() throws IOException, URISyntaxException {
addJobAccessBuilding();
httpServer.start();
checkJob(resource.findById("service:build:jenkins:bpr", "ligoj-bootstrap"), true);
}
@Test
void findByIdFail() {
httpServer.stubFor(get(urlEqualTo(
"/api/xml?depth=1&tree=jobs[displayName,name,color]&xpath=hudson/job[name='ligoj-bootstraps']&wrapper=hudson"))
.willReturn(aResponse().withStatus(HttpStatus.SC_OK).withBody("<hudson/>")));
httpServer.start();
MatcherUtil.assertThrows(Assertions.assertThrows(ValidationJsonException.class, () -> {
resource.findById("service:build:jenkins:bpr", "ligoj-bootstraps");
}), "service:build:jenkins:job", "jenkins-job");
}
private void addLoginAccess() throws IOException {
httpServer.stubFor(get(urlEqualTo("/login")).willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
httpServer.stubFor(get(urlEqualTo("/api/xml")).willReturn(aResponse().withStatus(HttpStatus.SC_OK)
.withBody(IOUtils.toString(
new ClassPathResource("mock-server/jenkins/jenkins-api-xml.xml").getInputStream(),
StandardCharsets.UTF_8))));
}
@Test
void create() throws IOException, URISyntaxException {
addLoginAccess();
addAdminAccess();
// retrieve template config.xml
httpServer.stubFor(get(urlEqualTo("/job/template/config.xml")).willReturn(aResponse()
.withStatus(HttpStatus.SC_OK)
.withBody(IOUtils.toString(
new ClassPathResource("mock-server/jenkins/jenkins-template-config.xml").getInputStream(),
StandardCharsets.UTF_8))));
// post new job config.xml
httpServer.stubFor(post(urlEqualTo("/createItem?name=ligoj-bootstrap"))
.withRequestBody(WireMock.containing("fdaugan@sample.com"))
.withRequestBody(WireMock.containing("<disabled>false</disabled>"))
.willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
httpServer.start();
// prepare new subscription
final Subscription subscription = em.find(Subscription.class, this.subscription);
createParameterValueTemplateJob(subscription);
this.resource.create(this.subscription);
}
@Test
void createFailed() throws IOException {
addLoginAccess();
addAdminAccess();
// retrieve template config.xml
httpServer.stubFor(get(urlEqualTo("/job/template/config.xml")).willReturn(aResponse()
.withStatus(HttpStatus.SC_OK)
.withBody(IOUtils.toString(
new ClassPathResource("mock-server/jenkins/jenkins-template-config.xml").getInputStream(),
StandardCharsets.UTF_8))));
// post new job config.xml
httpServer.stubFor(post(urlEqualTo("/createItem?name=ligoj-bootstrap"))
.willReturn(aResponse().withStatus(HttpStatus.SC_BAD_REQUEST)));
httpServer.start();
// prepare new subscription
final Subscription subscription = em.find(Subscription.class, this.subscription);
createParameterValueTemplateJob(subscription);
Assertions.assertThrows(BusinessException.class, () -> {
this.resource.create(this.subscription);
});
}
/**
* create a parameter value for template Job definition
*
* @param subscription
* future parameter value linked subscription
*/
private void createParameterValueTemplateJob(final Subscription subscription) {
final ParameterValue parameterValue = new ParameterValue();
parameterValue.setParameter(em.find(Parameter.class, "service:build:jenkins:template-job"));
parameterValue.setSubscription(subscription);
parameterValue.setData("template");
em.persist(parameterValue);
em.flush();
}
@Test
void buildFailed() throws IOException {
addLoginAccess();
addAdminAccess();
httpServer.start();
Assertions.assertThrows(BusinessException.class, () -> {
this.resource.build(subscription);
});
}
@Test
void build() throws IOException {
addLoginAccess();
addAdminAccess();
httpServer.stubFor(
post(urlEqualTo("/job/ligoj-bootstrap/build")).willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
httpServer.start();
this.resource.build(subscription);
}
@Test
void buildInvalidUrl() {
@SuppressWarnings("unchecked")
final Map<String, String> map = Mockito.mock(Map.class);
Mockito.when(map.get(JenkinsPluginResource.PARAMETER_USER)).thenReturn("some");
Mockito.when(map.get(JenkinsPluginResource.PARAMETER_TOKEN)).thenReturn("some");
Mockito.when(map.get(JenkinsPluginResource.PARAMETER_URL)).thenThrow(new RuntimeException());
Assertions.assertThrows(RuntimeException.class, () -> {
this.resource.build(map, null);
});
}
@Test
void buildParameters() throws IOException {
addLoginAccess();
addAdminAccess();
httpServer.stubFor(post(urlEqualTo("/job/ligoj-bootstrap/build"))
.willReturn(aResponse().withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
httpServer.stubFor(post(urlEqualTo("/job/ligoj-bootstrap/buildWithParameters"))
.willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
httpServer.start();
this.resource.build(subscription);
}
}
| 37.201942 | 115 | 0.764654 |
052fe1db0bdd15f4f08f5b6ace99de79bd6ba7e3 | 11,384 | package com.sunnsoft.sloa.actions.app.received;
import com.sunnsoft.sloa.actions.common.BaseParameter;
import com.sunnsoft.sloa.db.handler.Services;
import com.sunnsoft.sloa.db.vo.AttachmentItem;
import com.sunnsoft.sloa.db.vo.Mail;
import com.sunnsoft.sloa.db.vo.Receive;
import com.sunnsoft.sloa.helper.ReceiveHelper;
import com.sunnsoft.sloa.util.ConstantUtils;
import com.sunnsoft.util.PageUtils;
import com.sunnsoft.util.struts2.Results;
import org.gteam.db.helper.json.EachEntity2Map;
import org.springframework.util.Assert;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 收到传阅(PC端/APP端)---搜索:传阅关键词查询,全局模糊查询,包括主题、接收人,发起人、和传阅详情内容
*
* @author chenjian
*
*/
public class FindLikeList extends BaseParameter {
private static final long serialVersionUID = 1L;
private long userId; // 收件人Id(也是当前用户)
private String likeName; // 客户端传过来的(用户输入的)
private int status; // 0 无状态 1 传阅中 2 待办传阅 3 已完成 4 未读 5 已读 6 我的关注 (默认为 0)
private Integer page; // 当前页
private Integer pageRows; // 每页几条记录数
@Override
public String execute() throws Exception {
// 校验参数
Assert.notNull(userId, "收件人ID不能为空!");
Assert.notNull(status, "状态, 不能为空!");
// 设置默认参数
page = PageUtils.defaultPageNumber(page); // 1
pageRows = PageUtils.defaultPageSize(pageRows); // 10
ReceiveHelper helper = Services.getReceiveService().createHelper().getUserId().Eq(userId);
// 选择状态
switch (status) {
case 0: // 表示 展示所有收到的传阅
helper.getMailState().Ne(ConstantUtils.RECEIVE_WAIT_STATUS);
helper.enterMail().getEnabled().Eq(Boolean.FALSE).getStepStatus().In(1,3).ignoreEmptyValueCondiction()
.startOr().getTitle().Like(likeName).getAllReceiveName().Like(likeName)
.getLastName().Like(likeName).getMailContent().Like(likeName).stopOr()
.back2Receives();
break;
case 1: // 1 传阅中
helper.getStepStatus().Eq(ConstantUtils.MAIL_HALFWAY_STATUS);
break;
case 2: // 待办传阅
helper.getStepStatus().Eq(ConstantUtils.RECEIVE_AWAIT_STATUS);
break;
case 3: // 已完成
helper.getStepStatus().Eq(ConstantUtils.MAIL_COMPLETE_STATUS);
break;
case 5: // 未读
helper.getMailState().Eq(ConstantUtils.RECEIVE_UNREAD_STATUS);
break;
case 6: //已确认
helper.getStepStatus().Eq(ConstantUtils.MAIL_HALFWAY_STATUS);
break;
}
json = helper.json().listPageJson(page, pageRows, new EachEntity2Map<Receive>() {
@Override
public void each(Receive receive, Map<String, Object> map) {
map.clear();
map.put("receiveStepStatus", receive.getStepStatus());
map.put("receiveMailState", receive.getMailState());
map.put("receiveAttention", receive.getReceiveAttention());
map.put("receiveTime", receive.getReceiveTime());
map.put("receiveJoinTime", receive.getJoinTime());
Mail mail = receive.getMail();
map.put("mailId", mail.getMailId());
map.put("userId", mail.getUserId());
map.put("lastName", mail.getLastName());
map.put("loginId", mail.getLoginId());
map.put("subcompanyName", mail.getSubcompanyName());
map.put("departmentName", mail.getDepartmentName());
map.put("allReceiveName", mail.getAllReceiveName());
map.put("title", mail.getTitle());
map.put("mailContent", mail.getMailContent());
map.put("createTime", mail.getCreateTime());
map.put("sendTime", mail.getSendTime());
map.put("status", mail.getStatus());
map.put("stepStatus", mail.getStepStatus());
map.put("completeTime", mail.getCompleteTime());
map.put("hasAttachment", mail.getHasAttachment());
map.put("enabled", mail.isEnabled());
map.put("attention", mail.getAttention());
map.put("ruleName", mail.getRuleName());
map.put("deleteTime", mail.getDeleteTime());
map.put("ifAdd", mail.getIfAdd());
map.put("ifImportant", mail.getIfImportant());
map.put("ifNotify", mail.getIfNotify());
map.put("ifRead", mail.getIfRead());
map.put("ifRemind", mail.getIfRemind());
map.put("ifRemindAll", mail.getIfRemindAll());
map.put("ifSecrecy", mail.getIfSecrecy());
map.put("ifSequence", mail.getIfSequence());
map.put("ifUpdate", mail.getIfUpdate());
map.put("ifUpload", mail.getIfUpload());
List<AttachmentItem> attachmentItems = mail.getAttachmentItems();
List<Map<String, Object>> itemList = new ArrayList<>();
for (AttachmentItem attachmentItem : attachmentItems) {
Map<String, Object> itemMap = new HashMap<>();
itemMap.put("itemId", attachmentItem.getItemId());
itemMap.put("userId", attachmentItem.getUserId());
itemMap.put("reator", attachmentItem.getCreator());
itemMap.put("bulkId", attachmentItem.getBulkId());
itemMap.put("createTime", attachmentItem.getCreateTime());
itemMap.put("fileName", attachmentItem.getFileName());
itemMap.put("fileCategory", attachmentItem.getFileCategory());
itemMap.put("saveName", attachmentItem.getSaveName());
itemMap.put("urlPath", attachmentItem.getUrlPath());
itemMap.put("state", attachmentItem.getState());
itemMap.put("itemSize", attachmentItem.getItemSize());
itemMap.put("itemNeid", attachmentItem.getItemNeid());
itemMap.put("itemRev", attachmentItem.getItemRev());
itemList.add(itemMap);
}
map.put("attachmentItemss", itemList);
}
});
try {
if (json != null) {
success = true;
msg = "查询收到传阅成功";
code = "200";
return Results.GLOBAL_FORM_JSON;
} else {
success = true;
msg = "查询收到传阅成功";
code = "200";
return Results.GLOBAL_FORM_JSON;
}
} catch (Exception e) {
success = false;
msg = "网络繁忙!";
code = "404";
json = "null";
return Results.GLOBAL_FORM_JSON;
}
}
/**
* 设置开始时间 和 结束时间 以及 日期转换的格式
*
* @return
public String getDateTime() {
String timeStr = "";
if (startTime != null && endTime != null) {
startTime += " 00:00:00";
endTime += " 23:59:59";
timeStr = "yyyy-MM-dd HH:mm:ss";
}
return timeStr;
}*/
/**
* 字符串转换成日期
*
* @param str
* @return date
*/
public Date StrToDate(String str, String timeStr) {
SimpleDateFormat format = new SimpleDateFormat(timeStr);
Date date = null;
try {
date = format.parse(str);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
public String getMailStatus() {
ReceiveHelper helper = Services.getMailService().createHelper().ignoreEmptyValueCondiction().enterReceives()
.getUserId().Eq(userId).getMailState().Eq(status);
/*// 进行判断
if (startTime != null) {
// 设置开始时间 和 结束时间 以及 日期转换的格式
String timeStr = getDateTime();
helper.getReceiveTime().Ge(StrToDate(startTime, timeStr)).getReceiveTime().Le(StrToDate(endTime, timeStr));
}*/
// 分页查询
json = helper.getReceiveTime().Desc().back2Mail().startOr().getTitle().Like(likeName)
.getAllReceiveName().Like(likeName).getLastName().Like(likeName).getMailContent().Like(likeName)
.stopOr().json().listPageJson(page, pageRows, new EachEntity2Map<Mail>() {
@Override
public void each(Mail mail, Map<String, Object> map) {
List<AttachmentItem> attachmentItems = mail.getAttachmentItems();
List<Map<String, Object>> itemList = new ArrayList<>();
for (AttachmentItem attachmentItem : attachmentItems) {
Map<String, Object> itemMap = new HashMap<>();
itemMap.put("itemId", attachmentItem.getItemId());
itemMap.put("userId", attachmentItem.getUserId());
itemMap.put("reator", attachmentItem.getCreator());
itemMap.put("bulkId", attachmentItem.getBulkId());
itemMap.put("createTime", attachmentItem.getCreateTime());
itemMap.put("fileName", attachmentItem.getFileName());
itemMap.put("fileCategory", attachmentItem.getFileCategory());
itemMap.put("saveName", attachmentItem.getSaveName());
itemMap.put("urlPath", attachmentItem.getUrlPath());
itemMap.put("state", attachmentItem.getState());
itemMap.put("itemSize", attachmentItem.getItemSize());
itemMap.put("itemNeid", attachmentItem.getItemNeid());
itemMap.put("itemRev", attachmentItem.getItemRev());
itemList.add(itemMap);
}
map.put("attachmentItemss", itemList);
List<Receive> receives = mail.getReceives();
for (Receive receive : receives) {
if (receive.getUserId() == userId) {
map.put("receiveStepStatus", receive.getStepStatus());
map.put("receiveMailState", receive.getMailState());
map.put("receiveAttention", receive.getReceiveAttention());
}
}
}
});
return json;
}
public String getReceiveList() {
ReceiveHelper helper = Services.getMailService().createHelper().ignoreEmptyValueCondiction().enterReceives()
.getUserId().Eq(userId).getStepStatus().Eq(status);
// 进行判断
/*if (startTime != null) {
// 设置开始时间 和 结束时间 以及 日期转换的格式
String timeStr = getDateTime();
helper.getReceiveTime().Ge(StrToDate(startTime, timeStr)).getReceiveTime().Le(StrToDate(endTime, timeStr));
}*/
// 分页查询
json = helper.getReceiveTime().Desc().back2Mail().startOr().getTitle().Like(likeName).getAllReceiveName()
.Like(likeName).getLastName().Like(likeName).getMailContent().Like(likeName).stopOr().json()
.listPageJson(page, pageRows, new EachEntity2Map<Mail>() {
@Override
public void each(Mail mail, Map<String, Object> map) {
List<AttachmentItem> attachmentItems = mail.getAttachmentItems();
List<Map<String, Object>> itemList = new ArrayList<>();
for (AttachmentItem attachmentItem : attachmentItems) {
Map<String, Object> itemMap = new HashMap<>();
itemMap.put("itemId", attachmentItem.getItemId());
itemMap.put("userId", attachmentItem.getUserId());
itemMap.put("reator", attachmentItem.getCreator());
itemMap.put("bulkId", attachmentItem.getBulkId());
itemMap.put("createTime", attachmentItem.getCreateTime());
itemMap.put("fileName", attachmentItem.getFileName());
itemMap.put("fileCategory", attachmentItem.getFileCategory());
itemMap.put("saveName", attachmentItem.getSaveName());
itemMap.put("urlPath", attachmentItem.getUrlPath());
itemMap.put("state", attachmentItem.getState());
itemMap.put("itemSize", attachmentItem.getItemSize());
itemMap.put("itemNeid", attachmentItem.getItemNeid());
itemMap.put("itemRev", attachmentItem.getItemRev());
itemList.add(itemMap);
}
map.put("attachmentItemss", itemList);
List<Receive> receives = mail.getReceives();
for (Receive receive : receives) {
if (receive.getUserId() == userId) {
map.put("receiveStepStatus", receive.getStepStatus());
map.put("receiveMailState", receive.getMailState());
map.put("receiveAttention", receive.getReceiveAttention());
}
}
}
});
return json;
}
public String getLikeName() {
return likeName;
}
public void setLikeName(String likeName) {
this.likeName = likeName;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getPageRows() {
return pageRows;
}
public void setPageRows(Integer pageRows) {
this.pageRows = pageRows;
}
}
| 30.850949 | 110 | 0.679375 |
6df32be9f29f5b846102766dd7b3fdd3e6ed8e7d | 7,457 | package com.purbon.kafka.topology;
import static org.mockito.Matchers.anyCollection;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import com.purbon.kafka.topology.api.adminclient.TopologyBuilderAdminClient;
import com.purbon.kafka.topology.model.Impl.ProjectImpl;
import com.purbon.kafka.topology.model.Impl.TopicImpl;
import com.purbon.kafka.topology.model.Impl.TopologyImpl;
import com.purbon.kafka.topology.model.Platform;
import com.purbon.kafka.topology.model.Project;
import com.purbon.kafka.topology.model.Topic;
import com.purbon.kafka.topology.model.Topology;
import com.purbon.kafka.topology.model.User;
import com.purbon.kafka.topology.model.users.Connector;
import com.purbon.kafka.topology.model.users.Consumer;
import com.purbon.kafka.topology.model.users.KStream;
import com.purbon.kafka.topology.model.users.Producer;
import com.purbon.kafka.topology.model.users.platform.ControlCenter;
import com.purbon.kafka.topology.model.users.platform.ControlCenterInstance;
import com.purbon.kafka.topology.model.users.platform.SchemaRegistry;
import com.purbon.kafka.topology.model.users.platform.SchemaRegistryInstance;
import com.purbon.kafka.topology.roles.SimpleAclsProvider;
import com.purbon.kafka.topology.roles.acls.AclsBindingsBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.CreateAclsResult;
import org.apache.kafka.common.KafkaFuture;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class TopologyBuilderAdminClientTest {
@Mock CreateAclsResult createAclsResult;
@Mock KafkaFuture<Void> kafkaFuture;
@Mock AdminClient kafkaAdminClient;
@Mock TopologyBuilderConfig config;
TopologyBuilderAdminClient adminClient;
private SimpleAclsProvider aclsProvider;
private AclsBindingsBuilder bindingsBuilder;
private ExecutionPlan plan;
@Mock BackendController backendController;
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
private AccessControlManager accessControlManager;
@Before
public void setup() throws ExecutionException, InterruptedException, IOException {
adminClient = new TopologyBuilderAdminClient(kafkaAdminClient);
aclsProvider = new SimpleAclsProvider(adminClient);
bindingsBuilder = new AclsBindingsBuilder(config);
accessControlManager = new AccessControlManager(aclsProvider, bindingsBuilder);
plan = ExecutionPlan.init(backendController, System.out);
doNothing().when(backendController).add(Matchers.anyList());
doNothing().when(backendController).flushAndClose();
doReturn("foo").when(config).getConfluentCommandTopic();
doReturn("foo").when(config).getConfluentMetricsTopic();
doReturn("foo").when(config).getConfluentMonitoringTopic();
doReturn(new Object()).when(kafkaFuture).get();
doReturn(kafkaFuture).when(createAclsResult).all();
doReturn(createAclsResult).when(kafkaAdminClient).createAcls(anyCollection());
}
@Test
public void newConsumerACLsCreation() throws IOException {
List<Consumer> consumers = new ArrayList<>();
consumers.add(new Consumer("User:app1"));
Project project = new ProjectImpl();
project.setConsumers(consumers);
Topic topicA = new TopicImpl("topicA");
project.addTopic(topicA);
Topology topology = new TopologyImpl();
topology.addProject(project);
accessControlManager.apply(topology, plan);
plan.run();
verify(kafkaAdminClient, times(1)).createAcls(anyCollection());
}
@Test
public void newProducerACLsCreation() throws IOException {
List<Producer> producers = new ArrayList<>();
producers.add(new Producer("User:app1"));
Project project = new ProjectImpl();
project.setProducers(producers);
Topic topicA = new TopicImpl("topicA");
project.addTopic(topicA);
Topology topology = new TopologyImpl();
topology.addProject(project);
accessControlManager.apply(topology, plan);
plan.run();
verify(kafkaAdminClient, times(1)).createAcls(anyCollection());
}
@Test
public void newKafkaStreamsAppACLsCreation() throws IOException {
Project project = new ProjectImpl();
KStream app = new KStream();
app.setPrincipal("User:App0");
HashMap<String, List<String>> topics = new HashMap<>();
topics.put(KStream.READ_TOPICS, Arrays.asList("topicA", "topicB"));
topics.put(KStream.WRITE_TOPICS, Arrays.asList("topicC", "topicD"));
app.setTopics(topics);
project.setStreams(Collections.singletonList(app));
Topology topology = new TopologyImpl();
topology.addProject(project);
accessControlManager.apply(topology, plan);
plan.run();
verify(kafkaAdminClient, times(1)).createAcls(anyCollection());
}
@Test
public void newSchemaRegistryACLCreation() throws IOException {
Project project = new ProjectImpl();
Topology topology = new TopologyImpl();
topology.addProject(project);
Platform platform = new Platform();
SchemaRegistry sr = new SchemaRegistry();
SchemaRegistryInstance instance = new SchemaRegistryInstance();
instance.setPrincipal("User:foo");
sr.setInstances(Collections.singletonList(instance));
Map<String, List<User>> rbac = new HashMap<>();
rbac.put("SecurityAdmin", Collections.singletonList(new User("User:foo")));
rbac.put("ClusterAdmin", Collections.singletonList(new User("User:bar")));
sr.setRbac(Optional.of(rbac));
platform.setSchemaRegistry(sr);
topology.setPlatform(platform);
accessControlManager.apply(topology, plan);
plan.run();
verify(kafkaAdminClient, times(1)).createAcls(anyCollection());
}
@Test
public void newControlCenterACLCreation() throws IOException {
Project project = new ProjectImpl();
Topology topology = new TopologyImpl();
topology.addProject(project);
Platform platform = new Platform();
ControlCenter c3 = new ControlCenter();
ControlCenterInstance instance = new ControlCenterInstance();
instance.setPrincipal("User:foo");
instance.setAppId("appid");
c3.setInstances(Collections.singletonList(instance));
platform.setControlCenter(c3);
topology.setPlatform(platform);
accessControlManager.apply(topology, plan);
plan.run();
verify(kafkaAdminClient, times(1)).createAcls(anyCollection());
}
@Test
public void newKafkaConnectACLsCreation() throws IOException {
Project project = new ProjectImpl();
Connector connector1 = new Connector();
connector1.setPrincipal("User:Connect1");
HashMap<String, List<String>> topics = new HashMap<>();
topics.put(Connector.READ_TOPICS, Arrays.asList("topicA", "topicB"));
connector1.setTopics(topics);
project.setConnectors(Arrays.asList(connector1));
Topology topology = new TopologyImpl();
topology.addProject(project);
accessControlManager.apply(topology, plan);
plan.run();
verify(kafkaAdminClient, times(1)).createAcls(anyCollection());
}
}
| 33.59009 | 84 | 0.759689 |
8c705ed1a7ff13905216574cf836171b1872f57a | 690 | package com.hbgc.springbootdemo.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name="CATALOG")
@JsonIgnoreProperties
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Catalog extends BaseEntity implements Serializable,Cloneable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int cid;
@Column(length = 50)
private String id; //必须字符串,类别编号
@Column(length = 50)
private String cname; //类名名称
@Column(length = 50)
private String pid; //父类的编号
}
| 21.5625 | 75 | 0.76087 |
9826d8c472ee55d45e9990538629aa1f8716073b | 3,438 | package org.jenkinsci.plugins.github.webhook.subscriber;
import com.cloudbees.jenkins.GitHubPushTrigger;
import hudson.model.FreeStyleProject;
import hudson.plugins.git.GitSCM;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.kohsuke.github.GHEvent;
import static com.cloudbees.jenkins.GitHubWebHookFullTest.classpath;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* @author lanwen (Merkushev Kirill)
*/
public class DefaultPushGHEventListenerTest {
public static final GitSCM GIT_SCM_FROM_RESOURCE = new GitSCM("ssh://git@github.com/lanwen/test.git");
public static final String TRIGGERED_BY_USER_FROM_RESOURCE = "lanwen";
@Rule
public JenkinsRule jenkins = new JenkinsRule();
@Test
public void shouldBeNotApplicableForProjectWithoutTrigger() throws Exception {
FreeStyleProject prj = jenkins.createFreeStyleProject();
assertThat(new DefaultPushGHEventSubscriber().isApplicable(prj), is(false));
}
@Test
public void shouldBeApplicableForProjectWithTrigger() throws Exception {
FreeStyleProject prj = jenkins.createFreeStyleProject();
prj.addTrigger(new GitHubPushTrigger());
assertThat(new DefaultPushGHEventSubscriber().isApplicable(prj), is(true));
}
@Test
public void shouldParsePushPayload() throws Exception {
GitHubPushTrigger trigger = mock(GitHubPushTrigger.class);
FreeStyleProject prj = jenkins.createFreeStyleProject();
prj.addTrigger(trigger);
prj.setScm(GIT_SCM_FROM_RESOURCE);
new DefaultPushGHEventSubscriber()
.onEvent(GHEvent.PUSH, classpath("payloads/push.json"));
verify(trigger).onPost(TRIGGERED_BY_USER_FROM_RESOURCE);
}
@Test
@Issue("JENKINS-27136")
public void shouldReceivePushHookOnWorkflow() throws Exception {
WorkflowJob job = jenkins.getInstance().createProject(WorkflowJob.class, "test-workflow-job");
GitHubPushTrigger trigger = mock(GitHubPushTrigger.class);
job.addTrigger(trigger);
job.setDefinition(new CpsFlowDefinition(classpath(getClass(), "workflow-definition.groovy")));
// Trigger the build once to register SCMs
jenkins.assertBuildStatusSuccess(job.scheduleBuild2(0));
new DefaultPushGHEventSubscriber()
.onEvent(GHEvent.PUSH, classpath("payloads/push.json"));
verify(trigger).onPost(TRIGGERED_BY_USER_FROM_RESOURCE);
}
@Test
@Issue("JENKINS-27136")
public void shouldNotReceivePushHookOnWorkflowWithNoBuilds() throws Exception {
WorkflowJob job = jenkins.getInstance().createProject(WorkflowJob.class, "test-workflow-job");
GitHubPushTrigger trigger = mock(GitHubPushTrigger.class);
job.addTrigger(trigger);
job.setDefinition(new CpsFlowDefinition(classpath(getClass(), "workflow-definition.groovy")));
new DefaultPushGHEventSubscriber()
.onEvent(GHEvent.PUSH, classpath("payloads/push.json"));
verify(trigger, never()).onPost(TRIGGERED_BY_USER_FROM_RESOURCE);
}
}
| 37.78022 | 106 | 0.739674 |
ed24621650f12dd0e82ae8d167637ee480b15695 | 1,514 |
package com.gupao.edu.vip.lion.common.router;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Created by ohun on 2016/1/4.
*
* @author ohun@live.cn (夜色)
*/
public final class CachedRemoteRouterManager extends RemoteRouterManager {
private final Cache<String, Set<RemoteRouter>> cache = CacheBuilder
.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.expireAfterAccess(5, TimeUnit.MINUTES)
.build();
@Override
public Set<RemoteRouter> lookupAll(String userId) {
Set<RemoteRouter> cached = cache.getIfPresent(userId);
if (cached != null) return cached;
Set<RemoteRouter> remoteRouters = super.lookupAll(userId);
if (remoteRouters != null) {
cache.put(userId, remoteRouters);
}
return remoteRouters;
}
@Override
public RemoteRouter lookup(String userId, int clientType) {
Set<RemoteRouter> cached = this.lookupAll(userId);
for (RemoteRouter remoteRouter : cached) {
if (remoteRouter.getRouteValue().getClientType() == clientType) {
return remoteRouter;
}
}
return null;
}
/**
* 如果推送失败,可能是缓存不一致了,可以让本地缓存失效
* <p>
* 失效对应的本地缓存
*
* @param userId
*/
public void invalidateLocalCache(String userId) {
if (userId != null) cache.invalidate(userId);
}
}
| 27.527273 | 77 | 0.630779 |
c5a3e49bdea9e3f209a2cd40e92712c98a70efd1 | 1,092 | package io.acari.intro;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Forged in the flames of battle by alex.
*/
public class CommonCharacterCounterTest {
CommonCharacterCounter commonCharacterCounter = new CommonCharacterCounter();
@Test
public void commonCharacterCountOne() throws Exception {
assertEquals(3, commonCharacterCounter.commonCharacterCount("aabcc", "adcaa"));
}
@Test
public void commonCharacterCountTwo() throws Exception {
assertEquals(4, commonCharacterCounter.commonCharacterCount("zzzz", "zzzzzz"));
}
@Test
public void commonCharacterCountThree() throws Exception {
assertEquals(3, commonCharacterCounter.commonCharacterCount("abca", "xfzbac"));
}
@Test
public void commonCharacterCountFour() throws Exception {
assertEquals(0, commonCharacterCounter.commonCharacterCount("a", "b"));
}
@Test
public void commonCharacterCountFive() throws Exception {
assertEquals(1, commonCharacterCounter.commonCharacterCount("a", "aaa"));
}
} | 28.736842 | 87 | 0.720696 |
fb75cfa42c9ed2396397b4ff29e2feb46999f76e | 13,942 | package com.ksp.subitesv.actividades.conductor;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import com.ksp.subitesv.R;
import com.ksp.subitesv.actividades.MainActivity;
import com.ksp.subitesv.actividades.cliente.ActualizarPerfilActivity;
import com.ksp.subitesv.actividades.cliente.HistorialReservaClienteActivity;
import com.ksp.subitesv.actividades.cliente.MapClienteActivity;
import com.ksp.subitesv.includes.AppToolBar;
import com.ksp.subitesv.proveedores.AuthProveedores;
import com.ksp.subitesv.proveedores.ProveedorGeoFire;
import com.ksp.subitesv.proveedores.TokenProveedor;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MapaConductorActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private AuthProveedores mAuthProveedores;
private LocationRequest mLocationRequest;
private FusedLocationProviderClient mFusedLocation;
private ProveedorGeoFire mProveedorGeofire;
private TokenProveedor mTokenProveedor;
private final static int LOCATION_REQUEST_CODE = 1;
private final static int SETTINGS_REQUEST_CODE = 2;
private Marker mMarker;
private Button mButtonConectar;
private boolean misConnect = false;
private LatLng mLatLngActual;
private ValueEventListener mListener;
LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
if (getApplicationContext() != null) {
mLatLngActual = new LatLng(location.getLatitude(), location.getLongitude());
if (mMarker != null) {
mMarker.remove();
}
mMarker = mMap.addMarker(new MarkerOptions().position(
new LatLng(location.getLatitude(), location.getLongitude())
)
.title("Tu posicion")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_conductor))
);
//Obtener localizacion en tiempo real
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude()))
.zoom(15f)
.build()
));
actualizarUbicacion();
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa_conductor);
AppToolBar.mostrar(this, "Conductor", false);
mAuthProveedores = new AuthProveedores();
mProveedorGeofire = new ProveedorGeoFire("conductores_activos");
mTokenProveedor = new TokenProveedor();
mFusedLocation = LocationServices.getFusedLocationProviderClient(this);
SupportMapFragment mMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMapFragment.getMapAsync(this);
generarToken();
mButtonConectar = findViewById(R.id.btn_Conectar);
mButtonConectar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (misConnect) {
disconnect();
} else {
startLocation();
}
}
});
isConductorTrabajando();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mLocationCallback != null && mFusedLocation != null) {
mFusedLocation.removeLocationUpdates(mLocationCallback);
}
if (mListener!=null){
if (mAuthProveedores.sesionExistente()) {
mProveedorGeofire.isConductorTrabajando(mAuthProveedores.obetenerId()).removeEventListener(mListener);
}
}
}
private void isConductorTrabajando() {
mListener = mProveedorGeofire.isConductorTrabajando(mAuthProveedores.obetenerId()).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
disconnect();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void actualizarUbicacion() {
if (mAuthProveedores.sesionExistente() && mLatLngActual != null) {
mProveedorGeofire.guardarUbicacion(mAuthProveedores.obetenerId(), mLatLngActual);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(5);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (gpsActive()) {
mFusedLocation.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mMap.setMyLocationEnabled(true);
} else {
showAlertDialogGps();
}
} else {
checkLocationPermissions();
}
} else {
checkLocationPermissions();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SETTINGS_REQUEST_CODE && gpsActive()) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mFusedLocation.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mMap.setMyLocationEnabled(true);
} else {
showAlertDialogGps();
}
}
private void showAlertDialogGps() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Por favor activa tu ubicacion para continuar")
.setPositiveButton("Configuraciones", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), SETTINGS_REQUEST_CODE);
}
}).create().show();
}
private boolean gpsActive() {
boolean isActive = false;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
isActive = true;
}
return isActive;
}
private void disconnect() {
if (mFusedLocation != null) {
mButtonConectar.setText("Conectarse");
misConnect = false;
mFusedLocation.removeLocationUpdates(mLocationCallback);
if (mAuthProveedores.sesionExistente()) {
mProveedorGeofire.removerUbicacion(mAuthProveedores.obetenerId());
}
} else {
Toast.makeText(this, "No se puede desconectar", Toast.LENGTH_SHORT).show();
}
}
private void startLocation() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (gpsActive()) {
mButtonConectar.setText("Desconectarse");
misConnect = true;
mFusedLocation.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mMap.setMyLocationEnabled(true);
} else {
showAlertDialogGps();
}
} else {
checkLocationPermissions();
}
} else {
if (gpsActive()) {
mFusedLocation.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mMap.setMyLocationEnabled(true);
} else {
showAlertDialogGps();
}
}
}
private void checkLocationPermissions() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle("Proporciona los permisos para continuar")
.setMessage("Esta aplicacion requiere permisos de ubicacion para poder utilizarse")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MapaConductorActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(MapaConductorActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.conductor_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_cerrarSesion) {
cerrarSesion();
}
if (item.getItemId() == R.id.action_actualizar) {
Intent intent = new Intent(MapaConductorActivity.this, ActualizarPerfilConductorActivity.class);
startActivity(intent);
}
if (item.getItemId() == R.id.action_Historial) {
Intent intent = new Intent(MapaConductorActivity.this, HistorialReservaConductorActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
void cerrarSesion() {
disconnect();
mAuthProveedores.cerrarSesion();
Intent intent = new Intent(MapaConductorActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
void generarToken() {
mTokenProveedor.crear(mAuthProveedores.obetenerId());
}
} | 39.948424 | 263 | 0.650624 |
10c9beffc417f4220a9f3dcd62ed6221a54d765f | 3,263 | package yooco.uchain.uchainwallet.view.page.excitation;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import yooco.uchain.uchainwallet.data.bean.ExcitationBean;
import yooco.uchain.uchainwallet.data.bean.response.ResponseExcitation;
import yooco.uchain.uchainwallet.utils.UChainLog;
import yooco.uchain.uchainwallet.data.remote.INetCallback;
import yooco.uchain.uchainwallet.data.remote.OkHttpClientManager;
import yooco.uchain.uchainwallet.utils.GsonUtils;
import yooco.uchain.uchainwallet.utils.PhoneUtils;
public class GetExcitation implements Runnable, INetCallback {
private static final String TAG = GetExcitation.class.getSimpleName();
private String mAddress;
private IGetExcitationCallback mIGetExcitationCallback;
public GetExcitation(String mAddress, IGetExcitationCallback iGetExcitationCallback) {
this.mAddress = mAddress;
this.mIGetExcitationCallback = iGetExcitationCallback;
}
@Override
public void run() {
if (TextUtils.isEmpty(mAddress) || null == mIGetExcitationCallback) {
UChainLog.e(TAG, "run() -> mAddress or mIGetExcitationCallback is null!");
return;
}
OkHttpClientManager.getInstance().get(mAddress, this);
}
@Override
public void onSuccess(int statusCode, String msg, String result) {
UChainLog.i(TAG, "result:" + result);
List<ExcitationBean> excitationBeans = new ArrayList<>();
if (TextUtils.isEmpty(result)) {
UChainLog.i(TAG, "result == null ");
mIGetExcitationCallback.getExcitation(null);
return;
}
ResponseExcitation responseExcitation = GsonUtils.json2Bean(result, ResponseExcitation.class);
if (null == responseExcitation) {
UChainLog.i(TAG, "responseExcitation is null ");
mIGetExcitationCallback.getExcitation(null);
return;
}
List<ResponseExcitation.DataBean> datas = responseExcitation.getData();
if (null == datas || datas.isEmpty()) {
UChainLog.i(TAG, "ResponseExcitation.DataBean is null ");
mIGetExcitationCallback.getExcitation(null);
return;
}
for (ResponseExcitation.DataBean data : datas) {
ExcitationBean excitationBean = new ExcitationBean();
excitationBean.setEventNew(data.getNew_flag() == 1);
excitationBean.setNewEventPic(data.getImagesurl());
if (PhoneUtils.getAppLanguage().contains(Locale.CHINA.toString())) {
excitationBean.setNewEventText(data.getTitle_cn());
} else {
excitationBean.setNewEventText(data.getTitle_en());
}
excitationBean.setNewEventStatus(data.getStatus());
excitationBean.setGasLimit(data.getGas_limit());
excitationBean.setActivityId(data.getId());
excitationBeans.add(excitationBean);
}
mIGetExcitationCallback.getExcitation(excitationBeans);
}
@Override
public void onFailed(int failedCode, String msg) {
UChainLog.e(TAG, "onFailed() -> msg:" + msg);
mIGetExcitationCallback.getExcitation(null);
}
}
| 35.467391 | 102 | 0.680049 |
315615b8b87383e0af4aa75ee1d0af3c8cb9a5cc | 9,448 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.logic.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.annotation.JsonFlatten;
import com.azure.core.management.Resource;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.logic.models.AgreementContent;
import com.azure.resourcemanager.logic.models.AgreementType;
import com.azure.resourcemanager.logic.models.BusinessIdentity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
import java.util.Map;
/** The integration account agreement. */
@JsonFlatten
@Fluent
public class IntegrationAccountAgreementInner extends Resource {
@JsonIgnore private final ClientLogger logger = new ClientLogger(IntegrationAccountAgreementInner.class);
/*
* The created time.
*/
@JsonProperty(value = "properties.createdTime", access = JsonProperty.Access.WRITE_ONLY)
private OffsetDateTime createdTime;
/*
* The changed time.
*/
@JsonProperty(value = "properties.changedTime", access = JsonProperty.Access.WRITE_ONLY)
private OffsetDateTime changedTime;
/*
* The metadata.
*/
@JsonProperty(value = "properties.metadata")
private Object metadata;
/*
* The agreement type.
*/
@JsonProperty(value = "properties.agreementType", required = true)
private AgreementType agreementType;
/*
* The integration account partner that is set as host partner for this
* agreement.
*/
@JsonProperty(value = "properties.hostPartner", required = true)
private String hostPartner;
/*
* The integration account partner that is set as guest partner for this
* agreement.
*/
@JsonProperty(value = "properties.guestPartner", required = true)
private String guestPartner;
/*
* The business identity of the host partner.
*/
@JsonProperty(value = "properties.hostIdentity", required = true)
private BusinessIdentity hostIdentity;
/*
* The business identity of the guest partner.
*/
@JsonProperty(value = "properties.guestIdentity", required = true)
private BusinessIdentity guestIdentity;
/*
* The agreement content.
*/
@JsonProperty(value = "properties.content", required = true)
private AgreementContent content;
/**
* Get the createdTime property: The created time.
*
* @return the createdTime value.
*/
public OffsetDateTime createdTime() {
return this.createdTime;
}
/**
* Get the changedTime property: The changed time.
*
* @return the changedTime value.
*/
public OffsetDateTime changedTime() {
return this.changedTime;
}
/**
* Get the metadata property: The metadata.
*
* @return the metadata value.
*/
public Object metadata() {
return this.metadata;
}
/**
* Set the metadata property: The metadata.
*
* @param metadata the metadata value to set.
* @return the IntegrationAccountAgreementInner object itself.
*/
public IntegrationAccountAgreementInner withMetadata(Object metadata) {
this.metadata = metadata;
return this;
}
/**
* Get the agreementType property: The agreement type.
*
* @return the agreementType value.
*/
public AgreementType agreementType() {
return this.agreementType;
}
/**
* Set the agreementType property: The agreement type.
*
* @param agreementType the agreementType value to set.
* @return the IntegrationAccountAgreementInner object itself.
*/
public IntegrationAccountAgreementInner withAgreementType(AgreementType agreementType) {
this.agreementType = agreementType;
return this;
}
/**
* Get the hostPartner property: The integration account partner that is set as host partner for this agreement.
*
* @return the hostPartner value.
*/
public String hostPartner() {
return this.hostPartner;
}
/**
* Set the hostPartner property: The integration account partner that is set as host partner for this agreement.
*
* @param hostPartner the hostPartner value to set.
* @return the IntegrationAccountAgreementInner object itself.
*/
public IntegrationAccountAgreementInner withHostPartner(String hostPartner) {
this.hostPartner = hostPartner;
return this;
}
/**
* Get the guestPartner property: The integration account partner that is set as guest partner for this agreement.
*
* @return the guestPartner value.
*/
public String guestPartner() {
return this.guestPartner;
}
/**
* Set the guestPartner property: The integration account partner that is set as guest partner for this agreement.
*
* @param guestPartner the guestPartner value to set.
* @return the IntegrationAccountAgreementInner object itself.
*/
public IntegrationAccountAgreementInner withGuestPartner(String guestPartner) {
this.guestPartner = guestPartner;
return this;
}
/**
* Get the hostIdentity property: The business identity of the host partner.
*
* @return the hostIdentity value.
*/
public BusinessIdentity hostIdentity() {
return this.hostIdentity;
}
/**
* Set the hostIdentity property: The business identity of the host partner.
*
* @param hostIdentity the hostIdentity value to set.
* @return the IntegrationAccountAgreementInner object itself.
*/
public IntegrationAccountAgreementInner withHostIdentity(BusinessIdentity hostIdentity) {
this.hostIdentity = hostIdentity;
return this;
}
/**
* Get the guestIdentity property: The business identity of the guest partner.
*
* @return the guestIdentity value.
*/
public BusinessIdentity guestIdentity() {
return this.guestIdentity;
}
/**
* Set the guestIdentity property: The business identity of the guest partner.
*
* @param guestIdentity the guestIdentity value to set.
* @return the IntegrationAccountAgreementInner object itself.
*/
public IntegrationAccountAgreementInner withGuestIdentity(BusinessIdentity guestIdentity) {
this.guestIdentity = guestIdentity;
return this;
}
/**
* Get the content property: The agreement content.
*
* @return the content value.
*/
public AgreementContent content() {
return this.content;
}
/**
* Set the content property: The agreement content.
*
* @param content the content value to set.
* @return the IntegrationAccountAgreementInner object itself.
*/
public IntegrationAccountAgreementInner withContent(AgreementContent content) {
this.content = content;
return this;
}
/** {@inheritDoc} */
@Override
public IntegrationAccountAgreementInner withLocation(String location) {
super.withLocation(location);
return this;
}
/** {@inheritDoc} */
@Override
public IntegrationAccountAgreementInner withTags(Map<String, String> tags) {
super.withTags(tags);
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (agreementType() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property agreementType in model IntegrationAccountAgreementInner"));
}
if (hostPartner() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property hostPartner in model IntegrationAccountAgreementInner"));
}
if (guestPartner() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property guestPartner in model IntegrationAccountAgreementInner"));
}
if (hostIdentity() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property hostIdentity in model IntegrationAccountAgreementInner"));
} else {
hostIdentity().validate();
}
if (guestIdentity() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property guestIdentity in model IntegrationAccountAgreementInner"));
} else {
guestIdentity().validate();
}
if (content() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property content in model IntegrationAccountAgreementInner"));
} else {
content().validate();
}
}
}
| 31.181518 | 118 | 0.649979 |
647f6e6ce2dbf9cc475d7b9629379d4b4b88438c | 1,562 | package com.ivoryworks.pgma;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class FrameworkDrawalbeAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mLayoutInflater = null;
private ArrayList<FrameworkDrawable> mDrawableList;
public FrameworkDrawalbeAdapter(Context context) {
mContext = context;
mLayoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setDrawableList(ArrayList<FrameworkDrawable> drawableList) {
mDrawableList = drawableList;
}
@Override
public int getCount() {
return mDrawableList.size();
}
@Override
public Object getItem(int position) {
return mDrawableList.get(position);
}
@Override
public long getItemId(int position) {
return mDrawableList.get(position).getResId();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflater.inflate(R.layout.listitem_drawable_info, parent, false);
((TextView)convertView.findViewById(R.id.res_name)).setText(mDrawableList.get(position).getResName());
((ImageView)convertView.findViewById(R.id.thumbnail)).setImageResource(mDrawableList.get(position).getResId());
return convertView;
}
}
| 29.471698 | 119 | 0.736236 |
0a9cc5aa84b6d96b7e24bc36596836c2cf0e8eff | 13,339 | package com.augsmachado.pegsolitaire;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
// Initialize constants
public static final int MAX_MILLISECONDS = 1000;
public static final int MAX_MINUTES = 2;
public static final int MAX_RANDOM = 1000;
public static final int MAX_HAS_ZEROS = 50;
public static final int BOARD = 9;
// Initialize variables
private TextView mTimer;
private TextView mResults;
private TextView mScores;
// Initialize buttons
private Button mFirstButton, mSecondButton, mThirdButton, mFourthButton, mFifthButton;
private Button mSixthButton, mSeventhButton, mEighthButton, mNinthButton;
private Button mStart, mRestart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindViews();
// Initialize mStart button
mStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
newGame();
showButtons();
mStart.setVisibility(View.INVISIBLE);
mTimer.setVisibility(View.VISIBLE);
// Initialize timer duration
long duration = TimeUnit.MINUTES.toMillis(MAX_MINUTES);
// Initialize countdown timer
new CountDownTimer(duration, MAX_MILLISECONDS) {
@Override
public void onTick(long millisUntilFinished) {
// When tick, convert millisecond to minute and second
String sDuration = String.format(Locale.ENGLISH, " %02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
// Set converted string on text view
mTimer.setText(sDuration);
}
@Override
public void onFinish() {
// When finish, hide text view
mTimer.setVisibility(View.GONE);
hideButtons();
mStart.setVisibility(View.VISIBLE);
mRestart.setVisibility(View.INVISIBLE);
// Display toast
Toast.makeText(getApplicationContext(), "Countdown timer has ended", Toast.LENGTH_SHORT).show();
}
}.start();
}
});
// Restart with new game
mRestart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
newGame();
showButtons();
mRestart.setVisibility(View.INVISIBLE);
}
});
// Set behavior for each button displayed with numbers
// When button clicked, subtract corresponding clicked number
mFirstButton.setOnClickListener(v -> {
String str = (String) mFirstButton.getText();
subtractNumber(str);
mFirstButton.setClickable(false);
mFirstButton.setVisibility(View.INVISIBLE);
});
mSecondButton.setOnClickListener(v -> {
String str = (String) mSecondButton.getText();
subtractNumber(str);
mSecondButton.setClickable(false);
mSecondButton.setVisibility(View.INVISIBLE);
});
mThirdButton.setOnClickListener(v -> {
String str = (String) mThirdButton.getText();
subtractNumber(str);
mThirdButton.setClickable(false);
mThirdButton.setVisibility(View.INVISIBLE);
});
mFourthButton.setOnClickListener(v -> {
String str = (String) mFourthButton.getText();
subtractNumber(str);
mFourthButton.setClickable(false);
mFourthButton.setVisibility(View.INVISIBLE);
});
mFifthButton.setOnClickListener(v -> {
String str = (String) mFifthButton.getText();
subtractNumber(str);
mFifthButton.setClickable(false);
mFifthButton.setVisibility(View.INVISIBLE);
});
mSixthButton.setOnClickListener(v -> {
String str = (String) mSixthButton.getText();
subtractNumber(str);
mSixthButton.setClickable(false);
mSixthButton.setVisibility(View.INVISIBLE);
});
mSeventhButton.setOnClickListener(v -> {
String str = (String) mSeventhButton.getText();
subtractNumber(str);
mSeventhButton.setClickable(false);
mSeventhButton.setVisibility(View.INVISIBLE);
});
mEighthButton.setOnClickListener(v -> {
String str = (String) mEighthButton.getText();
subtractNumber(str);
mEighthButton.setClickable(false);
mEighthButton.setVisibility(View.INVISIBLE);
});
mNinthButton.setOnClickListener(v -> {
String str = (String) mNinthButton.getText();
subtractNumber(str);
mNinthButton.setClickable(false);
mNinthButton.setVisibility(View.INVISIBLE);
});
}
private void bindViews() {
// Initialize the components in view
mTimer = findViewById(R.id.timer);
mResults = findViewById(R.id.results);
mScores = findViewById(R.id.scores);
mFirstButton = findViewById(R.id.line1Button1);
mSecondButton = findViewById(R.id.line1Button2);
mThirdButton = findViewById(R.id.line1Button3);
mFourthButton = findViewById(R.id.line2Button1);
mFifthButton = findViewById(R.id.line2Button2);
mSixthButton = findViewById(R.id.line2Button3);
mSeventhButton = findViewById(R.id.line3Button1);
mEighthButton = findViewById(R.id.line3Button2);
mNinthButton = findViewById(R.id.line3Button3);
mStart = findViewById(R.id.startNewGame);
mRestart = findViewById(R.id.restart);
}
// Create a new game
private void newGame() {
// Generate random number above 2
int randomNumber = generateRandomNumber(MAX_RANDOM);
if (randomNumber < 2) randomNumber = 2;
// Generate game board and set mResults view
generateBoardGame(randomNumber);
mResults.setText(String.valueOf(randomNumber));
}
// Generate random number above 2
private int generateRandomNumber(int value) {
return ThreadLocalRandom.current().nextInt(value);
}
// Generate game board
private int[] generateBoardGame (int randomNumber) {
int[] array;
// Successive divisions of the random number
array = successiveDivisions(randomNumber);
// Difference between summation and random number
array = diffSummationRandomNumber(array, randomNumber);
// Verify if the board has positions with zero values
array = hasZeros(array, randomNumber);
// Shuffle the values of array
array = shuffleArray(array);
mFirstButton.setText(String.valueOf(array[0]));
mSecondButton.setText(String.valueOf(array[1]));
mThirdButton.setText(String.valueOf(array[2]));
mFourthButton.setText(String.valueOf(array[3]));
mFifthButton.setText(String.valueOf(array[4]));
mSixthButton.setText(String.valueOf(array[5]));
mSeventhButton.setText(String.valueOf(array[6]));
mEighthButton.setText(String.valueOf(array[7]));
mNinthButton.setText(String.valueOf(array[8]));
return array;
}
// Successive divisions of the random number
private int[] successiveDivisions (int randomNumber) {
int[] array = new int[BOARD];
array[0] = randomNumber / 2;
for(int i = 1; i < array.length - 1; i++) {
int div = (array[i-1]/ 2);
if ( div != 1) array[i] = div;
}
return array;
}
// When difference between summation and random number is sup 1 unity
private int[] diffSummationRandomNumber(int[] array, int randomNumber) {
int sum = 0;
// Summation of values on array
for (int i : array) {
sum = sum + i;
}
// Difference between summation and random number
int diff = randomNumber - sum - 1;
// Test and return the last position where is not zero
// Add diff in random position of array, if value different of zero
int i = generateRandomNumber(notZero(array));
array[i] = array[i] + diff;
return array;
}
// Return the last position is not zero
private int notZero(int[] array) {
int notZero = 0;
for (int i : array) {
if (i != 0) notZero++;
}
return notZero;
}
// When the board has zeros
private int[] hasZeros(int[] array, int randomNumber) {
for (int i = notZero(array); i < array.length; i++) {
// Verify if the position really have zero
if (array[i] == 0) {
// Generate number to position
array[i] = (randomNumber + generateRandomNumber(MAX_HAS_ZEROS) + 1) / 2;
}
}
return array;
}
// Shuffle the values of array
private int[] shuffleArray (int[] array) {
Random r = new Random();
for (int i = 0; i < array.length; i++) {
int randomPosition = r.nextInt(array.length);
int temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
return array;
}
// When button clicked, subtract corresponding clicked number
private void subtractNumber(String str) {
int buttonValue = Integer.parseInt(str);
String sResult = (String) mResults.getText();
int results = Integer.parseInt(sResult);
results = results - buttonValue;
addScores(results);
mResults.setText(String.valueOf(results));
}
// When results = 1 and timer > 0, add 1 in score
private void addScores(int results) {
String sScore = (String) mScores.getText();
String sTimer = (String) mTimer.getText();
int scores = Integer.parseInt(sScore);
boolean matches = sTimer.matches(" 00:00");
if (results == 1) {
scores = scores + 1;
mScores.setText(String.valueOf(scores));
mRestart.setVisibility(View.VISIBLE);
}
if (results < 1 || matches == true) {
hideButtons();
mRestart.setVisibility(View.VISIBLE);
}
}
// When results < 1 or time = 0, hide buttons
private void hideButtons() {
mFirstButton.setClickable(false);
mSecondButton.setClickable(false);
mThirdButton.setClickable(false);
mFourthButton.setClickable(false);
mFifthButton.setClickable(false);
mSixthButton.setClickable(false);
mSeventhButton.setClickable(false);
mEighthButton.setClickable(false);
mNinthButton.setClickable(false);
mFirstButton.setVisibility(View.INVISIBLE);
mSecondButton.setVisibility(View.INVISIBLE);
mThirdButton.setVisibility(View.INVISIBLE);
mFourthButton.setVisibility(View.INVISIBLE);
mFifthButton.setVisibility(View.INVISIBLE);
mSixthButton.setVisibility(View.INVISIBLE);
mSeventhButton.setVisibility(View.INVISIBLE);
mEighthButton.setVisibility(View.INVISIBLE);
mNinthButton.setVisibility(View.INVISIBLE);
}
// When start or restart game, show buttons
// Initialize the behavior of button
private void showButtons() {
mFirstButton.setClickable(true);
mSecondButton.setClickable(true);
mThirdButton.setClickable(true);
mFourthButton.setClickable(true);
mFifthButton.setClickable(true);
mSixthButton.setClickable(true);
mSeventhButton.setClickable(true);
mEighthButton.setClickable(true);
mNinthButton.setClickable(true);
mFirstButton.setVisibility(View.VISIBLE);
mSecondButton.setVisibility(View.VISIBLE);
mThirdButton.setVisibility(View.VISIBLE);
mFourthButton.setVisibility(View.VISIBLE);
mFifthButton.setVisibility(View.VISIBLE);
mSixthButton.setVisibility(View.VISIBLE);
mSeventhButton.setVisibility(View.VISIBLE);
mEighthButton.setVisibility(View.VISIBLE);
mNinthButton.setVisibility(View.VISIBLE);
mStart.setVisibility(View.INVISIBLE);
}
} | 32.85468 | 122 | 0.613839 |
8b27cfa5a8f04e07a5c87f38a050d4278c3890ad | 1,377 | package com.smart.module.sys.web;
import com.smart.common.model.Result;
import com.smart.module.sys.entity.SysOrg;
import com.smart.module.sys.service.SysOrgService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 机构管理
* 爪哇笔记:https://blog.52itstyle.vip
* @author 小柒2012
*/
@RestController
@RequestMapping("/sys/org")
public class OrgController {
@Autowired
private SysOrgService sysOrgService;
/**
* 机构列表
*/
@PostMapping("/list")
public Result list(SysOrg sysOrg){
return sysOrgService.list(sysOrg);
}
/**
* 树结构
*/
@RequestMapping("/select")
public Result select(Long parentId){
return sysOrgService.select(parentId);
}
/**
* 保存
*/
@PostMapping("/save")
@RequiresRoles("admin")
public Result save(@RequestBody SysOrg org){
return sysOrgService.save(org);
}
/**
* 删除
*/
@PostMapping("/delete")
@RequiresRoles("admin")
public Result delete(Long orgId){
return sysOrgService.delete(orgId);
}
}
| 23.338983 | 62 | 0.687727 |
4793079a49c3d5e8128e1fc1b3ad6a674cb47040 | 600 | import listeners.TopicListener;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ITopic;
import java.util.Date;
public class TopicExample {
public static void main(String[] args) throws Exception {
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
ITopic<String> textTopic = hz.getTopic("broadcast");
textTopic.addMessageListener(new TopicListener());
while (true) {
textTopic.publish(
new Date() + " - " + hz.getCluster().getLocalMember() + " says hello");
Thread.sleep(1000);
}
}
}
| 25 | 79 | 0.708333 |
aecfef13c1dea5aee1076ed9c6188b55f72444f3 | 318 | package hr.fer.oprpp1.custom.collections;
/**The Processor is a
* model of an object capable of performing some operation on the passed object.
* @author Leo Goršić
*
*/
public class Processor {
/**Performs some operation on <code>value</code>
* @param value
*/
public void process(Object value) {
}
}
| 18.705882 | 80 | 0.701258 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.