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
|
---|---|---|---|---|---|
0e480e59c716de853c216fa0f86ffd4e90109909 | 2,842 | package com.qsd.bookstore.po;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.qsd.bookstore.dao.CommodityDao;
import com.qsd.bookstore.dao.UserDao;
/**
* @Description
* @Author Esion
* @Data 2020年6月2日
*/
@Component
@Scope("singleton")
public class Global implements Serializable {
private static final long serialVersionUID = 4863051356636596454L;
@Autowired
private UserDao userDao;
@Autowired
private CommodityDao commodityDao;
private Integer id;
//网站的公告栏
private String notice = "尊敬的用户,您好\n 从6月15日起,本书店盛大开业,欢迎您的光临。";
//网站访问量
private int view = 0;
//网站在线人数
private int online = 0;
//商品卖出量
private int commoditySellNum = 0;
//营业额
private int turnover = 0;
//注册用户数量
private int userNum;
//上架图书数量
private int commodityNum;
@PostConstruct
public void update() {
this.view = 0;
this.online = 0;
this.commoditySellNum = 0;
this.turnover = 0;
this.userNum = userDao.getUserNum();
this.commodityNum = commodityDao.getCommodityNum();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNotice() {
return this.notice;
}
public void setNotice(String notice) {
this.notice = notice;
}
public int getView() {
return view;
}
public void addView() {
this.view += 1;
}
public int getOnline() {
return online;
}
public void addOnline() {
this.online += 1;
}
public void reduceOnline() {
this.online -= 1;
}
public int getCommoditySellNum() {
return commoditySellNum;
}
public void addCommoditySellNum() {
this.commoditySellNum += 1;
}
public int getTurnover() {
return turnover;
}
public void addTurnover(int money) {
this.turnover += money;
}
public void updateUserNum() {
userNum += 1;
}
public int getUserNum() {
return userNum;
}
public void updateCommodityNum() {
commodityNum += 1;
}
public int getCommodityNum() {
return commodityNum;
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public CommodityDao getCommodityDao() {
return commodityDao;
}
public void setCommodityDao(CommodityDao commodityDao) {
this.commodityDao = commodityDao;
}
public void setView(int view) {
this.view = view;
}
public void setOnline(int online) {
this.online = online;
}
public void setCommoditySellNum(int commoditySellNum) {
this.commoditySellNum = commoditySellNum;
}
public void setTurnover(int turnover) {
this.turnover = turnover;
}
public void setUserNum(int userNum) {
this.userNum = userNum;
}
public void setCommodityNum(int commodityNum) {
this.commodityNum = commodityNum;
}
}
| 20.897059 | 67 | 0.721323 |
941957c6b212bd459d0c80218bd4232f302a827b | 2,173 |
package com.attehuhtakangas.nightmode;
import android.app.UiModeManager;
import android.content.Context;
import android.support.annotation.Nullable;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Collections;
import java.util.Map;
public class NightModeModule extends ReactContextBaseJavaModule {
public NightModeModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "NightModeManager";
}
@Override
public
@Nullable
Map<String, Object> getConstants() {
return Collections.emptyMap();
}
@ReactMethod
public String isNightMode() {
final Context context = getReactApplicationContext();
UiModeManager manager = (UiModeManager) context.getSystemService(Context.UI_MODE_SERVICE);
switch (manager.getNightMode()) {
case UiModeManager.MODE_NIGHT_AUTO:
return "AUTO";
case UiModeManager.MODE_NIGHT_NO:
return "NO";
case UiModeManager.MODE_NIGHT_YES:
return "YES";
default:
return null;
}
}
@ReactMethod
public void setNightMode(String mode) {
final Context context = getReactApplicationContext();
UiModeManager manager = (UiModeManager) context.getSystemService(Context.UI_MODE_SERVICE);
int currentMode = manager.getNightMode();
switch (mode.toUpperCase()) {
case "YES":
if (currentMode == UiModeManager.MODE_NIGHT_YES) return;
manager.setNightMode(UiModeManager.MODE_NIGHT_YES);
case "NO":
if (currentMode == UiModeManager.MODE_NIGHT_NO) return;
manager.setNightMode(UiModeManager.MODE_NIGHT_NO);
case "AUTO":
if (currentMode == UiModeManager.MODE_NIGHT_AUTO) return;
manager.setNightMode(UiModeManager.MODE_NIGHT_AUTO);
default:
return;
}
}
} | 31.492754 | 98 | 0.652554 |
fbbdd56157bec013e7e7268ab41a85b3469fa3f4 | 798 | package org.lpw.photon.ctrl.context;
import java.io.IOException;
import java.io.OutputStream;
/**
* 输出适配器。
*/
public interface ResponseAdapter {
/**
* 设置类容类型。
*
* @param contentType 类容类型。
*/
void setContentType(String contentType);
/**
* 设置头信息。
*
* @param name 名称。
* @param value 值。
*/
void setHeader(String name, String value);
/**
* 获取输出流。
*
* @return 输出流。
*/
OutputStream getOutputStream();
/**
* 发送数据。
*
* @throws IOException 未处理IO读写异常。
*/
void send() throws IOException;
/**
* 跳转到指定URL地址。
*
* @param url 目标URL地址。
*/
void redirectTo(String url);
/**
* 发送错误码。
*
* @param code 错误码。
*/
void sendError(int code);
}
| 15.056604 | 46 | 0.52005 |
07b4c70c71750a9489f0701eddb2bcfcfb198d72 | 2,127 | package com.duy.pascal.interperter.declaration.lang.types;
import com.duy.pascal.interperter.ast.expressioncontext.ExpressionContext;
import com.duy.pascal.interperter.ast.runtime.value.RuntimeValue;
import com.duy.pascal.interperter.ast.runtime.value.boxing.ArrayBoxer;
import com.duy.pascal.interperter.linenumber.LineNumber;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class VarargsType implements ArgumentType {
private RuntimeType elementType;
public VarargsType(RuntimeType elementType) {
this.elementType = elementType;
}
@Override
public RuntimeValue convertArgType(Iterator<RuntimeValue> args,
ExpressionContext f) throws Exception {
List<RuntimeValue> convertedArgs = new ArrayList<>();
LineNumber line = null;
while (args.hasNext()) {
RuntimeValue tmp = elementType.convert(args.next(), f);
if (tmp == null) {
return null;
}
line = tmp.getLineNumber();
convertedArgs.add(tmp);
}
return new ArrayBoxer(convertedArgs.toArray(new RuntimeValue[convertedArgs.size()]),
elementType, line);
}
@Override
public String toString() {
return "args...";
}
@Override
public Class getRuntimeClass() {
return elementType.getClass();
}
@Override
public RuntimeValue perfectFit(Iterator<RuntimeValue> types,
ExpressionContext e) throws Exception {
LineNumber line = null;
List<RuntimeValue> converted = new ArrayList<>();
while (types.hasNext()) {
RuntimeValue fit = elementType.perfectFit(types, e);
if (fit == null) {
return null;
}
if (line == null) {
line = fit.getLineNumber();
}
converted.add(fit);
}
RuntimeValue[] convert = converted.toArray(new RuntimeValue[converted.size()]);
return new ArrayBoxer(convert, elementType, line);
}
}
| 32.227273 | 92 | 0.617301 |
aae229eb50204734716ceaa5028ef3e10f126a38 | 3,105 | package org.icatproject.ids.integration.two;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.icatproject.ids.integration.BaseTest;
import org.icatproject.ids.integration.util.Setup;
import org.icatproject.ids.integration.util.client.DataSelection;
import org.icatproject.ids.integration.util.client.InsufficientPrivilegesException;
import org.icatproject.ids.integration.util.client.NotFoundException;
import org.icatproject.ids.integration.util.client.TestingClient.Flag;
import org.icatproject.ids.integration.util.client.TestingClient.Status;
import org.junit.BeforeClass;
import org.junit.Test;
public class GetStatusExplicitTest extends BaseTest {
@BeforeClass
public static void setup() throws Exception {
setup = new Setup("two.properties");
icatsetup();
}
@Test
public void ping() throws Exception {
testingClient.ping(200);
}
@Test(expected = NotFoundException.class)
public void notFoundPreparedId() throws Exception {
testingClient.isPrepared("88888888-4444-4444-4444-cccccccccccc", 404);
}
@Test(expected = NotFoundException.class)
public void notFoundDatafileIdsTest() throws Exception {
testingClient.getStatus(sessionId,
new DataSelection().addDatasets(Arrays.asList(1L, 2L, 3L, 9999999L)), 404);
}
@Test(expected = InsufficientPrivilegesException.class)
public void forbiddenTest() throws Exception {
testingClient.getStatus(setup.getForbiddenSessionId(),
new DataSelection().addDatafiles(datafileIds), 403);
}
@Test
public void correctBehaviourTest() throws Exception {
Status status = testingClient.getStatus(sessionId,
new DataSelection().addDatafiles(datafileIds), 200);
assertEquals(status, Status.ARCHIVED);
waitForIds();
assertEquals(status, Status.ARCHIVED);
}
@Test
public void getStatusPreparedIdTest() throws Exception {
DataSelection selection = new DataSelection().addDatafile(datafileIds.get(0));
String preparedId = testingClient.prepareData(sessionId, selection, Flag.NONE, 200);
while (!testingClient.isPrepared(preparedId, 200)) {
Thread.sleep(1000);
}
assertEquals(testingClient.getStatus(preparedId, 200), Status.ONLINE);
testingClient.archive(sessionId, selection, 204);
waitForIds();
assertEquals(testingClient.getStatus(preparedId, 200), Status.ARCHIVED);
// verify that getStatus() as opposed to isPrepared() does not implicitly trigger a restore.
waitForIds();
assertEquals(testingClient.getStatus(preparedId, 200), Status.ARCHIVED);
}
@Test
public void restoringDatafileRestoresItsDatasetTest() throws Exception {
String preparedId = testingClient.prepareData(sessionId,
new DataSelection().addDatafile(datafileIds.get(0)), Flag.NONE, 200);
while (!testingClient.isPrepared(preparedId, 200)) {
Thread.sleep(1000);
}
Status status = testingClient.getStatus(sessionId,
new DataSelection().addDataset(datasetIds.get(0)), 200);
assertEquals(Status.ONLINE, status);
status = testingClient.getStatus(sessionId,
new DataSelection().addDataset(datasetIds.get(1)), 200);
assertEquals(Status.ARCHIVED, status);
}
}
| 34.5 | 94 | 0.779388 |
e1e8792735f7855252968cb00203ae84129c41b8 | 7,175 | /**
*/
package sql;
import org.eclipse.emf.ecore.EFactory;
/**
* <!-- begin-user-doc -->
* The <b>Factory</b> for the model.
* It provides a create method for each non-abstract class of the model.
* <!-- end-user-doc -->
* @see sql.SqlPackage
* @generated
*/
public interface SqlFactory extends EFactory {
/**
* The singleton instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
SqlFactory eINSTANCE = sql.impl.SqlFactoryImpl.init();
/**
* Returns a new object of class '<em>Select</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Select</em>'.
* @generated
*/
Select createSelect();
/**
* Returns a new object of class '<em>Plain Select</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Plain Select</em>'.
* @generated
*/
PlainSelect createPlainSelect();
/**
* Returns a new object of class '<em>Distinct</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Distinct</em>'.
* @generated
*/
Distinct createDistinct();
/**
* Returns a new object of class '<em>Group By Element</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Group By Element</em>'.
* @generated
*/
GroupByElement createGroupByElement();
/**
* Returns a new object of class '<em>Join</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Join</em>'.
* @generated
*/
Join createJoin();
/**
* Returns a new object of class '<em>Alias</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Alias</em>'.
* @generated
*/
Alias createAlias();
/**
* Returns a new object of class '<em>And Expression</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>And Expression</em>'.
* @generated
*/
AndExpression createAndExpression();
/**
* Returns a new object of class '<em>Or Expression</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Or Expression</em>'.
* @generated
*/
OrExpression createOrExpression();
/**
* Returns a new object of class '<em>Equals To</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Equals To</em>'.
* @generated
*/
EqualsTo createEqualsTo();
/**
* Returns a new object of class '<em>Greater Than</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Greater Than</em>'.
* @generated
*/
GreaterThan createGreaterThan();
/**
* Returns a new object of class '<em>Greater Than Equals</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Greater Than Equals</em>'.
* @generated
*/
GreaterThanEquals createGreaterThanEquals();
/**
* Returns a new object of class '<em>Minor Than</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Minor Than</em>'.
* @generated
*/
MinorThan createMinorThan();
/**
* Returns a new object of class '<em>Minor Than Equals</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Minor Than Equals</em>'.
* @generated
*/
MinorThanEquals createMinorThanEquals();
/**
* Returns a new object of class '<em>Not Equals To</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Not Equals To</em>'.
* @generated
*/
NotEqualsTo createNotEqualsTo();
/**
* Returns a new object of class '<em>All Columns</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>All Columns</em>'.
* @generated
*/
AllColumns createAllColumns();
/**
* Returns a new object of class '<em>Select Expression Item</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Select Expression Item</em>'.
* @generated
*/
SelectExpressionItem createSelectExpressionItem();
/**
* Returns a new object of class '<em>Table</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Table</em>'.
* @generated
*/
Table createTable();
/**
* Returns a new object of class '<em>Sub Select</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Sub Select</em>'.
* @generated
*/
SubSelect createSubSelect();
/**
* Returns a new object of class '<em>Not Expression</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Not Expression</em>'.
* @generated
*/
NotExpression createNotExpression();
/**
* Returns a new object of class '<em>Long Value</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Long Value</em>'.
* @generated
*/
LongValue createLongValue();
/**
* Returns a new object of class '<em>Null Value</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Null Value</em>'.
* @generated
*/
NullValue createNullValue();
/**
* Returns a new object of class '<em>Is Null Expression</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Is Null Expression</em>'.
* @generated
*/
IsNullExpression createIsNullExpression();
/**
* Returns a new object of class '<em>Function</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Function</em>'.
* @generated
*/
Function createFunction();
/**
* Returns a new object of class '<em>Column</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Column</em>'.
* @generated
*/
Column createColumn();
/**
* Returns a new object of class '<em>Case Expression</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Case Expression</em>'.
* @generated
*/
CaseExpression createCaseExpression();
/**
* Returns a new object of class '<em>When Clause</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>When Clause</em>'.
* @generated
*/
WhenClause createWhenClause();
/**
* Returns a new object of class '<em>String Value</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>String Value</em>'.
* @generated
*/
StringValue createStringValue();
/**
* Returns a new object of class '<em>Expression List</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Expression List</em>'.
* @generated
*/
ExpressionList createExpressionList();
/**
* Returns the package supported by this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the package supported by this factory.
* @generated
*/
SqlPackage getSqlPackage();
} //SqlFactory
| 25.087413 | 72 | 0.588711 |
5da56a7cf3d050c3ab259cbd427b6c2cc95a6dce | 9,243 | package org.oagi.score.repo.component.code_list;
import org.jooq.*;
import org.jooq.types.ULong;
import org.oagi.score.gateway.http.api.code_list_management.data.CodeListState;
import org.oagi.score.service.common.data.CcState;
import org.oagi.score.repo.api.impl.jooq.entity.tables.records.BccpManifestRecord;
import org.oagi.score.repo.api.impl.jooq.entity.tables.records.CodeListManifestRecord;
import org.oagi.score.repo.api.impl.jooq.entity.tables.records.DtScManifestRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.math.BigInteger;
import java.util.*;
import java.util.Comparator;
import java.util.stream.Collectors;
import static org.jooq.impl.DSL.and;
import static org.jooq.impl.DSL.trueCondition;
import static org.oagi.score.repo.api.impl.jooq.entity.Tables.*;
@Repository
public class CodeListReadRepository {
@Autowired
private DSLContext dslContext;
public CodeListManifestRecord getCodeListManifestByManifestId(BigInteger codeListManifestId) {
return dslContext.selectFrom(CODE_LIST_MANIFEST)
.where(CODE_LIST_MANIFEST.CODE_LIST_MANIFEST_ID.eq(ULong.valueOf(codeListManifestId)))
.fetchOne();
}
public List<AvailableCodeList> availableCodeListByBccpManifestId(BigInteger bccpManifestId, List<CodeListState> states) {
BccpManifestRecord bccpManifestRecord = dslContext.selectFrom(BCCP_MANIFEST)
.where(BCCP_MANIFEST.BCCP_MANIFEST_ID.eq(ULong.valueOf(bccpManifestId)))
.fetchOneInto(BccpManifestRecord.class);
Result<Record2<ULong, ULong>> result = dslContext.selectDistinct(
CODE_LIST_MANIFEST.CODE_LIST_MANIFEST_ID,
BCCP_MANIFEST.RELEASE_ID)
.from(BCCP_MANIFEST)
.join(DT_MANIFEST).on(BCCP_MANIFEST.BDT_MANIFEST_ID.eq(DT_MANIFEST.DT_MANIFEST_ID))
.join(BDT_PRI_RESTRI).on(DT_MANIFEST.DT_ID.eq(BDT_PRI_RESTRI.BDT_ID))
.join(CODE_LIST_MANIFEST).on(and(
BDT_PRI_RESTRI.CODE_LIST_ID.eq(CODE_LIST_MANIFEST.CODE_LIST_ID),
BCCP_MANIFEST.RELEASE_ID.eq(CODE_LIST_MANIFEST.RELEASE_ID)
))
.join(CODE_LIST).on(and(CODE_LIST_MANIFEST.CODE_LIST_ID.eq(CODE_LIST.CODE_LIST_ID),
states.isEmpty() ? trueCondition() : CODE_LIST.STATE.in(states)))
.where(BCCP_MANIFEST.BCCP_MANIFEST_ID.eq(bccpManifestRecord.getBccpManifestId()))
.fetch();
if (result.size() > 0) {
return result.stream().map(e ->
availableCodeListByCodeListManifestId(
e.get(CODE_LIST_MANIFEST.CODE_LIST_MANIFEST_ID).toBigInteger(), states))
.flatMap(e -> e.stream())
.distinct()
.sorted(Comparator.comparing(AvailableCodeList::getCodeListName))
.collect(Collectors.toList());
} else {
return availableCodeListByReleaseId(bccpManifestRecord.getReleaseId().toBigInteger(), states);
}
}
private List<AvailableCodeList> availableCodeListByCodeListManifestId(BigInteger codeListManifestId, List<CodeListState> states) {
if (codeListManifestId == null) {
return Collections.emptyList();
}
List<AvailableCodeList> availableCodeLists =
dslContext.select(
CODE_LIST_MANIFEST.CODE_LIST_MANIFEST_ID,
CODE_LIST_MANIFEST.BASED_CODE_LIST_MANIFEST_ID,
CODE_LIST.CODE_LIST_ID,
CODE_LIST.NAME.as("code_list_name"),
CODE_LIST.VERSION_ID,
CODE_LIST.STATE)
.from(CODE_LIST)
.join(CODE_LIST_MANIFEST).on(CODE_LIST.CODE_LIST_ID.eq(CODE_LIST_MANIFEST.CODE_LIST_ID))
.where(and(CODE_LIST_MANIFEST.CODE_LIST_MANIFEST_ID.eq(ULong.valueOf(codeListManifestId)),
states.isEmpty() ? trueCondition() : CODE_LIST.STATE.in(states)))
.fetchInto(AvailableCodeList.class);
List<BigInteger> associatedCodeLists = dslContext.selectDistinct(CODE_LIST_MANIFEST.CODE_LIST_MANIFEST_ID)
.from(CODE_LIST_MANIFEST)
.join(CODE_LIST).on(and(CODE_LIST_MANIFEST.CODE_LIST_ID.eq(CODE_LIST.CODE_LIST_ID),
states.isEmpty() ? trueCondition() : CODE_LIST.STATE.in(states)))
.where(CODE_LIST_MANIFEST.CODE_LIST_MANIFEST_ID.in(
availableCodeLists.stream()
.filter(e -> e.getBasedCodeListManifestId() != null)
.map(e -> e.getBasedCodeListManifestId())
.distinct()
.collect(Collectors.toList())
))
.fetchInto(BigInteger.class);
List<AvailableCodeList> mergedCodeLists = new ArrayList();
mergedCodeLists.addAll(availableCodeLists);
for (BigInteger associatedCodeListId : associatedCodeLists) {
mergedCodeLists.addAll(
availableCodeListByCodeListManifestId(
associatedCodeListId, states)
);
}
// #1094: Add Code list which is base availableCodeLists
List<AvailableCodeList> baseCodeLists =
dslContext.select(
CODE_LIST_MANIFEST.CODE_LIST_MANIFEST_ID,
CODE_LIST_MANIFEST.BASED_CODE_LIST_MANIFEST_ID,
CODE_LIST.CODE_LIST_ID,
CODE_LIST.NAME.as("code_list_name"),
CODE_LIST.VERSION_ID,
CODE_LIST.STATE,
CODE_LIST.IS_DEPRECATED)
.from(CODE_LIST)
.join(CODE_LIST_MANIFEST).on(CODE_LIST.CODE_LIST_ID.eq(CODE_LIST_MANIFEST.CODE_LIST_ID))
.where(and(CODE_LIST_MANIFEST.BASED_CODE_LIST_MANIFEST_ID.eq(ULong.valueOf(codeListManifestId)),
states.isEmpty() ? trueCondition() : CODE_LIST.STATE.in(states)))
.fetchInto(AvailableCodeList.class);
mergedCodeLists.addAll(baseCodeLists);
return mergedCodeLists.stream().distinct().collect(Collectors.toList());
}
private List<AvailableCodeList> availableCodeListByReleaseId(BigInteger releaseId, List<CodeListState> states) {
List<Condition> conditions = new ArrayList();
conditions.add(CODE_LIST_MANIFEST.RELEASE_ID.eq(ULong.valueOf(releaseId)));
if (!states.isEmpty()) {
conditions.add(CODE_LIST.STATE.in(states));
}
return dslContext.select(
CODE_LIST_MANIFEST.CODE_LIST_MANIFEST_ID,
CODE_LIST_MANIFEST.BASED_CODE_LIST_MANIFEST_ID,
CODE_LIST.CODE_LIST_ID,
CODE_LIST.NAME.as("code_list_name"),
CODE_LIST.VERSION_ID,
CODE_LIST.STATE,
CODE_LIST.IS_DEPRECATED)
.from(CODE_LIST)
.join(CODE_LIST_MANIFEST).on(CODE_LIST.CODE_LIST_ID.eq(CODE_LIST_MANIFEST.CODE_LIST_ID))
.where(conditions)
.fetchInto(AvailableCodeList.class);
}
public List<AvailableCodeList> availableCodeListByBdtScManifestId(BigInteger bdtScManifestId, List<CodeListState> states) {
DtScManifestRecord dtScManifestRecord = dslContext.selectFrom(DT_SC_MANIFEST)
.where(DT_SC_MANIFEST.DT_SC_MANIFEST_ID.eq(ULong.valueOf(bdtScManifestId)))
.fetchOneInto(DtScManifestRecord.class);
Result<Record2<ULong, ULong>> result = dslContext.selectDistinct(
CODE_LIST_MANIFEST.CODE_LIST_MANIFEST_ID,
DT_SC_MANIFEST.RELEASE_ID)
.from(DT_SC_MANIFEST)
.join(BDT_SC_PRI_RESTRI).on(DT_SC_MANIFEST.DT_SC_ID.eq(BDT_SC_PRI_RESTRI.BDT_SC_ID))
.join(CODE_LIST_MANIFEST).on(and(
BDT_SC_PRI_RESTRI.CODE_LIST_ID.eq(CODE_LIST_MANIFEST.CODE_LIST_ID),
DT_SC_MANIFEST.RELEASE_ID.eq(CODE_LIST_MANIFEST.RELEASE_ID)
))
.join(CODE_LIST).on(and(CODE_LIST_MANIFEST.CODE_LIST_ID.eq(CODE_LIST.CODE_LIST_ID),
states.isEmpty() ? trueCondition() : CODE_LIST.STATE.in(states)))
.where(DT_SC_MANIFEST.DT_SC_MANIFEST_ID.eq(dtScManifestRecord.getDtScManifestId()))
.fetch();
if (result.size() > 0) {
return result.stream().map(e ->
availableCodeListByCodeListManifestId(
e.get(CODE_LIST_MANIFEST.CODE_LIST_MANIFEST_ID).toBigInteger(), states))
.flatMap(e -> e.stream())
.distinct()
.sorted(Comparator.comparing(AvailableCodeList::getCodeListName))
.collect(Collectors.toList());
} else {
return availableCodeListByReleaseId(dtScManifestRecord.getReleaseId().toBigInteger(), states);
}
}
}
| 49.962162 | 134 | 0.633561 |
759a41a98a3f71a3c065786b92cb5de85348b46a | 812 |
package org.company.controllers;
import com.sdl.webapp.common.api.model.page.PageModelImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import static com.sdl.webapp.common.controller.RequestAttributeNames.PAGE_MODEL;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
@Controller
public class CustomController {
/**
* Custom routes for gui entry points
*
* @param request
* @return
*/
@RequestMapping(
value = {"/productfamilylist"},
method = GET
)
public String productFamilyList(HttpServletRequest request) {
request.setAttribute(PAGE_MODEL, new PageModelImpl());
return "home";
}
} | 27.066667 | 80 | 0.724138 |
6b3ac4dc16b11af0c60a0cb8fb566b7fc38afd14 | 1,991 | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.model;
import java.io.Serializable;
import java.util.Arrays;
import org.drools.model.bitmask.BitMaskUtil;
import org.drools.model.bitmask.LongBitMask;
import org.drools.model.bitmask.OpenBitSet;
public interface BitMask extends Serializable, Cloneable {
BitMask set( int index );
BitMask setAll( BitMask mask );
BitMask reset( int index );
BitMask resetAll( BitMask mask );
boolean isSet( int index );
boolean isAllSet();
boolean isEmpty();
boolean intersects( BitMask mask );
BitMask clone();
String getInstancingStatement();
Class<?> getPatternClass();
void setPatternClass( Class<?> patternClass );
static BitMask getPatternMask( Class<?> clazz, String... listenedProperties ) {
BitMask bitMask = BitMaskUtil.calculatePatternMask( clazz, Arrays.asList( listenedProperties ) );
bitMask.setPatternClass( clazz );
return bitMask;
}
static BitMask getEmpty(int numBits) {
return numBits <= 64 ? new LongBitMask() : new OpenBitSet( numBits);
}
static BitMask getFull(int numBits) {
if (numBits <= 64) {
return new LongBitMask(-1L);
}
int nWords = (numBits / 64) + 1;
long[] bits = new long[nWords];
for (int i = 0; i < bits.length; i++) {
bits[i] = -1L;
}
return new OpenBitSet(bits, nWords);
}
}
| 28.855072 | 105 | 0.670015 |
67976a31107c7e554f37a2bcec9a5888e969c474 | 276 | package world.biome;
import java.awt.Color;
/*
BenjaminWilcox
Dec 5, 2016
GNGH_2
*/
public class Desert extends Biome
{
public Desert()
{
name = "Desert";
type = 4;
color = new Color(255, 209, 114);
text = "~";
}
}
| 12.545455 | 41 | 0.525362 |
0f3c39e79cfbded9953aeb86631a79babf64f73f | 1,732 | /* Copyright © 2021, SAS Institute Inc., Cary, NC, USA. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.sas.ci360.agent.impl;
import java.util.Properties;
import org.json.JSONObject;
import com.sas.ci360.agent.PostEventCallback;
import com.sas.ci360.agent.cache.IdentityCache;
import com.sas.ci360.agent.cache.MessageCache;
public class PostEventCacheCallback implements PostEventCallback {
private static final String JSON_RECIPIENT = "recipient";
private static final String JSON_DATAHUB_ID = "datahub_id";
private static final String JSON_MSG_ID = "msgId";
private static final String INTL_PREFIX = "+";
private MessageCache msgCache;
private IdentityCache identityCache;
private boolean identityCacheEnabled = false;
public PostEventCacheCallback(MessageCache msgCache, IdentityCache identityCache, Properties config) {
this.msgCache = msgCache;
this.identityCache = identityCache;
if (config.getProperty("agent.twoWay.identityCacheEnabled", "false").equalsIgnoreCase("TRUE")) {
identityCacheEnabled = true;
}
}
@Override
public void postEvent(JSONObject eventData) throws Exception {
this.msgCache.put(eventData.getString(JSON_MSG_ID), eventData);
if (identityCacheEnabled) {
if (eventData.getString(JSON_RECIPIENT).startsWith(INTL_PREFIX)) {
this.identityCache.put(eventData.getString(JSON_RECIPIENT), eventData.getString(JSON_DATAHUB_ID));
}
else {
// prepend + to phone number (webhook phone numbers are always in full intl format)
// TODO: check if we need to handle webhook for FB/WeChat differently
this.identityCache.put(INTL_PREFIX + eventData.getString(JSON_RECIPIENT), eventData.getString(JSON_DATAHUB_ID));
}
}
}
}
| 34.64 | 116 | 0.772517 |
1be69294f95eb08d751629bbd181728372d7af74 | 690 | package com.mgc.letobox.happy.domain;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
/**
* Created by DELL on 2018/8/15.
*/
public class BitMapResponse implements Comparable<BitMapResponse> {
private int id;
private Bitmap bitmap;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
@Override
public int compareTo(@NonNull BitMapResponse bitMapResponse) {
int i = this.getId() - bitMapResponse.getId();
return i;
}
}
| 18.648649 | 67 | 0.633333 |
08de85774c3486c9adc084dfe5f8e3b778dba01b | 8,890 | package chuangyuan.ycj.videolibrary.source;
import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.util.Base64;
import android.util.Log;
import com.google.android.exoplayer2.upstream.AssetDataSource;
import com.google.android.exoplayer2.upstream.ContentDataSource;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.upstream.FileDataSource;
import com.google.android.exoplayer2.upstream.TransferListener;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Util;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* Created by yangc on 2017/11/13
* E-Mail:[email protected]
* Deprecated:
*/
public class MyDefaultDataSource implements DataSource {
private static final String TAG = "DefaultDataSource";
private static final String SCHEME_ASSET = "asset";
private static final String SCHEME_CONTENT = "content";
private static final String SCHEME_RTMP = "rtmp";
private final Context context;
private final TransferListener<? super DataSource> listener;
private final DataSource baseDataSource;
private DataSource fileDataSource;
private DataSource assetDataSource;
private DataSource contentDataSource;
private DataSource rtmpDataSource;
private DataSource dataSource;
private Cipher mCipher;
private SecretKeySpec mSecretKeySpec;
private IvParameterSpec mIvParameterSpec;
/**
* Constructs a new instance, optionally configured to follow cross-protocol redirects.
*
* @param context A context.
* @param listener An optional listener.
* @param userAgent The User-Agent string that should be used when requesting remote data.
* @param allowCrossProtocolRedirects Whether cross-protocol redirects (i.e. redirects from HTTP
* to HTTPS and vice versa) are enabled when fetching remote data.
*/
public MyDefaultDataSource(Context context, TransferListener<? super DataSource> listener,
String userAgent, boolean allowCrossProtocolRedirects) {
this(context, listener, userAgent, DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,
DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS, allowCrossProtocolRedirects);
}
/**
* Constructs a new instance, optionally configured to follow cross-protocol redirects.
*
* @param context A context.
* @param listener An optional listener.
* @param userAgent The User-Agent string that should be used when requesting remote data.
* @param connectTimeoutMillis The connection timeout that should be used when requesting remote
* data, in milliseconds. A timeout of zero is interpreted as an infinite timeout.
* @param readTimeoutMillis The read timeout that should be used when requesting remote data,
* in milliseconds. A timeout of zero is interpreted as an infinite timeout.
* @param allowCrossProtocolRedirects Whether cross-protocol redirects (i.e. redirects from HTTP
* to HTTPS and vice versa) are enabled when fetching remote data.
*/
public MyDefaultDataSource(Context context, TransferListener<? super DataSource> listener,
String userAgent, int connectTimeoutMillis, int readTimeoutMillis,
boolean allowCrossProtocolRedirects) {
this(context, listener,
new DefaultHttpDataSource(userAgent, null, listener, connectTimeoutMillis,
readTimeoutMillis, allowCrossProtocolRedirects, null));
}
/**
* Constructs a new instance that delegates to a provided {@link DataSource} for URI schemes other
* than file, asset and content.
*
* @param context A context.
* constants in {@link Base64}
* @param listener An optional listener.
* @param baseDataSource A {@link DataSource} to use for URI schemes other than file, asset and
* content. This {@link DataSource} should normally support at least http(s).
*/
public MyDefaultDataSource(Context context, TransferListener<? super DataSource> listener,
DataSource baseDataSource) {
this.context = context.getApplicationContext();
this.listener = listener;
this.baseDataSource = Assertions.checkNotNull(baseDataSource);
}
public MyDefaultDataSource(@NonNull Context context, @NonNull Cipher cipher, @NonNull SecretKeySpec secretKeySpec, @NonNull IvParameterSpec ivParameterSpec, @NonNull TransferListener<? super DataSource> listener, @NonNull DataSource baseDataSource) {
this.context = context.getApplicationContext();
mCipher = cipher;
mSecretKeySpec = secretKeySpec;
mIvParameterSpec = ivParameterSpec;
this.listener = listener;
this.baseDataSource = Assertions.checkNotNull(baseDataSource);
}
@Override
public long open(DataSpec dataSpec) throws IOException {
Assertions.checkState(dataSource == null);
String scheme = dataSpec.uri.getScheme();
if (Util.isLocalFileUri(dataSpec.uri)) {
if (dataSpec.uri.getPath().startsWith("/android_asset/")) {
dataSource = getAssetDataSource();
} else {
dataSource = getFileDataSource();
}
} else if (SCHEME_ASSET.equals(scheme)) {
dataSource = getAssetDataSource();
} else if (SCHEME_CONTENT.equals(scheme)) {
dataSource = getContentDataSource();
} else if (SCHEME_RTMP.equals(scheme)) {
dataSource = getRtmpDataSource();
} else {
dataSource = baseDataSource;
}
// Open the source and return.
return dataSource.open(dataSpec);
}
@Override
public int read(byte[] buffer, int offset, int readLength) throws IOException {
return dataSource.read(buffer, offset, readLength);
}
@Override
public Uri getUri() {
return dataSource == null ? null : dataSource.getUri();
}
@Override
public void close() throws IOException {
if (dataSource != null) {
try {
dataSource.close();
} finally {
dataSource = null;
}
}
}
private DataSource getFileDataSource() {
if (fileDataSource == null) {
if (mCipher != null && null != mSecretKeySpec && null != mIvParameterSpec) {
fileDataSource = new EncryptedFileDataSource(mCipher, mSecretKeySpec, mIvParameterSpec, listener);
} else {
fileDataSource = new FileDataSource(listener);
}
}
return fileDataSource;
}
private DataSource getAssetDataSource() {
if (assetDataSource == null) {
assetDataSource = new AssetDataSource(context, listener);
}
return assetDataSource;
}
private DataSource getContentDataSource() {
if (contentDataSource == null) {
contentDataSource = new ContentDataSource(context, listener);
}
return contentDataSource;
}
private DataSource getRtmpDataSource() {
if (rtmpDataSource == null) {
try {
Class<?> clazz = Class.forName("com.google.android.exoplayer2.ext.rtmp.RtmpDataSource");
rtmpDataSource = (DataSource) clazz.getDeclaredConstructor().newInstance();
} catch (ClassNotFoundException e) {
Log.w(TAG, "Attempting to play RTMP stream without depending on the RTMP extension");
} catch (InstantiationException e) {
Log.e(TAG, "Error instantiating RtmpDataSource", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Error instantiating RtmpDataSource", e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Error instantiating RtmpDataSource", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Error instantiating RtmpDataSource", e);
}
if (rtmpDataSource == null) {
rtmpDataSource = baseDataSource;
}
}
return rtmpDataSource;
}
}
| 43.793103 | 254 | 0.650281 |
eb2adcd294cbc2c079e6a7652717d32ca91b72e4 | 2,168 | /**
*
* Copyright 2017 Florian Erhard
*
* 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 gedi.riboseq.javapipeline;
import java.io.File;
import java.io.IOException;
import gedi.core.data.reads.AlignedReadsData;
import gedi.core.genomic.Genomic;
import gedi.core.region.GenomicRegionStorage;
import gedi.riboseq.cleavage.CleavageModelEstimator;
import gedi.util.io.text.LineOrientedFile;
import gedi.util.program.GediProgram;
import gedi.util.program.GediProgramContext;
import gedi.util.userInteraction.progress.Progress;
public class PriceCollectSufficientStatistics extends GediProgram {
public PriceCollectSufficientStatistics(PriceParameterSet params) {
addInput(params.prefix);
addInput(params.filter);
addInput(params.genomic);
addInput(params.reads);
addInput(params.percond);
addInput(params.skipmt);
addOutput(params.estimateData);
}
public String execute(GediProgramContext context) throws IOException {
String prefix = getParameter(0);
String filter = getParameter(1);
Genomic genomic = getParameter(2);
GenomicRegionStorage<AlignedReadsData> reads = getParameter(3);
boolean percond = getBooleanParameter(4);
boolean skipMt = getBooleanParameter(5);
CleavageModelEstimator em = new CleavageModelEstimator(genomic.getTranscripts(),reads,filter);
em.setProgress(context.getProgress());
if (skipMt)
em.setSkiptMT(skipMt);
em.setMerge(!percond);
em.collectEstimateData(new LineOrientedFile(prefix+".summary"));
new File(prefix+".summary").delete();
em.writeEstimateData(new LineOrientedFile(prefix+".estimateData"));
return null;
}
}
| 29.69863 | 96 | 0.759225 |
0e8031222bade664621a6becda485200c21a6575 | 28,579 |
package carrental;
import javax.swing.JOptionPane;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
public class Rents extends javax.swing.JFrame {
public Rents() {
initComponents();
DisplayCars();
GetCustomers();
DisplayRents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
RentIdTb = new javax.swing.JTextField();
RegNumTb = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
FeeTb = new javax.swing.JTextField();
ResetBtn = new javax.swing.JButton();
EditBtn = new javax.swing.JButton();
SaveBtn = new javax.swing.JButton();
jLabel15 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
CarsTable = new javax.swing.JTable();
CustCb = new javax.swing.JComboBox<>();
jLabel17 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
RentTable = new javax.swing.JTable();
jLabel18 = new javax.swing.JLabel();
PrintBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
jPanel1.setBackground(new java.awt.Color(255, 153, 0));
jLabel6.setFont(new java.awt.Font("Montserrat Medium", 0, 18)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("Customer");
jLabel6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel6MouseClicked(evt);
}
});
jLabel7.setFont(new java.awt.Font("Montserrat Medium", 0, 18)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 255, 255));
jLabel7.setText("Cars");
jLabel7.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel7MouseClicked(evt);
}
});
jLabel8.setFont(new java.awt.Font("Montserrat Medium", 0, 18)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 255));
jLabel8.setText("Return Car");
jLabel8.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel8MouseClicked(evt);
}
});
jLabel16.setFont(new java.awt.Font("Montserrat Medium", 0, 18)); // NOI18N
jLabel16.setForeground(new java.awt.Color(255, 255, 255));
jLabel16.setText("Log out");
jLabel16.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel16MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(44, 44, 44)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(jLabel6)
.addComponent(jLabel7)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel16)))
.addContainerGap(46, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(236, Short.MAX_VALUE)
.addComponent(jLabel6)
.addGap(33, 33, 33)
.addComponent(jLabel7)
.addGap(38, 38, 38)
.addComponent(jLabel8)
.addGap(225, 225, 225)
.addComponent(jLabel16)
.addContainerGap())
);
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jLabel5.setFont(new java.awt.Font("Montserrat ExtraBold", 0, 18)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 153, 0));
jLabel5.setText("x");
jLabel5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel5MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(0, 0, Short.MAX_VALUE))
);
jLabel10.setFont(new java.awt.Font("Impact", 0, 24)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 153, 51));
jLabel10.setText("Cars Rental");
jLabel13.setFont(new java.awt.Font("Montserrat Medium", 1, 14)); // NOI18N
jLabel13.setForeground(new java.awt.Color(255, 153, 51));
jLabel13.setText("Rent Id");
RegNumTb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RegNumTbActionPerformed(evt);
}
});
jLabel11.setFont(new java.awt.Font("Montserrat Medium", 1, 14)); // NOI18N
jLabel11.setForeground(new java.awt.Color(255, 153, 51));
jLabel11.setText("Registration");
jLabel14.setFont(new java.awt.Font("Montserrat Medium", 1, 14)); // NOI18N
jLabel14.setForeground(new java.awt.Color(255, 153, 51));
jLabel14.setText("Fees");
ResetBtn.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N
ResetBtn.setForeground(new java.awt.Color(255, 153, 0));
ResetBtn.setText("RESET");
ResetBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResetBtnActionPerformed(evt);
}
});
EditBtn.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N
EditBtn.setForeground(new java.awt.Color(255, 153, 0));
EditBtn.setText("EDIT");
EditBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EditBtnActionPerformed(evt);
}
});
SaveBtn.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N
SaveBtn.setForeground(new java.awt.Color(255, 153, 0));
SaveBtn.setText("SAVE");
SaveBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveBtnActionPerformed(evt);
}
});
jLabel15.setFont(new java.awt.Font("Impact", 0, 24)); // NOI18N
jLabel15.setForeground(new java.awt.Color(255, 153, 51));
jLabel15.setText("Cars List");
CarsTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null}
},
new String [] {
"Registration", "Brand", "Model", "Status", "Price"
}
));
CarsTable.setRowHeight(25);
CarsTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
CarsTableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(CarsTable);
CustCb.setFont(new java.awt.Font("Montserrat Medium", 0, 14)); // NOI18N
jLabel17.setFont(new java.awt.Font("Montserrat Medium", 1, 14)); // NOI18N
jLabel17.setForeground(new java.awt.Color(255, 153, 51));
jLabel17.setText("Customer Name");
RentTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null}
},
new String [] {
"Rent Id", "Registration", "Customer Name", "Rent Fee"
}
));
RentTable.setRowHeight(25);
RentTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
RentTableMouseClicked(evt);
}
});
jScrollPane2.setViewportView(RentTable);
jLabel18.setFont(new java.awt.Font("Impact", 0, 24)); // NOI18N
jLabel18.setForeground(new java.awt.Color(255, 153, 51));
jLabel18.setText("Cars on Rent");
PrintBtn.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N
PrintBtn.setForeground(new java.awt.Color(255, 153, 0));
PrintBtn.setText("PRINT");
PrintBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PrintBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addComponent(jScrollPane2)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(154, 154, 154)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addComponent(jLabel13)
.addGap(83, 83, 83)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(54, 54, 54)
.addComponent(jLabel17))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(RentIdTb, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(165, 165, 165)
.addComponent(RegNumTb, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(48, 48, 48)
.addComponent(CustCb, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(FeeTb, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(86, 86, 86)
.addComponent(jLabel14))))
.addGroup(layout.createSequentialGroup()
.addGap(396, 396, 396)
.addComponent(jLabel10))
.addGroup(layout.createSequentialGroup()
.addGap(396, 396, 396)
.addComponent(jLabel18))
.addGroup(layout.createSequentialGroup()
.addGap(298, 298, 298)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel15)
.addGroup(layout.createSequentialGroup()
.addComponent(SaveBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(EditBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(ResetBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 118, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(411, 411, 411)
.addComponent(PrintBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel10)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11)
.addComponent(jLabel13)
.addComponent(jLabel17)
.addComponent(jLabel14))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(RegNumTb, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(RentIdTb, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustCb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(FeeTb, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SaveBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EditBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ResetBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabel15)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jLabel18)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(PrintBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(7, 7, 7))
);
pack();
}// </editor-fold>//GEN-END:initComponents
Connection Con = null;
Statement St = null;
ResultSet Rs = null;
private void DisplayCars()
{
String CarStatus = "Available";
try{
Con = DriverManager.getConnection("http://sql11.freemysqlhosting.net","sql11418929","XasvuJM2QP");
St = Con.createStatement();
Rs = St.executeQuery("select * from CarTbl where Status='"+CarStatus+"'");
while(Rs.next()){
int id = Rs.getInt("id");
String name = Rs.getString("name");
float average = Rs.getFloat("average");
boolean active = Rs.getBoolean("active");
}
}catch(SQLException e)
{
e.printStackTrace();
}
}
private void DisplayRents()
{
//String CarStatus = "Available";
try{
Con = DriverManager.getConnection("http://sql11.freemysqlhosting.net","sql11418929","XasvuJM2QP");
St = Con.createStatement();
Rs = St.executeQuery("select * from RentTbl");
while(Rs.next()){
int id = Rs.getInt("id");
String name = Rs.getString("name");
float average = Rs.getFloat("average");
boolean active = Rs.getBoolean("active");
}
}catch(SQLException e)
{
e.printStackTrace();
}
}
private void GetCustomers()
{
try{
Con = DriverManager.getConnection("http://sql11.freemysqlhosting.net","sql11418929","XasvuJM2QP");
St = Con.createStatement();
String query ="select * from sql11418929.CustomerTb1";
Rs = St.executeQuery(query);
while (Rs.next()){
String Customer = Rs.getString("CustName");
CustCb.addItem(Customer);
}
}catch(Exception e)
{
e.printStackTrace();
}
}
private void UpdateCar()
{
try {
Con = DriverManager.getConnection("http://sql11.freemysqlhosting.net","sql11418929","XasvuJM2QP");
String Reg= RegNumTb.getText();
String CarStatus = "Booked";
String Query= "Update sql11418929.CarTb1 set Status='"+CarStatus+"'where CarReg='"+Reg+"'";
Statement Add = Con.createStatement();
Add.executeUpdate(Query);
JOptionPane.showMessageDialog(this,"Car Updated Successfully");
DisplayCars();
Reset();
} catch (Exception e){
e.printStackTrace();
}
}
private void RegNumTbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RegNumTbActionPerformed
}//GEN-LAST:event_RegNumTbActionPerformed
private void Reset()
{
RentIdTb.setText("");
RegNumTb.setText("");
CustCb.setSelectedIndex(0);
FeeTb.setText("");
}
private void ResetBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ResetBtnActionPerformed
Reset();
}//GEN-LAST:event_ResetBtnActionPerformed
private void EditBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditBtnActionPerformed
if(RegNumTb.getText().isEmpty() || FeeTb.getText().isEmpty() || RentIdTb.getText().isEmpty() || CustCb.getSelectedIndex() == -1)
{
JOptionPane.showMessageDialog(this,"Select The Rent To be Updated");
}else{
try {
Con = DriverManager.getConnection("http://sql11.freemysqlhosting.net","sql11418929","XasvuJM2QP");
int RId= Integer.valueOf(RentIdTb.getText());
String Query= "Update sql11418929.RentTb1 set CarReg='"+RegNumTb.getText()+"',CustName='"+CustCb.getSelectedItem().toString()+"',RentFee="+FeeTb.getText()+" where RentId='"+RId;
Statement Add = Con.createStatement();
Add.executeUpdate(Query);
JOptionPane.showMessageDialog(this,"Car Updated Successfully");
DisplayRents();
Reset();
} catch (Exception e){
e.printStackTrace();
}
}
}//GEN-LAST:event_EditBtnActionPerformed
private void SaveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveBtnActionPerformed
if(RegNumTb.getText().isEmpty() || FeeTb.getText().isEmpty() || RentIdTb.getText().isEmpty() || CustCb.getSelectedIndex() == -1)
{
JOptionPane.showMessageDialog(this,"Missing information");
}else{
try {
Con = DriverManager.getConnection("http://sql11.freemysqlhosting.net","sql11418929","XasvuJM2QP");
PreparedStatement add = Con.prepareStatement("insert into RentTbl values(?,?,?,?,?)");
add.setInt(1,Integer.valueOf(RentIdTb.getText()));
add.setString(2,RegNumTb.getText());
add.setString(3,CustCb.getSelectedItem().toString());
add.setInt(5,Integer.valueOf(FeeTb.getText()));
int row = add.executeUpdate();
JOptionPane.showMessageDialog(this,"Car Rented Successfully");
DisplayRents();
UpdateCar();
DisplayCars();
} catch (Exception e){
e.printStackTrace();
}}
}//GEN-LAST:event_SaveBtnActionPerformed
private void CarsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CarsTableMouseClicked
DefaultTableModel model = (DefaultTableModel)CarsTable.getModel();
int MyIndex = CarsTable.getSelectedRow();
RegNumTb.setText(model.getValueAt(MyIndex, 0).toString());
}//GEN-LAST:event_CarsTableMouseClicked
private void RentTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_RentTableMouseClicked
DefaultTableModel model = (DefaultTableModel)RentTable.getModel();
int MyIndex = RentTable.getSelectedRow();
RentIdTb.setText(model.getValueAt(MyIndex, 0).toString());
RegNumTb.setText(model.getValueAt(MyIndex, 1).toString());
CustCb.setSelectedItem(model.getValueAt(MyIndex, 2).toString());
FeeTb.setText(model.getValueAt(MyIndex, 3).toString());
}//GEN-LAST:event_RentTableMouseClicked
private void PrintBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PrintBtnActionPerformed
try{
RentTable.print();
}catch(Exception e){
}
}//GEN-LAST:event_PrintBtnActionPerformed
private void jLabel6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel6MouseClicked
new Customers().setVisible(true);
this.dispose();
}//GEN-LAST:event_jLabel6MouseClicked
private void jLabel7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel7MouseClicked
try {
new Cars().setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(Rents.class.getName()).log(Level.SEVERE, null, ex);
}
this.dispose();
}//GEN-LAST:event_jLabel7MouseClicked
private void jLabel8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel8MouseClicked
new Returns().setVisible(true);
this.dispose();
}//GEN-LAST:event_jLabel8MouseClicked
private void jLabel16MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel16MouseClicked
new Login().setVisible(true);
this.dispose();
}//GEN-LAST:event_jLabel16MouseClicked
private void jLabel5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel5MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabel5MouseClicked
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Rents().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTable CarsTable;
private javax.swing.JComboBox<String> CustCb;
private javax.swing.JButton EditBtn;
private javax.swing.JTextField FeeTb;
private javax.swing.JButton PrintBtn;
private javax.swing.JTextField RegNumTb;
private javax.swing.JTextField RentIdTb;
private javax.swing.JTable RentTable;
private javax.swing.JButton ResetBtn;
private javax.swing.JButton SaveBtn;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration//GEN-END:variables
}
| 49.189329 | 189 | 0.600616 |
534efe17e9782607984e4cf7335047dbe1285f85 | 3,999 | /**
* Copyright (C) 2016 LinkedIn Corp.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.linkedin.android.testbutler;
import android.app.Instrumentation;
import android.os.IBinder;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* A helper class for enabling/disabling Animations before/after running Espresso tests.
* <p>
* Google recommends that animations are disabled when Espresso tests are being run:
* https://code.google.com/p/android-test-kit/wiki/Espresso#Getting_Started
*/
final class AnimationDisabler {
private static String TAG = AnimationDisabler.class.getSimpleName();
private static final float DISABLED = 0.0f;
private float[] originalScaleFactors;
private Method setAnimationScalesMethod;
private Method getAnimationScalesMethod;
private Object windowManagerObject;
AnimationDisabler() {
try {
Class<?> windowManagerStubClazz = Class.forName("android.view.IWindowManager$Stub");
Method asInterface = windowManagerStubClazz.getDeclaredMethod("asInterface", IBinder.class);
Class<?> serviceManagerClazz = Class.forName("android.os.ServiceManager");
Method getService = serviceManagerClazz.getDeclaredMethod("getService", String.class);
Class<?> windowManagerClazz = Class.forName("android.view.IWindowManager");
// pre-cache the relevant Method objects using reflection so they're ready to use
setAnimationScalesMethod = windowManagerClazz.getDeclaredMethod("setAnimationScales", float[].class);
getAnimationScalesMethod = windowManagerClazz.getDeclaredMethod("getAnimationScales");
IBinder windowManagerBinder = (IBinder) getService.invoke(null, "window");
windowManagerObject = asInterface.invoke(null, windowManagerBinder);
} catch (Exception e) {
throw new RuntimeException("Failed to access animation methods", e);
}
}
/**
* Usually should be called inside {@link Instrumentation#onStart()}, before calling super.
*/
void disableAnimations() {
try {
originalScaleFactors = getAnimationScaleFactors();
setAnimationScaleFactors(DISABLED);
} catch (Exception e) {
Log.e(TAG, "Failed to disable animations", e);
}
}
/**
* Usually should be called inside {@link Instrumentation#onDestroy()}, before calling super.
*/
void enableAnimations() {
try {
restoreAnimationScaleFactors();
} catch (Exception e) {
Log.e(TAG, "Failed to enable animations", e);
}
}
private float[] getAnimationScaleFactors() throws InvocationTargetException, IllegalAccessException {
return (float[]) getAnimationScalesMethod.invoke(windowManagerObject);
}
private void setAnimationScaleFactors(float scaleFactor) throws InvocationTargetException, IllegalAccessException {
float[] scaleFactors = new float[originalScaleFactors.length];
Arrays.fill(scaleFactors, scaleFactor);
setAnimationScalesMethod.invoke(windowManagerObject, new Object[]{scaleFactors});
}
private void restoreAnimationScaleFactors() throws InvocationTargetException, IllegalAccessException {
setAnimationScalesMethod.invoke(windowManagerObject, new Object[]{originalScaleFactors});
}
}
| 39.205882 | 119 | 0.712178 |
9246daa47dd5dd9c9f8cc21accc861cc9a4ed837 | 2,811 | /*
* Copyright © 2022 DATAMART 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.
*/
package ru.datamart.kafka.postgres.writer.configuration;
import ru.datamart.kafka.postgres.writer.configuration.properties.PostgresProperties;
import ru.datamart.kafka.postgres.writer.service.executor.PostgresExecutor;
import io.vertx.core.Vertx;
import io.vertx.pgclient.PgConnectOptions;
import io.vertx.pgclient.PgPool;
import io.vertx.sqlclient.PoolOptions;
import lombok.val;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Configuration
public class PostgresConfiguration {
@Bean
public List<PostgresExecutor> postgresExecutors(Vertx vertx, PostgresProperties postgresProperties) {
return Arrays.stream(postgresProperties.getHosts().split(","))
.map(host -> {
val pgPool = prepareNewPool(host, postgresProperties, vertx);
return new PostgresExecutor(pgPool);
})
.collect(Collectors.toList());
}
private PgPool prepareNewPool(String hostPort, PostgresProperties postgresProperties, Vertx vertx) {
val hostPortArr = hostPort.split(":");
val host = hostPortArr[0];
val port = Integer.parseInt(hostPortArr[1]);
val pgConnectOptions = new PgConnectOptions();
pgConnectOptions.setDatabase(postgresProperties.getDatabase());
pgConnectOptions.setHost(host);
pgConnectOptions.setPort(port);
pgConnectOptions.setUser(postgresProperties.getUser());
pgConnectOptions.setPassword(postgresProperties.getPassword());
pgConnectOptions.setPreparedStatementCacheMaxSize(postgresProperties.getPreparedStatementsCacheMaxSize());
pgConnectOptions.setPreparedStatementCacheSqlLimit(postgresProperties.getPreparedStatementsCacheSqlLimit());
pgConnectOptions.setCachePreparedStatements(postgresProperties.isPreparedStatementsCache());
pgConnectOptions.setPipeliningLimit(1);
val poolOptions = new PoolOptions();
poolOptions.setMaxSize(postgresProperties.getPoolSize());
return PgPool.pool(vertx, pgConnectOptions, poolOptions);
}
}
| 43.246154 | 116 | 0.745286 |
fdd14d5072bd28533970dabe04c9b523b1241ca1 | 1,525 | package com.creche.crecheapi.entity;
import com.creche.crecheapi.exception.TipoTelefoneNaoExisteException;
import com.creche.crecheapi.request.TelefoneRequest;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
@Builder
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Document
@Table(value = "telefone")
public class Telefone {
@Id
@Column(value = "numero_telefone")
private String numero;
private String tipo;
@JsonIgnore
private Responsavel responsavel;
public Telefone(TelefoneRequest telefoneRequest) {
this.numero = telefoneRequest.getNumero();
if(telefoneRequest.getTipo().equalsIgnoreCase("fixo")) {
this.tipo = String.valueOf(TipoTelefone.FIXO);
} else if (telefoneRequest.getTipo().equalsIgnoreCase("celular")) {
this.tipo = String.valueOf(TipoTelefone.CELULAR);
} else if (telefoneRequest.getTipo().equalsIgnoreCase("comercial")) {
this.tipo = String.valueOf(TipoTelefone.COMERCIAL);
} else {
throw new TipoTelefoneNaoExisteException(telefoneRequest.getTipo());
}
}
}
| 31.770833 | 80 | 0.748197 |
61d59afb06efa7cd5e3b7fd6a05776f79388cac7 | 252 | package youdu.com.imoocsdk.module.emevent;
import java.util.ArrayList;
import youdu.com.imoocsdk.module.monitor.Monitor;
/**
* @author: vision
* @function:
* @date: 16/6/13
*/
public class PauseEvent {
public ArrayList<Monitor> content;
}
| 14.823529 | 49 | 0.714286 |
421da3e258b0553b0818fa1d9798e28d925e235d | 10,819 | /*
* Copyright 2017 EntIT Software LLC, a Micro Focus company, L.P.
* 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.hp.octane.integrations.dto.tests;
import com.hp.octane.integrations.dto.DTOFactory;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.*;
/**
* Testing Tests DTOs
*/
public class TestsDTOsTest {
private static final DTOFactory dtoFactory = DTOFactory.getInstance();
private static final String moduleName = "module";
private static final String packageName = "package";
private static final String className = "class";
private static final String testName = "test";
private static final TestRunResult result = TestRunResult.PASSED;
private static final long duration = 3000;
private static final long started = System.currentTimeMillis();
@Test
public void test_A() {
TestRun tr = dtoFactory.newDTO(TestRun.class)
.setModuleName(moduleName)
.setPackageName(packageName)
.setClassName(className)
.setTestName(testName)
.setResult(result)
.setStarted(started)
.setDuration(duration);
String xml = dtoFactory.dtoToXml(tr);
assertNotNull(xml);
assertTrue("external_run_id should not be in xml", !xml.contains("external_run_id"));
assertTrue("external_test_id should not be in xml", !xml.contains("external_test_id"));
TestRun backO = dtoFactory.dtoFromXml(xml, TestRun.class);
assertNotNull(backO);
assertEquals(moduleName, backO.getModuleName());
assertEquals(packageName, backO.getPackageName());
assertEquals(className, backO.getClassName());
assertEquals(testName, backO.getTestName());
assertEquals(result, backO.getResult());
assertEquals(started, backO.getStarted());
assertEquals(duration, backO.getDuration());
}
@Test
public void test_A_with_externalRunAndTest() {
String externalTestId = "externalTestId111";
String externalRunId = "externalRunId111";
TestRun tr = dtoFactory.newDTO(TestRun.class)
.setModuleName(moduleName)
.setPackageName(packageName)
.setClassName(className)
.setTestName(testName)
.setResult(result)
.setStarted(started)
.setDuration(duration)
.setExternalTestId(externalTestId)
.setExternalRunId(externalRunId);
String xml = dtoFactory.dtoToXml(tr);
assertNotNull(xml);
TestRun backO = dtoFactory.dtoFromXml(xml, TestRun.class);
assertNotNull(backO);
assertEquals(moduleName, backO.getModuleName());
assertEquals(packageName, backO.getPackageName());
assertEquals(className, backO.getClassName());
assertEquals(testName, backO.getTestName());
assertEquals(result, backO.getResult());
assertEquals(started, backO.getStarted());
assertEquals(duration, backO.getDuration());
assertEquals(externalRunId, backO.getExternalRunId());
assertEquals(externalTestId, backO.getExternalTestId());
}
@Test
public void test_B() {
TestRun tr1 = dtoFactory.newDTO(TestRun.class)
.setModuleName(moduleName)
.setPackageName(packageName)
.setClassName(className)
.setTestName(testName)
.setResult(result)
.setStarted(started)
.setDuration(duration);
TestRun tr2 = dtoFactory.newDTO(TestRun.class)
.setModuleName(moduleName)
.setPackageName(packageName)
.setClassName(className)
.setTestName(testName)
.setResult(result)
.setStarted(started)
.setDuration(duration);
TestRun tr3 = dtoFactory.newDTO(TestRun.class)
.setModuleName(moduleName)
.setPackageName(packageName)
.setClassName(className)
.setTestName(testName)
.setResult(result)
.setStarted(started)
.setDuration(duration);
TestsResult result = dtoFactory.newDTO(TestsResult.class)
.setTestRuns(Arrays.asList(tr1, tr2, tr3));
String xml = dtoFactory.dtoToXml(result);
assertNotNull(xml);
TestsResult backO = dtoFactory.dtoFromXml(xml, TestsResult.class);
assertNotNull(backO);
assertNotNull(backO.getTestRuns());
assertEquals(3, backO.getTestRuns().size());
}
@Test
public void parsingMqmTestResults() {
String payload = "<test_result><build server_id=\"to-be-filled-in-SDK\" job_id=\"simpleTests\" build_id=\"284\"/><test_fields><test_field type=\"Test_Type\" value=\"End to End\"/><test_field type=\"Testing_Tool_Type\" value=\"Selenium\"/>" +
"</test_fields><test_runs><test_run module=\"/helloWorld\" package=\"hello\" class=\"HelloWorldTest\" name=\"testTwo\" status=\"Failed\" duration=\"2\" started=\"1430919316223\">" +
"<error type=\"java.lang.AssertionError\" message=\"expected:'111' but was:'222'\">java.lang.AssertionError :aaa</error><description>My run description</description></test_run></test_runs></test_result>";
TestsResult result = dtoFactory.dtoFromXml(payload, TestsResult.class);
assertNotNull(result.getBuildContext());
assertNotNull(result.getTestFields());
assertNotNull(result.getTestRuns());
assertEquals(result.getBuildContext().getServerId(), "to-be-filled-in-SDK");
assertEquals(result.getBuildContext().getJobId(), "simpleTests");
assertEquals(result.getBuildContext().getBuildId(), "284");
assertEquals(result.getTestFields().size(), 2);
assertEquals(result.getTestFields().get(0).getValue(), "End to End");
assertEquals(result.getTestFields().get(0).getType(), "Test_Type");
assertEquals(result.getTestFields().get(1).getValue(), "Selenium");
assertEquals(result.getTestFields().get(1).getType(), "Testing_Tool_Type");
assertEquals(result.getTestRuns().get(0).getModuleName(), "/helloWorld");
assertEquals(result.getTestRuns().get(0).getPackageName(), "hello");
assertEquals(result.getTestRuns().get(0).getClassName(), "HelloWorldTest");
assertEquals(result.getTestRuns().get(0).getTestName(), "testTwo");
assertEquals(result.getTestRuns().get(0).getResult(), TestRunResult.FAILED);
assertEquals(result.getTestRuns().get(0).getDuration(), 2);
assertEquals(result.getTestRuns().get(0).getStarted(), 1430919316223l);
assertEquals(result.getTestRuns().get(0).getError().getErrorType(), "java.lang.AssertionError");
assertEquals(result.getTestRuns().get(0).getError().getErrorType(), "java.lang.AssertionError");
assertEquals(result.getTestRuns().get(0).getError().getErrorMessage(), "expected:'111' but was:'222'");
assertEquals(result.getTestRuns().get(0).getError().getStackTrace(), "java.lang.AssertionError :aaa");
assertEquals(result.getTestRuns().get(0).getDescription(), "My run description");
String converted = dtoFactory.dtoToXml(result);
assertEquals(payload, converted);
}
@Test
public void parsingJUnitTestResults() {
String payload = "<testsuite><properties><property name=\"nameAAA\" value=\"valueAAA\"/><property name=\"nameBBB\" value=\"valueBBB\"/></properties><testcase name=\"testAppErr\" classname=\"MF.simple.tests.AppTest\" time=\"0.002\"><failure type=\"junit.framework.AssertionFailedError\">junit.framework.AssertionFailedError at MF.simple.tests.AppTest.testAppC2(AppTest.java:56)</failure></testcase><testcase name=\"testAppA\" classname=\"MF.simple.tests.AppTest\" time=\"0.001\"/><testcase name=\"testAppB\" classname=\"MF.simple.tests.AppTest\" time=\"0.003\"/><testcase name=\"testAppC\" classname=\"MF.simple.tests.AppTest\" time=\"0\"/></testsuite>";
TestSuite result = dtoFactory.dtoFromXml(payload, TestSuite.class);
assertEquals(2, result.getProperties().size());
assertEquals("nameAAA", result.getProperties().get(0).getPropertyName());
assertEquals("valueAAA", result.getProperties().get(0).getPropertyValue());
assertEquals("nameBBB", result.getProperties().get(1).getPropertyName());
assertEquals("valueBBB", result.getProperties().get(1).getPropertyValue());
assertEquals(4, result.getTestCases().size());
assertEquals("testAppErr", result.getTestCases().get(0).getName());
assertEquals("MF.simple.tests.AppTest", result.getTestCases().get(0).getClassName());
assertEquals("0.002", result.getTestCases().get(0).getTime());
assertNotNull(result.getTestCases().get(0).getFailure());
assertEquals("junit.framework.AssertionFailedError", result.getTestCases().get(0).getFailure().getType());
assertEquals("junit.framework.AssertionFailedError at MF.simple.tests.AppTest.testAppC2(AppTest.java:56)", result.getTestCases().get(0).getFailure().getStackTrace());
assertEquals("testAppA", result.getTestCases().get(1).getName());
assertEquals("MF.simple.tests.AppTest", result.getTestCases().get(1).getClassName());
assertEquals("0.001", result.getTestCases().get(1).getTime());
assertNull(result.getTestCases().get(1).getFailure());
assertEquals("testAppB", result.getTestCases().get(2).getName());
assertEquals("MF.simple.tests.AppTest", result.getTestCases().get(2).getClassName());
assertEquals("0.003", result.getTestCases().get(2).getTime());
assertNull(result.getTestCases().get(2).getFailure());
assertEquals("testAppC", result.getTestCases().get(3).getName());
assertEquals("MF.simple.tests.AppTest", result.getTestCases().get(3).getClassName());
assertEquals("0", result.getTestCases().get(3).getTime());
assertNull(result.getTestCases().get(3).getFailure());
String converted = dtoFactory.dtoToXml(result);
assertEquals(payload, converted);
}
}
| 50.793427 | 661 | 0.663093 |
d895a2daffb0345bc0f998f0f8c08f0648204e84 | 7,288 | package org.n3r.eql.util;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.val;
import org.n3r.eql.config.EqlConfig;
import org.n3r.eql.map.EqlRun;
import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import static com.google.common.collect.Lists.newArrayList;
@SuppressWarnings("unchecked")
public class EqlUtils {
public static final String USER_HOME = System.getProperty("user.home");
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static String expandUserHome(String path) {
if (path.startsWith("~")) {
return USER_HOME + path.substring(1);
}
return path;
}
public static void compatibleWithUserToUsername(Map<String, String> params) {
if (params.containsKey("username")) return;
if (params.containsKey("user"))
params.put("username", params.get("user"));
}
@SneakyThrows
public static String getDriverNameFromConnection(DataSource dataSource) {
@Cleanup val connection = dataSource.getConnection();
return connection.getMetaData().getDriverName();
}
@SneakyThrows
public static String getJdbcUrlFromConnection(DataSource dataSource) {
@Cleanup val connection = dataSource.getConnection();
return connection.getMetaData().getURL();
}
public static Map<String, Object> newExecContext(Object[] originParams, Object[] dynamics) {
val execContext = Maps.<String, Object>newHashMap();
execContext.put("_time", new Timestamp(System.currentTimeMillis()));
execContext.put("_date", new java.util.Date());
execContext.put("_host", HostAddress.getHost());
execContext.put("_ip", HostAddress.getIp());
execContext.put("_results", newArrayList());
execContext.put("_lastResult", "");
Object[] params = convertParams(originParams);
execContext.put("_params", params);
if (params != null) {
execContext.put("_paramsCount", params.length);
for (int i = 0; i < params.length; ++i)
execContext.put("_" + (i + 1), params[i]);
}
execContext.put("_dynamics", dynamics);
if (dynamics != null)
execContext.put("_dynamicsCount", dynamics.length);
return execContext;
}
private static Object[] convertParams(Object[] originParams) {
if (originParams == null) return null;
Object[] objects = new Object[originParams.length];
for (int i = 0; i < originParams.length; ++i) {
objects[i] = convertParam(originParams[i]);
}
return objects;
}
private static Object convertParam(Object originParam) {
if (originParam instanceof List) return originParam;
if (originParam instanceof Iterable) {
return Lists.newArrayList((Iterable) originParam);
}
return originParam;
}
static Pattern endWithWhere = Pattern.compile("\\bWHERE$");
static Pattern endWithAnd = Pattern.compile("\\bAND$");
static Pattern endWithOr = Pattern.compile("\\bOR$");
public static String trimLastUnusedPart(String sql) {
val returnSql = S.trimRight(sql);
val upper = S.upperCase(returnSql);
if (endWithWhere.matcher(upper).find())
return S.trimRight(returnSql.substring(0, returnSql.length() - "WHERE".length()));
if (endWithAnd.matcher(upper).find())
return S.trimRight(returnSql.substring(0, returnSql.length() - "AND".length()));
if (endWithOr.matcher(upper).find())
return S.trimRight(returnSql.substring(0, returnSql.length() - "OR".length()));
return returnSql;
}
@SneakyThrows
public static PreparedStatement prepareSQL(
String sqlClassPath, EqlConfig eqlConfig, EqlRun eqlRun, String sqlId, String tagSqlId) {
val log = Logs.createLogger(eqlConfig, sqlClassPath, sqlId, tagSqlId, "prepare");
log.debug(eqlRun.getPrintSql());
val conn = eqlRun.getConnection();
val sql = eqlRun.getRunSql();
val procedure = eqlRun.getSqlType().isProcedure();
val ps = procedure ? conn.prepareCall(sql) : conn.prepareStatement(sql);
setQueryTimeout(eqlConfig, ps);
return ps;
}
public static int getConfigInt(EqlConfig eqlConfig, String key, int defaultValue) {
val configValue = eqlConfig.getStr(key);
if (S.isBlank(configValue)) return defaultValue;
if (configValue.matches("\\d+")) return Integer.parseInt(configValue);
return defaultValue;
}
@SneakyThrows
public static void setQueryTimeout(EqlConfig eqlConfig, Statement stmt) {
int queryTimeout = getConfigInt(eqlConfig, "query.timeout.seconds", 60);
if (queryTimeout <= 0) queryTimeout = 60;
try {
stmt.setQueryTimeout(queryTimeout);
} catch (Exception ignore) {
}
}
public static Iterable<?> evalCollection(String collectionExpr, EqlRun eqlRun) {
val evaluator = eqlRun.getEqlConfig().getExpressionEvaluator();
val value = evaluator.eval(collectionExpr, eqlRun);
if (value == null) return null;
if (value instanceof Iterable) return (Iterable<?>) value;
if (value.getClass().isArray()) return newArrayList((Object[]) value);
if (value instanceof Map) return ((Map) value).entrySet();
throw new RuntimeException(collectionExpr + " in "
+ eqlRun.getParamBean() + " is not an expression of a collection");
}
public static String collectionExprString(String collectionExpr, EqlRun eqlRun) {
val evaluator = eqlRun.getEqlConfig().getExpressionEvaluator();
val value = evaluator.eval(collectionExpr, eqlRun);
if (value == null) return null;
if (value instanceof Iterable || value.getClass().isArray()) return collectionExpr;
if (value instanceof Map) return collectionExpr + ".entrySet().toArray()";
throw new RuntimeException(collectionExpr + " in "
+ eqlRun.getParamBean() + " is not an expression of a collection");
}
/*
* Determine if SQLException#getSQLState() of the catched SQLException
* starts with 23 which is a constraint violation as per the SQL specification.
* It can namely be caused by more factors than "just" a constraint violation.
* You should not amend every SQLException as a constraint violation.
* ORACLE:
* [2017-03-26 15:13:07] [23000][1] ORA-00001: 违反唯一约束条件 (SYSTEM.SYS_C007109)
* MySQL:
* [2017-03-26 15:17:27] [23000][1062] Duplicate entry '1' for key 'PRIMARY'
* H2:
* [2017-03-26 15:19:52] [23505][23505] Unique index or primary key violation:
* "PRIMARY KEY ON PUBLIC.TT(A)"; SQL statement:
*
*/
public static boolean isConstraintViolation(Exception e) {
return e instanceof SQLException
&& ((SQLException) e).getSQLState().startsWith("23");
}
}
| 36.994924 | 101 | 0.657656 |
5bc308d9bc68ffcbb1b92a1795f3d644ef8ccb91 | 397 | package com.example.customer.application.business.exception;
@SuppressWarnings("serial")
public class ExistingCustomerException extends RuntimeException {
private final String identity;
public ExistingCustomerException(String message, String identity) {
super(message);
this.identity = identity;
}
public String getIdentity() {
return identity;
}
} | 23.352941 | 71 | 0.722922 |
d318f14e512ae335bcec78ba35f1fe527e1eaf3f | 8,504 | /*
* Copyright (c) 2012 EMC Corporation
* All Rights Reserved
*/
package com.emc.storageos.db.client.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import java.net.URI;
import java.util.Date;
/**
* Object storage hosting device details
*/
@Cf("HostingDeviceInfo")
@XmlRootElement(name = "hosting_device")
public class HostingDeviceInfo extends DataObject {
// Type of physical device on which this is hosted
private String _deviceType;
// State of the hosting device
private String _deviceState;
// Additional info required for initialization of a controller which communicates with the device
private String _additionalInfo;
// any info required for the device that must be encrypted
private String _encryptedInfo;
// version number to mach additionalInfo
// allow key controller to determine if update available
// incremented on DataStore update API
private Long _additionalInfoVersion = 0L;
// virtual pool for this hosting device
private URI _virtualPool;
// User specified description associated with this device
private String _deviceDescription;
private Long _totalSizeInB;
private Long _totalAvailableInB;
private Long _totalSizeInGB;
private Long _totalAvailableInGB;
// Time when this row was last updated
private Date _storageCapacityUpdatedTime;
// IP address of the data node that successfully mounted this hosting device
private String _dataNodeMountSuccessful;
// IP address of the data node that ran into failure while mounting this device
private String _dataNodeMountFailure;
// Failure message from the data node which ran into failure while mounting this device
private String _dataNodeFailureMessage;
// useful in ingestion
private Boolean _readOnly;
public static enum DeviceState {
unknown,
initializing,
initialized,
readytouse,
error,
intentToDelete,
deleting,
deleted
}
public HostingDeviceInfo()
{
super();
}
/**
* <p>
* Additional information specific to the protocol and hosting device
* </p>
* <p>
* read-only, can not modify
* </p>
*
* @return XML String
*/
@XmlElement
@Name("additionalInfo")
public String getAdditionalInfo() {
return _additionalInfo;
}
public void setAdditionalInfo(String additionalInfo)
{
_additionalInfo = additionalInfo;
setChanged("additionalInfo");
}
/**
* IP address of the data node which successfully mounted this device
*
* @return
*/
@XmlElement
@Name("dataNodeMountSuccessful")
public String getDataNodeMountSuccessful() {
return _dataNodeMountSuccessful;
}
public void setDataNodeMountSuccessful(String dataNodeMountSuccessful) {
_dataNodeMountSuccessful = dataNodeMountSuccessful;
setChanged("dataNodeMountSuccessful");
}
/**
* IP address of the data node which failed to mount this device
*
* @return
*/
@XmlElement
@Name("dataNodeMountFailure")
public String getDataNodeMountFailure() {
return _dataNodeMountFailure;
}
public void setDataNodeMountFailure(String dataNodeMountFailure) {
_dataNodeMountFailure = dataNodeMountFailure;
setChanged("dataNodeMountFailure");
}
/**
* Failure message from the data node which ran into failure while mounting this device
*
* @return
*/
@XmlElement
@Name("dataNodeFailureMessage")
public String getDataNodeFailureMessage() {
return _dataNodeFailureMessage;
}
public void setDataNodeFailureMessage(String dataNodeMountFailure) {
_dataNodeFailureMessage = dataNodeMountFailure;
setChanged("dataNodeFailureMessage");
}
/**
* Time when this key pool information was last updated
*
* @return
*/
@XmlElement
@Name("storageCapacityUpdatedTime")
public Date getStorageCapacityUpdatedTime() {
return _storageCapacityUpdatedTime;
}
public void setStorageCapacityUpdatedTime(Date lastUpdated) {
_storageCapacityUpdatedTime = lastUpdated;
setChanged("storageCapacityUpdatedTime");
}
/**
* version number associated with additionalInfo
*
* @return
*/
@XmlElement
@Name("additionalInfoVersion")
public Long getAdditionalInfoVersion() {
return _additionalInfoVersion;
}
public void setAdditionalInfoVersion(Long version) {
_additionalInfoVersion = version;
setChanged("additionalInfoVersion");
}
/**
* <p>
* Type of physical device on which this is hosted
* </p>
* <p>
* The following device types are known to web storage
* </p>
* <li>UNKNOWN - invalid or not set</li> <li>LOCAL - reserved, do not use</li> <li>NFS - NFS file share created on demand</li> <li>
* NFS_SERVER - Pre-allocated file share</li> <li>S3 - Amazon S3 format</li> <li>FC - Fibre channel or iSCSI</li> <li>ATMOS - EMC Atmos
* storage system</li>
*
* @return web storage device type
*/
@XmlElement
@Name("deviceType")
public String getDeviceType() {
return _deviceType;
}
public void setDeviceType(String deviceType)
{
_deviceType = deviceType;
setChanged("deviceType");
}
/**
* <p>
* State of the hosting device
* </p>
* <li>uninitialized - has not been initialized, unavailable for use</li> <li>initializing - being initialized</li> <li>initialized -
* initialized, ready for use</li> <li>deleting - being deleted, can not be used</li> <li>deleted - deleted, no longer exists</li>
*
* @return
*/
@XmlElement
@Name("deviceState")
public String getDeviceState() {
return _deviceState != null ? _deviceState : DeviceState.unknown.name();
}
public void setDeviceState(String newState) {
_deviceState = newState;
setChanged("deviceState");
}
/**
* class of service for this hosting device
*
* @return
*/
@XmlElement
@Name("virtualPool")
public URI getVirtualPool() {
return _virtualPool;
}
public void setVirtualPool(URI virtualPool) {
_virtualPool = virtualPool;
setChanged("virtualPool");
}
@XmlElement
@Name("description")
public String getDescription() {
return _deviceDescription;
}
public void setDescription(String description) {
_deviceDescription = description;
setChanged("description");
}
@XmlElement
@Name("capacity")
public Long getCapacity() {
return _totalSizeInB;
}
public void setCapacity(Long totalSize) {
_totalSizeInB = totalSize;
setChanged("capacity");
}
@Name("capacityInGB")
public Long getCapacityInGB() {
return _totalSizeInGB;
}
public void setCapacityInGB(Long totalSize) {
_totalSizeInGB = totalSize;
setChanged("capacityInGB");
}
@XmlElement
@Name("availableStorage")
public Long getAvailableStorage() {
return _totalAvailableInB;
}
public void setAvailableStorage(Long availableStorage) {
_totalAvailableInB = availableStorage;
setChanged("availableStorage");
setStorageCapacityUpdatedTime(new Date());
}
@Name("availableStorageInGB")
public Long getAvailableStorageInGB() {
return _totalAvailableInGB;
}
public void setAvailableStorageInGB(Long availableStorage) {
_totalAvailableInGB = availableStorage;
setChanged("availableStorageInGB");
setStorageCapacityUpdatedTime(new Date());
}
@Encrypt
@Name("encryptedInfo")
public String getEncryptedInfo() {
return _encryptedInfo;
}
public void setEncryptedInfo(String encryptedInfo)
{
_encryptedInfo = encryptedInfo;
setChanged("encryptedInfo");
}
// internal flag, won't be exposed to user.
@XmlTransient
@Name("readOnly")
public Boolean getReadOnly() {
return (_readOnly != null) && _readOnly;
}
public void setReadOnly(Boolean readOnly) {
_readOnly = readOnly;
setChanged("readOnly");
}
}
| 26.08589 | 139 | 0.659572 |
060d8444e360aab8c976d2ae9c05e24dcedde281 | 2,490 | package uk.ac.cam.cl.pico.data.session;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import uk.ac.cam.cl.pico.crypto.AuthToken;
import uk.ac.cam.cl.pico.crypto.SimpleAuthToken;
import uk.ac.cam.cl.pico.data.DataFactory;
import uk.ac.cam.cl.pico.data.pairing.Pairing;
import uk.ac.cam.cl.pico.data.pairing.PairingTest;
import uk.ac.cam.cl.pico.data.test.TestDataFactory;
import uk.ac.cam.cl.pico.util.UsesCryptoTest;
public class SessionTest extends UsesCryptoTest {
public static final DataFactory DATA_FACTORY = new TestDataFactory();
public static final SessionImpFactory FACTORY = DATA_FACTORY;
public static final String REMOTE_ID = "session remote ID";
public static final SecretKey SECRET_KEY = new SecretKeySpec("secret".getBytes(), "AES");
public static final Pairing PAIRING = PairingTest.getPairing();
public static final AuthToken AUTH_TOKEN = new SimpleAuthToken("auth");
@Test
public void testSessionSessionImpFactorySession() {
fail("Not yet implemented");
}
@Test
public void testNewInstanceActive() {
Session s = Session.newInstanceActive(
FACTORY, REMOTE_ID, SECRET_KEY, PAIRING, AUTH_TOKEN);
assertNotNull(s);
}
@Test
public void testNewInstanceClosed() {
fail("Not yet implemented");
}
@Test
public void testNewInstanceInError() {
fail("Not yet implemented");
}
@Test
public void testEqualsObject() {
fail("Not yet implemented");
}
@Test
public void testSetStatus() {
fail("Not yet implemented");
}
@Test
public void testSetError() {
fail("Not yet implemented");
}
@Test
public void testSetLastAuthDate() {
fail("Not yet implemented");
}
@Test
public void testHasAuthToken() {
fail("Not yet implemented");
}
@Test
public void testGetAuthToken() {
fail("Not yet implemented");
}
@Test
public void testCheckRemoteIdNull() {
fail("Not yet implemented");
}
@Test
public void testCheckRemoteIdEmpty() {
fail("Not yet implemented");
}
@Test
public void testCheckLastAuthDateNull() {
fail("Not yet implemented");
}
@Test
public void testCheckLastAuthDateFuture() {
fail("Not yet implemented");
}
}
| 24.9 | 93 | 0.669478 |
7edc8037edfc38f96383ee24025b0576deeb7837 | 1,315 | package eg.edu.alexu.csd.oop.jdbcTests;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.junit.Test;
import eg.edu.alexu.csd.oop.jdbc.Driver;
import eg.edu.alexu.csd.oop.jdbc.TestRunner;
public class TestConnection {
private static String protocol = "xmldb";
private static String temp = System.getProperty("java.io.tmpdir");
private Connection createUseDatabase(String databaseName) throws SQLException {
Driver driver = new Driver();
Properties info = new Properties();
File dbDir = new File(temp + "/jdbc/" + Math.round((((float) Math.random()) * 100000)));
info.put("path", dbDir.getAbsoluteFile());
Connection connection = driver.connect("jdbc:" + protocol + "://localhost", info);
Statement statement = connection.createStatement();
statement.execute("CREATE DATABASE " + databaseName);
statement.execute("USE " + databaseName);
statement.close();
return connection;
}
@Test
public void testConnection() throws SQLException {
Connection connection = createUseDatabase("Home");
try {
connection.close();
Statement statement = connection.createStatement();
statement.close();
} catch (SQLException e) {
}
}
}
| 32.073171 | 91 | 0.702662 |
6ffbbf78f90034fb7ca2114fcb89c7917d08537a | 6,333 | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* C E D A R
* S O L U T I O N S "Software done right."
* S O F T W A R E
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Copyright (c) 2013 Kenneth J. Pronovici.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Apache License, Version 2.0.
* See LICENSE for more information about the licensing terms.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Author : Kenneth J. Pronovici <[email protected]>
* Language : Java 6
* Project : Secret Santa Exchange
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
package com.cedarsolutions.santa.client.internal.view;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import com.cedarsolutions.client.gwt.event.UnifiedEvent;
import com.cedarsolutions.client.gwt.event.UnifiedEventType;
import com.cedarsolutions.client.gwt.event.ViewEventHandler;
import com.cedarsolutions.santa.client.internal.view.EditParticipantTabView.AddConflictClickHandler;
import com.cedarsolutions.santa.client.internal.view.EditParticipantTabView.CancelClickHandler;
import com.cedarsolutions.santa.client.internal.view.EditParticipantTabView.DeleteConflictClickHandler;
import com.cedarsolutions.santa.client.internal.view.EditParticipantTabView.EmailColumn;
import com.cedarsolutions.santa.client.internal.view.EditParticipantTabView.NameColumn;
import com.cedarsolutions.santa.client.internal.view.EditParticipantTabView.SaveClickHandler;
import com.cedarsolutions.santa.client.junit.StubbedClientTestCase;
import com.cedarsolutions.santa.shared.domain.exchange.Participant;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.event.dom.client.ClickEvent;
/**
* Unit test for EditParticipantTabView.
* @author Kenneth J. Pronovici <[email protected]>
*/
public class EditParticipantTabViewTest extends StubbedClientTestCase {
/** Test NameColumn. */
@Test public void testNameColumn() {
Participant item = mock(Participant.class);
NameColumn column = new NameColumn();
assertTrue(column.getCell() instanceof TextCell);
assertFalse(column.isSortable());
assertEquals("", column.getValue(null));
when(item.getName()).thenReturn(null);
assertEquals("", column.getValue(item));
when(item.getName()).thenReturn("name");
assertEquals("name", column.getValue(item));
}
/** Test EmailColumn. */
@Test public void testEmailColumn() {
Participant item = mock(Participant.class);
EmailColumn column = new EmailColumn();
assertTrue(column.getCell() instanceof TextCell);
assertFalse(column.isSortable());
assertEquals("", column.getValue(null));
when(item.getEmailAddress()).thenReturn(null);
assertEquals("", column.getValue(item));
when(item.getEmailAddress()).thenReturn("email");
assertEquals("email", column.getValue(item));
}
/** Test SaveClickHandler. */
@Test public void testSaveClickHandler() {
ClickEvent event = mock(ClickEvent.class);
EditParticipantTabView view = mock(EditParticipantTabView.class);
SaveClickHandler handler = new SaveClickHandler(view);
assertSame(view, handler.getParent());
when(view.getSaveHandler()).thenReturn(null);
handler.onClick(event); // just make sure it doesn't blow up
ArgumentCaptor<UnifiedEvent> captor = ArgumentCaptor.forClass(UnifiedEvent.class);
ViewEventHandler saveEventHandler = mock(ViewEventHandler.class);
when(view.getSaveHandler()).thenReturn(saveEventHandler);
handler.onClick(event);
verify(saveEventHandler).handleEvent(captor.capture());
assertEquals(UnifiedEventType.CLICK_EVENT, captor.getValue().getEventType());
assertSame(event, captor.getValue().getClickEvent());
}
/** Test CancelClickHandler. */
@Test public void testCancelClickHandler() {
ClickEvent event = mock(ClickEvent.class);
EditParticipantTabView view = mock(EditParticipantTabView.class);
CancelClickHandler handler = new CancelClickHandler(view);
assertSame(view, handler.getParent());
when(view.getCancelHandler()).thenReturn(null);
handler.onClick(event); // just make sure it doesn't blow up
ArgumentCaptor<UnifiedEvent> captor = ArgumentCaptor.forClass(UnifiedEvent.class);
ViewEventHandler cancelEventHandler = mock(ViewEventHandler.class);
when(view.getCancelHandler()).thenReturn(cancelEventHandler);
handler.onClick(event);
verify(cancelEventHandler).handleEvent(captor.capture());
assertEquals(UnifiedEventType.CLICK_EVENT, captor.getValue().getEventType());
assertSame(event, captor.getValue().getClickEvent());
}
/** Test AddConflictClickHandler. */
@Test public void testAddConflictClickHandler() {
ClickEvent event = mock(ClickEvent.class);
EditParticipantTabView view = mock(EditParticipantTabView.class);
AddConflictClickHandler handler = new AddConflictClickHandler(view);
assertSame(view, handler.getParent());
handler.onClick(event);
verify(view).addSelectedConflict();
}
/** Test DeleteConflictClickHandler. */
@Test public void testDeleteConflictClickHandler() {
ClickEvent event = mock(ClickEvent.class);
EditParticipantTabView view = mock(EditParticipantTabView.class);
DeleteConflictClickHandler handler = new DeleteConflictClickHandler(view);
assertSame(view, handler.getParent());
handler.onClick(event);
verify(view).deleteSelectedConflicts();
}
}
| 40.858065 | 104 | 0.672193 |
cc601147714d69d3e83b2f0181f5526aa9753205 | 4,149 | /*
* Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8267555
* @requires vm.jvmti
* @summary Class redefinition with a different class file version
* @library /test/lib
* @compile TestClassOld.jasm TestClassNew.jasm
* @run main RedefineClassHelper
* @run main/othervm -javaagent:redefineagent.jar ClassVersionAfterRedefine
*/
import java.io.InputStream;
import java.lang.reflect.Method;
import static jdk.test.lib.Asserts.assertTrue;
public class ClassVersionAfterRedefine extends ClassLoader {
private static String myName = ClassVersionAfterRedefine.class.getName();
private static byte[] getBytecodes(String name) throws Exception {
InputStream is = ClassVersionAfterRedefine.class.getResourceAsStream(name + ".class");
byte[] buf = is.readAllBytes();
System.out.println("sizeof(" + name + ".class) == " + buf.length);
return buf;
}
private static int getStringIndex(String needle, byte[] buf) {
return getStringIndex(needle, buf, 0);
}
private static int getStringIndex(String needle, byte[] buf, int offset) {
outer:
for (int i = offset; i < buf.length - offset - needle.length(); i++) {
for (int j = 0; j < needle.length(); j++) {
if (buf[i + j] != (byte)needle.charAt(j)) continue outer;
}
return i;
}
return 0;
}
private static void replaceString(byte[] buf, String name, int index) {
for (int i = index; i < index + name.length(); i++) {
buf[i] = (byte)name.charAt(i - index);
}
}
private static void replaceAllStrings(byte[] buf, String oldString, String newString) throws Exception {
assertTrue(oldString.length() == newString.length(), "must have same length");
int index = -1;
while ((index = getStringIndex(oldString, buf, index + 1)) != 0) {
replaceString(buf, newString, index);
}
}
public static void main(String[] s) throws Exception {
byte[] buf = getBytecodes("TestClassOld");
// Poor man's renaming of class "TestClassOld" to "TestClassXXX"
replaceAllStrings(buf, "TestClassOld", "TestClassXXX");
ClassVersionAfterRedefine cvar = new ClassVersionAfterRedefine();
Class<?> old = cvar.defineClass(null, buf, 0, buf.length);
Method foo = old.getMethod("foo");
Object result = foo.invoke(null);
assertTrue("java-lang-String".equals(result));
System.out.println(old.getSimpleName() + ".foo() = " + result);
buf = getBytecodes("TestClassNew");
// Rename class "TestClassNew" to "TestClassXXX" so we can use it for
// redefining the original version of "TestClassXXX" (i.e. "TestClassOld").
replaceAllStrings(buf, "TestClassNew", "TestClassXXX");
// Now redine the original version of "TestClassXXX" (i.e. "TestClassOld").
RedefineClassHelper.redefineClass(old, buf);
result = foo.invoke(null);
assertTrue("java.lang.String".equals(result));
System.out.println(old.getSimpleName() + ".foo() = " + result);
}
}
| 40.281553 | 108 | 0.66498 |
c1b18614276abd590f96917fe85ec6d9ebb9393a | 39,449 | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.wifi;
import static android.net.wifi.WifiManager.WIFI_MODE_FULL;
import static android.net.wifi.WifiManager.WIFI_MODE_FULL_HIGH_PERF;
import static android.net.wifi.WifiManager.WIFI_MODE_NO_LOCKS_HELD;
import static android.net.wifi.WifiManager.WIFI_MODE_SCAN_ONLY;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.os.WorkSource;
import android.provider.Settings;
import android.util.Slog;
import com.android.internal.util.Protocol;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;
import java.io.FileDescriptor;
import java.io.PrintWriter;
/**
* WifiController is the class used to manage on/off state of WifiStateMachine for various operating
* modes (normal, airplane, wifi hotspot, etc.).
*/
public class WifiController extends StateMachine {
private static final String TAG = "WifiController";
private static final boolean DBG = false;
private Context mContext;
private boolean mScreenOff;
private boolean mDeviceIdle;
private int mPluggedType;
private int mStayAwakeConditions;
private long mIdleMillis;
private int mSleepPolicy;
private boolean mFirstUserSignOnSeen = false;
private AlarmManager mAlarmManager;
private PendingIntent mIdleIntent;
private static final int IDLE_REQUEST = 0;
/**
* See {@link Settings.Global#WIFI_IDLE_MS}. This is the default value if a
* Settings.Global value is not present. This timeout value is chosen as
* the approximate point at which the battery drain caused by Wi-Fi
* being enabled but not active exceeds the battery drain caused by
* re-establishing a connection to the mobile data network.
*/
private static final long DEFAULT_IDLE_MS = 15 * 60 * 1000; /* 15 minutes */
/**
* See {@link Settings.Global#WIFI_REENABLE_DELAY_MS}. This is the default value if a
* Settings.Global value is not present. This is the minimum time after wifi is disabled
* we'll act on an enable. Enable requests received before this delay will be deferred.
*/
private static final long DEFAULT_REENABLE_DELAY_MS = 500;
// finding that delayed messages can sometimes be delivered earlier than expected
// probably rounding errors.. add a margin to prevent problems
private static final long DEFER_MARGIN_MS = 5;
NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
private static final String ACTION_DEVICE_IDLE =
"com.android.server.WifiManager.action.DEVICE_IDLE";
/* References to values tracked in WifiService */
private final WifiStateMachine mWifiStateMachine;
private final WifiSettingsStore mSettingsStore;
private final WifiLockManager mWifiLockManager;
/**
* Temporary for computing UIDS that are responsible for starting WIFI.
* Protected by mWifiStateTracker lock.
*/
private final WorkSource mTmpWorkSource = new WorkSource();
private long mReEnableDelayMillis;
private FrameworkFacade mFacade;
private static final int BASE = Protocol.BASE_WIFI_CONTROLLER;
static final int CMD_EMERGENCY_MODE_CHANGED = BASE + 1;
static final int CMD_SCREEN_ON = BASE + 2;
static final int CMD_SCREEN_OFF = BASE + 3;
static final int CMD_BATTERY_CHANGED = BASE + 4;
static final int CMD_DEVICE_IDLE = BASE + 5;
static final int CMD_LOCKS_CHANGED = BASE + 6;
static final int CMD_SCAN_ALWAYS_MODE_CHANGED = BASE + 7;
static final int CMD_WIFI_TOGGLED = BASE + 8;
static final int CMD_AIRPLANE_TOGGLED = BASE + 9;
static final int CMD_SET_AP = BASE + 10;
static final int CMD_DEFERRED_TOGGLE = BASE + 11;
static final int CMD_USER_PRESENT = BASE + 12;
static final int CMD_AP_START_FAILURE = BASE + 13;
static final int CMD_EMERGENCY_CALL_STATE_CHANGED = BASE + 14;
static final int CMD_AP_STOPPED = BASE + 15;
static final int CMD_STA_START_FAILURE = BASE + 16;
// Command used to trigger a wifi stack restart when in active mode
static final int CMD_RESTART_WIFI = BASE + 17;
// Internal command used to complete wifi stack restart
private static final int CMD_RESTART_WIFI_CONTINUE = BASE + 18;
private DefaultState mDefaultState = new DefaultState();
private StaEnabledState mStaEnabledState = new StaEnabledState();
private ApStaDisabledState mApStaDisabledState = new ApStaDisabledState();
private StaDisabledWithScanState mStaDisabledWithScanState = new StaDisabledWithScanState();
private ApEnabledState mApEnabledState = new ApEnabledState();
private DeviceActiveState mDeviceActiveState = new DeviceActiveState();
private DeviceInactiveState mDeviceInactiveState = new DeviceInactiveState();
private ScanOnlyLockHeldState mScanOnlyLockHeldState = new ScanOnlyLockHeldState();
private FullLockHeldState mFullLockHeldState = new FullLockHeldState();
private FullHighPerfLockHeldState mFullHighPerfLockHeldState = new FullHighPerfLockHeldState();
private NoLockHeldState mNoLockHeldState = new NoLockHeldState();
private EcmState mEcmState = new EcmState();
WifiController(Context context, WifiStateMachine wsm, WifiSettingsStore wss,
WifiLockManager wifiLockManager, Looper looper, FrameworkFacade f) {
super(TAG, looper);
mFacade = f;
mContext = context;
mWifiStateMachine = wsm;
mSettingsStore = wss;
mWifiLockManager = wifiLockManager;
mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
mIdleIntent = mFacade.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
addState(mDefaultState);
addState(mApStaDisabledState, mDefaultState);
addState(mStaEnabledState, mDefaultState);
addState(mDeviceActiveState, mStaEnabledState);
addState(mDeviceInactiveState, mStaEnabledState);
addState(mScanOnlyLockHeldState, mDeviceInactiveState);
addState(mFullLockHeldState, mDeviceInactiveState);
addState(mFullHighPerfLockHeldState, mDeviceInactiveState);
addState(mNoLockHeldState, mDeviceInactiveState);
addState(mStaDisabledWithScanState, mDefaultState);
addState(mApEnabledState, mDefaultState);
addState(mEcmState, mDefaultState);
boolean isAirplaneModeOn = mSettingsStore.isAirplaneModeOn();
boolean isWifiEnabled = mSettingsStore.isWifiToggleEnabled();
boolean isScanningAlwaysAvailable = mSettingsStore.isScanAlwaysAvailable();
log("isAirplaneModeOn = " + isAirplaneModeOn +
", isWifiEnabled = " + isWifiEnabled +
", isScanningAvailable = " + isScanningAlwaysAvailable);
if (isScanningAlwaysAvailable) {
setInitialState(mStaDisabledWithScanState);
} else {
setInitialState(mApStaDisabledState);
}
setLogRecSize(100);
setLogOnlyTransitions(false);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_DEVICE_IDLE);
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
mContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ACTION_DEVICE_IDLE)) {
sendMessage(CMD_DEVICE_IDLE);
} else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
WifiManager.EXTRA_NETWORK_INFO);
} else if (action.equals(WifiManager.WIFI_AP_STATE_CHANGED_ACTION)) {
int state = intent.getIntExtra(
WifiManager.EXTRA_WIFI_AP_STATE,
WifiManager.WIFI_AP_STATE_FAILED);
if (state == WifiManager.WIFI_AP_STATE_FAILED) {
loge(TAG + "SoftAP start failed");
sendMessage(CMD_AP_START_FAILURE);
} else if (state == WifiManager.WIFI_AP_STATE_DISABLED) {
sendMessage(CMD_AP_STOPPED);
}
} else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
int state = intent.getIntExtra(
WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN);
if (state == WifiManager.WIFI_STATE_UNKNOWN) {
loge(TAG + "Wifi turn on failed");
sendMessage(CMD_STA_START_FAILURE);
}
}
}
},
new IntentFilter(filter));
initializeAndRegisterForSettingsChange(looper);
}
private void initializeAndRegisterForSettingsChange(Looper looper) {
Handler handler = new Handler(looper);
readStayAwakeConditions();
registerForStayAwakeModeChange(handler);
readWifiIdleTime();
registerForWifiIdleTimeChange(handler);
readWifiSleepPolicy();
registerForWifiSleepPolicyChange(handler);
readWifiReEnableDelay();
}
private void readStayAwakeConditions() {
mStayAwakeConditions = mFacade.getIntegerSetting(mContext,
Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
}
private void readWifiIdleTime() {
mIdleMillis = mFacade.getLongSetting(mContext,
Settings.Global.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
}
private void readWifiSleepPolicy() {
mSleepPolicy = mFacade.getIntegerSetting(mContext,
Settings.Global.WIFI_SLEEP_POLICY,
Settings.Global.WIFI_SLEEP_POLICY_NEVER);
}
private void readWifiReEnableDelay() {
mReEnableDelayMillis = mFacade.getLongSetting(mContext,
Settings.Global.WIFI_REENABLE_DELAY_MS, DEFAULT_REENABLE_DELAY_MS);
}
/**
* Observes settings changes to scan always mode.
*/
private void registerForStayAwakeModeChange(Handler handler) {
ContentObserver contentObserver = new ContentObserver(handler) {
@Override
public void onChange(boolean selfChange) {
readStayAwakeConditions();
}
};
mFacade.registerContentObserver(mContext,
Settings.Global.getUriFor(Settings.Global.STAY_ON_WHILE_PLUGGED_IN), false,
contentObserver);
}
/**
* Observes settings changes to wifi idle time.
*/
private void registerForWifiIdleTimeChange(Handler handler) {
ContentObserver contentObserver = new ContentObserver(handler) {
@Override
public void onChange(boolean selfChange) {
readWifiIdleTime();
}
};
mFacade.registerContentObserver(mContext,
Settings.Global.getUriFor(Settings.Global.WIFI_IDLE_MS), false, contentObserver);
}
/**
* Observes changes to wifi sleep policy
*/
private void registerForWifiSleepPolicyChange(Handler handler) {
ContentObserver contentObserver = new ContentObserver(handler) {
@Override
public void onChange(boolean selfChange) {
readWifiSleepPolicy();
}
};
mFacade.registerContentObserver(mContext,
Settings.Global.getUriFor(Settings.Global.WIFI_SLEEP_POLICY), false,
contentObserver);
}
/**
* Determines whether the Wi-Fi chipset should stay awake or be put to
* sleep. Looks at the setting for the sleep policy and the current
* conditions.
*
* @see #shouldDeviceStayAwake(int)
*/
private boolean shouldWifiStayAwake(int pluggedType) {
if (mSleepPolicy == Settings.Global.WIFI_SLEEP_POLICY_NEVER) {
// Never sleep
return true;
} else if ((mSleepPolicy == Settings.Global.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
(pluggedType != 0)) {
// Never sleep while plugged, and we're plugged
return true;
} else {
// Default
return shouldDeviceStayAwake(pluggedType);
}
}
/**
* Determine whether the bit value corresponding to {@code pluggedType} is set in
* the bit string mStayAwakeConditions. This determines whether the device should
* stay awake based on the current plugged type.
*
* @param pluggedType the type of plug (USB, AC, or none) for which the check is
* being made
* @return {@code true} if {@code pluggedType} indicates that the device is
* supposed to stay awake, {@code false} otherwise.
*/
private boolean shouldDeviceStayAwake(int pluggedType) {
return (mStayAwakeConditions & pluggedType) != 0;
}
private void updateBatteryWorkSource() {
mTmpWorkSource.clear();
if (mDeviceIdle) {
mTmpWorkSource.add(mWifiLockManager.createMergedWorkSource());
}
mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
}
class DefaultState extends State {
@Override
public boolean processMessage(Message msg) {
switch (msg.what) {
case CMD_SCREEN_ON:
mAlarmManager.cancel(mIdleIntent);
mScreenOff = false;
mDeviceIdle = false;
updateBatteryWorkSource();
break;
case CMD_SCREEN_OFF:
mScreenOff = true;
/*
* Set a timer to put Wi-Fi to sleep, but only if the screen is off
* AND the "stay on while plugged in" setting doesn't match the
* current power conditions (i.e, not plugged in, plugged in to USB,
* or plugged in to AC).
*/
if (!shouldWifiStayAwake(mPluggedType)) {
//Delayed shutdown if wifi is connected
if (mNetworkInfo.getDetailedState() ==
NetworkInfo.DetailedState.CONNECTED) {
if (DBG) Slog.d(TAG, "set idle timer: " + mIdleMillis + " ms");
mAlarmManager.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + mIdleMillis, mIdleIntent);
} else {
sendMessage(CMD_DEVICE_IDLE);
}
}
break;
case CMD_DEVICE_IDLE:
mDeviceIdle = true;
updateBatteryWorkSource();
break;
case CMD_BATTERY_CHANGED:
/*
* Set a timer to put Wi-Fi to sleep, but only if the screen is off
* AND we are transitioning from a state in which the device was supposed
* to stay awake to a state in which it is not supposed to stay awake.
* If "stay awake" state is not changing, we do nothing, to avoid resetting
* the already-set timer.
*/
int pluggedType = msg.arg1;
if (DBG) Slog.d(TAG, "battery changed pluggedType: " + pluggedType);
if (mScreenOff && shouldWifiStayAwake(mPluggedType) &&
!shouldWifiStayAwake(pluggedType)) {
long triggerTime = System.currentTimeMillis() + mIdleMillis;
if (DBG) Slog.d(TAG, "set idle timer for " + mIdleMillis + "ms");
mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
}
mPluggedType = pluggedType;
break;
case CMD_SET_AP:
case CMD_SCAN_ALWAYS_MODE_CHANGED:
case CMD_LOCKS_CHANGED:
case CMD_WIFI_TOGGLED:
case CMD_AIRPLANE_TOGGLED:
case CMD_EMERGENCY_MODE_CHANGED:
case CMD_EMERGENCY_CALL_STATE_CHANGED:
case CMD_AP_START_FAILURE:
case CMD_AP_STOPPED:
case CMD_STA_START_FAILURE:
case CMD_RESTART_WIFI:
case CMD_RESTART_WIFI_CONTINUE:
break;
case CMD_USER_PRESENT:
mFirstUserSignOnSeen = true;
break;
case CMD_DEFERRED_TOGGLE:
log("DEFERRED_TOGGLE ignored due to state change");
break;
default:
throw new RuntimeException("WifiController.handleMessage " + msg.what);
}
return HANDLED;
}
}
class ApStaDisabledState extends State {
private int mDeferredEnableSerialNumber = 0;
private boolean mHaveDeferredEnable = false;
private long mDisabledTimestamp;
@Override
public void enter() {
mWifiStateMachine.setSupplicantRunning(false);
// Supplicant can't restart right away, so not the time we switched off
mDisabledTimestamp = SystemClock.elapsedRealtime();
mDeferredEnableSerialNumber++;
mHaveDeferredEnable = false;
mWifiStateMachine.clearANQPCache();
}
@Override
public boolean processMessage(Message msg) {
switch (msg.what) {
case CMD_WIFI_TOGGLED:
case CMD_AIRPLANE_TOGGLED:
if (mSettingsStore.isWifiToggleEnabled()) {
if (doDeferEnable(msg)) {
if (mHaveDeferredEnable) {
// have 2 toggles now, inc serial number an ignore both
mDeferredEnableSerialNumber++;
}
mHaveDeferredEnable = !mHaveDeferredEnable;
break;
}
if (mDeviceIdle == false) {
// wifi is toggled, we need to explicitly tell WifiStateMachine that we
// are headed to connect mode before going to the DeviceActiveState
// since that will start supplicant and WifiStateMachine may not know
// what state to head to (it might go to scan mode).
mWifiStateMachine.setOperationalMode(WifiStateMachine.CONNECT_MODE);
transitionTo(mDeviceActiveState);
} else {
checkLocksAndTransitionWhenDeviceIdle();
}
} else if (mSettingsStore.isScanAlwaysAvailable()) {
transitionTo(mStaDisabledWithScanState);
}
break;
case CMD_SCAN_ALWAYS_MODE_CHANGED:
if (mSettingsStore.isScanAlwaysAvailable()) {
transitionTo(mStaDisabledWithScanState);
}
break;
case CMD_SET_AP:
if (msg.arg1 == 1) {
if (msg.arg2 == 0) { // previous wifi state has not been saved yet
mSettingsStore.setWifiSavedState(WifiSettingsStore.WIFI_DISABLED);
}
mWifiStateMachine.setHostApRunning((SoftApModeConfiguration) msg.obj,
true);
transitionTo(mApEnabledState);
}
break;
case CMD_DEFERRED_TOGGLE:
if (msg.arg1 != mDeferredEnableSerialNumber) {
log("DEFERRED_TOGGLE ignored due to serial mismatch");
break;
}
log("DEFERRED_TOGGLE handled");
sendMessage((Message)(msg.obj));
break;
case CMD_RESTART_WIFI_CONTINUE:
transitionTo(mDeviceActiveState);
break;
default:
return NOT_HANDLED;
}
return HANDLED;
}
private boolean doDeferEnable(Message msg) {
long delaySoFar = SystemClock.elapsedRealtime() - mDisabledTimestamp;
if (delaySoFar >= mReEnableDelayMillis) {
return false;
}
log("WifiController msg " + msg + " deferred for " +
(mReEnableDelayMillis - delaySoFar) + "ms");
// need to defer this action.
Message deferredMsg = obtainMessage(CMD_DEFERRED_TOGGLE);
deferredMsg.obj = Message.obtain(msg);
deferredMsg.arg1 = ++mDeferredEnableSerialNumber;
sendMessageDelayed(deferredMsg, mReEnableDelayMillis - delaySoFar + DEFER_MARGIN_MS);
return true;
}
}
class StaEnabledState extends State {
@Override
public void enter() {
mWifiStateMachine.setSupplicantRunning(true);
}
@Override
public boolean processMessage(Message msg) {
switch (msg.what) {
case CMD_WIFI_TOGGLED:
if (! mSettingsStore.isWifiToggleEnabled()) {
if (mSettingsStore.isScanAlwaysAvailable()) {
transitionTo(mStaDisabledWithScanState);
} else {
transitionTo(mApStaDisabledState);
}
}
break;
case CMD_AIRPLANE_TOGGLED:
/* When wi-fi is turned off due to airplane,
* disable entirely (including scan)
*/
if (! mSettingsStore.isWifiToggleEnabled()) {
transitionTo(mApStaDisabledState);
}
break;
case CMD_STA_START_FAILURE:
if (!mSettingsStore.isScanAlwaysAvailable()) {
transitionTo(mApStaDisabledState);
} else {
transitionTo(mStaDisabledWithScanState);
}
break;
case CMD_EMERGENCY_CALL_STATE_CHANGED:
case CMD_EMERGENCY_MODE_CHANGED:
boolean getConfigWiFiDisableInECBM = mFacade.getConfigWiFiDisableInECBM(mContext);
log("WifiController msg " + msg + " getConfigWiFiDisableInECBM "
+ getConfigWiFiDisableInECBM);
if ((msg.arg1 == 1) && getConfigWiFiDisableInECBM) {
transitionTo(mEcmState);
}
break;
case CMD_SET_AP:
if (msg.arg1 == 1) {
// remeber that we were enabled
mSettingsStore.setWifiSavedState(WifiSettingsStore.WIFI_ENABLED);
deferMessage(obtainMessage(msg.what, msg.arg1, 1, msg.obj));
transitionTo(mApStaDisabledState);
}
break;
default:
return NOT_HANDLED;
}
return HANDLED;
}
}
class StaDisabledWithScanState extends State {
private int mDeferredEnableSerialNumber = 0;
private boolean mHaveDeferredEnable = false;
private long mDisabledTimestamp;
@Override
public void enter() {
// need to set the mode before starting supplicant because WSM will assume we are going
// in to client mode
mWifiStateMachine.setOperationalMode(WifiStateMachine.SCAN_ONLY_WITH_WIFI_OFF_MODE);
mWifiStateMachine.setSupplicantRunning(true);
// Supplicant can't restart right away, so not the time we switched off
mDisabledTimestamp = SystemClock.elapsedRealtime();
mDeferredEnableSerialNumber++;
mHaveDeferredEnable = false;
mWifiStateMachine.clearANQPCache();
}
@Override
public boolean processMessage(Message msg) {
switch (msg.what) {
case CMD_WIFI_TOGGLED:
if (mSettingsStore.isWifiToggleEnabled()) {
if (doDeferEnable(msg)) {
if (mHaveDeferredEnable) {
// have 2 toggles now, inc serial number and ignore both
mDeferredEnableSerialNumber++;
}
mHaveDeferredEnable = !mHaveDeferredEnable;
break;
}
if (mDeviceIdle == false) {
transitionTo(mDeviceActiveState);
} else {
checkLocksAndTransitionWhenDeviceIdle();
}
}
break;
case CMD_AIRPLANE_TOGGLED:
if (mSettingsStore.isAirplaneModeOn() &&
! mSettingsStore.isWifiToggleEnabled()) {
transitionTo(mApStaDisabledState);
}
break;
case CMD_SCAN_ALWAYS_MODE_CHANGED:
if (! mSettingsStore.isScanAlwaysAvailable()) {
transitionTo(mApStaDisabledState);
}
break;
case CMD_SET_AP:
// Before starting tethering, turn off supplicant for scan mode
if (msg.arg1 == 1) {
mSettingsStore.setWifiSavedState(WifiSettingsStore.WIFI_DISABLED);
deferMessage(obtainMessage(msg.what, msg.arg1, 1, msg.obj));
transitionTo(mApStaDisabledState);
}
break;
case CMD_DEFERRED_TOGGLE:
if (msg.arg1 != mDeferredEnableSerialNumber) {
log("DEFERRED_TOGGLE ignored due to serial mismatch");
break;
}
logd("DEFERRED_TOGGLE handled");
sendMessage((Message)(msg.obj));
break;
default:
return NOT_HANDLED;
}
return HANDLED;
}
private boolean doDeferEnable(Message msg) {
long delaySoFar = SystemClock.elapsedRealtime() - mDisabledTimestamp;
if (delaySoFar >= mReEnableDelayMillis) {
return false;
}
log("WifiController msg " + msg + " deferred for " +
(mReEnableDelayMillis - delaySoFar) + "ms");
// need to defer this action.
Message deferredMsg = obtainMessage(CMD_DEFERRED_TOGGLE);
deferredMsg.obj = Message.obtain(msg);
deferredMsg.arg1 = ++mDeferredEnableSerialNumber;
sendMessageDelayed(deferredMsg, mReEnableDelayMillis - delaySoFar + DEFER_MARGIN_MS);
return true;
}
}
/**
* Only transition out of this state when AP failed to start or AP is stopped.
*/
class ApEnabledState extends State {
/**
* Save the pending state when stopping the AP, so that it will transition
* to the correct state when AP is stopped. This is to avoid a possible
* race condition where the new state might try to update the driver/interface
* state before AP is completely torn down.
*/
private State mPendingState = null;
/**
* Determine the next state based on the current settings (e.g. saved
* wifi state).
*/
private State getNextWifiState() {
if (mSettingsStore.getWifiSavedState() == WifiSettingsStore.WIFI_ENABLED) {
return mDeviceActiveState;
}
if (mSettingsStore.isScanAlwaysAvailable()) {
return mStaDisabledWithScanState;
}
return mApStaDisabledState;
}
@Override
public boolean processMessage(Message msg) {
switch (msg.what) {
case CMD_AIRPLANE_TOGGLED:
if (mSettingsStore.isAirplaneModeOn()) {
mWifiStateMachine.setHostApRunning(null, false);
mPendingState = mApStaDisabledState;
}
break;
case CMD_WIFI_TOGGLED:
if (mSettingsStore.isWifiToggleEnabled()) {
mWifiStateMachine.setHostApRunning(null, false);
mPendingState = mDeviceActiveState;
}
break;
case CMD_SET_AP:
if (msg.arg1 == 0) {
mWifiStateMachine.setHostApRunning(null, false);
mPendingState = getNextWifiState();
}
break;
case CMD_AP_STOPPED:
if (mPendingState == null) {
/**
* Stop triggered internally, either tether notification
* timed out or wifi is untethered for some reason.
*/
mPendingState = getNextWifiState();
}
if (mPendingState == mDeviceActiveState && mDeviceIdle) {
checkLocksAndTransitionWhenDeviceIdle();
} else {
// go ahead and transition because we are not idle or we are not going
// to the active state.
transitionTo(mPendingState);
}
break;
case CMD_EMERGENCY_CALL_STATE_CHANGED:
case CMD_EMERGENCY_MODE_CHANGED:
if (msg.arg1 == 1) {
mWifiStateMachine.setHostApRunning(null, false);
mPendingState = mEcmState;
}
break;
case CMD_AP_START_FAILURE:
transitionTo(getNextWifiState());
break;
default:
return NOT_HANDLED;
}
return HANDLED;
}
}
class EcmState extends State {
// we can enter EcmState either because an emergency call started or because
// emergency callback mode started. This count keeps track of how many such
// events happened; so we can exit after all are undone
private int mEcmEntryCount;
@Override
public void enter() {
mWifiStateMachine.setSupplicantRunning(false);
mWifiStateMachine.clearANQPCache();
mEcmEntryCount = 1;
}
@Override
public boolean processMessage(Message msg) {
if (msg.what == CMD_EMERGENCY_CALL_STATE_CHANGED) {
if (msg.arg1 == 1) {
// nothing to do - just says emergency call started
mEcmEntryCount++;
} else if (msg.arg1 == 0) {
// emergency call ended
decrementCountAndReturnToAppropriateState();
}
return HANDLED;
} else if (msg.what == CMD_EMERGENCY_MODE_CHANGED) {
if (msg.arg1 == 1) {
// Transitioned into emergency callback mode
mEcmEntryCount++;
} else if (msg.arg1 == 0) {
// out of emergency callback mode
decrementCountAndReturnToAppropriateState();
}
return HANDLED;
} else {
return NOT_HANDLED;
}
}
private void decrementCountAndReturnToAppropriateState() {
boolean exitEcm = false;
if (mEcmEntryCount == 0) {
loge("mEcmEntryCount is 0; exiting Ecm");
exitEcm = true;
} else if (--mEcmEntryCount == 0) {
exitEcm = true;
}
if (exitEcm) {
if (mSettingsStore.isWifiToggleEnabled()) {
if (mDeviceIdle == false) {
transitionTo(mDeviceActiveState);
} else {
checkLocksAndTransitionWhenDeviceIdle();
}
} else if (mSettingsStore.isScanAlwaysAvailable()) {
transitionTo(mStaDisabledWithScanState);
} else {
transitionTo(mApStaDisabledState);
}
}
}
}
/* Parent: StaEnabledState */
class DeviceActiveState extends State {
@Override
public void enter() {
mWifiStateMachine.setOperationalMode(WifiStateMachine.CONNECT_MODE);
mWifiStateMachine.setHighPerfModeEnabled(false);
}
@Override
public boolean processMessage(Message msg) {
if (msg.what == CMD_DEVICE_IDLE) {
checkLocksAndTransitionWhenDeviceIdle();
// We let default state handle the rest of work
} else if (msg.what == CMD_USER_PRESENT) {
// TLS networks can't connect until user unlocks keystore. KeyStore
// unlocks when the user punches PIN after the reboot. So use this
// trigger to get those networks connected.
if (mFirstUserSignOnSeen == false) {
mWifiStateMachine.reloadTlsNetworksAndReconnect();
}
mFirstUserSignOnSeen = true;
return HANDLED;
} else if (msg.what == CMD_RESTART_WIFI) {
deferMessage(obtainMessage(CMD_RESTART_WIFI_CONTINUE));
transitionTo(mApStaDisabledState);
return HANDLED;
}
return NOT_HANDLED;
}
}
/* Parent: StaEnabledState */
class DeviceInactiveState extends State {
@Override
public boolean processMessage(Message msg) {
switch (msg.what) {
case CMD_LOCKS_CHANGED:
checkLocksAndTransitionWhenDeviceIdle();
updateBatteryWorkSource();
return HANDLED;
case CMD_SCREEN_ON:
transitionTo(mDeviceActiveState);
// More work in default state
return NOT_HANDLED;
default:
return NOT_HANDLED;
}
}
}
/* Parent: DeviceInactiveState. Device is inactive, but an app is holding a scan only lock. */
class ScanOnlyLockHeldState extends State {
@Override
public void enter() {
mWifiStateMachine.setOperationalMode(WifiStateMachine.SCAN_ONLY_MODE);
}
}
/* Parent: DeviceInactiveState. Device is inactive, but an app is holding a full lock. */
class FullLockHeldState extends State {
@Override
public void enter() {
mWifiStateMachine.setOperationalMode(WifiStateMachine.CONNECT_MODE);
mWifiStateMachine.setHighPerfModeEnabled(false);
}
}
/* Parent: DeviceInactiveState. Device is inactive, but an app is holding a high perf lock. */
class FullHighPerfLockHeldState extends State {
@Override
public void enter() {
mWifiStateMachine.setOperationalMode(WifiStateMachine.CONNECT_MODE);
mWifiStateMachine.setHighPerfModeEnabled(true);
}
}
/* Parent: DeviceInactiveState. Device is inactive and no app is holding a wifi lock. */
class NoLockHeldState extends State {
@Override
public void enter() {
mWifiStateMachine.setOperationalMode(WifiStateMachine.DISABLED_MODE);
}
}
private void checkLocksAndTransitionWhenDeviceIdle() {
switch (mWifiLockManager.getStrongestLockMode()) {
case WIFI_MODE_NO_LOCKS_HELD:
if (mSettingsStore.isScanAlwaysAvailable()) {
transitionTo(mScanOnlyLockHeldState);
} else {
transitionTo(mNoLockHeldState);
}
break;
case WIFI_MODE_FULL:
transitionTo(mFullLockHeldState);
break;
case WIFI_MODE_FULL_HIGH_PERF:
transitionTo(mFullHighPerfLockHeldState);
break;
case WIFI_MODE_SCAN_ONLY:
transitionTo(mScanOnlyLockHeldState);
break;
}
}
@Override
public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
super.dump(fd, pw, args);
pw.println("mScreenOff " + mScreenOff);
pw.println("mDeviceIdle " + mDeviceIdle);
pw.println("mPluggedType " + mPluggedType);
pw.println("mIdleMillis " + mIdleMillis);
pw.println("mSleepPolicy " + mSleepPolicy);
}
}
| 42.281886 | 102 | 0.567594 |
ff4f947b4944a2f706b98c709c55701fb8249177 | 900 | package cn.gson.oasys.threadExample.suanfa;
import java.util.Stack;
/**
* 描述
* 用两个栈来实现一个队列,分别完成在队列尾部插入整数(push)和在队列头部删除整数(pop)的功能。
* 队列中的元素为int类型。保证操作合法,即保证pop操作时队列内已有元素。
*
* 示例:
* 输入:
* ["PSH1","PSH2","POP","POP"]
* 返回:
* 1,2
* 解析:
* "PSH1":代表将1插入队列尾部
* "PSH2":代表将2插入队列尾部
* "POP“:代表删除一个元素,先进先出=>返回1
* "POP“:代表删除一个元素,先进先出=>返回2
* 示例1
* 输入:["PSH1","PSH2","POP","POP"]
* 返回值:1,2
*/
public class SolutionStack {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack1.empty() && stack2.empty()){
throw new RuntimeException("Queue is empty");
}
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
| 20.454545 | 57 | 0.564444 |
fcd00e1de66c6278d8ac92505482edcac17d238c | 2,616 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.06.07 at 06:10:45 PM EEST
//
package gr.helix.core.web.model.openaire.server;
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 fundingParentType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="fundingParentType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice minOccurs="0">
* <element name="funding_level_1" type="{http://namespace.openaire.eu/oaf}fundingType"/>
* <element name="funding_level_0" type="{http://namespace.openaire.eu/oaf}fundingType"/>
* </choice>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "fundingParentType", propOrder = {
"fundingLevel1",
"fundingLevel0"
})
public class FundingParentType {
@XmlElement(name = "funding_level_1")
protected FundingType fundingLevel1;
@XmlElement(name = "funding_level_0")
protected FundingType fundingLevel0;
/**
* Gets the value of the fundingLevel1 property.
*
* @return
* possible object is
* {@link FundingType }
*
*/
public FundingType getFundingLevel1() {
return fundingLevel1;
}
/**
* Sets the value of the fundingLevel1 property.
*
* @param value
* allowed object is
* {@link FundingType }
*
*/
public void setFundingLevel1(FundingType value) {
this.fundingLevel1 = value;
}
/**
* Gets the value of the fundingLevel0 property.
*
* @return
* possible object is
* {@link FundingType }
*
*/
public FundingType getFundingLevel0() {
return fundingLevel0;
}
/**
* Sets the value of the fundingLevel0 property.
*
* @param value
* allowed object is
* {@link FundingType }
*
*/
public void setFundingLevel0(FundingType value) {
this.fundingLevel0 = value;
}
}
| 26.693878 | 122 | 0.636468 |
296cbbeff4aea0581672db365c4310adbb95ef75 | 2,210 | package org.tarantool.jdbc.type;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.JDBCType;
import java.sql.NClob;
/**
* Describes supported JDBC types that match
* Tarantool SQL types.
*
* Skipped unsupported types are
* numeric types {@link JDBCType#NUMERIC}, {@link JDBCType#DECIMAL};
* date types {@link JDBCType#DATE}, {@link JDBCType#TIME}, {@link JDBCType#TIMESTAMP};
* xml type {@link JDBCType#SQLXML}.
*/
public enum JdbcType {
UNKNOWN(Object.class, JDBCType.OTHER, false),
CHAR(String.class, JDBCType.CHAR, true),
VARCHAR(String.class, JDBCType.VARCHAR, true),
LONGVARCHAR(String.class, JDBCType.LONGNVARCHAR, true),
NCHAR(String.class, JDBCType.NCHAR, true),
NVARCHAR(String.class, JDBCType.NVARCHAR, true),
LONGNVARCHAR(String.class, JDBCType.LONGNVARCHAR, true),
BINARY(byte[].class, JDBCType.BINARY, true),
VARBINARY(byte[].class, JDBCType.VARBINARY, true),
LONGVARBINARY(byte[].class, JDBCType.LONGVARBINARY, true),
BIT(Boolean.class, JDBCType.BIT, false),
BOOLEAN(Boolean.class, JDBCType.BOOLEAN, false),
REAL(Float.class, JDBCType.REAL, false),
FLOAT(Double.class, JDBCType.FLOAT, false),
DOUBLE(Double.class, JDBCType.DOUBLE, false),
TINYINT(Byte.class, JDBCType.TINYINT, false),
SMALLINT(Short.class, JDBCType.SMALLINT, false),
INTEGER(Integer.class, JDBCType.INTEGER, false),
BIGINT(Long.class, JDBCType.BIGINT, false),
CLOB(Clob.class, JDBCType.CLOB, false),
NCLOB(NClob.class, JDBCType.NCLOB, false),
BLOB(Blob.class, JDBCType.BLOB, false);
private final Class<?> javaType;
private final JDBCType targetJdbcType;
private final boolean trimmable;
JdbcType(Class<?> javaType, JDBCType targetJdbcType, boolean trimmable) {
this.javaType = javaType;
this.targetJdbcType = targetJdbcType;
this.trimmable = trimmable;
}
public Class<?> getJavaType() {
return javaType;
}
public JDBCType getTargetJdbcType() {
return targetJdbcType;
}
public boolean isTrimmable() {
return trimmable;
}
public int getTypeNumber() {
return targetJdbcType.getVendorTypeNumber();
}
}
| 29.466667 | 87 | 0.697285 |
e6dd189fee074462fd24be5628802afce20566d1 | 2,825 | package com.ruoyi.project.mbkj.systemtransactionlog.domain;
import com.ruoyi.framework.aspectj.lang.annotation.Excel;
import com.ruoyi.framework.web.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.util.Date;
/**
* 交易记录对象 system_transaction_log
*
* @author 云晓得峰
* @date 2020-08-06
*/
public class SystemTransactionLog extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 主键 */
private Long id;
/** 客户id */
@Excel(name = "客户id")
private Long clientid;
/** 用户id */
@Excel(name = "用户id")
private Long userid;
/** 指标id */
@Excel(name = "指标id")
private Long standardid;
/** 指标数 */
@Excel(name = "指标数")
private String mytarget;
/** st_usertarget表中的主键 */
@Excel(name = "st_usertarget表中的主键")
private Long usertargetid;
/** 资产类型 1 正资产 2负资产 */
@Excel(name = "资产类型 1 正资产 2负资产")
private Long assettype;
private Date createtime;
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public void setId(Long id)
{
this.id = id;
}
public Long getId()
{
return id;
}
public void setClientid(Long clientid)
{
this.clientid = clientid;
}
public Long getClientid()
{
return clientid;
}
public void setUserid(Long userid)
{
this.userid = userid;
}
public Long getUserid()
{
return userid;
}
public void setStandardid(Long standardid)
{
this.standardid = standardid;
}
public Long getStandardid()
{
return standardid;
}
public void setMytarget(String mytarget)
{
this.mytarget = mytarget;
}
public String getMytarget()
{
return mytarget;
}
public void setUsertargetid(Long usertargetid)
{
this.usertargetid = usertargetid;
}
public Long getUsertargetid()
{
return usertargetid;
}
public void setAssettype(Long assettype)
{
this.assettype = assettype;
}
public Long getAssettype()
{
return assettype;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("clientid", getClientid())
.append("userid", getUserid())
.append("standardid", getStandardid())
.append("mytarget", getMytarget())
.append("usertargetid", getUsertargetid())
.append("createtime", getCreatetime())
.append("assettype", getAssettype())
.toString();
}
}
| 20.925926 | 71 | 0.60354 |
cdcfef2c829dfc90f547a73d7609f8e7b96a3f9d | 17,315 | /*
* 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.myfaces.trinidadinternal.share.xml.beans;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xml.sax.Attributes;
import org.apache.myfaces.trinidad.logging.TrinidadLogger;
import org.apache.myfaces.trinidadinternal.share.xml.BaseNodeParser;
import org.apache.myfaces.trinidadinternal.share.xml.NodeParser;
import org.apache.myfaces.trinidadinternal.share.xml.ParseContext;
/**
* The node parser for UIX Beans.
*
* @version $Name: $ ($Revision: adfrt/faces/adf-faces-impl/src/main/java/oracle/adfinternal/view/faces/share/xml/beans/BeanParser.java#0 $) $Date: 10-nov-2005.18:59:18 $
*/
public class BeanParser extends BaseNodeParser
{
/**
* Creates a BeanParser based on a bean definition.
* @param beanDef the bean definition
*/
public BeanParser(
BeanDef beanDef)
{
if (beanDef == null)
throw new NullPointerException();
_beanDef = beanDef;
}
@Override
public void startElement(
ParseContext context,
String namespaceURI,
String localName,
Attributes attrs)
{
try
{
Object bean = _beanDef.createBean(namespaceURI, localName);
int length = attrs.getLength();
if (length > 0)
{
boolean otherNamespaces = _parseAttributes(context, bean, attrs, true);
if (otherNamespaces)
_parseAttributes(context, bean, attrs, false);
}
_namespaceURI = namespaceURI;
_bean = bean;
// Default properties: act as if the envelope element
// for the property is inserted around all the child elements
PropertyDef defaultPropertyDef = _beanDef.getDefaultPropertyDef();
if (defaultPropertyDef != null)
{
// "String" default properties simply mean that
// any text content will get set as that string - _not_ that
// there is a bonus envelope element
if (defaultPropertyDef.getPropertyType() != String.class)
{
_currentPropDef = defaultPropertyDef;
startEnvelopeChildProperty(context,
namespaceURI,
defaultPropertyDef.getName(),
null,
defaultPropertyDef);
}
}
}
catch (Exception e)
{
if (_LOG.isWarning())
_LOG.warning(e);
}
}
@Override
public NodeParser startChildElement(
ParseContext context,
String namespaceURI,
String localName,
Attributes attrs)
{
if (_bean == null)
return null;
// Inside an envelope property: we know what type we're looking for
if (_currentPropDef != null)
{
if (_currentPropDefUsed)
{
_LOG.warning("ONLY_ONE_CHILD_ELEMENT_ALLOWED");
return null;
}
// An array - get a parser for the component type of the array
if (_currentPropDefIsArray)
{
Class<?> cls = _currentPropDef.getPropertyType().getComponentType();
return context.getParser(cls,
namespaceURI,
localName);
}
// Not an array - get a parser for the type
else
{
// Mark the property definition as "used" - only one child
// element is allowed
_currentPropDefUsed = true;
return context.getParser(_currentPropDef.getPropertyType(),
namespaceURI,
localName);
}
}
PropertyDef def = null;
// Same namespace as the element itself: see if it matches up
// with a standard (not-namespaced) property definition
if (namespaceURI == _namespaceURI)
def = _beanDef.getPropertyDef(localName);
// OK, that didn't work - try a PropertyDef specific to the element.
if (def == null)
def = _beanDef.getElementPropertyDef(namespaceURI,
localName,
attrs);
if (def != null)
return startChildProperty(context,
namespaceURI,
localName,
attrs,
def);
return null;
}
@Override
public void endChildElement(
ParseContext context,
String namespaceURI,
String localName)
{
// Finishing up an array
if (_currentPropDefIsArray)
{
assert ((_currentPropDef != null) && (_currentArray != null));
// Extract the list into an array
Object[] array = _getArray(_currentPropDef, _currentArray);
// And set the array on the property definition
_currentPropDef.setValue(context, _bean, array);
// GC the array early
_currentArray = null;
}
// But always clear the property definition
_currentPropDef = null;
}
@Override
public void addText(
ParseContext context,
char[] text,
int start,
int length)
{
// We support text in only the following case:
// (1) There is a default property definition
// (2) That default property definition is a String
PropertyDef defaultPropertyDef = _beanDef.getDefaultPropertyDef();
if ((defaultPropertyDef != null) &&
(defaultPropertyDef.getPropertyType() == String.class))
{
String s = new String(text, start, length);
if (_defaultPropertyText == null)
_defaultPropertyText = s;
else
_defaultPropertyText = _defaultPropertyText + s;
}
}
@Override
public void addCompletedChild(
ParseContext context,
String namespaceURI,
String localName,
Object child)
{
if (child == null)
{
if (_currentPropDefInline)
_currentPropDef = null;
return;
}
assert ((_currentPropDef != null) && (_bean != null));
// For arrays, just add the child
if (_currentPropDefIsArray)
{
// Inline arrays - add the child to the correct list
if (_currentPropDefInline)
{
_inlineArrays.get(_currentPropDef).add(child);
_currentPropDef = null;
}
else
{
_currentArray.add(child);
}
}
// For non-arrays, set the value and we're done with this property
else
{
_currentPropDef.setValue(context, _bean, child);
// Inline properties won't get an "endChildElement()" call,
// so clean up immediately
if (_currentPropDefInline)
_currentPropDef = null;
}
}
@Override
public Object endElement(
ParseContext context,
String namespaceURI,
String localName)
{
if (_bean == null)
return null;
// For default properties, close the virtual element
PropertyDef defaultPropertyDef = _beanDef.getDefaultPropertyDef();
if (defaultPropertyDef != null)
{
// See above for the meaning of default properties for string
// values
if (defaultPropertyDef.getPropertyType() != String.class)
{
endChildElement(context, namespaceURI, defaultPropertyDef.getName());
}
else
{
if (_defaultPropertyText != null)
{
defaultPropertyDef.setValue(context, _bean, _defaultPropertyText);
}
}
}
// If we have any inline arrays, set those
if (_inlineArrays != null)
{
for(Map.Entry<PropertyDef, List<Object>> entry : _inlineArrays.entrySet())
{
PropertyDef def = entry.getKey();
Object[] array = _getArray(def, entry.getValue());
def.setValue(context, _bean, array);
}
}
return _beanDef.finishBean(_bean);
}
/**
* Called when an XML element is being parsed as a bean property.
* @see #startInlineChildProperty
* @see #startEnvelopeChildProperty
* @param context the parsing context
* @param namespaceURI the namespace of the element
* @param localName the local name of the element
* @param attrs the attributes attached to the element
* @param def the property definition
*/
final protected NodeParser startChildProperty(
ParseContext context,
String namespaceURI,
String localName,
Attributes attrs,
PropertyDef def)
{
if (isInlineChildProperty(context, namespaceURI, localName, def))
{
return startInlineChildProperty(context, namespaceURI, localName,
attrs, def);
}
else
{
return startEnvelopeChildProperty(context, namespaceURI, localName,
attrs, def);
}
}
/**
* Called to parse an XML element an inline bean property.
* Inline child properties do not use an envelope element - they
* are parsed directly off of the current element.
*
* @param context the parsing context
* @param namespaceURI the namespace of the element
* @param localName the local name of the element
* @param attrs the attributes attached to the element
* @param def the property definition
*/
protected NodeParser startInlineChildProperty(
ParseContext context,
String namespaceURI,
String localName,
Attributes attrs,
PropertyDef def)
{
Class<?> cls = def.getPropertyType();
boolean isArray = cls.isArray();
if (isArray)
cls = cls.getComponentType();
NodeParser parser = context.getParser(cls,
namespaceURI,
localName);
if (parser != null)
{
_currentPropDef = def;
_currentPropDefUsed = true;
_currentPropDefInline = true;
_currentPropDefIsArray = isArray;
// Inline arrays - we store a map of each inline array,
// and buffer up one ArrayList for each definition.
if (isArray)
{
if (_inlineArrays == null)
{
_inlineArrays = new HashMap<PropertyDef, List<Object>>(3);
}
// =-=AEW This assumes that either BeanDef is returning
// the same PropertyDef each time, or PropertyDef implements
// equals() correctly.
if (_inlineArrays.get(def) == null)
{
_inlineArrays.put(def, new ArrayList<Object>());
}
}
}
return parser;
}
/**
* Called to parse an XML element an inline bean property.
* Envelope child properties use an envelope element that
* names the property, but does not define its value. Instead,
* the envelope contains one further child XML element that
* defines the value. Most types are parsed in this fashion.
*
* @param context the parsing context
* @param namespaceURI the namespace of the element
* @param localName the local name of the element
* @param attrs the attributes attached to the element
* @param def the property definition
*/
protected NodeParser startEnvelopeChildProperty(
ParseContext context,
String namespaceURI,
String localName,
Attributes attrs,
PropertyDef def)
{
_currentPropDef = def;
_currentPropDefUsed = false;
_currentPropDefInline = false;
// Detect when we're starting an array
_currentPropDefIsArray = def.getPropertyType().isArray();
if (_currentPropDefIsArray)
{
_currentArray = new ArrayList<Object>();
}
return this;
}
/**
* Returns whether a given property definition
* is parsed inline. By default, this version always
* returns false.
* <p>
* @param context the parsing context
* @param def the property definition
*/
protected boolean isInlineChildProperty(
ParseContext context,
String namespaceURI,
String localName,
PropertyDef def)
{
return _beanDef.isInlineChildProperty(namespaceURI, localName, def);
}
/**
* An accessor function for retrieving the bean defintion.
*/
final protected BeanDef getBeanDef()
{
return _beanDef;
}
/**
* An accessor function for retrieving the bean currently being built.
*/
final protected Object getBean()
{
return _bean;
}
//
// Parse the XML attributes. Called first to parse
// the default namespace, then again to try all other
// namespaces.
//
private boolean _parseAttributes(
ParseContext context,
Object bean,
Attributes attrs,
boolean defaultNamespace)
{
boolean otherNamespaces = false;
int length = attrs.getLength();
for (int i = 0; i < length; i++)
{
String attrNamespace = attrs.getURI(i);
// Check if the namespace is correct for this pass
if ("".equals(attrNamespace) ^ !defaultNamespace)
{
String attrLocalName = attrs.getLocalName(i);
// Get the property
PropertyDef propertyDef;
if (defaultNamespace)
propertyDef = _beanDef.getPropertyDef(attrLocalName);
else
propertyDef = _beanDef.getPropertyDef(attrNamespace,
attrLocalName);
// If we find an property def, parse the text and
// set the value.
if (propertyDef != null)
{
String valueText = attrs.getValue(i);
try
{
Object value = propertyDef.parseText(context, attrNamespace,
valueText);
propertyDef.setValue(context, bean, value);
}
catch (IllegalArgumentException iae)
{
if (_LOG.isWarning())
{
if (defaultNamespace)
{
_LOG.warning("CANNOT_PARSE_ATTRIBUTE_VALUE", attrLocalName);
_LOG.warning(iae);
}
else
{
_LOG.warning("CANNOT_PARSE_ATTRIBUTE_VALUE_NAMESPACE", new Object[] {attrLocalName, attrNamespace});
_LOG.warning(iae);
}
}
}
}
else
{
logUnknownAttribute(context, attrNamespace, attrLocalName);
}
}
else
{
otherNamespaces = true;
}
}
return otherNamespaces;
}
/**
* Records that an attribute was unknown.
* @param context the parsing context
* @param namespaceURI the namespace of the attribute, or an
* empty string for no namespace
* @param localName the local name of the attribute
*/
protected void logUnknownAttribute(
ParseContext context,
String namespaceURI,
String localName)
{
if (_LOG.isWarning())
{
if ("".equals(namespaceURI))
_LOG.warning("UNKNOWN_ATTRIBUTE", localName);
else
_LOG.warning("UNKNOWN_ATTRIBUTE_NAMESPACE", new Object[]{localName, namespaceURI});
}
}
//
// Convert an ArrayList into an array of the correct Java type
//
static private Object[] _getArray(
PropertyDef def,
List<Object> list)
{
Object[] array = (Object[])
Array.newInstance(def.getPropertyType().getComponentType(),
list.size());
list.toArray(array);
return array;
}
// The bean definition
private final BeanDef _beanDef;
// The bean being built
private Object _bean;
// The namespace of the top-level element
private String _namespaceURI;
// The current property definition being worked on
private PropertyDef _currentPropDef;
// If true, then the current property has already been set,
// and additional elements should be treated as errors
private boolean _currentPropDefUsed;
// If true, the current property is an inline element (that is,
// one without an envelope wrapper)
private boolean _currentPropDefInline;
// If true, the current property is actually an array
// that is being buffered up
private boolean _currentPropDefIsArray;
// The list of the current property definition - used
// only for "envelope" elements
private List<Object> _currentArray;
// A map of all the "inline" array properties
private Map<PropertyDef, List<Object>> _inlineArrays;
// Text being accumulated for the default property
private String _defaultPropertyText;
private static final TrinidadLogger _LOG = TrinidadLogger.createTrinidadLogger(BeanParser.class);
}
| 28.762458 | 171 | 0.619232 |
1966cdf4dc88991e93f81fb34fb073447edc04f4 | 2,672 | package io.appium.uiautomator2.http;
import java.util.List;
import java.util.logging.Level;
import io.appium.uiautomator2.http.impl.NettyHttpRequest;
import io.appium.uiautomator2.http.impl.NettyHttpResponse;
import io.appium.uiautomator2.utils.Logger;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
public class ServerHandler extends ChannelInboundHandlerAdapter {
private final static java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(ServerHandler.class.getName());
private List<io.appium.uiautomator2.http.IHttpServlet> httpHandlers;
public ServerHandler(List<io.appium.uiautomator2.http.IHttpServlet> handlers) {
this.httpHandlers = handlers;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Logger.info("channel read invoked!");
if (!(msg instanceof FullHttpRequest)) {
return;
}
FullHttpRequest request = (FullHttpRequest) msg;
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
response.headers().add("Connection", "close");
Logger.info("channel read: " + request.getMethod().toString() + " " + request.getUri());
io.appium.uiautomator2.http.IHttpRequest httpRequest = new NettyHttpRequest(request);
io.appium.uiautomator2.http.IHttpResponse httpResponse = new NettyHttpResponse(response);
for (io.appium.uiautomator2.http.IHttpServlet handler : httpHandlers) {
handler.handleHttpRequest(httpRequest, httpResponse);
if (httpResponse.isClosed()) {
break;
}
}
if (!httpResponse.isClosed()) {
httpResponse.setStatus(404);
httpResponse.end();
}
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
super.channelRead(ctx, msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
ctx.fireChannelReadComplete();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOGGER.log(Level.SEVERE, "Error handling request", cause);
ctx.close();
super.exceptionCaught(ctx, cause);
}
}
| 37.111111 | 125 | 0.716317 |
d75fa5e4830785ac1dacc135cfb4e114c3d42f05 | 2,361 | package mod.acgaming.smava.init;
import mod.acgaming.smava.Reference;
import mod.acgaming.smava.entity.SmavaCreeperEntity;
import mod.acgaming.smava.utils.ConfigurationHandler;
import net.minecraft.entity.EntityClassification;
import net.minecraft.entity.EntitySpawnPlacementRegistry;
import net.minecraft.entity.EntitySpawnPlacementRegistry.PlacementType;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.ai.attributes.GlobalEntityTypeAttributes;
import net.minecraft.entity.monster.MonsterEntity;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.MobSpawnInfo;
import net.minecraft.world.biome.MobSpawnInfo.Spawners;
import net.minecraft.world.gen.Heightmap.Type;
import net.minecraftforge.event.world.BiomeLoadingEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.registries.ForgeRegistries;
import java.util.List;
@Mod.EventBusSubscriber(modid = Reference.MOD_ID)
public class SmavaEntities
{
@SubscribeEvent(priority = EventPriority.HIGH)
public static void addSpawn(BiomeLoadingEvent event)
{
Biome biome = ForgeRegistries.BIOMES.getValue(event.getName());
if (biome != null)
{
MobSpawnInfo info = biome.getMobSpawnInfo();
List<MobSpawnInfo.Spawners> spawns = event.getSpawns().getSpawner(EntityClassification.MONSTER);
for (Spawners entry : info.getSpawners(EntityClassification.MONSTER))
{
registerSpawn(spawns, entry, EntityType.CREEPER, SmavaRegistry.SMAVA_CREEPER.get());
}
}
}
public static void initializeEntities()
{
EntitySpawnPlacementRegistry.register(SmavaRegistry.SMAVA_CREEPER.get(), PlacementType.ON_GROUND, Type.MOTION_BLOCKING_NO_LEAVES, MonsterEntity::canMonsterSpawnInLight);
GlobalEntityTypeAttributes.put(SmavaRegistry.SMAVA_CREEPER.get(), SmavaCreeperEntity.registerAttributes().create());
}
public static void registerSpawn(List<Spawners> spawns, Spawners entry, EntityType<? extends LivingEntity> oldEntity, EntityType<? extends LivingEntity> newEntity)
{
if (entry.type == oldEntity)
{
spawns.add(new MobSpawnInfo.Spawners(newEntity, ConfigurationHandler.SPAWN.weight.get(), ConfigurationHandler.SPAWN.min.get(), ConfigurationHandler.SPAWN.max.get()));
}
}
} | 42.160714 | 171 | 0.817027 |
e7cd7c2a513af47dec8acc8f3a27455daf898251 | 4,647 | // Copyright (c) 2018-2019 Amit Green. All rights reserved.
package link.crystal.Capital.Format;
import java.lang.String;
import link.crystal.Capital.Core.Capital_StringBuilder;
import link.crystal.Capital.Core.Zone;
import link.crystal.Capital.Format.ArgumentSegmentFormatter_Inspection;
import link.crystal.Capital.Format.MessageFormatter_Base;
import link.crystal.Capital.Interface.Inspectable;
import link.crystal.Capital.Interface.MessageFormattable;
import link.crystal.Capital.Interface.SegmentFormattable;
public abstract class ArgumentSegmentFormatter<INSPECTION extends ArgumentSegmentFormatter_Inspection>
extends MessageFormatter_Base <INSPECTION>
// extends Inspectable_Object <INSPECTION>
// extends Object
implements MessageFormattable <INSPECTION>,
SegmentFormattable <INSPECTION>,
Inspectable <INSPECTION>//,
{
//
// Members
//
protected final int argument_index;
//
// Constructor
//
protected ArgumentSegmentFormatter(final int argument_index)
{
this.argument_index = argument_index;
}
//
// Interface Inspectable
//
public abstract INSPECTION inspect();
//
// Interface MessageFormattable
//
public abstract void augment(final Capital_StringBuilder builder, int depth, final Object v);
public abstract void augment_1_plus(
final Capital_StringBuilder builder,
final int depth,
final Object v,
final Object ... other_arguments//,
);
//
// Interface SegmentFormattable
//
public abstract void choose(final Capital_StringBuilder builder, final int depth);
public abstract void choose(final Capital_StringBuilder builder, final int depth, final Object v);
public abstract void choose(
final Capital_StringBuilder builder,
final int depth,
final Object v,
final Object w//,
);
public abstract void choose(
final Capital_StringBuilder builder,
final int depth,
final Object v,
final Object w,
final Object x//,
);
public abstract void choose(
final Capital_StringBuilder builder,
final int depth,
final Object v,
final Object w,
final Object x,
final Object y//,
);
public abstract void choose(
final Capital_StringBuilder builder,
final int depth,
final Object v,
final Object w,
final Object x,
final Object y4,
final Object y5//,
);
public abstract void choose(
Capital_StringBuilder builder,
int depth,
Object v,
Object w,
Object x,
Object y4,
Object y5,
Object y6//,
);
public abstract void choose(
final Capital_StringBuilder builder,
final int depth,
final Object v,
final Object w,
final Object x,
final Object y4,
final Object y5,
final Object y6,
final Object y7,
final Object ... other_arguments//,
);
//
// Interface Inspectable
//
@Override
public final void portray(final Capital_StringBuilder builder)
{
builder.append("<", this.inspect().simple_class_name, " ", this.argument_index, ">");
}
}
| 34.93985 | 117 | 0.467829 |
031cb8da49f249363535158845ffcf1affe389f2 | 2,818 | package com.lp.techDemo.metaq.producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.lp.techDemo.http.message.MessageEntity;
import com.lp.techDemo.message.provider.MessagePublisher;
import com.lp.techDemo.metaq.entity.MetaqDemoEntity;
import com.taobao.metamorphosis.Message;
import com.taobao.metamorphosis.client.MessageSessionFactory;
import com.taobao.metamorphosis.client.MetaClientConfig;
import com.taobao.metamorphosis.client.MetaMessageSessionFactory;
import com.taobao.metamorphosis.client.extension.spring.MessageBuilder;
import com.taobao.metamorphosis.client.extension.spring.MetaqTemplate;
import com.taobao.metamorphosis.client.producer.MessageProducer;
import com.taobao.metamorphosis.client.producer.SendResult;
import com.taobao.metamorphosis.utils.ZkUtils.ZKConfig;
public class MetaqDemoProducer {
private static final Logger LOGGER = LoggerFactory.getLogger(MetaqDemoProducer.class);
private MetaqTemplate template;
public static void main(String[] args) throws Exception {
// sendWithPureMetaq();
sendWithSpring();
}
static void sendWithPureMetaq() throws Exception{
final MetaClientConfig metaClientConfig = new MetaClientConfig();
final ZKConfig zkConfig = new ZKConfig();
//设置zookeeper地址
zkConfig.zkConnect = "127.0.0.1:2181";
metaClientConfig.setZkConfig(zkConfig);
// New session factory,强烈建议使用单例
MessageSessionFactory sessionFactory = new MetaMessageSessionFactory(metaClientConfig);
// create producer,强烈建议使用单例
MessageProducer producer = sessionFactory.createProducer();
// publish topic
final String topic = "test";
producer.publish(topic);
for (int i = 0; i < 50; i++){
// send message
SendResult sendResult = producer.sendMessage(new Message(topic, (topic + i).getBytes()));
// check result
if (!sendResult.isSuccess()) {
System.err.println("Send message failed,error message:" + sendResult.getErrorMessage());
}
else {
System.out.println("Send message successfully,sent to " + sendResult.getPartition());
}
}
}
static void sendWithSpring(){
ClassPathXmlApplicationContext c = new ClassPathXmlApplicationContext("metaq-producer.xml");
c.start();
MetaqTemplate mt = (MetaqTemplate) c.getBean("metaqTemplate");
for (long i = 0; i < 50; i++){
MetaqDemoEntity entity = new MetaqDemoEntity();
entity.setSendOrder(i);
try {
mt.send(MessageBuilder.withTopic("mytopic").withBody(entity));
} catch (InterruptedException e) {
LOGGER.error("send to mytopic fails", e);
e.printStackTrace();
}
}
c.close();
}
}
| 37.573333 | 104 | 0.721079 |
f8003b8f88774312157419b1193e51f8492ca85c | 648 | package bank.customer;
import java.util.LinkedList;
import java.util.List;
import bank.products.Account;
import bank.products.Credit;
public class BusinessCustomer {
private String name;
private List<Account> accounts;
private List<Credit> credits;
public BusinessCustomer(String name) {
this.name = name;
accounts = new LinkedList<Account>();
credits = new LinkedList<Credit>();
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public List<Account> getAccounts() {
return accounts;
}
public List<Credit> getCredits() {
return credits;
}
}
| 12.96 | 41 | 0.695988 |
be29b8c0930645365efc3255234cbb0c2b534c2b | 2,728 | package com.chickenkiller.upods2.models;
import com.chickenkiller.upods2.interfaces.IMediaItemView;
import com.chickenkiller.upods2.utils.GlobalUtils;
import java.util.ArrayList;
/**
* Created by Alon Zilberman on 7/3/15.
* Basic class for any media item, can be show in feature screen.
*/
public abstract class MediaItem extends SQLModel implements IMediaItemView {
/**
* Created by Alon Zilberman on 10/23/15.
* Use it to transfer MediaItems and tracks in one object
*/
public static class MediaItemBucket {
public MediaItem mediaItem;
public Track track;
}
protected String name;
protected String coverImageUrl;
protected float score;
public boolean isSubscribed;
public MediaItem() {
}
public String getCoverImageUrl() {
return coverImageUrl;
}
public String getName() {
return name;
}
public String getSubHeader() {
return "";
}
public String getBottomHeader() {
return "";
}
public boolean hasTracks() {
return false;
}
public String getDescription() {
return "";
}
public String getAudeoLink() {
return null;
}
public String getBitrate() {
return "";
}
public void syncWithDB(){
}
public void syncWithMediaItem(MediaItem updatedMediaItem) {
this.id = updatedMediaItem.id;
this.isSubscribed = updatedMediaItem.isSubscribed;
this.isExistsInDb = updatedMediaItem.isExistsInDb;
}
public static boolean hasMediaItemWithName(ArrayList<? extends MediaItem> mediaItems, MediaItem mediaItemToCheck) {
for (MediaItem mediaItem : mediaItems) {
if (mediaItem.getName().equals(mediaItemToCheck.getName())) {
return true;
}
}
return false;
}
public static MediaItem getMediaItemByName(ArrayList<? extends MediaItem> mediaItems, MediaItem mediaItemTarget) {
return getMediaItemByName(mediaItems, mediaItemTarget.getName());
}
public static MediaItem getMediaItemByName(ArrayList<? extends MediaItem> mediaItems, String targetName) {
for (MediaItem mediaItem : mediaItems) {
if (GlobalUtils.safeTitleEquals(mediaItem.getName(), targetName)) {
return mediaItem;
}
}
return null;
}
public static ArrayList<String> getIds(ArrayList<? extends MediaItem> mediaItems) {
ArrayList<String> ids = new ArrayList<>();
for (MediaItem mediaItem : mediaItems) {
ids.add(String.valueOf(mediaItem.id));
}
return ids;
}
public float getScore(){
return score;
}
}
| 24.8 | 119 | 0.641862 |
1c5df24a14168f421300fc86a95ba90ab1f7c81d | 1,542 | package com.atguigu.gmall.psm.service.impl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.core.bean.PageVo;
import com.atguigu.core.bean.Query;
import com.atguigu.core.bean.QueryCondition;
import com.atguigu.gmall.psm.dao.CategoryDao;
import com.atguigu.gmall.psm.entity.CategoryEntity;
import com.atguigu.gmall.psm.service.CategoryService;
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
@Override
public PageVo queryPage(QueryCondition params) {
IPage<CategoryEntity> page = this.page(
new Query<CategoryEntity>().getPage(params),
new QueryWrapper<CategoryEntity>()
);
return new PageVo(page);
}
@GlobalTransactional
@Override
public PageVo queryGroupByPage(QueryCondition queryCondition, Long catId) {
QueryWrapper<CategoryEntity> queryWrapper= new QueryWrapper<CategoryEntity>();
if(catId !=null){
queryWrapper.eq("catelog_id",catId);
}
IPage<CategoryEntity> page = this.page(
new Query<CategoryEntity>().getPage(queryCondition),
queryWrapper
);
return new PageVo(page);
}
} | 33.521739 | 110 | 0.724384 |
62ccc5b78e773f9ada0273a830888ddab6e4c2ec | 21,472 | /*
* Copyright 2019-present HiveMQ 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 com.hivemq.persistence.local.memory;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import com.google.common.collect.ImmutableSet;
import com.hivemq.annotations.ExecuteInSingleWriter;
import com.hivemq.bootstrap.ioc.lazysingleton.LazySingleton;
import com.hivemq.configuration.service.InternalConfigurations;
import com.hivemq.extension.sdk.api.annotations.NotNull;
import com.hivemq.extension.sdk.api.annotations.Nullable;
import com.hivemq.extensions.iteration.BucketChunkResult;
import com.hivemq.logging.EventLog;
import com.hivemq.metrics.HiveMQMetrics;
import com.hivemq.metrics.MetricsHolder;
import com.hivemq.persistence.NoSessionException;
import com.hivemq.persistence.PersistenceEntry;
import com.hivemq.persistence.clientsession.ClientSession;
import com.hivemq.persistence.clientsession.ClientSessionWill;
import com.hivemq.persistence.clientsession.PendingWillMessages;
import com.hivemq.persistence.exception.InvalidSessionExpiryIntervalException;
import com.hivemq.persistence.local.ClientSessionLocalPersistence;
import com.hivemq.persistence.local.xodus.bucket.BucketUtils;
import com.hivemq.persistence.payload.PublishPayloadPersistence;
import com.hivemq.util.ClientSessions;
import com.hivemq.util.ObjectMemoryEstimation;
import com.hivemq.util.ThreadPreConditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.hivemq.mqtt.message.connect.Mqtt5CONNECT.SESSION_EXPIRE_ON_DISCONNECT;
import static com.hivemq.mqtt.message.disconnect.DISCONNECT.SESSION_EXPIRY_NOT_SET;
import static com.hivemq.util.ThreadPreConditions.SINGLE_WRITER_THREAD_PREFIX;
/**
* @author Georg Held
*/
@LazySingleton
public class ClientSessionMemoryLocalPersistence implements ClientSessionLocalPersistence {
private static final @NotNull Logger log = LoggerFactory.getLogger(ClientSessionMemoryLocalPersistence.class);
private final @NotNull PublishPayloadPersistence payloadPersistence;
private final @NotNull MetricsHolder metricsHolder;
private final @NotNull EventLog eventLog;
private final @NotNull Map<String, PersistenceEntry<ClientSession>> @NotNull [] buckets;
private final @NotNull AtomicInteger sessionsCount = new AtomicInteger(0);
private final @NotNull AtomicLong currentMemorySize = new AtomicLong();
private final int bucketCount;
@Inject
ClientSessionMemoryLocalPersistence(
final @NotNull PublishPayloadPersistence payloadPersistence,
final @NotNull MetricRegistry metricRegistry,
final @NotNull MetricsHolder metricsHolder,
final @NotNull EventLog eventLog) {
this.payloadPersistence = payloadPersistence;
this.metricsHolder = metricsHolder;
this.eventLog = eventLog;
bucketCount = InternalConfigurations.PERSISTENCE_BUCKET_COUNT.get();
//noinspection unchecked
buckets = new Map[bucketCount];
for (int i = 0; i < bucketCount; i++) {
buckets[i] = new HashMap<>();
}
metricRegistry.register(HiveMQMetrics.CLIENT_SESSIONS_MEMORY_PERSISTENCE_TOTAL_SIZE.name(),
(Gauge<Long>) currentMemorySize::get);
}
private @NotNull Map<String, PersistenceEntry<ClientSession>> getBucket(final int bucketIndex) {
checkArgument(bucketIndex <= bucketCount, "Bucket must be less or equal than bucketCount");
return buckets[bucketIndex];
}
@Override
public @Nullable ClientSession getSession(
final @NotNull String clientId, final int bucketIndex, final boolean checkExpired) {
return getSession(clientId, bucketIndex, checkExpired, true);
}
@Override
public @Nullable ClientSession getSession(final @NotNull String clientId, final int bucketIndex) {
return getSession(clientId, bucketIndex, true, true);
}
@Override
public @Nullable ClientSession getSession(final @NotNull String clientId, final boolean checkExpired) {
final int bucketIndex = BucketUtils.getBucket(clientId, bucketCount);
return getSession(clientId, bucketIndex, checkExpired, true);
}
@Override
public @Nullable ClientSession getSession(
final @NotNull String clientId, final boolean checkExpired, final boolean includeWill) {
final int bucketIndex = BucketUtils.getBucket(clientId, bucketCount);
return getSession(clientId, bucketIndex, checkExpired, includeWill);
}
@Override
public @Nullable ClientSession getSession(final @NotNull String clientId) {
final int bucketIndex = BucketUtils.getBucket(clientId, bucketCount);
return getSession(clientId, bucketIndex, true, true);
}
private @Nullable ClientSession getSession(
final @NotNull String clientId,
final int bucketIndex,
final boolean checkExpired,
final boolean includeWill) {
final Map<String, PersistenceEntry<ClientSession>> bucket = getBucket(bucketIndex);
final PersistenceEntry<ClientSession> storedSession = bucket.get(clientId);
if (storedSession == null) {
return null;
}
final ClientSession clientSession = storedSession.getObject().deepCopy();
if (checkExpired &&
ClientSessions.isExpired(clientSession, System.currentTimeMillis() - storedSession.getTimestamp())) {
return null;
}
if (includeWill) {
loadWillPayload(clientSession);
}
return clientSession;
}
@Override
public @Nullable Long getTimestamp(final @NotNull String clientId) {
final int bucketIndex = BucketUtils.getBucket(clientId, bucketCount);
return getTimestamp(clientId, bucketIndex);
}
@Override
public @Nullable Long getTimestamp(final @NotNull String clientId, final int bucketIndex) {
final Map<String, PersistenceEntry<ClientSession>> bucket = getBucket(bucketIndex);
final PersistenceEntry<ClientSession> storedSession = bucket.get(clientId);
if (storedSession == null) {
return null;
}
return storedSession.getTimestamp();
}
@Override
@ExecuteInSingleWriter
public void put(
final @NotNull String clientId,
final @NotNull ClientSession newClientSession,
final long timestamp,
final int bucketIndex) {
checkNotNull(clientId, "Client id must not be null");
checkNotNull(newClientSession, "Client session must not be null");
checkArgument(timestamp > 0, "Timestamp must be greater than 0");
ThreadPreConditions.startsWith(SINGLE_WRITER_THREAD_PREFIX);
final Map<String, PersistenceEntry<ClientSession>> sessions = getBucket(bucketIndex);
final ClientSession usedSession = newClientSession.deepCopy();
sessions.compute(clientId, (ignored, storedSession) -> {
final boolean addClientIdSize;
if (storedSession == null) {
sessionsCount.incrementAndGet();
addClientIdSize = true;
} else {
final ClientSession oldSession = storedSession.getObject();
currentMemorySize.addAndGet(-storedSession.getEstimatedSize());
removeWillReference(oldSession);
final boolean oldSessionIsPersistent = isPersistent(oldSession);
if (!oldSessionIsPersistent && !oldSession.isConnected()) {
sessionsCount.incrementAndGet();
}
addClientIdSize = false;
}
final ClientSessionWill newWill = newClientSession.getWillPublish();
if (newWill != null) {
metricsHolder.getStoredWillMessagesCount().inc();
payloadPersistence.add(newWill.getPayload(), 1, newWill.getPublishId());
}
final PersistenceEntry<ClientSession> newEntry = new PersistenceEntry<>(usedSession, timestamp);
currentMemorySize.addAndGet(newEntry.getEstimatedSize());
if (addClientIdSize) {
currentMemorySize.addAndGet(ObjectMemoryEstimation.stringSize(clientId));
}
return newEntry;
});
}
@Override
@ExecuteInSingleWriter
public @NotNull ClientSession disconnect(
final @NotNull String clientId,
final long timestamp,
final boolean sendWill,
final int bucketIndex,
final long sessionExpiryInterval) {
ThreadPreConditions.startsWith(SINGLE_WRITER_THREAD_PREFIX);
final Map<String, PersistenceEntry<ClientSession>> bucket = getBucket(bucketIndex);
final ClientSession storedSession = bucket.compute(clientId, (ignored, oldEntry) -> {
if (oldEntry == null) {
// we create a tombstone here which will be removed at next cleanup
final ClientSession clientSession = new ClientSession(false, SESSION_EXPIRE_ON_DISCONNECT);
final PersistenceEntry<ClientSession> persistenceEntry = new PersistenceEntry<>(clientSession, timestamp);
currentMemorySize.addAndGet(persistenceEntry.getEstimatedSize() + ObjectMemoryEstimation.stringSize(clientId));
return persistenceEntry;
}
currentMemorySize.addAndGet(-oldEntry.getEstimatedSize());
final ClientSession oldSession = oldEntry.getObject();
final ClientSession newSession;
if (sendWill) {
newSession = oldSession;
} else {
removeWillReference(oldSession);
newSession = oldSession.copyWithoutWill();
}
if (sessionExpiryInterval != SESSION_EXPIRY_NOT_SET) {
newSession.setSessionExpiryInterval(sessionExpiryInterval);
}
if (newSession.isConnected() && !isPersistent(newSession)) {
sessionsCount.decrementAndGet();
}
newSession.setConnected(false);
loadWillPayload(newSession, false);
final PersistenceEntry<ClientSession> newEntry = new PersistenceEntry<>(newSession, timestamp);
currentMemorySize.addAndGet(newEntry.getEstimatedSize());
return newEntry;
}).getObject().deepCopy();
loadWillPayload(storedSession);
return storedSession;
}
@Override
public @NotNull Set<String> getAllClients(final int bucketIndex) {
final Map<String, PersistenceEntry<ClientSession>> bucket = getBucket(bucketIndex);
return ImmutableSet.copyOf(bucket.keySet());
}
@Override
@ExecuteInSingleWriter
public void removeWithTimestamp(final @NotNull String clientId, final int bucketIndex) {
final Map<String, PersistenceEntry<ClientSession>> bucket = getBucket(bucketIndex);
final PersistenceEntry<ClientSession> remove = bucket.remove(clientId);
if (remove != null) {
final ClientSession clientSession = remove.getObject();
if (isPersistent(clientSession) || clientSession.isConnected()) {
sessionsCount.decrementAndGet();
}
removeWillReference(clientSession);
currentMemorySize.addAndGet(-(remove.getEstimatedSize() + ObjectMemoryEstimation.stringSize(clientId)));
}
}
@Override
@ExecuteInSingleWriter
public @NotNull Set<String> cleanUp(final int bucketIndex) {
ThreadPreConditions.startsWith(SINGLE_WRITER_THREAD_PREFIX);
final Map<String, PersistenceEntry<ClientSession>> bucket = getBucket(bucketIndex);
final long currentTimeMillis = System.currentTimeMillis();
final Iterator<Map.Entry<String, PersistenceEntry<ClientSession>>> iterator = bucket.entrySet().iterator();
final ImmutableSet.Builder<String> expiredClientIds = ImmutableSet.builder();
while (iterator.hasNext()) {
final Map.Entry<String, PersistenceEntry<ClientSession>> entry = iterator.next();
final PersistenceEntry<ClientSession> storedEntry = entry.getValue();
final long timestamp = storedEntry.getTimestamp();
final ClientSession clientSession = storedEntry.getObject();
final long sessionExpiryInterval = clientSession.getSessionExpiryInterval();
if (ClientSessions.isExpired(clientSession, currentTimeMillis - timestamp)) {
if (sessionExpiryInterval > SESSION_EXPIRE_ON_DISCONNECT) {
sessionsCount.decrementAndGet();
}
eventLog.clientSessionExpired(timestamp + sessionExpiryInterval * 1000, entry.getKey());
expiredClientIds.add(entry.getKey());
currentMemorySize.addAndGet(-(storedEntry.getEstimatedSize() + ObjectMemoryEstimation.stringSize(entry.getKey())));
iterator.remove();
}
}
return expiredClientIds.build();
}
@Override
public @NotNull Set<String> getDisconnectedClients(final int bucketIndex) {
final Map<String, PersistenceEntry<ClientSession>> bucket = getBucket(bucketIndex);
final long currentTimeMillis = System.currentTimeMillis();
return bucket.entrySet()
.stream()
.filter(entry -> !entry.getValue().getObject().isConnected())
.filter(entry -> entry.getValue().getObject().getSessionExpiryInterval() > 0)
.filter(entry -> !ClientSessions.isExpired(
entry.getValue().getObject(),
currentTimeMillis - entry.getValue().getTimestamp()))
.map(Map.Entry::getKey)
.collect(ImmutableSet.toImmutableSet());
}
@Override
public int getSessionsCount() {
return sessionsCount.get();
}
@Override
@ExecuteInSingleWriter
public void setSessionExpiryInterval(
final @NotNull String clientId, final long sessionExpiryInterval, final int bucketIndex) {
checkNotNull(clientId, "Client Id must not be null");
ThreadPreConditions.startsWith(SINGLE_WRITER_THREAD_PREFIX);
if (sessionExpiryInterval < 0) {
throw new InvalidSessionExpiryIntervalException("Invalid session expiry interval " + sessionExpiryInterval);
}
final Map<String, PersistenceEntry<ClientSession>> bucket = getBucket(bucketIndex);
bucket.compute(clientId, (ignored, storedSession) -> {
if (storedSession == null) {
throw NoSessionException.INSTANCE;
}
final ClientSession clientSession = storedSession.getObject();
// is tombstone?
if (!clientSession.isConnected() && !isPersistent(clientSession)) {
throw NoSessionException.INSTANCE;
}
clientSession.setSessionExpiryInterval(sessionExpiryInterval);
return new PersistenceEntry<>(clientSession, storedSession.getTimestamp());
});
}
@Override
public @NotNull Map<String, PendingWillMessages.PendingWill> getPendingWills(
final int bucketIndex) {
final Map<String, PersistenceEntry<ClientSession>> bucket = getBucket(bucketIndex);
return bucket.entrySet()
.stream()
.filter(entry -> !entry.getValue().getObject().isConnected())
.filter(entry -> entry.getValue().getObject().getWillPublish() != null)
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, entry -> {
final PersistenceEntry<ClientSession> storedSession = entry.getValue();
final ClientSessionWill willPublish = storedSession.getObject().getWillPublish();
return new PendingWillMessages.PendingWill(Math.min(willPublish.getDelayInterval(),
storedSession.getObject().getSessionExpiryInterval()),
willPublish.getDelayInterval());
}));
}
@Override
@ExecuteInSingleWriter
public @Nullable PersistenceEntry<ClientSession> deleteWill(final @NotNull String clientId, final int bucketIndex) {
ThreadPreConditions.startsWith(SINGLE_WRITER_THREAD_PREFIX);
final Map<String, PersistenceEntry<ClientSession>> bucket = getBucket(bucketIndex);
final PersistenceEntry<ClientSession> persistenceEntry =
bucket.computeIfPresent(clientId, (ignored, oldEntry) -> {
final ClientSession oldSession = oldEntry.getObject();
// Just to be save, we do nothing
if (oldSession.isConnected()) {
return oldEntry;
}
currentMemorySize.addAndGet(-oldEntry.getEstimatedSize());
removeWillReference(oldSession);
final PersistenceEntry<ClientSession> newEntry = new PersistenceEntry<>(oldSession.copyWithoutWill(), oldEntry.getTimestamp());
currentMemorySize.addAndGet(newEntry.getEstimatedSize());
return newEntry;
});
if (persistenceEntry == null) {
return null;
}
final ClientSession session = persistenceEntry.getObject();
if (session.isConnected()) {
return null;
}
return new PersistenceEntry<>(session.deepCopy(), persistenceEntry.getTimestamp());
}
// in contrast to the file persistence method we already have everything in memory. The sizing and pagination are ignored.
@Override
public @NotNull BucketChunkResult<Map<String, ClientSession>> getAllClientsChunk(
final int bucketIndex, final @Nullable String ignored, final int alsoIgnored) {
final long currentTimeMillis = System.currentTimeMillis();
final Map<String, PersistenceEntry<ClientSession>> bucket = getBucket(bucketIndex);
final Map<String, ClientSession> sessions =
bucket.entrySet()
.stream()
.filter(entry -> {
final PersistenceEntry<ClientSession> value = entry.getValue();
return !ClientSessions.isExpired(value.getObject(),
currentTimeMillis - value.getTimestamp());
})
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
entry -> entry.getValue().getObject().copyWithoutWill()));
return new BucketChunkResult<>(sessions, true, null, bucketIndex);
}
@Override
@ExecuteInSingleWriter
public void closeDB(final int bucketIndex) {
getBucket(bucketIndex).clear();
//happens for every bucket, but its faster than calculating all sizes
//and decrementing the memory and count every time,
sessionsCount.set(0);
currentMemorySize.set(0);
}
private void removeWillReference(final @NotNull ClientSession clientSession) {
final ClientSessionWill willPublish = clientSession.getWillPublish();
if (willPublish == null) {
return;
}
metricsHolder.getStoredWillMessagesCount().dec();
payloadPersistence.decrementReferenceCounter(willPublish.getPublishId());
}
private void loadWillPayload(final @NotNull ClientSession clientSession) {
loadWillPayload(clientSession, true);
}
private void loadWillPayload(final @NotNull ClientSession clientSession, final boolean setPayload) {
final ClientSessionWill willPublish = clientSession.getWillPublish();
if (willPublish == null) {
return;
}
if (willPublish.getPayload() != null) {
return;
}
final byte[] payload = payloadPersistence.getPayloadOrNull(willPublish.getPublishId());
if (payload == null) {
clientSession.setWillPublish(null);
log.warn("Will Payload for payloadid {} not found", willPublish.getPublishId());
return;
}
if (setPayload) {
willPublish.getMqttWillPublish().setPayload(payload);
}
}
private static boolean isPersistent(final @NotNull ClientSession clientSession) {
return clientSession.getSessionExpiryInterval() > SESSION_EXPIRE_ON_DISCONNECT;
}
}
| 41.292308 | 147 | 0.672411 |
9017429d9cc55b9745997504f190520420a68e05 | 1,508 | /*
* 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.geode.internal.cache.xmlcache;
import org.junit.Before;
import org.xml.sax.EntityResolver;
/**
* Unit test for {@link PivotalEntityResolver} and {@link DefaultEntityResolver2}.
*
* @since GemFire 8.1
*/
public class PivotalEntityResolverJUnitTest extends AbstractEntityResolverTest {
private EntityResolver entityResolver;
private final String systemId = "http://schema.pivotal.io/gemfire/cache/cache-8.1.xsd";
@Before
public void setup() throws Exception {
entityResolver = new PivotalEntityResolver();
}
@Override
protected EntityResolver getEntityResolver() {
return entityResolver;
}
@Override
protected String getSystemId() {
return systemId;
}
}
| 31.416667 | 100 | 0.757958 |
237639ddb6c432c6e0d835b4ca02db3c2ca27dc5 | 1,333 | package net.mdln.englisc;
import androidx.test.espresso.IdlingResource;
import java.util.ArrayList;
/**
* An {@link androidx.test.espresso.IdlingResource} implementation that is idle only if
* {@link MainActivity} does not have any pending searches. This way {@link MainActivityTest} can
* be sure that when it searches for a word, it doesn't look at the top search result until the
* searches are all completed.
*/
class SearchPendingIdlingResource implements IdlingResource {
private final MainActivity activity;
private final ArrayList<ResourceCallback> callbacks = new ArrayList<>();
SearchPendingIdlingResource(MainActivity activity) {
this.activity = activity;
activity.onSearchFinished(new Runnable() {
@Override
public void run() {
if (isIdleNow()) {
for (ResourceCallback cb : callbacks) {
cb.onTransitionToIdle();
}
}
}
});
}
@Override
public String getName() {
return "SearchPending";
}
@Override
public boolean isIdleNow() {
return activity.pendingSearches() == 0;
}
@Override
public void registerIdleTransitionCallback(ResourceCallback callback) {
callbacks.add(callback);
}
} | 29.622222 | 97 | 0.63916 |
36f9d95f87cc4db9152289c7fff670640a692164 | 767 | package koks.module.world;
import koks.api.event.Event;
import koks.api.registry.module.Module;
import koks.api.registry.module.ModuleRegistry;
import koks.event.CanBlockPlaceEvent;
@Module.Info(name = "AlwaysPlace", description = "You can place inside you", category = Module.Category.WORLD)
public class AlwaysPlace extends Module {
@Override
@Event.Info(priority = Event.Priority.HIGH)
public void onEvent(Event event) {
if (event instanceof final CanBlockPlaceEvent canBlockPlaceEvent) {
if (!ModuleRegistry.getModule(Scaffold.class).isToggled())
canBlockPlaceEvent.setAllowedToPlace(true);
}
}
@Override
public void onEnable() {
}
@Override
public void onDisable() {
}
}
| 25.566667 | 110 | 0.698827 |
a4f8cecbbef699b1eb05739c10fb634d0c4b9b80 | 4,092 | package co.colector.network;
import android.content.Context;
import android.util.Log;
import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe;
import co.colector.model.ImageRequest;
import co.colector.model.ImageResponse;
import co.colector.model.request.GetSurveysRequest;
import co.colector.model.request.LoginRequest;
import co.colector.model.request.SendSurveyRequest;
import co.colector.model.response.ErrorResponse;
import co.colector.model.response.GetSurveysResponse;
import co.colector.model.response.LoginResponse;
import co.colector.model.response.SendSurveyResponse;
import co.colector.session.AppSession;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by Jose Rodriguez on 11/06/2016.
*/
public class ApiCallsManager {
private static final String TAG = "ApiCalls";
private Context mContext;
private Bus mBus;
private ApiClient mApiClient;
public ApiCallsManager(Context mContext, Bus mBus) {
this.mContext = mContext;
this.mBus = mBus;
mApiClient = ApiClient.getInstance(mContext);
}
@Subscribe
public void doUploadImage(ImageRequest imageRequest){
mApiClient.doUploadImage(imageRequest).enqueue(new Callback<ImageResponse>() {
@Override
public void onResponse(Call<ImageResponse> call, Response<ImageResponse> response) {
if (response.isSuccessful())
mBus.post(response.body());
}
@Override
public void onFailure(Call<ImageResponse> call, Throwable t)
{
mBus.post(new ErrorResponse(0, ""));
Log.d(TAG, "Failure do surveys");
}
});
}
@Subscribe
public void doLogin(LoginRequest loginRequest) {
mApiClient.doLogin(loginRequest).enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (response.isSuccessful())
mBus.post(response.body());
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t)
{
Log.d(TAG, "Failure do Login");
mBus.post(new ErrorResponse(0, ""));
}
});
}
@Subscribe
public void getSurveys(GetSurveysRequest surveysRequest) {
if (AppSession.getInstance().getUser() != null) {
mApiClient.getSurveys(surveysRequest, AppSession.getInstance().getUser()
.getToken()).enqueue(new Callback<GetSurveysResponse>() {
@Override
public void onResponse(Call<GetSurveysResponse> call,
Response<GetSurveysResponse> response) {
if (response.isSuccessful())
mBus.post(response.body());
}
@Override
public void onFailure(Call<GetSurveysResponse> call, Throwable t) {
mBus.post(new ErrorResponse(0, ""));
Log.d(TAG, "Failure do surveys");
t.printStackTrace();
}
});
}
}
@Subscribe
public void uploadSurveys(SendSurveyRequest uploadSurvey) {
if (AppSession.getInstance().getUser() != null) {
mApiClient.uploadSurveys(
uploadSurvey,
AppSession.getInstance().getUser().getToken()
).enqueue(new Callback<SendSurveyResponse>()
{
@Override
public void onResponse(Call<SendSurveyResponse> call, Response<SendSurveyResponse> response) {
if (response.isSuccessful())
mBus.post(response.body());
}
@Override
public void onFailure(Call<SendSurveyResponse> call, Throwable t) {
Log.d(TAG, "Failure upload survey");
}
});
}
}
}
| 33.268293 | 110 | 0.592864 |
7104767f902b8230dca1602a8d9ee6c8633b5520 | 48,027 | /*
* Copyright 2014 Goldman Sachs.
*
* 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.gs.collections.impl.bimap.mutable;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.gs.collections.api.LazyIterable;
import com.gs.collections.api.RichIterable;
import com.gs.collections.api.bag.MutableBag;
import com.gs.collections.api.bimap.ImmutableBiMap;
import com.gs.collections.api.bimap.MutableBiMap;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.function.Function0;
import com.gs.collections.api.block.function.Function2;
import com.gs.collections.api.block.function.primitive.BooleanFunction;
import com.gs.collections.api.block.function.primitive.ByteFunction;
import com.gs.collections.api.block.function.primitive.CharFunction;
import com.gs.collections.api.block.function.primitive.DoubleFunction;
import com.gs.collections.api.block.function.primitive.DoubleObjectToDoubleFunction;
import com.gs.collections.api.block.function.primitive.FloatFunction;
import com.gs.collections.api.block.function.primitive.FloatObjectToFloatFunction;
import com.gs.collections.api.block.function.primitive.IntFunction;
import com.gs.collections.api.block.function.primitive.IntObjectToIntFunction;
import com.gs.collections.api.block.function.primitive.LongFunction;
import com.gs.collections.api.block.function.primitive.LongObjectToLongFunction;
import com.gs.collections.api.block.function.primitive.ShortFunction;
import com.gs.collections.api.block.predicate.Predicate;
import com.gs.collections.api.block.predicate.Predicate2;
import com.gs.collections.api.block.procedure.Procedure;
import com.gs.collections.api.block.procedure.Procedure2;
import com.gs.collections.api.block.procedure.primitive.ObjectIntProcedure;
import com.gs.collections.api.collection.MutableCollection;
import com.gs.collections.api.collection.primitive.MutableBooleanCollection;
import com.gs.collections.api.collection.primitive.MutableByteCollection;
import com.gs.collections.api.collection.primitive.MutableCharCollection;
import com.gs.collections.api.collection.primitive.MutableDoubleCollection;
import com.gs.collections.api.collection.primitive.MutableFloatCollection;
import com.gs.collections.api.collection.primitive.MutableIntCollection;
import com.gs.collections.api.collection.primitive.MutableLongCollection;
import com.gs.collections.api.collection.primitive.MutableShortCollection;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.map.MutableMap;
import com.gs.collections.api.map.sorted.MutableSortedMap;
import com.gs.collections.api.multimap.MutableMultimap;
import com.gs.collections.api.multimap.set.MutableSetMultimap;
import com.gs.collections.api.partition.PartitionMutableCollection;
import com.gs.collections.api.set.MutableSet;
import com.gs.collections.api.set.sorted.MutableSortedSet;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.impl.block.procedure.MapCollectProcedure;
import com.gs.collections.impl.list.fixed.ArrayAdapter;
import com.gs.collections.impl.map.mutable.UnifiedMap;
import com.gs.collections.impl.utility.Iterate;
import com.gs.collections.impl.utility.MapIterate;
abstract class AbstractMutableBiMap<K, V> implements MutableBiMap<K, V>
{
private UnifiedMap<K, V> delegate;
private AbstractMutableBiMap<V, K> inverse;
private AbstractMutableBiMap(Map<K, V> delegate, AbstractMutableBiMap<V, K> valuesToKeys)
{
this.delegate = UnifiedMap.newMap(delegate);
this.inverse = valuesToKeys;
}
AbstractMutableBiMap(Map<K, V> map)
{
this.delegate = UnifiedMap.newMap();
this.inverse = new Inverse<V, K>(UnifiedMap.<V, K>newMap(), this);
this.putAll(map);
}
AbstractMutableBiMap(Map<K, V> delegate, Map<V, K> inverse)
{
this.checkNull(delegate, inverse);
this.checkSame(delegate, inverse);
this.delegate = UnifiedMap.newMap(delegate);
this.inverse = new Inverse<V, K>(inverse, this);
}
private void checkNull(Map<K, V> delegate, Map<V, K> inverse)
{
if (delegate == null || inverse == null)
{
throw new IllegalArgumentException("The delegate maps cannot be null.");
}
}
private void checkSame(Map<K, V> keysToValues, Map<V, K> valuesToKeys)
{
if (keysToValues == valuesToKeys)
{
throw new IllegalArgumentException("The delegate maps cannot be same.");
}
}
private static boolean nullSafeEquals(Object value, Object other)
{
if (value == null)
{
if (other == null)
{
return true;
}
}
else if (other == value || value.equals(other))
{
return true;
}
return false;
}
public MutableSetMultimap<V, K> flip()
{
// TODO: We could optimize this since we know the values are unique
return MapIterate.flip(this);
}
@Override
public MutableBiMap<K, V> clone()
{
return new HashBiMap<K, V>(this);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (!(obj instanceof Map))
{
return false;
}
Map<?, ?> map = (Map<?, ?>) obj;
return this.delegate.equals(map);
}
@Override
public int hashCode()
{
return this.delegate.hashCode();
}
@Override
public String toString()
{
return this.delegate.toString();
}
public V put(K key, V value)
{
if (this.inverse.delegate.containsKey(value))
{
if (AbstractMutableBiMap.nullSafeEquals(key, this.inverse.delegate.get(value)))
{
return value;
}
throw new IllegalArgumentException("Value " + value + " already exists in map!");
}
boolean containsKey = this.delegate.containsKey(key);
V put = this.delegate.put(key, value);
if (containsKey)
{
this.inverse.delegate.removeKey(put);
}
this.inverse.delegate.put(value, key);
return put;
}
public V forcePut(K key, V value)
{
boolean containsValue = this.inverse.delegate.containsKey(value);
if (containsValue)
{
if (AbstractMutableBiMap.nullSafeEquals(key, this.inverse.delegate.get(value)))
{
return value;
}
}
boolean containsKey = this.delegate.containsKey(key);
V put = this.delegate.put(key, value);
if (containsKey)
{
this.inverse.delegate.removeKey(put);
}
K oldKey = this.inverse.delegate.put(value, key);
if (containsValue)
{
this.delegate.removeKey(oldKey);
}
return put;
}
public V remove(Object key)
{
if (!this.delegate.containsKey(key))
{
return null;
}
V oldValue = this.delegate.remove(key);
this.inverse.delegate.remove(oldValue);
return oldValue;
}
public void putAll(Map<? extends K, ? extends V> map)
{
Set<? extends Map.Entry<? extends K, ? extends V>> entries = map.entrySet();
for (Map.Entry<? extends K, ? extends V> entry : entries)
{
this.put(entry.getKey(), entry.getValue());
}
}
public void clear()
{
this.delegate.clear();
this.inverse.delegate.clear();
}
public Set<K> keySet()
{
return new KeySet();
}
public Collection<V> values()
{
return new ValuesCollection();
}
public Set<Map.Entry<K, V>> entrySet()
{
return new EntrySet();
}
public boolean containsKey(Object key)
{
return this.delegate.containsKey(key);
}
public int size()
{
return this.delegate.size();
}
public boolean isEmpty()
{
return this.delegate.isEmpty();
}
public boolean notEmpty()
{
return this.delegate.notEmpty();
}
public V getFirst()
{
return this.delegate.getFirst();
}
public V getLast()
{
return this.delegate.getLast();
}
public boolean contains(Object object)
{
return this.inverse.delegate.containsKey(object);
}
public boolean containsAllIterable(Iterable<?> source)
{
return this.inverse.delegate.keysView().containsAllIterable(source);
}
public boolean containsAll(Collection<?> source)
{
return this.inverse.delegate.keysView().containsAll(source);
}
public boolean containsAllArguments(Object... elements)
{
return this.inverse.delegate.keysView().containsAllArguments(elements);
}
public <R extends Collection<V>> R select(Predicate<? super V> predicate, R target)
{
return this.delegate.select(predicate, target);
}
public <P> RichIterable<V> selectWith(Predicate2<? super V, ? super P> predicate, P parameter)
{
return this.delegate.selectWith(predicate, parameter);
}
public <P> RichIterable<V> rejectWith(Predicate2<? super V, ? super P> predicate, P parameter)
{
return this.delegate.rejectWith(predicate, parameter);
}
public <VV> MutableCollection<VV> collect(Function<? super V, ? extends VV> function)
{
return this.delegate.collect(function);
}
public MutableBooleanCollection collectBoolean(BooleanFunction<? super V> booleanFunction)
{
return this.delegate.collectBoolean(booleanFunction);
}
public <R extends MutableBooleanCollection> R collectBoolean(BooleanFunction<? super V> booleanFunction, R target)
{
return this.delegate.collectBoolean(booleanFunction, target);
}
public MutableByteCollection collectByte(ByteFunction<? super V> byteFunction)
{
return this.delegate.collectByte(byteFunction);
}
public <R extends MutableByteCollection> R collectByte(ByteFunction<? super V> byteFunction, R target)
{
return this.delegate.collectByte(byteFunction, target);
}
public MutableCharCollection collectChar(CharFunction<? super V> charFunction)
{
return this.delegate.collectChar(charFunction);
}
public <R extends MutableCharCollection> R collectChar(CharFunction<? super V> charFunction, R target)
{
return this.delegate.collectChar(charFunction, target);
}
public <P, R extends Collection<V>> R selectWith(Predicate2<? super V, ? super P> predicate, P parameter, R targetCollection)
{
return this.delegate.selectWith(predicate, parameter, targetCollection);
}
public MutableDoubleCollection collectDouble(DoubleFunction<? super V> doubleFunction)
{
return this.delegate.collectDouble(doubleFunction);
}
public <R extends MutableDoubleCollection> R collectDouble(DoubleFunction<? super V> doubleFunction, R target)
{
return this.delegate.collectDouble(doubleFunction, target);
}
public MutableFloatCollection collectFloat(FloatFunction<? super V> floatFunction)
{
return this.delegate.collectFloat(floatFunction);
}
public <R extends MutableFloatCollection> R collectFloat(FloatFunction<? super V> floatFunction, R target)
{
return this.delegate.collectFloat(floatFunction, target);
}
public MutableIntCollection collectInt(IntFunction<? super V> intFunction)
{
return this.delegate.collectInt(intFunction);
}
public <R extends MutableIntCollection> R collectInt(IntFunction<? super V> intFunction, R target)
{
return this.delegate.collectInt(intFunction, target);
}
public MutableLongCollection collectLong(LongFunction<? super V> longFunction)
{
return this.delegate.collectLong(longFunction);
}
public <R extends MutableLongCollection> R collectLong(LongFunction<? super V> longFunction, R target)
{
return this.delegate.collectLong(longFunction, target);
}
public MutableShortCollection collectShort(ShortFunction<? super V> shortFunction)
{
return this.delegate.collectShort(shortFunction);
}
public <R extends MutableShortCollection> R collectShort(ShortFunction<? super V> shortFunction, R target)
{
return this.delegate.collectShort(shortFunction, target);
}
public <VV> MutableCollection<VV> collectIf(Predicate<? super V> predicate, Function<? super V, ? extends VV> function)
{
return this.delegate.collectIf(predicate, function);
}
public MutableCollection<V> reject(Predicate<? super V> predicate)
{
return this.delegate.reject(predicate);
}
public MutableCollection<V> select(Predicate<? super V> predicate)
{
return this.delegate.select(predicate);
}
public PartitionMutableCollection<V> partition(Predicate<? super V> predicate)
{
return this.delegate.partition(predicate);
}
public <P> PartitionMutableCollection<V> partitionWith(Predicate2<? super V, ? super P> predicate, P parameter)
{
return this.delegate.partitionWith(predicate, parameter);
}
public <S> MutableCollection<S> selectInstancesOf(Class<S> clazz)
{
return this.delegate.selectInstancesOf(clazz);
}
public MutableCollection<Pair<V, Integer>> zipWithIndex()
{
return this.delegate.zipWithIndex();
}
public <R extends Collection<V>> R reject(Predicate<? super V> predicate, R target)
{
return this.delegate.reject(predicate, target);
}
public <P, R extends Collection<V>> R rejectWith(Predicate2<? super V, ? super P> predicate, P parameter, R targetCollection)
{
return this.delegate.rejectWith(predicate, parameter, targetCollection);
}
public <K2, V2> MutableMap<K2, V2> aggregateBy(Function<? super V, ? extends K2> groupBy, Function0<? extends V2> zeroValueFactory, Function2<? super V2, ? super V, ? extends V2> nonMutatingAggregator)
{
return this.delegate.aggregateBy(groupBy, zeroValueFactory, nonMutatingAggregator);
}
public <VV, R extends Collection<VV>> R collect(Function<? super V, ? extends VV> function, R target)
{
return this.delegate.collect(function, target);
}
public <P, VV> MutableList<VV> collectWith(Function2<? super V, ? super P, ? extends VV> function, P parameter)
{
return this.delegate.collectWith(function, parameter);
}
public <P, VV, R extends Collection<VV>> R collectWith(Function2<? super V, ? super P, ? extends VV> function, P parameter, R targetCollection)
{
return this.delegate.collectWith(function, parameter, targetCollection);
}
public <VV, R extends Collection<VV>> R collectIf(Predicate<? super V> predicate, Function<? super V, ? extends VV> function, R target)
{
return this.delegate.collectIf(predicate, function, target);
}
public <VV> MutableCollection<VV> flatCollect(Function<? super V, ? extends Iterable<VV>> function)
{
return this.delegate.flatCollect(function);
}
public <VV, R extends Collection<VV>> R flatCollect(Function<? super V, ? extends Iterable<VV>> function, R target)
{
return this.delegate.flatCollect(function, target);
}
public V detect(Predicate<? super V> predicate)
{
return this.delegate.detect(predicate);
}
public <P> V detectWith(Predicate2<? super V, ? super P> predicate, P parameter)
{
return this.delegate.detectWith(predicate, parameter);
}
public V detectIfNone(Predicate<? super V> predicate, Function0<? extends V> function)
{
return this.delegate.detectIfNone(predicate, function);
}
public <P> V detectWithIfNone(Predicate2<? super V, ? super P> predicate, P parameter, Function0<? extends V> function)
{
return this.delegate.detectWithIfNone(predicate, parameter, function);
}
public int count(Predicate<? super V> predicate)
{
return this.delegate.count(predicate);
}
public <P> int countWith(Predicate2<? super V, ? super P> predicate, P parameter)
{
return this.delegate.countWith(predicate, parameter);
}
public boolean anySatisfy(Predicate<? super V> predicate)
{
return this.delegate.anySatisfy(predicate);
}
public <P> boolean anySatisfyWith(Predicate2<? super V, ? super P> predicate, P parameter)
{
return this.delegate.anySatisfyWith(predicate, parameter);
}
public boolean allSatisfy(Predicate<? super V> predicate)
{
return this.delegate.allSatisfy(predicate);
}
public <P> boolean allSatisfyWith(Predicate2<? super V, ? super P> predicate, P parameter)
{
return this.delegate.allSatisfyWith(predicate, parameter);
}
public boolean noneSatisfy(Predicate<? super V> predicate)
{
return this.delegate.noneSatisfy(predicate);
}
public <P> boolean noneSatisfyWith(Predicate2<? super V, ? super P> predicate, P parameter)
{
return this.delegate.noneSatisfyWith(predicate, parameter);
}
public <IV> IV injectInto(IV injectedValue, Function2<? super IV, ? super V, ? extends IV> function)
{
return this.delegate.injectInto(injectedValue, function);
}
public int injectInto(int injectedValue, IntObjectToIntFunction<? super V> function)
{
return this.delegate.injectInto(injectedValue, function);
}
public long injectInto(long injectedValue, LongObjectToLongFunction<? super V> function)
{
return this.delegate.injectInto(injectedValue, function);
}
public float injectInto(float injectedValue, FloatObjectToFloatFunction<? super V> function)
{
return this.delegate.injectInto(injectedValue, function);
}
public double injectInto(double injectedValue, DoubleObjectToDoubleFunction<? super V> function)
{
return this.delegate.injectInto(injectedValue, function);
}
public MutableList<V> toList()
{
return this.delegate.toList();
}
public MutableList<V> toSortedList()
{
return this.delegate.toSortedList();
}
public MutableList<V> toSortedList(Comparator<? super V> comparator)
{
return this.delegate.toSortedList(comparator);
}
public <VV extends Comparable<? super VV>> MutableList<V> toSortedListBy(Function<? super V, ? extends VV> function)
{
return this.delegate.toSortedListBy(function);
}
public MutableSet<V> toSet()
{
return this.delegate.toSet();
}
public MutableSortedSet<V> toSortedSet()
{
return this.delegate.toSortedSet();
}
public MutableSortedSet<V> toSortedSet(Comparator<? super V> comparator)
{
return this.delegate.toSortedSet(comparator);
}
public <VV extends Comparable<? super VV>> MutableSortedSet<V> toSortedSetBy(Function<? super V, ? extends VV> function)
{
return this.delegate.toSortedSetBy(function);
}
public MutableBag<V> toBag()
{
return this.delegate.toBag();
}
public <NK, NV> MutableMap<NK, NV> toMap(Function<? super V, ? extends NK> keyFunction, Function<? super V, ? extends NV> valueFunction)
{
return this.delegate.toMap(keyFunction, valueFunction);
}
public <NK, NV> MutableSortedMap<NK, NV> toSortedMap(Function<? super V, ? extends NK> keyFunction, Function<? super V, ? extends NV> valueFunction)
{
return this.delegate.toSortedMap(keyFunction, valueFunction);
}
public <NK, NV> MutableSortedMap<NK, NV> toSortedMap(Comparator<? super NK> comparator, Function<? super V, ? extends NK> keyFunction, Function<? super V, ? extends NV> valueFunction)
{
return this.delegate.toSortedMap(comparator, keyFunction, valueFunction);
}
public LazyIterable<V> asLazy()
{
return this.delegate.asLazy();
}
public Object[] toArray()
{
return this.delegate.toArray();
}
public <T> T[] toArray(T[] a)
{
return this.delegate.toArray(a);
}
public V min(Comparator<? super V> comparator)
{
return this.delegate.min(comparator);
}
public V max(Comparator<? super V> comparator)
{
return this.delegate.max(comparator);
}
public V min()
{
return this.delegate.min();
}
public V max()
{
return this.delegate.max();
}
public <VV extends Comparable<? super VV>> V minBy(Function<? super V, ? extends VV> function)
{
return this.delegate.minBy(function);
}
public <VV extends Comparable<? super VV>> V maxBy(Function<? super V, ? extends VV> function)
{
return this.delegate.maxBy(function);
}
public long sumOfInt(IntFunction<? super V> function)
{
return this.delegate.sumOfInt(function);
}
public double sumOfFloat(FloatFunction<? super V> function)
{
return this.delegate.sumOfFloat(function);
}
public long sumOfLong(LongFunction<? super V> function)
{
return this.delegate.sumOfLong(function);
}
public double sumOfDouble(DoubleFunction<? super V> function)
{
return this.delegate.sumOfDouble(function);
}
public String makeString()
{
return this.delegate.makeString();
}
public String makeString(String separator)
{
return this.delegate.makeString(separator);
}
public String makeString(String start, String separator, String end)
{
return this.delegate.makeString(start, separator, end);
}
public void appendString(Appendable appendable)
{
this.delegate.appendString(appendable);
}
public void appendString(Appendable appendable, String separator)
{
this.delegate.appendString(appendable, separator);
}
public void appendString(Appendable appendable, String start, String separator, String end)
{
this.delegate.appendString(appendable, start, separator, end);
}
public <VV> MutableMultimap<VV, V> groupBy(Function<? super V, ? extends VV> function)
{
return this.delegate.groupBy(function);
}
public <VV, R extends MutableMultimap<VV, V>> R groupBy(Function<? super V, ? extends VV> function, R target)
{
return this.delegate.groupBy(function, target);
}
public <VV> MutableMultimap<VV, V> groupByEach(Function<? super V, ? extends Iterable<VV>> function)
{
return this.delegate.groupByEach(function);
}
public <VV, R extends MutableMultimap<VV, V>> R groupByEach(Function<? super V, ? extends Iterable<VV>> function, R target)
{
return this.delegate.groupByEach(function, target);
}
public <VV> MutableMap<VV, V> groupByUniqueKey(Function<? super V, ? extends VV> function)
{
return this.delegate.groupByUniqueKey(function);
}
public <S> MutableCollection<Pair<V, S>> zip(Iterable<S> that)
{
return this.delegate.zip(that);
}
public <S, R extends Collection<Pair<V, S>>> R zip(Iterable<S> that, R target)
{
return this.delegate.zip(that, target);
}
public <R extends Collection<Pair<V, Integer>>> R zipWithIndex(R target)
{
return this.delegate.zipWithIndex(target);
}
public RichIterable<RichIterable<V>> chunk(int size)
{
return this.delegate.chunk(size);
}
public <K2, V2> MutableMap<K2, V2> aggregateInPlaceBy(Function<? super V, ? extends K2> groupBy, Function0<? extends V2> zeroValueFactory, Procedure2<? super V2, ? super V> mutatingAggregator)
{
return this.delegate.aggregateInPlaceBy(groupBy, zeroValueFactory, mutatingAggregator);
}
public boolean containsValue(Object value)
{
return this.inverse.delegate.containsKey(value);
}
public V get(Object key)
{
return this.delegate.get(key);
}
public HashBiMap<K, V> select(final Predicate2<? super K, ? super V> predicate)
{
final HashBiMap<K, V> result = HashBiMap.newMap();
this.delegate.forEachKeyValue(new Procedure2<K, V>()
{
public void value(K key, V value)
{
if (predicate.accept(key, value))
{
result.put(key, value);
}
}
});
return result;
}
public <R> HashBiMap<K, R> collectValues(final Function2<? super K, ? super V, ? extends R> function)
{
final HashBiMap<K, R> result = HashBiMap.newMap();
this.delegate.forEachKeyValue(new Procedure2<K, V>()
{
public void value(K key, V value)
{
result.put(key, function.value(key, value));
}
});
return result;
}
public <K2, V2> HashBiMap<K2, V2> collect(final Function2<? super K, ? super V, Pair<K2, V2>> function)
{
final HashBiMap<K2, V2> result = HashBiMap.newMap();
this.delegate.forEachKeyValue(new Procedure2<K, V>()
{
public void value(K key, V value)
{
Pair<K2, V2> pair = function.value(key, value);
result.put(pair.getOne(), pair.getTwo());
}
});
return result;
}
public HashBiMap<K, V> reject(final Predicate2<? super K, ? super V> predicate)
{
final HashBiMap<K, V> result = HashBiMap.newMap();
this.delegate.forEachKeyValue(new Procedure2<K, V>()
{
public void value(K key, V value)
{
if (!predicate.accept(key, value))
{
result.put(key, value);
}
}
});
return result;
}
public void forEachValue(Procedure<? super V> procedure)
{
this.inverse.delegate.forEachKey(procedure);
}
public void forEachKey(Procedure<? super K> procedure)
{
this.delegate.forEachKey(procedure);
}
public void forEachKeyValue(Procedure2<? super K, ? super V> procedure)
{
this.delegate.forEachKeyValue(procedure);
}
public MutableBiMap<V, K> flipUniqueValues()
{
return new HashBiMap<V, K>(this.inverse());
}
public V getIfAbsent(K key, Function0<? extends V> function)
{
return this.delegate.getIfAbsent(key, function);
}
public V getIfAbsentValue(K key, V value)
{
return this.delegate.getIfAbsentValue(key, value);
}
public <P> V getIfAbsentWith(K key, Function<? super P, ? extends V> function, P parameter)
{
return this.delegate.getIfAbsentWith(key, function, parameter);
}
public <A> A ifPresentApply(K key, Function<? super V, ? extends A> function)
{
return this.delegate.ifPresentApply(key, function);
}
public RichIterable<K> keysView()
{
return this.delegate.keysView();
}
public RichIterable<V> valuesView()
{
return this.delegate.valuesView();
}
public RichIterable<Pair<K, V>> keyValuesView()
{
return this.delegate.keyValuesView();
}
public Pair<K, V> detect(Predicate2<? super K, ? super V> predicate)
{
return this.delegate.detect(predicate);
}
public ImmutableBiMap<K, V> toImmutable()
{
throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".toImmutable() not implemented yet");
}
public MutableBiMap<K, V> asSynchronized()
{
throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".asSynchronized() not implemented yet");
}
public MutableBiMap<K, V> asUnmodifiable()
{
throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".asUnmodifiable() not implemented yet");
}
public <E> MutableMap<K, V> collectKeysAndValues(Iterable<E> iterable, Function<? super E, ? extends K> keyFunction, Function<? super E, ? extends V> valueFunction)
{
Iterate.forEach(iterable, new MapCollectProcedure<E, K, V>(this, keyFunction, valueFunction));
return this;
}
public V removeKey(K key)
{
return this.remove(key);
}
public V getIfAbsentPut(K key, Function0<? extends V> function)
{
V value = this.delegate.get(key);
if (value != null || this.delegate.containsKey(key))
{
return value;
}
V newValue = function.value();
this.put(key, newValue);
return newValue;
}
public V getIfAbsentPut(K key, V value)
{
V oldValue = this.delegate.get(key);
if (oldValue != null || this.delegate.containsKey(key))
{
return oldValue;
}
this.put(key, value);
return value;
}
public V getIfAbsentPutWithKey(K key, Function<? super K, ? extends V> function)
{
V value = this.delegate.get(key);
if (value != null || this.delegate.containsKey(key))
{
return value;
}
V newValue = function.valueOf(key);
this.put(key, newValue);
return newValue;
}
public <P> V getIfAbsentPutWith(K key, Function<? super P, ? extends V> function, P parameter)
{
V value = this.delegate.get(key);
if (value != null || this.delegate.containsKey(key))
{
return value;
}
V newValue = function.valueOf(parameter);
this.put(key, newValue);
return newValue;
}
public V add(Pair<K, V> keyValuePair)
{
return this.put(keyValuePair.getOne(), keyValuePair.getTwo());
}
public MutableBiMap<K, V> withKeyValue(K key, V value)
{
this.put(key, value);
return this;
}
public MutableBiMap<K, V> withAllKeyValues(Iterable<? extends Pair<? extends K, ? extends V>> keyValues)
{
for (Pair<? extends K, ? extends V> keyVal : keyValues)
{
this.put(keyVal.getOne(), keyVal.getTwo());
}
return this;
}
public MutableBiMap<K, V> withAllKeyValueArguments(Pair<? extends K, ? extends V>... keyValuePairs)
{
return this.withAllKeyValues(ArrayAdapter.adapt(keyValuePairs));
}
public MutableBiMap<K, V> withoutKey(K key)
{
this.removeKey(key);
return this;
}
public MutableMap<K, V> withoutAllKeys(Iterable<? extends K> keys)
{
for (K key : keys)
{
this.removeKey(key);
}
return this;
}
public HashBiMap<K, V> newEmpty()
{
return new HashBiMap<K, V>();
}
public V updateValue(K key, Function0<? extends V> factory, Function<? super V, ? extends V> function)
{
if (this.delegate.containsKey(key))
{
V newValue = function.valueOf(this.delegate.get(key));
this.put(key, newValue);
return newValue;
}
V newValue = function.valueOf(factory.value());
this.put(key, newValue);
return newValue;
}
public <P> V updateValueWith(K key, Function0<? extends V> factory, Function2<? super V, ? super P, ? extends V> function, P parameter)
{
if (this.delegate.containsKey(key))
{
V newValue = function.value(this.delegate.get(key), parameter);
this.put(key, newValue);
return newValue;
}
V newValue = function.value(factory.value(), parameter);
this.put(key, newValue);
return newValue;
}
public MutableBiMap<V, K> inverse()
{
return this.inverse;
}
public void forEach(Procedure<? super V> procedure)
{
this.inverse.delegate.forEachKey(procedure);
}
public void forEachWithIndex(ObjectIntProcedure<? super V> objectIntProcedure)
{
this.delegate.forEachWithIndex(objectIntProcedure);
}
public <P> void forEachWith(Procedure2<? super V, ? super P> procedure, P parameter)
{
this.delegate.forEachWith(procedure, parameter);
}
public Iterator<V> iterator()
{
return new InternalIterator();
}
public void writeExternal(ObjectOutput out) throws IOException
{
this.delegate.writeExternal(out);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
{
this.delegate = UnifiedMap.newMap();
this.delegate.readExternal(in);
final UnifiedMap<V, K> inverseDelegate = UnifiedMap.newMap();
this.delegate.forEachKeyValue(new Procedure2<K, V>()
{
public void value(K key, V value)
{
inverseDelegate.put(value, key);
}
});
this.inverse = new Inverse<V, K>(inverseDelegate, this);
}
private class InternalIterator implements Iterator<V>
{
private final Iterator<V> iterator = AbstractMutableBiMap.this.delegate.iterator();
private V currentValue;
public boolean hasNext()
{
return this.iterator.hasNext();
}
public V next()
{
V next = this.iterator.next();
this.currentValue = next;
return next;
}
public void remove()
{
this.iterator.remove();
AbstractMutableBiMap.this.inverse.delegate.remove(this.currentValue);
}
}
private class KeySet implements Set<K>
{
@Override
public boolean equals(Object obj)
{
return AbstractMutableBiMap.this.delegate.keySet().equals(obj);
}
@Override
public int hashCode()
{
return AbstractMutableBiMap.this.delegate.keySet().hashCode();
}
public int size()
{
return AbstractMutableBiMap.this.size();
}
public boolean isEmpty()
{
return AbstractMutableBiMap.this.isEmpty();
}
public boolean contains(Object key)
{
return AbstractMutableBiMap.this.delegate.containsKey(key);
}
public Object[] toArray()
{
return AbstractMutableBiMap.this.delegate.keySet().toArray();
}
public <T> T[] toArray(T[] a)
{
return AbstractMutableBiMap.this.delegate.keySet().toArray(a);
}
public boolean add(K key)
{
throw new UnsupportedOperationException("Cannot call add() on " + this.getClass().getSimpleName());
}
public boolean remove(Object key)
{
int oldSize = AbstractMutableBiMap.this.size();
AbstractMutableBiMap.this.remove(key);
return AbstractMutableBiMap.this.size() != oldSize;
}
public boolean containsAll(Collection<?> source)
{
for (Object key : source)
{
if (!AbstractMutableBiMap.this.delegate.containsKey(key))
{
return false;
}
}
return true;
}
public boolean addAll(Collection<? extends K> source)
{
throw new UnsupportedOperationException("Cannot call addAll() on " + this.getClass().getSimpleName());
}
public boolean retainAll(Collection<?> collection)
{
int oldSize = AbstractMutableBiMap.this.size();
Iterator<K> iterator = this.iterator();
while (iterator.hasNext())
{
K next = iterator.next();
if (!collection.contains(next))
{
this.remove(next);
}
}
return oldSize != AbstractMutableBiMap.this.size();
}
public boolean removeAll(Collection<?> collection)
{
int oldSize = AbstractMutableBiMap.this.size();
for (Object object : collection)
{
AbstractMutableBiMap.this.remove(object);
}
return oldSize != AbstractMutableBiMap.this.size();
}
public void clear()
{
AbstractMutableBiMap.this.clear();
}
public Iterator<K> iterator()
{
return AbstractMutableBiMap.this.inverse().iterator();
}
@Override
public String toString()
{
return Iterate.makeString(this, "[", ", ", "]");
}
}
private class ValuesCollection implements Collection<V>
{
public int size()
{
return AbstractMutableBiMap.this.size();
}
public boolean isEmpty()
{
return AbstractMutableBiMap.this.isEmpty();
}
public boolean contains(Object key)
{
return AbstractMutableBiMap.this.inverse.delegate.containsKey(key);
}
public Object[] toArray()
{
return AbstractMutableBiMap.this.delegate.values().toArray();
}
public <T> T[] toArray(T[] a)
{
return AbstractMutableBiMap.this.delegate.values().toArray(a);
}
public boolean add(V v)
{
throw new UnsupportedOperationException("Cannot call add() on " + this.getClass().getSimpleName());
}
public boolean remove(Object value)
{
int oldSize = AbstractMutableBiMap.this.size();
AbstractMutableBiMap.this.inverse().remove(value);
return oldSize != AbstractMutableBiMap.this.size();
}
public boolean containsAll(Collection<?> collection)
{
for (Object key : collection)
{
if (!AbstractMutableBiMap.this.inverse.delegate.containsKey(key))
{
return false;
}
}
return true;
}
public boolean addAll(Collection<? extends V> collection)
{
throw new UnsupportedOperationException("Cannot call addAll() on " + this.getClass().getSimpleName());
}
public boolean removeAll(Collection<?> collection)
{
int oldSize = AbstractMutableBiMap.this.size();
for (Object object : collection)
{
this.remove(object);
}
return oldSize != AbstractMutableBiMap.this.size();
}
public boolean retainAll(Collection<?> collection)
{
int oldSize = AbstractMutableBiMap.this.size();
Iterator<V> iterator = this.iterator();
while (iterator.hasNext())
{
V next = iterator.next();
if (!collection.contains(next))
{
this.remove(next);
}
}
return oldSize != AbstractMutableBiMap.this.size();
}
public void clear()
{
AbstractMutableBiMap.this.clear();
}
public Iterator<V> iterator()
{
return AbstractMutableBiMap.this.iterator();
}
@Override
public String toString()
{
return Iterate.makeString(this, "[", ", ", "]");
}
}
private class EntrySet implements Set<Map.Entry<K, V>>
{
@Override
public boolean equals(Object obj)
{
if (obj instanceof Set)
{
Set<?> other = (Set<?>) obj;
if (other.size() == this.size())
{
return this.containsAll(other);
}
}
return false;
}
@Override
public int hashCode()
{
return AbstractMutableBiMap.this.hashCode();
}
public int size()
{
return AbstractMutableBiMap.this.size();
}
public boolean isEmpty()
{
return AbstractMutableBiMap.this.isEmpty();
}
public boolean contains(Object o)
{
if (!(o instanceof Map.Entry))
{
return false;
}
Map.Entry<K, V> entry = (Map.Entry<K, V>) o;
K key = entry.getKey();
V actualValue = AbstractMutableBiMap.this.get(key);
if (actualValue != null)
{
return actualValue.equals(entry.getValue());
}
return entry.getValue() == null && AbstractMutableBiMap.this.containsKey(key);
}
public Object[] toArray()
{
Object[] result = new Object[AbstractMutableBiMap.this.size()];
return this.copyEntries(result);
}
public <T> T[] toArray(T[] result)
{
int size = AbstractMutableBiMap.this.size();
if (result.length < size)
{
result = (T[]) Array.newInstance(result.getClass().getComponentType(), size);
}
this.copyEntries(result);
if (size < result.length)
{
result[size] = null;
}
return result;
}
public boolean add(Map.Entry<K, V> entry)
{
throw new UnsupportedOperationException();
}
public boolean remove(Object e)
{
if (!(e instanceof Map.Entry))
{
return false;
}
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) e;
K key = (K) entry.getKey();
V value = (V) entry.getValue();
V actualValue = AbstractMutableBiMap.this.delegate.get(key);
if (actualValue != null)
{
if (actualValue.equals(value))
{
AbstractMutableBiMap.this.remove(key);
return true;
}
return false;
}
if (value == null && AbstractMutableBiMap.this.delegate.containsKey(key))
{
AbstractMutableBiMap.this.remove(key);
return true;
}
return false;
}
public boolean containsAll(Collection<?> collection)
{
for (Object obj : collection)
{
if (!this.contains(obj))
{
return false;
}
}
return true;
}
public boolean addAll(Collection<? extends Map.Entry<K, V>> collection)
{
throw new UnsupportedOperationException("Cannot call addAll() on " + this.getClass().getSimpleName());
}
public boolean retainAll(Collection<?> collection)
{
int oldSize = AbstractMutableBiMap.this.size();
Iterator<Map.Entry<K, V>> iterator = this.iterator();
while (iterator.hasNext())
{
Map.Entry<K, V> next = iterator.next();
if (!collection.contains(next))
{
iterator.remove();
}
}
return oldSize != AbstractMutableBiMap.this.size();
}
public boolean removeAll(Collection<?> collection)
{
boolean changed = false;
for (Object obj : collection)
{
if (this.remove(obj))
{
changed = true;
}
}
return changed;
}
public void clear()
{
AbstractMutableBiMap.this.clear();
}
public Iterator<Map.Entry<K, V>> iterator()
{
return new InternalEntrySetIterator();
}
private Object[] copyEntries(Object[] result)
{
int count = 0;
for (Pair<K, V> pair : AbstractMutableBiMap.this.keyValuesView())
{
result[count] = new InternalEntry(pair.getOne(), pair.getTwo());
count++;
}
return result;
}
private class InternalEntrySetIterator implements Iterator<Entry<K, V>>
{
private final Iterator<Entry<K, V>> iterator = AbstractMutableBiMap.this.delegate.entrySet().iterator();
private V currentValue;
public boolean hasNext()
{
return this.iterator.hasNext();
}
public Entry<K, V> next()
{
Entry<K, V> next = this.iterator.next();
Entry<K, V> result = new InternalEntry(next.getKey(), next.getValue());
this.currentValue = result.getValue();
return result;
}
public void remove()
{
this.iterator.remove();
AbstractMutableBiMap.this.inverse.delegate.removeKey(this.currentValue);
}
}
private final class InternalEntry implements Entry<K, V>
{
private final K key;
private V value;
private InternalEntry(K key, V value)
{
this.key = key;
this.value = value;
}
public K getKey()
{
return this.key;
}
public V getValue()
{
return this.value;
}
@Override
public boolean equals(Object obj)
{
if (obj instanceof Entry)
{
Entry<?, ?> other = (Entry<?, ?>) obj;
Object otherKey = other.getKey();
Object otherValue = other.getValue();
return AbstractMutableBiMap.nullSafeEquals(this.key, otherKey)
&& AbstractMutableBiMap.nullSafeEquals(this.value, otherValue);
}
return false;
}
@Override
public int hashCode()
{
return (this.key == null ? 0 : this.key.hashCode())
^ (this.value == null ? 0 : this.value.hashCode());
}
@Override
public String toString()
{
return this.key + "=" + this.value;
}
public V setValue(V value)
{
V result = AbstractMutableBiMap.this.put(this.key, value);
this.value = value;
return result;
}
}
}
private static class Inverse<K, V> extends AbstractMutableBiMap<K, V> implements Externalizable
{
private static final long serialVersionUID = 1L;
public Inverse()
{
// Empty constructor for Externalizable class
super(UnifiedMap.<K, V>newMap(), UnifiedMap.<V, K>newMap());
}
Inverse(Map<K, V> delegate, AbstractMutableBiMap<V, K> inverse)
{
super(delegate, inverse);
}
}
}
| 29.719678 | 205 | 0.601308 |
636b82c0f562ea7c233b8962d914ed6dbea10408 | 5,675 | package com.zoomulus.speakeasy.sdp.messages;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Optional;
import lombok.Value;
import lombok.experimental.Accessors;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.net.MediaType;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.zoomulus.speakeasy.core.message.Message;
import com.zoomulus.speakeasy.core.types.EmailAddress;
import com.zoomulus.speakeasy.sdp.messages.exceptions.SDPMessageException;
import com.zoomulus.speakeasy.sdp.messages.exceptions.SDPParseException;
import com.zoomulus.speakeasy.sdp.types.SDPBandwidth;
import com.zoomulus.speakeasy.sdp.types.SDPConnectionData;
import com.zoomulus.speakeasy.sdp.types.SDPOrigin;
import com.zoomulus.speakeasy.sdp.types.SDPTimePeriod;
/**
* An implementation of RFC 4566.
*/
@Value
@Accessors(fluent=true)
public class SDPMessage implements Message
{
public static final String VERSION = "0";
final MediaType contentType = MediaType.create("application", "sdp");
final String version;
final SDPOrigin origin;
final String sessionName;
final Optional<String> sessionInformation;
final Optional<URI> uri;
final Optional<EmailAddress> emailAddress;
final Optional<PhoneNumber> phoneNumber;
final Optional<SDPConnectionData> connectionData;
final Optional<SDPBandwidth> bandwidth;
final SDPTimePeriod timing;
@Override
public ByteBuffer buffer()
{
// TODO Auto-generated method stub
return null;
}
private SDPMessage(final String version,
final SDPOrigin origin
) throws SDPMessageException
{
if (! VERSION.equals(version)) {
throw new SDPMessageException(String.format("Invalid SDP version \"%s\"", version));
}
this.version = version;
this.origin = origin;
sessionName = new String(" ");
sessionInformation = Optional.<String> empty();
uri = Optional.<URI> empty();
emailAddress = Optional.<EmailAddress> empty();
phoneNumber = Optional.<PhoneNumber> empty();
connectionData = Optional.<SDPConnectionData> empty();
bandwidth = Optional.<SDPBandwidth> empty();
timing = new SDPTimePeriod();
}
private static final String getNextExpectedToken()
{
return getNextExpectedToken(null);
}
private static final String getNextExpectedToken(final String currentToken)
{
if (Strings.isNullOrEmpty(currentToken)) { return Tokens.VERSION_TOKEN; }
switch (currentToken) {
case Tokens.VERSION_TOKEN:
return Tokens.ORIGIN_TOKEN;
default:
return Tokens.NO_TOKEN;
}
}
public static SDPMessage parse(final ByteBuffer in) throws SDPMessageException
{
SDPMessageBuilder sdpBuilder = builder();
String expectedToken = getNextExpectedToken();
List<String> value;
while (in.hasRemaining())
{
char c = (char) in.get();
if (c != expectedToken.charAt(0))
{
throw new SDPParseException(String.format("SDP parse failure - expected %s but got %c", expectedToken, (char)c));
}
if ('=' != (char) in.get())
{
throw new SDPParseException(String.format("SDP parse failure - token %c must be followed by '='", (char)c));
}
value = nextLine(in);
switch (expectedToken)
{
case Tokens.VERSION_TOKEN:
sdpBuilder = sdpBuilder.version(value.size() > 0 ? value.get(0) : "");
break;
case Tokens.ORIGIN_TOKEN:
sdpBuilder = sdpBuilder.origin(SDPOrigin.parse(value));
break;
}
expectedToken = getNextExpectedToken(expectedToken);
}
return sdpBuilder.build();
}
static List<String> nextLine(final ByteBuffer in)
{
final List<String> line = Lists.newArrayList();
StringBuilder token = new StringBuilder();
while (in.hasRemaining())
{
char c = (char) in.get();
if (('\n' == c || ' ' == c) && token.length() > 0)
{
line.add(token.toString());
if ('\n' == c) break;
token = new StringBuilder();
}
else if ('\n' == c)
{
token.append("");
break;
}
else token.append(c);
}
return line;
}
public static SDPMessageBuilder builder()
{
return new SDPMessageBuilder();
}
public static class SDPMessageBuilder
{
String version = VERSION;
SDPOrigin origin = null;
SDPMessageBuilder version(final String version)
{
this.version = version;
return this;
}
public SDPMessageBuilder origin(final SDPOrigin origin) {
this.origin = origin;
return this;
}
public SDPMessage build() throws SDPMessageException
{
if (null == origin) origin = new SDPOrigin();
return new SDPMessage(version, origin);
}
}
public static class Tokens
{
static final String NO_TOKEN = "";
public static final String VERSION_TOKEN = "v";
public static final String ORIGIN_TOKEN = "o";
}
}
| 31.353591 | 129 | 0.599295 |
7694d64abee35bbe469d58727e8d3c580a8ace6c | 21,231 | /*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.mergejoin;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.step.errorhandling.StreamInterface;
/**
* Merge rows from 2 sorted streams and output joined rows with matched key fields.
* Use this instead of hash join is both your input streams are too big to fit in
* memory. Note that both the inputs must be sorted on the join key.
*
* This is a first prototype implementation that only handles two streams and
* inner join. It also always outputs all values from both streams. Ideally, we should:
* 1) Support any number of incoming streams
* 2) Allow user to choose the join type (inner, outer) for each stream
* 3) Allow user to choose which fields to push to next step
* 4) Have multiple output ports as follows:
* a) Containing matched records
* b) Unmatched records for each input port
* 5) Support incoming rows to be sorted either on ascending or descending order.
* The currently implementation only supports ascending
* @author Biswapesh
* @since 24-nov-2006
*/
public class MergeJoin extends BaseStep implements StepInterface
{
private static Class<?> PKG = MergeJoinMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private MergeJoinMeta meta;
private MergeJoinData data;
public MergeJoin(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(MergeJoinMeta)smi;
data=(MergeJoinData)sdi;
int compare;
if (first)
{
first = false;
// Find the RowSet to read from
//
List<StreamInterface> infoStreams = meta.getStepIOMeta().getInfoStreams();
data.oneRowSet = findInputRowSet(infoStreams.get(0).getStepname());
if (data.oneRowSet==null) {
throw new KettleException( BaseMessages.getString(PKG, "MergeJoin.Exception.UnableToFindSpecifiedStep", infoStreams.get(0).getStepname()) );
}
data.twoRowSet = findInputRowSet(infoStreams.get(1).getStepname());
if (data.twoRowSet==null) {
throw new KettleException( BaseMessages.getString(PKG, "MergeJoin.Exception.UnableToFindSpecifiedStep", infoStreams.get(1).getStepname()) );
}
data.one=getRowFrom(data.oneRowSet);
if (data.one!=null)
{
data.oneMeta=data.oneRowSet.getRowMeta();
}
else
{
data.one=null;
data.oneMeta=getTransMeta().getStepFields(infoStreams.get(0).getStepname());
}
data.two=getRowFrom(data.twoRowSet);
if (data.two!=null)
{
data.twoMeta=data.twoRowSet.getRowMeta();
}
else
{
data.two=null;
data.twoMeta=getTransMeta().getStepFields(infoStreams.get(1).getStepname());
}
// just for speed: oneMeta+twoMeta
//
data.outputRowMeta=new RowMeta();
data.outputRowMeta.mergeRowMeta( data.oneMeta.clone() );
data.outputRowMeta.mergeRowMeta( data.twoMeta.clone() );
if (data.one!=null)
{
// Find the key indexes:
data.keyNrs1 = new int[meta.getKeyFields1().length];
for (int i=0;i<data.keyNrs1.length;i++)
{
data.keyNrs1[i] = data.oneMeta.indexOfValue(meta.getKeyFields1()[i]);
if (data.keyNrs1[i]<0)
{
String message = BaseMessages.getString(PKG, "MergeJoin.Exception.UnableToFindFieldInReferenceStream",meta.getKeyFields1()[i]);
logError(message);
throw new KettleStepException(message);
}
}
}
if (data.two!=null)
{
// Find the key indexes:
data.keyNrs2 = new int[meta.getKeyFields2().length];
for (int i=0;i<data.keyNrs2.length;i++)
{
data.keyNrs2[i] = data.twoMeta.indexOfValue(meta.getKeyFields2()[i]);
if (data.keyNrs2[i]<0)
{
String message = BaseMessages.getString(PKG, "MergeJoin.Exception.UnableToFindFieldInReferenceStream",meta.getKeyFields2()[i]);
logError(message);
throw new KettleStepException(message);
}
}
}
// Calculate one_dummy... defaults to null
data.one_dummy=RowDataUtil.allocateRowData( data.oneMeta.size() + data.twoMeta.size() );
// Calculate two_dummy... defaults to null
//
data.two_dummy=new Object[data.twoMeta.size()];
}
if (log.isRowLevel()) logRowlevel(BaseMessages.getString(PKG, "MergeJoin.Log.DataInfo",data.oneMeta.getString(data.one)+"")+data.twoMeta.getString(data.two));
/*
* We can stop processing if any of the following is true:
* a) Both streams are empty
* b) First stream is empty and join type is INNER or LEFT OUTER
* c) Second stream is empty and join type is INNER or RIGHT OUTER
*/
if ((data.one == null && data.two == null) ||
(data.one == null && data.one_optional == false) ||
(data.two == null && data.two_optional == false))
{
// Before we stop processing, we have to make sure that all rows from both input streams are depleted!
// If we don't do this, the transformation can stall.
//
while (data.one!=null && !isStopped()) data.one = getRowFrom(data.oneRowSet);
while (data.two!=null && !isStopped()) data.two = getRowFrom(data.twoRowSet);
setOutputDone();
return false;
}
if (data.one == null)
{
compare = -1;
}
else
{
if (data.two == null)
{
compare = 1;
}
else
{
int cmp = data.oneMeta.compare(data.one, data.twoMeta, data.two, data.keyNrs1, data.keyNrs2);
compare = cmp>0?1 : cmp<0?-1 : 0;
}
}
switch (compare)
{
case 0:
/*
* We've got a match. This is what we do next (to handle duplicate keys correctly):
* Read the next record from both streams
* If any of the keys match, this means we have duplicates. We therefore
* Create an array of all rows that have the same keys
* Push a Cartesian product of the two arrays to output
* Else
* Just push the combined rowset to output
*/
data.one_next = getRowFrom(data.oneRowSet);
data.two_next = getRowFrom(data.twoRowSet);
int compare1 = (data.one_next == null) ? -1 : data.oneMeta.compare(data.one, data.one_next, data.keyNrs1, data.keyNrs1);
int compare2 = (data.two_next == null) ? -1 : data.twoMeta.compare(data.two, data.two_next, data.keyNrs2, data.keyNrs2);
if (compare1 == 0 || compare2 == 0) // Duplicate keys
{
if (data.ones == null)
data.ones = new ArrayList<Object[]>();
else
data.ones.clear();
if (data.twos == null)
data.twos = new ArrayList<Object[]>();
else
data.twos.clear();
data.ones.add(data.one);
if (compare1 == 0) // First stream has duplicates
{
data.ones.add(data.one_next);
for(;!isStopped();)
{
data.one_next = getRowFrom(data.oneRowSet);
if (0 != ((data.one_next == null) ? -1 : data.oneMeta.compare(data.one, data.one_next, data.keyNrs1, data.keyNrs1))) {
break;
}
data.ones.add(data.one_next);
}
if (isStopped()) return false;
}
data.twos.add(data.two);
if (compare2 == 0) // Second stream has duplicates
{
data.twos.add(data.two_next);
for(;!isStopped();)
{
data.two_next = getRowFrom(data.twoRowSet);
if (0 != ((data.two_next == null) ? -1 : data.twoMeta.compare(data.two, data.two_next, data.keyNrs2, data.keyNrs2))) {
break;
}
data.twos.add(data.two_next);
}
if (isStopped()) return false;
}
for (Iterator<Object[]> oneIter = data.ones.iterator(); oneIter.hasNext() && !isStopped(); ) {
Object[] one = oneIter.next();
for (Iterator<Object[]> twoIter = data.twos.iterator(); twoIter.hasNext() && !isStopped(); ) {
Object[] two = twoIter.next();
Object[] oneBig = RowDataUtil.createResizedCopy(one, data.oneMeta.size() + data.twoMeta.size());
Object[] combi = RowDataUtil.addRowData(oneBig, data.oneMeta.size(), two);
putRow(data.outputRowMeta, combi);
}
// Remove the rows as we merge them to keep the overall memory footprint minimal
oneIter.remove();
}
data.twos.clear();
}
else // No duplicates
{
Object[] outputRowData = RowDataUtil.addRowData(data.one, data.oneMeta.size(), data.two);
putRow(data.outputRowMeta, outputRowData);
}
data.one = data.one_next;
data.two = data.two_next;
break;
case 1:
//if (log.isDebug()) logDebug("First stream has missing key");
/*
* First stream is greater than the second stream. This means:
* a) This key is missing in the first stream
* b) Second stream may have finished
* So, if full/right outer join is set and 2nd stream is not null,
* we push a record to output with only the values for the second
* row populated. Next, if 2nd stream is not finished, we get a row
* from it; otherwise signal that we are done
*/
if (data.one_optional == true)
{
if (data.two != null)
{
Object[] outputRowData = RowDataUtil.createResizedCopy(data.one_dummy, data.outputRowMeta.size());
outputRowData = RowDataUtil.addRowData(outputRowData, data.oneMeta.size(), data.two);
putRow(data.outputRowMeta, outputRowData);
data.two = getRowFrom(data.twoRowSet);
}
else if (data.two_optional == false)
{
/*
* If we are doing right outer join then we are done since
* there are no more rows in the second set
*/
// Before we stop processing, we have to make sure that all rows from both input streams are depleted!
// If we don't do this, the transformation can stall.
//
while (data.one!=null && !isStopped()) data.one = getRowFrom(data.oneRowSet);
while (data.two!=null && !isStopped()) data.two = getRowFrom(data.twoRowSet);
setOutputDone();
return false;
}
else
{
/*
* We are doing full outer join so print the 1st stream and
* get the next row from 1st stream
*/
Object[] outputRowData = RowDataUtil.createResizedCopy(data.one, data.outputRowMeta.size());
outputRowData = RowDataUtil.addRowData(outputRowData, data.oneMeta.size(), data.two_dummy);
putRow(data.outputRowMeta, outputRowData);
data.one = getRowFrom(data.oneRowSet);
}
}
else if (data.two == null && data.two_optional == true)
{
/**
* We have reached the end of stream 2 and there are records
* present in the first stream. Also, join is left or full outer.
* So, create a row with just the values in the first stream
* and push it forward
*/
Object[] outputRowData = RowDataUtil.createResizedCopy(data.one, data.outputRowMeta.size());
outputRowData = RowDataUtil.addRowData(outputRowData, data.oneMeta.size(), data.two_dummy);
putRow(data.outputRowMeta, outputRowData);
data.one = getRowFrom(data.oneRowSet);
}
else if (data.two != null)
{
/*
* We are doing an inner or left outer join, so throw this row away
* from the 2nd stream
*/
data.two = getRowFrom(data.twoRowSet);
}
break;
case -1:
//if (log.isDebug()) logDebug("Second stream has missing key");
/*
* Second stream is greater than the first stream. This means:
* a) This key is missing in the second stream
* b) First stream may have finished
* So, if full/left outer join is set and 1st stream is not null,
* we push a record to output with only the values for the first
* row populated. Next, if 1st stream is not finished, we get a row
* from it; otherwise signal that we are done
*/
if (data.two_optional == true)
{
if (data.one != null)
{
Object[] outputRowData = RowDataUtil.createResizedCopy(data.one, data.outputRowMeta.size());
outputRowData = RowDataUtil.addRowData(outputRowData, data.oneMeta.size(), data.two_dummy);
putRow(data.outputRowMeta, outputRowData);
data.one = getRowFrom(data.oneRowSet);
}
else if (data.one_optional == false)
{
/*
* We are doing a left outer join and there are no more rows
* in the first stream; so we are done
*/
// Before we stop processing, we have to make sure that all rows from both input streams are depleted!
// If we don't do this, the transformation can stall.
//
while (data.one!=null && !isStopped()) data.one = getRowFrom(data.oneRowSet);
while (data.two!=null && !isStopped()) data.two = getRowFrom(data.twoRowSet);
setOutputDone();
return false;
}
else
{
/*
* We are doing a full outer join so print the 2nd stream and
* get the next row from the 2nd stream
*/
Object[] outputRowData = RowDataUtil.createResizedCopy(data.one_dummy, data.outputRowMeta.size());
outputRowData = RowDataUtil.addRowData(outputRowData, data.oneMeta.size(), data.two);
putRow(data.outputRowMeta, outputRowData);
data.two = getRowFrom(data.twoRowSet);
}
}
else if (data.one == null && data.one_optional == true)
{
/*
* We have reached the end of stream 1 and there are records
* present in the second stream. Also, join is right or full outer.
* So, create a row with just the values in the 2nd stream
* and push it forward
*/
Object[] outputRowData = RowDataUtil.createResizedCopy(data.one_dummy, data.outputRowMeta.size());
outputRowData = RowDataUtil.addRowData(outputRowData, data.oneMeta.size(), data.two);
putRow(data.outputRowMeta, outputRowData);
data.two = getRowFrom(data.twoRowSet);
}
else if (data.one != null)
{
/*
* We are doing an inner or right outer join so a non-matching row
* in the first stream is of no use to us - throw it away and get the
* next row
*/
data.one = getRowFrom(data.oneRowSet);
}
break;
default:
logDebug("We shouldn't be here!!");
// Make sure we do not go into an infinite loop by continuing to read data
data.one = getRowFrom(data.oneRowSet);
data.two = getRowFrom(data.twoRowSet);
break;
}
if (checkFeedback(getLinesRead())) logBasic(BaseMessages.getString(PKG, "MergeJoin.LineNumber")+getLinesRead());
return true;
}
/**
* @see StepInterface#init( org.pentaho.di.trans.step.StepMetaInterface , org.pentaho.di.trans.step.StepDataInterface)
*/
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(MergeJoinMeta)smi;
data=(MergeJoinData)sdi;
if (super.init(smi, sdi))
{
List<StreamInterface> infoStreams = meta.getStepIOMeta().getInfoStreams();
if (infoStreams.get(0).getStepMeta()==null || infoStreams.get(1).getStepMeta()==null)
{
logError(BaseMessages.getString(PKG, "MergeJoin.Log.BothTrueAndFalseNeeded"));
return false;
}
String joinType = meta.getJoinType();
for (int i = 0; i < MergeJoinMeta.join_types.length; ++i)
{
if (joinType.equalsIgnoreCase(MergeJoinMeta.join_types[i]))
{
data.one_optional = MergeJoinMeta.one_optionals[i];
data.two_optional = MergeJoinMeta.two_optionals[i];
return true;
}
}
logError(BaseMessages.getString(PKG, "MergeJoin.Log.InvalidJoinType", meta.getJoinType()));
return false;
}
return true;
}
/**
* Checks whether incoming rows are join compatible. This essentially
* means that the keys being compared should be of the same datatype
* and both rows should have the same number of keys specified
* @param row1 Reference row
* @param row2 Row to compare to
*
* @return true when templates are compatible.
*/
protected boolean isInputLayoutValid(RowMetaInterface row1, RowMetaInterface row2)
{
if (row1!=null && row2!=null)
{
// Compare the key types
String keyFields1[] = meta.getKeyFields1();
int nrKeyFields1 = keyFields1.length;
String keyFields2[] = meta.getKeyFields2();
int nrKeyFields2 = keyFields2.length;
if (nrKeyFields1 != nrKeyFields2)
{
logError("Number of keys do not match " + nrKeyFields1 + " vs " + nrKeyFields2);
return false;
}
for (int i=0;i<nrKeyFields1;i++)
{
ValueMetaInterface v1 = row1.searchValueMeta(keyFields1[i]);
if (v1 == null)
{
return false;
}
ValueMetaInterface v2 = row2.searchValueMeta(keyFields2[i]);
if (v2 == null)
{
return false;
}
if ( v1.getType()!=v2.getType() )
{
return false;
}
}
}
// we got here, all seems to be ok.
return true;
}
} | 41.385965 | 168 | 0.56149 |
3f9678909fc7e7698ad1e44f9f84afa88d5b34ff | 409 | package io.exeqt.engine.execution.conversion;
/**
* Responsible for performing conversion between sql specific types to java
*
* @author anatolii vakaliuk
*/
@FunctionalInterface
public interface SQLValueConversion<R> {
/**
* Converts {@code source} to target type
*
* @param sqlValue sql value to convert
* @return converted value
*/
R convert(final Object sqlValue);
}
| 22.722222 | 75 | 0.694377 |
2ae254c61aa749176a5c371def86b5f462844492 | 7,207 | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.ixeption.libgdx.transitions;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.utils.Array;
/** An {@link Game} that delegates to a {@link Screen}. Allows to apply different transitions to screens.
*
* Screens are not disposed automatically. You must handle whether you want to keep screens around or dispose of them when another
* screen is set.
* @author iXeption */
public class FadingGame extends Game {
final protected Batch batch;
private final Array<TransitionListener> listeners;
protected FrameBuffer currentScreenFBO;
protected FrameBuffer nextScreenFBO;
protected Screen nextScreen;
private float transitionDuration;
private float currentTransitionTime;
private boolean transitionRunning;
private ScreenTransition screenTransition;
public FadingGame(Batch batch) {
this.batch = batch;
this.listeners = new Array<TransitionListener>();
}
@Override
public void create() {
this.currentScreenFBO = new FrameBuffer(Pixmap.Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
this.nextScreenFBO = new FrameBuffer(Pixmap.Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
}
@Override
public void dispose() {
if (screen != null) screen.hide();
if (nextScreen != null) nextScreen.hide();
this.currentScreenFBO.dispose();
this.nextScreenFBO.dispose();
}
@Override
public void pause() {
if (screen != null) screen.pause();
if (nextScreen != null) nextScreen.pause();
}
@Override
public void resume() {
if (screen != null) screen.resume();
if (nextScreen != null) nextScreen.resume();
}
@Override
public void render() {
float delta = Gdx.graphics.getDeltaTime();
if (nextScreen == null) {
// no other screen
screen.render(delta);
} else {
if (transitionRunning && currentTransitionTime >= transitionDuration) {
// is active and time limit reached
this.screen.hide();
this.screen = this.nextScreen;
this.screen.resume();
transitionRunning = false;
this.nextScreen = null;
notifyFinished();
this.screen.render(delta);
} else {
// transition is active
if (screenTransition != null) {
currentScreenFBO.begin();
this.screen.render(delta);
currentScreenFBO.end();
nextScreenFBO.begin();
this.nextScreen.render(delta);
nextScreenFBO.end();
float percent = currentTransitionTime / transitionDuration;
screenTransition.render(batch, currentScreenFBO.getColorBufferTexture(), nextScreenFBO.getColorBufferTexture(),
percent);
currentTransitionTime += delta;
}
}
}
}
@Override
public void resize(int width, int height) {
if (screen != null) screen.resize(width, height);
if (nextScreen != null) nextScreen.resize(width, height);
this.currentScreenFBO.dispose();
this.nextScreenFBO.dispose();
this.currentScreenFBO = new FrameBuffer(Format.RGBA8888, width, height, false);
this.nextScreenFBO = new FrameBuffer(Format.RGBA8888, width, height, false);
}
/** Sets the {@link ScreenTransition} which is used. May be {@code null} to use instant switching.
* @param screenTransition may be {@code null}
* @param duration the transition duration in seconds
* @return {@code true} if successful false if transition is running */
public boolean setTransition(ScreenTransition screenTransition, float duration) {
if (transitionRunning) return false;
this.screenTransition = screenTransition;
this.transitionDuration = duration;
return true;
}
/** @return the currently active {@link Screen}. */
@Override
public Screen getScreen() {
return screen;
}
/** Sets the current screen. {@link Screen#hide()} is called on any old screen, and {@link Screen#show()} is called on the new
* screen, if any.
* @param screen may be {@code null} */
@Override
public void setScreen(Screen screen) {
screen.show();
if (transitionRunning)
Gdx.app.log(FadingGame.class.getSimpleName(), "Changed Screen while transition in progress");
if (this.screen == null) {
this.screen = screen;
} else {
if (screenTransition == null) {
this.screen.hide();
this.screen = screen;
} else {
this.nextScreen = screen;
this.screen.pause();
this.nextScreen.pause();
currentTransitionTime = 0;
transitionRunning = true;
notifyStarted();
}
}
this.screen.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
/** @return the next {@link Screen}. */
public Screen getNextScreen() {
return nextScreen;
}
/** @param listener to get transition events */
public void addTransitionListener(TransitionListener listener) {
listeners.add(listener);
return;
}
/** @param listener to remove
* @return {@code true} if successful */
public boolean removeTransitionListener(TransitionListener listener) {
return listeners.removeValue(listener, true);
}
/** Clear listeners */
public void clearTransitionListeners() {
listeners.clear();
}
private void notifyFinished() {
for (TransitionListener transitionListener : listeners) {
transitionListener.onTransitionFinished();
}
}
private void notifyStarted() {
for (TransitionListener transitionListener : listeners) {
transitionListener.onTransitionStart();
}
}
}
| 33.365741 | 131 | 0.611211 |
cb72af929ae42759d9143b3507539a2639c8de5a | 1,989 | package collection_framework;
import java.util.*;
public class AssetImple implements Asset{
Collection linkedList=new LinkedList();
Collection collection=new ArrayList();
@Override
public void removeLastAsset() {
System.out.println("Involked removeLastAsset");
LinkedList list=(LinkedList)linkedList;
System.out.println(list.removeLast());
}
@Override
public void removeFirstAsset() {
System.out.println("Involked removeFirstAsset");
LinkedList list=(LinkedList)linkedList;
System.out.println(list.removeFirst());
}
@Override
public void getFirstAsset() {
System.out.println("Involked getFirstAsset");
LinkedList list=(LinkedList)linkedList;
System.out.println(list.getFirst());
}
@Override
public void getLastAsset() {
System.out.println("Involked getLastAsset");
LinkedList list=(LinkedList)linkedList;
System.out.println(list.getLast());
}
@Override
public void addFirstAsset(Object object) {
System.out.println("Involked addFirstAsset");
LinkedList list=(LinkedList)linkedList;
list.addFirst(object);
}
@Override
public void addLastAsset(Object object) {
System.out.println("Involked addLastAsset");
LinkedList list=(LinkedList)linkedList;
list.addLast(object);
}
@Override
public void addAsset(Object object) {
System.out.println("Involked removeLastAsset");
}
@Override
public boolean searchAsset(Object object) {
// TODO Auto-generated method stub
return false;
}
@Override
public void updateAsset(Object object, String newName) {
// TODO Auto-generated method stub
}
@Override
public void deleteAsset(Object object) {
// TODO Auto-generated method stub
}
@Override
public void listOfAllAssets() {
System.out.println("Involked listOfAllAssets");
Iterator iterator= collection.iterator();
while(iterator.hasNext()) {
Object object=iterator.next();
System.out.println(object);
}
}
}
| 20.090909 | 57 | 0.711413 |
52f52c28bcc9b1c812ee32b0b5758f153fee33e9 | 325 | package ar.com.kfgodel.function.arrays.boxed.ints.arrays.boxed;
import ar.com.kfgodel.function.arrays.boxed.ints.arrays.ArrayOfBoxedIntegerToArrayOfObjectFunction;
/**
* Date: 29/07/17 - 19:57
*/
public interface ArrayOfBoxedIntegerToArrayOfBoxedByteFunction extends ArrayOfBoxedIntegerToArrayOfObjectFunction<Byte> {
}
| 29.545455 | 121 | 0.827692 |
652ecaf3ea92bbdb9825c5fffcaf1ad8ea51b365 | 998 | package stsutil.cardimagescreator;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
CardImagesCreator cardImagesCreator = new CardImagesCreator();
File folder = new File("cards");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
try {
cardImagesCreator.createCardImages(file);
System.out.println("Correctly processed file: " + file.getName());
} catch (Exception e){
System.out.println("Exception during processing file " + file.getName());
e.printStackTrace();
}
}
}
} catch (IOException e) {
System.out.println("Exception during Main method ");
e.printStackTrace();
}
}
}
| 28.514286 | 97 | 0.509018 |
85bd3bc722f74badc2b56817f49322920a150200 | 11,885 | class jcxR17B {
}
class de {
public boolean Ry2X_lM7 () {
boolean GHaObzYFPBURMy = new UAq().gJZw9j;
while ( !( -false[ -new int[ -!WLi4J().WoZwP]._BkYmw()])[ !!!--!true[ -new byh().F_6RAjsJbhNLk]]) while ( !this.ScAsiviJWNr) ;
void u0ktWkqDOGj = new V()[ iB3oES().OrKWMAqp()];
!this.CtwACWX9;
vQrK5vXB[][][] ODjF35uxx;
return;
boolean Bmh_uHI;
;
if ( !!!UfG3re_Kg.Rkq) return;
boolean l1n7eq5_6i = Uihv8.V6v9() = this.mjgUyYdwBwSFRa;
{
if ( true.bE0jIzzh8) ;
int hlzBNnAc4c;
while ( ( -this.Z_ihnGhxsSmC)[ -new nx6cwyFy_Ahj().UkDMJ33h()]) ;
boolean[][] oaHQS2Wbt7L;
return;
void[][][][][] oZGugG;
while ( -2.I6()) -Udo.uzI;
boolean[][] puOA9PbjOZh;
return;
}
{
{
if ( null.tjUxg6TVOt) if ( false[ !new int[ -!false.gnHlrUaoLf]._V]) -!!!--this[ !!657[ null.j3D()]];
}
;
int RBsye8OQTzKk;
void dKjPZ3HV;
boolean[][] lkFI7TLxcTOG7;
boolean[][] vKdc5wU;
boolean Wxt9FmCgPEq;
int DkFUMVhXkY;
}
;
}
public static void Jnz6emLXE_ (String[] xZ4oipR) {
;
boolean[] UjxPm3JlVBx8i;
{
return;
boolean[] E39azK;
null[ -false[ !false.pcI5ilwnOT]];
XmZ2CRrVnXk[] KiNja2;
Xq5gTsLSx TSdPI0rzp;
int Z;
{
int ofVoyjkoCUsKx;
}
int YE3qK22CQ6g2;
while ( -!TafbDP4c.s_gtx8k5sIPXOE()) -this[ !!false.JNSeuTHKxB];
;
while ( -!!( -!-813.qPF7zLSS_Ajx8N())[ !!new void[ --!MqT4WHkpe.k].vTVRa885rO()]) if ( --dEIyREjcBS4[ this.XSwIifwWFuIh]) {
;
}
if ( new fZ5_DuF[ new int[ rv_b.e7()].XaH32()].z1jOXwXwmVVS) return;
}
boolean wt_mX8B = new void[ false.G].brRG7b0();
int MXk_3Q1p6BUN = !-( ( -this.TG)[ false._3()]).haQ630UEJoK8M;
}
public void[][] bCvseOG (int[][] l2bMT82cW, wPeqp2ile7 ZcRPdSgT, void J6apI8E4k8loIE, void eV) {
if ( !!!410771004.auCQ()) while ( ---this.pJelPgbUauNDRK) if ( !Bt2OUVT_UZft9.AfNMQYRDP) {
boolean[][] Y;
}
int PokmGJzmmNSgY;
void Syt;
;
boolean[] jPkyiB = null.FvQb2gulnd;
while ( false[ new fwTxdAcueG().E48IjS()]) if ( !U[ -!!-this.y()]) {
JK9xReq3ifY5Z[] eDgCaLxtwUSh;
}
while ( -759692.e5C7jGavD9eB()) ;
;
{
!!jW96()[ true.vpM];
dvXPfN2U9cw7 erfZs_LHi0p;
( !-6708432[ gy5zvA0A9SXmh.I8BiVbKBw7])[ !rrOJSpYSWm[ -!!sGCc3K()[ --true.Lh_JRf9CP()]]];
{
int[] s_KlaTDdMZZVdX;
}
int[] Lec;
void[][] fy1w6gw1BZdQ;
while ( -new void[ false.gfeFoB2q].Nv6FStx) ---!null.LAhuVrs1();
while ( -new rrtNQgMc_uJo().AY) ;
{
!true[ 5255._yvbQTV8x];
}
if ( true.i1S57eg) while ( false[ dkWml.x_2gfOP()]) if ( !-true.nkvxgfe2SgVRse()) SsyEVyQEFGIll().myIZeUNILI;
{
{
void[][][][][][] ortVRY4a25y;
}
}
K[] kw9hkiipB;
void[] rYndsWDZE;
while ( WFHt.FE1e1zOsmzd()) return;
void[] e;
boolean pQDbuglvEpPC;
if ( --!true.UL2iwzgYtLWx) !new qFDbavYP0Khz().L737E0WSnQ5fV_();
ycdb0J[] a;
}
boolean[] bYoqOKK3E;
boolean Dr5Z3 = this[ -!!-8.og6d4] = true[ oqwjz[ !--this.okGv4Q()]];
!!!73310.iFIiNgi;
{
void hfVn3MdYMHZ;
;
void G5gryR;
int[][][][][][][][][] U;
boolean A03pXDXqD;
if ( ( !-new pPbACk().lgR).whn3kAHYlU8MA) return;
wkhpTZ8DxZzEH oCk8;
void hawR1;
;
int _2Xy;
{
{
!9082.fyPcezIbOkVA();
}
}
YLkIK0Kgi9YVr_ oiIf3oL3;
;
}
void RFnbzD8 = jSwSVE9W[ true.bo4Xb()];
while ( ( -n9n5().ZQEXefl).JWIb()) --new B().KIOMPw8qlhAZ;
boolean oeZpKCK7;
{
;
while ( !--new N_TeIV4ItHzTj()[ -( TXiriGIFxKl4().n()).MUzO()]) {
int inhEsF;
}
if ( new void[ hSNrUFCnNgN().gTo].aIR) return;
}
if ( !-!!Q7pFqiM0.BVm8) return;else if ( -BNyDVI.ghH9G4V427T3) {
void d;
}
}
public static void EIXkj53 (String[] wB) throws FAY18q6 {
if ( null.ICHQDkJ) if ( !new wFwImWn4xc()[ null[ --null.V_9XX]]) while ( !null[ !true.UYQB_jnv]) return;
{
int[] oUu1po32oM;
int[][] l;
boolean[][][] Qp;
int Yp0XgYyLSQo1;
;
if ( new P[ -!!---vQ6yFnWzv.ElD0lzMjvE60K].LigO) return;
;
boolean RV;
void[][] hhaElnPUWzK;
int hTtjxamAhO4I;
}
return 7.TffKqndhw2lOGD();
UJghEyEYKR7l6[] aLsGx7nlb1qK = !-false.fQBUwM6UT3DblC() = true.r1vA4dXFIWRKG;
boolean[][][] PWUscmgR = this.XOkr767dK0f;
}
public void jQkdCC_bq;
public void[][][] fqiY0gO () throws PYU {
int RK8m;
void[][][] b = pkMgMwe[ rLlExHAI5().mn()] = true[ XUgqPGPz.ZQJkYl];
;
;
{
_Ft_o4[] TA8UFLe;
JvOBuFVS[] q4DiVH6WPo;
boolean[][][][] j7;
if ( false.urxz1Wl()) while ( !( ( new int[ true.QmR][ !!-true.bi84Cp9]).jshoht).ntL3rA_je9) while ( new boolean[ !new boolean[ -!!-27.t5zR93N2jec1].cH()].hq5Q0NHjRj()) {
if ( -( ( true[ ------!ClwS0g().tTp8NFL2e])[ !false._7GIPyg2MN3Dh])[ true.cNmHgw4Lm14()]) while ( --null.fyYYd2V) return;
}
boolean M;
return;
true.uneHK;
return;
int[][] qJr1M1FAbp;
boolean[][] _Uvts;
while ( k8[ -true[ !( -( new Dc0g8TO0().OvuGsj())[ !-1.YU]).YW9TN()]]) ;
if ( !-dTzFW().UQfIzi07B2fzS()) true.KMNqS4r9fkaKoP();
int[][][][][][] Od;
return;
void HavCW_zJr;
boolean Tl;
while ( 774[ -!-null.Vo3uaeQP]) {
int GM;
}
return;
return;
int[] NXOFGwJBa;
}
void fpc204_;
void mPv = ( !7027872[ new vn2GBS2().Z4WefbNVqoYE4()]).QUfuIAj7L02() = true.y();
return;
while ( false.Vo06JdVaWY2x()) while ( !-F8v2N().H()) new void[ false.DJZqha].dLV6nj5KC;
int[][][] Tv5TmBje;
if ( this.lOpo9) null.iUAQTmV7hQ3Q;else while ( 883126.DtqqCg24H1Pi8()) while ( !-!-2079094.YwQIDNh4N8h_cq()) ;
{
void E_E3Z8;
!!727401.c();
return;
--new void[ true.xEkhcy()].l1CaA3WVwUZ1();
boolean[][] SNN;
boolean[] SR3;
;
{
int[][] gJdWj;
}
UMs6aesiWN0u3b[][][][] Uha8xfh;
while ( 7406[ new CBRiiICF().Xde()]) if ( new SBYVL().NuJAP8ott()) while ( 41900[ !3453[ false.Qk]]) while ( !-uM4MJsFaShVf()[ w3TLvQx().MVD()]) ;
int dGdfr;
j3AZy4HWBXw9DB[][][] xIkmXH;
{
{
return;
}
}
int B4bbx8p5M6twHU;
void jB;
boolean[] RJbWm;
}
}
public static void lp57DiTM (String[] nxDeey4Z) {
;
boolean yEy7pUMJ74mEgu = 0064839.dNdTlMH_vh() = !this[ !wO94_G7DAlV5x4().Hp6h3Yc3T2uHr];
while ( new boolean[ !false.EuXgJTS9kF()][ -new bDNZ6rypTxMPH()[ C6e.syqE]]) ;
if ( -!-null[ -( -true.bfaq)[ new boolean[ --true.dHzuxQw5hkT()].SYvl99h1mFVTn]]) {
;
}else return;
int[][][][][][][] r1OkoLt;
void[][] czxEbj_8;
while ( new PPQ7qmsy[ !-sq0Cd3OSffX()[ ( null[ !!!!VEfPFU().yP8_s()])[ !2790.uXW5FI()]]].WLJDxHi5v4()) ;
if ( null.g2bggc9aHq) return;else -this._u3ZLBg84yMeKK();
m_iMIZH[][] ggWDW7Gkj1VAM1;
BTL6lMjLNcC[] alpaiAeT72jbZ;
{
!null.AE_A_51A5o();
;
{
while ( false.ML) while ( new boolean[ --new boolean[ !-!-this._()][ -jB1Vc_qxfE5.c010Velr]].U7dQ9t_pj5Q) ;
}
while ( -HASSa9ARbyk().DJZ7()) if ( -( Rz1JE0[ !true.VjjAX3()]).tAYvgAG1jj4pFr()) while ( !!!( !!!false.aXkwJGSiDeov_P).s) return;
;
if ( !-false.rWhefPv) while ( -FD().FqTnKYnYBHZF) {
{
return;
}
}
while ( new boolean[ cG9aMmsmAmGg[ new void[ new IQC().Xn50W6][ --!false[ !-oQLXbj23kP.AmNZ]]]][ null.PB1E]) if ( true.qT5f()) ;
if ( ( true[ !!-!!!null[ ---false.fufNOw6Wa]]).fcy3gWRBXE()) ;
}
}
public _B[] OBik5iBdZxvP;
public static void v (String[] Kt84J9vs90P) throws UA2wS5aok6 {
while ( 552963973[ -new rHZcI8eaH2().cY6i()]) ;
boolean[] plb4 = ( --null.F9PxjxQsJD9).S7wR();
int i2zbVFfUKp = -979[ !new R9().DDYX2rO6()];
{
boolean[][] EmGzNyHIFVizr;
;
return;
return;
;
}
void kpJDWlArSnPK = false[ -this.F84()];
if ( ( !!-new uAQBIhHP2[ new ytOCp3G1b9zS()[ true.QfkZjET()]].sxklze).eeG9BOas0RbI) {
void MbNYLHWhlBjy_;
}
;
i4z83NlLF8xZ0u racYcqg7prOweQ = ( !false.OIok5wwdqBPiLp()).Axiwfu();
void MoqKq;
Dn1ZtQSJ RdOadPSKwo;
;
return;
while ( zMx0e().xGBg68NT) {
boolean ZRTX3;
}
gIRUiQ gIuuhVoTB5F;
void BEPnXNfmzr;
while ( -new O()[ new int[ false[ !024[ -!null.QagIz]]]._Vm()]) while ( !!!new B0YkKnkHDuIk()[ -!false.tsk2CSeYT]) while ( !( new boolean[ --!--null[ !new int[ null.IteZN9bVdFZXP()][ this[ new int[ true.ItCcT3Om1].SHw()]]]].iwOQseb)[ true.zx6]) ;
int IZDe_V5u = false.AWvfP5I();
if ( ( !-true.vArq78pMF()).CW7MnHPTp22r()) while ( !---!-!-!!false.EFJklsJ7q9) return;else {
j ifa5wNzjuJZQ;
}
int[][] gHdF37SWRS;
}
public static void lwMnM52wWgx (String[] LZsl_wkwn) {
-true[ this.J_A1eihkZnXzY()];
while ( !---null[ --!GzloW2JKs[ !-!!!-true.cufWlUondyPA]]) while ( new s1U[ -!-!!-!!this.AtsGC6s][ !!-iik9hHZlyYe.iGtnxE1wS()]) !!false[ J()[ -new mNfJXDe().iw3ptSp0d5HgCs()]];
return true.v_fCCfdN_R();
!--16473752[ !( true.ZJh5LD9G()).jr4FI()];
while ( -this.uyNok3HZ) ;
while ( !!!( ---pod7BJCq0.r5AdBNrBI)[ true.REdLSPrN]) {
void[] AXPKJ6;
}
a0bbHS lz = !false.mjEIvslfh__8() = true.U3jlTUzsX;
while ( !!4.V3kQx()) {
boolean[] KdisWJP1;
}
{
;
void[] g4CI54Z3e;
int[] ndV3RM25_piw;
return;
FUoORhAVGMUz2 xtT6rSo2;
RYfhz4eyCma[][][][][][] Ckxn0p;
void[][][] vVhCr8x0;
void gs;
OLRKeIcV[][] VlUcR3DzMpJ79;
if ( new iTUiZVUqGl_().Ihu()) ;
int[] bh;
if ( true.hz077dxQkiTZEo()) while ( -!--( APnWQEkiArje().I).jnlNi1MasFC6) {
while ( -!!-new zPd58jKiee6qb()[ !null.xUUY9RSRj3]) return;
}
}
void[] Glw4NfkMeFyD = false.ysJpZ0vYeC42() = new w2JrL5D17().gN95WZ1();
lSggOWgBqOp2Z[] h3hDA1Kg;
n0[] A = nQam5K4rmsdyA.D07qe1kk4UnBY;
}
public void tHTaxl;
public void IoRCz4VJtUOYP;
}
| 36.682099 | 254 | 0.473117 |
ac42ed7cc54ef8052c69d3831560b7767539f721 | 1,015 | package com.mapper.xiaoqu;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.model.FK_Community;
@Mapper
public interface XiaoQuMapper {
/*
@Select("SELECT * FROM UserTest WHERE NAME = #{name}")
FK_House findByName(@Param("name") String name);
@Insert("INSERT INTO UserTest(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
@Select("SELECT * FROM UserTest WHERE ID = #{id}")
UserTest findByUserById(@Param("id") Integer id);*/
/*@Select("SELECT * FROM B_Order WHERE ID = #{id}")
B_Order findOrder(@Param("id") String id);*/
//小区表和小区图片表关联查询
@Select("SELECT TOP 3 * FROM FK_Community JOIN FK_CommunityPhoto ON FK_Community.id = FK_CommunityPhoto.CommunityId")
List<FK_Community> findXiaoQu();
@Select("SELECT * FROM FK_Community WHERE ID = #{id}")
FK_Community selectById(@Param("id") String id);
}
| 30.757576 | 118 | 0.70936 |
3f6254195a5fb42fdf1df3dce6b194435ffe654a | 3,117 | /*
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.sun.xml.ws.api.model;
/**
* Denotes the binding of a parameter.
*
* <p>
* This is somewhat like an enumeration (but it is <b>NOT</b> an enumeration.)
*
* <p>
* The possible values are
* BODY, HEADER, UNBOUND, and ATTACHMENT. BODY, HEADER, and UNBOUND
* has a singleton semantics, but there are multiple ATTACHMENT instances
* as it carries additional MIME type parameter.
*
* <p>
* So don't use '==' for testing the equality.
*/
public final class ParameterBinding {
/**
* Singleton instance that represents 'BODY'
*/
public static final ParameterBinding BODY = new ParameterBinding(Kind.BODY,null);
/**
* Singleton instance that represents 'HEADER'
*/
public static final ParameterBinding HEADER = new ParameterBinding(Kind.HEADER,null);
/**
* Singleton instance that represents 'UNBOUND',
* meaning the parameter doesn't have a representation in a SOAP message.
*/
public static final ParameterBinding UNBOUND = new ParameterBinding(Kind.UNBOUND,null);
/**
* Creates an instance that represents the attachment
* with a given MIME type.
*
* <p>
* TODO: shall we consider givint the singleton semantics by using
* a cache? It's more elegant to do so, but
* no where in JAX-WS RI two {@link ParameterBinding}s are compared today,
*/
public static ParameterBinding createAttachment(String mimeType) {
return new ParameterBinding(Kind.ATTACHMENT,mimeType);
}
/**
* Represents 4 kinds of binding.
*/
public static enum Kind {
BODY, HEADER, UNBOUND, ATTACHMENT;
}
/**
* Represents the kind of {@link ParameterBinding}.
* Always non-null.
*/
public final Kind kind;
/**
* Only used with attachment binding.
*/
private String mimeType;
private ParameterBinding(Kind kind,String mimeType) {
this.kind = kind;
this.mimeType = mimeType;
}
public String toString() {
return kind.toString();
}
/**
* Returns the MIME type associated with this binding.
*
* @throws IllegalStateException
* if this binding doesn't represent an attachment.
* IOW, if {@link #isAttachment()} returns false.
* @return
* Can be null, if the MIME type is not known.
*/
public String getMimeType() {
if(!isAttachment())
throw new IllegalStateException();
return mimeType;
}
public boolean isBody(){
return this==BODY;
}
public boolean isHeader(){
return this==HEADER;
}
public boolean isUnbound(){
return this==UNBOUND;
}
public boolean isAttachment(){
return kind==Kind.ATTACHMENT;
}
}
| 26.87069 | 91 | 0.643568 |
aab53f5d28cb6fbfffd3d28a24e66ed61ab85629 | 420 | import java.util.Scanner;
public class Lista0103 {
public static void main(String[] args) {
Scanner ler = new Scanner(System.in);
float nota1;
float nota2;
float nota3;
nota1 = ler.nextFloat( );
nota2 = ler.nextFloat( );
nota3 = ler.nextFloat( );
System.out.println("A media final do aluno eh: " + ((nota1 * 2 + nota2 * 3 + nota3 * 5)/10));
}
}
| 24.705882 | 101 | 0.561905 |
35c16642af0539383ee6b618fc76d03b6075a4da | 4,109 |
package com.prowidesoftware.swift.model.mx.dic;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* Instrument that has or represents monetary value and is used to process a payment instruction.
*
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PaymentInstrument9", propOrder = {
"sttlmCcy",
"cshAcctDtls",
"chqDtls",
"bkrsDrftDtls"
})
public class PaymentInstrument9 {
@XmlElement(name = "SttlmCcy", required = true)
protected String sttlmCcy;
@XmlElement(name = "CshAcctDtls")
protected List<CashAccount4> cshAcctDtls;
@XmlElement(name = "ChqDtls")
protected Cheque4 chqDtls;
@XmlElement(name = "BkrsDrftDtls")
protected Cheque4 bkrsDrftDtls;
/**
* Gets the value of the sttlmCcy property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSttlmCcy() {
return sttlmCcy;
}
/**
* Sets the value of the sttlmCcy property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public PaymentInstrument9 setSttlmCcy(String value) {
this.sttlmCcy = value;
return this;
}
/**
* Gets the value of the cshAcctDtls property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cshAcctDtls property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCshAcctDtls().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CashAccount4 }
*
*
*/
public List<CashAccount4> getCshAcctDtls() {
if (cshAcctDtls == null) {
cshAcctDtls = new ArrayList<CashAccount4>();
}
return this.cshAcctDtls;
}
/**
* Gets the value of the chqDtls property.
*
* @return
* possible object is
* {@link Cheque4 }
*
*/
public Cheque4 getChqDtls() {
return chqDtls;
}
/**
* Sets the value of the chqDtls property.
*
* @param value
* allowed object is
* {@link Cheque4 }
*
*/
public PaymentInstrument9 setChqDtls(Cheque4 value) {
this.chqDtls = value;
return this;
}
/**
* Gets the value of the bkrsDrftDtls property.
*
* @return
* possible object is
* {@link Cheque4 }
*
*/
public Cheque4 getBkrsDrftDtls() {
return bkrsDrftDtls;
}
/**
* Sets the value of the bkrsDrftDtls property.
*
* @param value
* allowed object is
* {@link Cheque4 }
*
*/
public PaymentInstrument9 setBkrsDrftDtls(Cheque4 value) {
this.bkrsDrftDtls = value;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
/**
* Adds a new item to the cshAcctDtls list.
* @see #getCshAcctDtls()
*
*/
public PaymentInstrument9 addCshAcctDtls(CashAccount4 cshAcctDtls) {
getCshAcctDtls().add(cshAcctDtls);
return this;
}
}
| 24.170588 | 97 | 0.605743 |
a0d954342c1b0600e773f58c837cb962da730434 | 950 | package com.rafa.cursojava.exerciciosLista01;
import java.util.Scanner;
/**
*
* @author Raphaa JP
*/
public class Exer11 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Informe um numero: ");
int num1 = scan.nextInt();
System.out.println("Informe o segundo numero: ");
int num2 = scan.nextInt();
System.out.println("Informe o terceiro numero: ");
double num3 = scan.nextDouble();
int resultado = (num1 * 2) * (num2 / 2);
double resultado2 = (num1 * 3) + num3;
double resultado3 = Math.pow(num3, 3);
System.out.println("O resultado 1: " + resultado);
System.out.println("O resultado2: " + resultado2);
System.out.println("O resultado 3: " + resultado3);
}
}
| 23.75 | 59 | 0.528421 |
fb2cb44e91b57207d0a2513bfd7f5d5143774c37 | 561 | package uk.gov.pay.api.validation;
import javax.inject.Inject;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class ReturnUrlValidator implements ConstraintValidator<ValidReturnUrl, String> {
private URLValidator urlValidator;
@Inject
public ReturnUrlValidator(URLValidator urlValidator) {
this.urlValidator = urlValidator;
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return urlValidator.isValid(value);
}
}
| 26.714286 | 88 | 0.768271 |
972f31d4b00f82831330ede0f4a8a9dec081890b | 5,259 | package org.biopax.paxtools.controller;
import org.biopax.paxtools.model.BioPAXElement;
import org.biopax.paxtools.model.BioPAXLevel;
import org.biopax.paxtools.util.IllegalBioPAXArgumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
/**
* Provides a simple editor map for a level with a given factory.
*
* This class initializes 3 singletons( 1 for each level) from a tab delimited text resources that lists the
* properties and their domains. This is done to remove any dependencies to Jena.
*
* The recommended usage is to use the {@link #get(org.biopax.paxtools.model.BioPAXLevel)} method.
* @author Emek Demir
*/
public enum SimpleEditorMap implements EditorMap
{
L2(BioPAXLevel.L2),
L3(BioPAXLevel.L3);
private static final Logger log = LoggerFactory.getLogger(EditorMapImpl.class);
private final SimpleEditorMapImpl impl;
SimpleEditorMap(BioPAXLevel level)
{
this.impl = new SimpleEditorMapImpl(level);
}
/**
* To obtain a copy of the editor map for the corresponding level, use the
* @param level the BioPAX level
* @return SimpleEditorMap implementation for the BioPAX L2 or L3
*/
public static SimpleEditorMap get(BioPAXLevel level)
{
for (SimpleEditorMap value : values())
{
if (value.getLevel().equals(level)) return value;
}
//should never reach here
throw new IllegalBioPAXArgumentException("Unknown level:" + level);
}
static class SimpleEditorMapImpl extends EditorMapImpl implements EditorMap
{
SimpleEditorMapImpl(BioPAXLevel level)
{
super(level);
InputStream stream = this.getClass().getResourceAsStream(level + "Editor.properties");
readEditors(level, stream, this);
}
}
public <D extends BioPAXElement> PropertyEditor<? super D, ?> getEditorForProperty(String property,
Class<D> javaClass)
{
return impl.getEditorForProperty(property, javaClass);
}
@Override public Set<PropertyEditor> getEditorsForProperty(String property)
{
return impl.getEditorsForProperty(property);
}
@Override
public <D extends BioPAXElement> Set<PropertyEditor<? extends D, ?>> getSubclassEditorsForProperty(String property,
Class<D> domain)
{
return impl.getSubclassEditorsForProperty(property, domain);
}
@Override public Set<PropertyEditor> getEditorsOf(BioPAXElement bpe)
{
return impl.getEditorsOf(bpe);
}
@Override public Set<ObjectPropertyEditor> getInverseEditorsOf(BioPAXElement bpe)
{
return impl.getInverseEditorsOf(bpe);
}
@Override public <E extends BioPAXElement> Set<? extends Class<E>> getKnownSubClassesOf(Class<E> javaClass)
{
return impl.getKnownSubClassesOf(javaClass);
}
public BioPAXLevel getLevel()
{
return impl.getLevel();
}
@Override public Set<PropertyEditor> getEditorsOf(Class<? extends BioPAXElement> domain)
{
return impl.getEditorsOf(domain);
}
@Override public Set<ObjectPropertyEditor> getInverseEditorsOf(Class<? extends BioPAXElement> domain)
{
return impl.getInverseEditorsOf(domain);
}
@Override
public Iterator<PropertyEditor> iterator()
{
return impl.iterator();
}
static void readEditors(BioPAXLevel level, InputStream stream, EditorMapImpl map)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
try
{
String line = reader.readLine();
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreElements())
{
map.registerModelClass(st.nextToken());
}
while ((line = reader.readLine()) != null)
{
if (!line.startsWith("#"))
{
st = new StringTokenizer(line);
String domain = st.nextToken();
Class<? extends BioPAXElement> domainInterface = map.getLevel().getInterfaceForName(domain);
String propertyName = st.nextToken();
Map<Class<? extends BioPAXElement>, Set<Class<? extends BioPAXElement>>> rangeRestrictions =
new HashMap<Class<? extends BioPAXElement>, Set<Class<? extends BioPAXElement>>>();
while (st.hasMoreTokens())
{
String rToken = st.nextToken();
if (rToken.startsWith("R:"))
{
StringTokenizer rt = new StringTokenizer(rToken.substring(2), "=");
Class<? extends BioPAXElement> rDomain = level.getInterfaceForName(rt.nextToken());
Set<Class<? extends BioPAXElement>> rRanges = new HashSet<Class<? extends
BioPAXElement>>();
for (StringTokenizer dt = new StringTokenizer(rt.nextToken(), ","); dt.hasMoreTokens(); )
{
rRanges.add(level.getInterfaceForName(dt.nextToken()));
}
rangeRestrictions.put(rDomain, rRanges);
}
}
map.createAndRegisterBeanEditor(propertyName, domainInterface, rangeRestrictions);
}
}
}
catch (IOException e)
{
log.error("Could not initialize " + "Editor Map", e);
}
finally
{
try
{
stream.close();
}
catch (IOException ignore)
{
log.error("Could not close stream! Exiting");
System.exit(1);
}
}
}
public static EditorMap buildCustomEditorMap(BioPAXLevel level, InputStream stream)
{
EditorMapImpl editorMap = new EditorMapImpl(level);
readEditors(level,stream,editorMap);
return editorMap;
}
}
| 26.695431 | 116 | 0.724092 |
53783f7b614b0d9921fdc313001bee2138691c35 | 17,755 | /*
* GROOVE: GRaphs for Object Oriented VErification Copyright 2003--2007
* University of Twente
*
* 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.
*
* $Id: FindReplaceDialog.java 5787 2016-08-04 10:36:41Z rensink $
*/
package groove.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EtchedBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import groove.grammar.type.TypeGraph;
import groove.grammar.type.TypeLabel;
import groove.grammar.type.TypeNode;
import groove.graph.EdgeRole;
import groove.io.HTMLConverter;
import groove.util.parse.FormatException;
/**
* Dialog finding/replacing labels.
* @author Arend Rensink
* @author Eduardo Zambon
*/
public class FindReplaceDialog {
/** Cancel result. */
public static final int CANCEL = 0;
/** Find result. */
public static final int FIND = 1;
/** Replace result. */
public static final int REPLACE = 2;
/**
* Constructs a dialog instance, given a set of existing names (that should
* not be used) as well as a suggested value for the new rule name.
* @param typeGraph the type graph containing all labels and sublabels
* @param oldLabel the label to rename; may be <code>null</code>
*/
public FindReplaceDialog(TypeGraph typeGraph, TypeLabel oldLabel) {
this.typeGraph = typeGraph;
this.suggestedLabel = oldLabel;
}
/**
* Creates a dialog and makes it visible, so that the user can choose the
* label to rename and its new version.
* @param frame the frame on which the dialog is shown.
* @param title the title for the dialog; if <code>null</code>, a default
* title is used
* @return <code>true</code> if the user agreed with the outcome of the
* dialog.
*/
public int showDialog(JFrame frame, String title) {
// set the suggested name in the name field
if (this.suggestedLabel != null) {
getOldField().setSelectedItem(this.suggestedLabel);
propagateSelection();
}
setReplaceEnabled();
JDialog dialog = getOptionPane().createDialog(frame, title == null ? DEFAULT_TITLE : title);
dialog.setVisible(true);
Object response = getOptionPane().getValue();
int result;
if (response == getReplaceButton() || response == getNewField()) {
result = REPLACE;
} else if (response == getFindButton()) {
result = FIND;
} else {
result = CANCEL;
}
return result;
}
/**
* Propagates the selection in the old field to all other GUI elements.
*/
private void propagateSelection() {
TypeLabel selection = (TypeLabel) getOldField().getSelectedItem();
getOldTypeLabel().setText(selection.getRole().getDescription(true));
getNewTypeCombobox().setSelectedIndex(EdgeRole.getIndex(selection.getRole()));
getNewField().setText(selection.text());
getNewField().setSelectionStart(0);
getNewField().setSelectionEnd(selection.text().length());
getNewField().requestFocus();
}
/** Returns the label to be renamed. */
public TypeLabel getOldLabel() {
return (TypeLabel) getOldField().getSelectedItem();
}
/** Returns the renamed label. */
public TypeLabel getNewLabel() {
TypeLabel result;
try {
result = getNewLabelWithErrors();
} catch (FormatException exc) {
result = null;
}
return result;
}
/**
* Returns the renamed label, or throws an exception if the renamed label is
* not OK.
*/
private TypeLabel getNewLabelWithErrors() throws FormatException {
TypeLabel result = null;
String text = getNewField().getText();
if (text.length() > 0) {
int labelType = getNewTypeCombobox().getSelectedIndex();
result = TypeLabel.createLabel(EdgeRole.getRole(labelType), text);
TypeLabel oldLabel = getOldLabel();
if (result.equals(oldLabel)) {
throw new FormatException("Old and new labels coincide");
} else if (this.typeGraph.isNodeType(oldLabel) && this.typeGraph.isNodeType(result)) {
TypeNode oldType = this.typeGraph.getNode(oldLabel);
TypeNode newType = this.typeGraph.getNode(result);
if (newType != null) {
if (this.typeGraph.isSubtype(oldType, newType)) {
throw new FormatException("New label '%s' is an existing supertype of '%s'",
result, oldLabel);
} else if (this.typeGraph.isSubtype(newType, oldType)) {
throw new FormatException("New label '%s' is an existing subtype of '%s'",
result, oldLabel);
}
}
}
} else {
throw new FormatException("Empty replacement label not allowed");
}
return result;
}
/**
* Enables or disables the Replace-button, depending on the validity of the
* renaming. Displays the error in {@link #getErrorLabel()} if the renaming
* is not valid.
*/
private void setReplaceEnabled() {
boolean enabled;
try {
getNewLabelWithErrors();
getErrorLabel().setText("");
enabled = true;
} catch (FormatException exc) {
getErrorLabel().setText(exc.getMessage());
enabled = false;
}
getReplaceButton().setEnabled(enabled);
getNameFieldListener().setEnabled(enabled);
}
/**
* Lazily creates and returns the option pane that is to form the content of
* the dialog.
*/
private JOptionPane getOptionPane() {
if (this.optionPane == null) {
JLabel oldLabel = new JLabel(OLD_TEXT);
JLabel newLabel = new JLabel(NEW_TEXT);
oldLabel.setPreferredSize(newLabel.getPreferredSize());
JPanel oldPanel = new JPanel(new BorderLayout());
oldPanel.add(oldLabel, BorderLayout.WEST);
oldPanel.add(getOldField(), BorderLayout.CENTER);
oldPanel.add(getOldTypeLabel(), BorderLayout.EAST);
JPanel newPanel = new JPanel(new BorderLayout());
newPanel.add(newLabel, BorderLayout.WEST);
newPanel.add(getNewField(), BorderLayout.CENTER);
newPanel.add(getNewTypeCombobox(), BorderLayout.EAST);
JPanel errorPanel = new JPanel(new BorderLayout());
errorPanel.add(getErrorLabel());
errorPanel.setPreferredSize(oldPanel.getPreferredSize());
this.optionPane = new JOptionPane(new Object[] {oldPanel, newPanel, errorPanel},
JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null,
new Object[] {getFindButton(), getReplaceButton(), getCancelButton()});
}
return this.optionPane;
}
/** The option pane that is the core of the dialog. */
private JOptionPane optionPane;
/**
* Returns the Replace button on the dialog.
*/
private JButton getReplaceButton() {
if (this.replaceButton == null) {
this.replaceButton = new JButton("Replace");
this.replaceButton.addActionListener(new CloseListener());
}
return this.replaceButton;
}
/** The OK button in the dialog. */
private JButton replaceButton;
/**
* Returns the Find button on the dialog.
*/
private JButton getFindButton() {
if (this.findButton == null) {
this.findButton = new JButton("Find");
this.findButton.addActionListener(new CloseListener());
}
return this.findButton;
}
/** The find button in the dialog. */
private JButton findButton;
/**
* Returns the cancel button on the dialog.
*/
private JButton getCancelButton() {
if (this.cancelButton == null) {
this.cancelButton = new JButton("Cancel");
this.cancelButton.addActionListener(new CloseListener());
}
return this.cancelButton;
}
/** The Cancel button in the dialog. */
private JButton cancelButton;
/** Returns the text field in which the user is to enter his input. */
private JComboBox<TypeLabel> getOldField() {
if (this.oldField == null) {
final JComboBox<TypeLabel> result = this.oldField = getLabelComboBox(this.typeGraph);
result.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
propagateSelection();
}
});
}
return this.oldField;
}
/** The text field where the original label is entered. */
private JComboBox<TypeLabel> oldField;
/** Returns the text field in which the user is to enter his input. */
private JTextField getNewField() {
if (this.newField == null) {
this.newField = new JTextField();
this.newField.getDocument().addDocumentListener(new OverlapListener());
this.newField.addActionListener(getNameFieldListener());
}
return this.newField;
}
/** Returns the close listener for the name field. */
private CloseListener getNameFieldListener() {
if (this.nameFieldListener == null) {
this.nameFieldListener = new CloseListener();
}
return this.nameFieldListener;
}
/** The text field where the renamed label is entered. */
private JTextField newField;
/** Close listener for the new name field. */
private CloseListener nameFieldListener;
/** Returns the label displaying the current error in the renaming (if any). */
private JLabel getErrorLabel() {
if (this.errorLabel == null) {
JLabel result = this.errorLabel = new JLabel();
result.setForeground(Color.RED);
result.setMinimumSize(getReplaceButton().getPreferredSize());
}
return this.errorLabel;
}
/** Label displaying the current error in the renaming (if any). */
private JLabel errorLabel;
/** Returns the combo box for the old label's type. */
private JLabel getOldTypeLabel() {
if (this.oldTypeLabel == null) {
final JLabel result = this.oldTypeLabel = new JLabel();
result.setText(getOldLabel().getRole().getDescription(true));
result.setPreferredSize(getNewTypeCombobox().getPreferredSize());
result.setBorder(new EtchedBorder());
result.setEnabled(true);
result.setFocusable(false);
}
return this.oldTypeLabel;
}
/** Combobox showing the new label's type. */
private JLabel oldTypeLabel;
/** Returns the combo box for the label in the given type graph. */
private JComboBox<TypeLabel> getLabelComboBox(TypeGraph typeGraph) {
final JComboBox<TypeLabel> result = new JComboBox<>();
result.setFocusable(false);
result.setRenderer(new DefaultListCellRenderer() {
@SuppressWarnings("rawtypes")
@Override
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
if (value instanceof TypeLabel) {
value = HTMLConverter.HTML_TAG.on(((TypeLabel) value).toLine().toHTMLString());
}
return super.getListCellRendererComponent(list,
value,
index,
isSelected,
cellHasFocus);
}
});
for (TypeLabel label : sortLabels(typeGraph.getLabels())) {
if (!label.isDataType() && label != TypeLabel.NODE) {
result.addItem(label);
}
}
return result;
}
private List<TypeLabel> sortLabels(Set<TypeLabel> labels) {
List<TypeLabel> result = new ArrayList<>(labels.size());
List<TypeLabel> nodeTypes = new ArrayList<>();
List<TypeLabel> flags = new ArrayList<>();
List<TypeLabel> binary = new ArrayList<>();
for (TypeLabel label : labels) {
switch (label.getRole()) {
case NODE_TYPE:
nodeTypes.add(label);
break;
case FLAG:
flags.add(label);
break;
case BINARY:
binary.add(label);
}
}
Collections.sort(nodeTypes);
Collections.sort(flags);
Collections.sort(binary);
result.addAll(nodeTypes);
result.addAll(flags);
result.addAll(binary);
return result;
}
/** Returns the combobox for the new label's type. */
private JComboBox<String> getNewTypeCombobox() {
if (this.newTypeChoice == null) {
final JComboBox<String> result = this.newTypeChoice = new JComboBox<>();
for (EdgeRole kind : EdgeRole.values()) {
result.addItem(kind.getDescription(true));
}
result.setSelectedIndex(EdgeRole.getIndex(getOldLabel().getRole()));
result.setEnabled(true);
result.setFocusable(false);
result.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Font font = getNewField().getFont();
int fontProperty;
switch (EdgeRole.getRole(result.getSelectedIndex())) {
case NODE_TYPE:
fontProperty = Font.BOLD;
break;
case FLAG:
fontProperty = Font.ITALIC;
break;
default:
fontProperty = Font.PLAIN;
}
font = font.deriveFont(fontProperty);
getNewField().setFont(font);
setReplaceEnabled();
}
});
}
return this.newTypeChoice;
}
/** Combobox showing the old label's type. */
private JComboBox<String> newTypeChoice;
/** Set of existing rule names. */
private final TypeGraph typeGraph;
/** The old label value suggested at construction time; may be {@code null}. */
private final TypeLabel suggestedLabel;
/** Default dialog title. */
static private String DEFAULT_TITLE = "Find/Replace Labels";
/** Text of find label on dialog. */
static private String OLD_TEXT = "Find label: ";
/** Text of replace label on dialog */
static private String NEW_TEXT = "Replace with: ";
/**
* Action listener that closes the dialog and sets the option pane's value
* to the source of the event, provided the source of the event is the
* cancel button, or the value of the text field is a valid rule name.
*/
private class CloseListener implements ActionListener {
/** Empty constructor with the right visibility. */
CloseListener() {
this.enabled = true;
}
/** Enables or disables the close listened. */
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public void actionPerformed(ActionEvent e) {
if (this.enabled) {
getOptionPane().setValue(e.getSource());
getOptionPane().setVisible(false);
}
}
private boolean enabled;
}
/**
* Document listener that enables or disables the OK button, using
* {@link #setReplaceEnabled()}
*/
private class OverlapListener implements DocumentListener {
/**
* Empty constructor with the right visibility.
*/
OverlapListener() {
// empty
}
@Override
public void changedUpdate(DocumentEvent e) {
testRenaming();
}
@Override
public void insertUpdate(DocumentEvent e) {
testRenaming();
}
@Override
public void removeUpdate(DocumentEvent e) {
testRenaming();
}
/**
* Tests if the content of the name field is a good choice of rule name.
* The OK button is enabled or disabled as a consequence of this.
*/
private void testRenaming() {
setReplaceEnabled();
}
}
}
| 36.014199 | 100 | 0.603886 |
0b72b3b2461a10e7c54256409d7f39b5ae73fa18 | 1,636 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package NguoiDung;
/**
*
* @author Ngan
*/
public class NguoiDung {
private String maNguoidung,tenTaikhoan,tenNguoiDung,matKhau,loaiTaiKhoan;
public NguoiDung() {
}
public NguoiDung(String maNguoidung) {
this.maNguoidung = maNguoidung;
}
public NguoiDung(String maNguoidung, String tenTaikhoan, String tenNguoiDung, String matKhau, String loaiTaiKhoan) {
this.maNguoidung = maNguoidung;
this.tenTaikhoan = tenTaikhoan;
this.tenNguoiDung = tenNguoiDung;
this.matKhau = matKhau;
this.loaiTaiKhoan = loaiTaiKhoan;
}
public String getMaNguoidung() {
return maNguoidung;
}
public String getTenTaikhoan() {
return tenTaikhoan;
}
public String getTenNguoiDung() {
return tenNguoiDung;
}
public String getMatKhau() {
return matKhau;
}
public String getLoaiTaiKhoan() {
return loaiTaiKhoan;
}
public void setMaNguoidung(String maNguoidung) {
this.maNguoidung = maNguoidung;
}
public void setTenTaikhoan(String tenTaikhoan) {
this.tenTaikhoan = tenTaikhoan;
}
public void setTenNguoiDung(String tenNguoiDung) {
this.tenNguoiDung = tenNguoiDung;
}
public void setMatKhau(String matKhau) {
this.matKhau = matKhau;
}
public void setLoaiTaiKhoan(String loaiTaiKhoan) {
this.loaiTaiKhoan = loaiTaiKhoan;
}
}
| 23.371429 | 120 | 0.662592 |
19e503414b566d8bbdf18eb7daff9077d20ac59e | 2,615 | package ticket;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class OutputClass {
DecimalFormat df = new DecimalFormat ( "###,###,###,###,###" );
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(ConstantValue.Today_Save);
SimpleDateFormat sdfd = new SimpleDateFormat(ConstantValue.Today_Data);
// 티켓 금액 출력
public void printPrice(int ticketPrice) {
System.out.println("총 가격은 " + ticketPrice + "원 입니다.");
System.out.println("감사합니다.\n");
}
// 티켓 발권 종료 출력
public void printResult(int num, String[][] totalData) {
System.out.println("티켓 발권을 종료합니다. 감사합니다.\n");
System.out.println("=============== 에버랜드 ===============");
int totalsum = 0;
for(int i = 0; i < num; i++) {
System.out.printf("%3s %3s X %s %8s원 *%s\n", totalData[i][0], totalData[i][1],
totalData[i][2], df.format(Integer.parseInt(totalData[i][3])), totalData[i][4]);
}
for(int k = 0; k < num; k++) {
totalsum += Integer.parseInt(totalData[k][3]);
}
System.out.println("\n입장료 총액은 " + df.format(totalsum) + "원 입니다.");
System.out.println("========================================\n");
}
// 에러 메세지 출력
public void errorMessage() {
System.out.println("다시 입력해주세요.");
}
// txt 파일의 1행 출력
public void startFile() throws IOException {
FileWriter fw = new FileWriter(ConstantValue.PATH, true);
String manual = "날짜,권종,연령,수량,가격,우대사항\n";
fw.write(manual);
fw.close();
}
// CSV 형태의 파일 생성
public void writeFile(String[] data) throws IOException {
FileWriter fw = new FileWriter(ConstantValue.PATH, true);
String text = sdf.format(cal.getTime()) + ",";
for (int i = 0; i < 5; i++) {
if (i <= 3) {
text += data[i] + ",";
} else
text += data[i];
}
String text1 = text + "\n";
fw.write(text1);
fw.close();
}
// mySQL 데이터베이스에 삽입
public void database(String data[]) throws ClassNotFoundException, SQLException {
System.out.println(data[0]);
Class.forName(ConstantValue.Java_Path);
Connection conn = DriverManager.getConnection(ConstantValue.Driver_Path);
Statement stmt = conn.createStatement();
String text = "INSERT INTO `ticket` (`Date`, `Type`, `Age`, `Count`, `Price`, `Discount`) VALUES ('" + sdfd.format(cal.getTime()) + "', '"
+ data[0] + "', '" + data[1] + "', '" + data[2] + "', '" + data[3] + "', '" + data[4] + "');";
stmt.execute(text);
stmt.close();
conn.close();
}
} | 31.890244 | 140 | 0.627533 |
be338b3af4fa6d0512f712d7a1985c8d16234547 | 9,920 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_package
DECL|package|org.jabref.logic.util.io
package|package
name|org
operator|.
name|jabref
operator|.
name|logic
operator|.
name|util
operator|.
name|io
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|StringWriter
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|AbstractList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Collections
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Optional
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|RandomAccess
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|transform
operator|.
name|OutputKeys
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|transform
operator|.
name|Transformer
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|transform
operator|.
name|TransformerException
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|transform
operator|.
name|TransformerFactory
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|transform
operator|.
name|dom
operator|.
name|DOMSource
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|transform
operator|.
name|stream
operator|.
name|StreamResult
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_import
import|import
name|org
operator|.
name|w3c
operator|.
name|dom
operator|.
name|Document
import|;
end_import
begin_import
import|import
name|org
operator|.
name|w3c
operator|.
name|dom
operator|.
name|Element
import|;
end_import
begin_import
import|import
name|org
operator|.
name|w3c
operator|.
name|dom
operator|.
name|NamedNodeMap
import|;
end_import
begin_import
import|import
name|org
operator|.
name|w3c
operator|.
name|dom
operator|.
name|Node
import|;
end_import
begin_import
import|import
name|org
operator|.
name|w3c
operator|.
name|dom
operator|.
name|NodeList
import|;
end_import
begin_comment
comment|/** * Currently used for debugging only */
end_comment
begin_class
DECL|class|XMLUtil
specifier|public
class|class
name|XMLUtil
block|{
DECL|field|LOGGER
specifier|private
specifier|static
specifier|final
name|Logger
name|LOGGER
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|XMLUtil
operator|.
name|class
argument_list|)
decl_stmt|;
DECL|method|XMLUtil ()
specifier|private
name|XMLUtil
parameter_list|()
block|{ }
comment|/** * Prints out the document to standard out. Used to generate files for test cases. */
DECL|method|printDocument (Document doc)
specifier|public
specifier|static
name|void
name|printDocument
parameter_list|(
name|Document
name|doc
parameter_list|)
block|{
try|try
block|{
name|DOMSource
name|domSource
init|=
operator|new
name|DOMSource
argument_list|(
name|doc
argument_list|)
decl_stmt|;
name|StringWriter
name|writer
init|=
operator|new
name|StringWriter
argument_list|()
decl_stmt|;
name|StreamResult
name|result
init|=
operator|new
name|StreamResult
argument_list|(
name|writer
argument_list|)
decl_stmt|;
name|TransformerFactory
name|tf
init|=
name|TransformerFactory
operator|.
name|newInstance
argument_list|()
decl_stmt|;
name|Transformer
name|transformer
init|=
name|tf
operator|.
name|newTransformer
argument_list|()
decl_stmt|;
name|transformer
operator|.
name|setOutputProperty
argument_list|(
name|OutputKeys
operator|.
name|INDENT
argument_list|,
literal|"yes"
argument_list|)
expr_stmt|;
name|transformer
operator|.
name|transform
argument_list|(
name|domSource
argument_list|,
name|result
argument_list|)
expr_stmt|;
name|System
operator|.
name|out
operator|.
name|println
argument_list|(
name|writer
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|TransformerException
name|ex
parameter_list|)
block|{
name|LOGGER
operator|.
name|error
argument_list|(
literal|""
argument_list|,
name|ex
argument_list|)
expr_stmt|;
block|}
block|}
DECL|method|asList (NodeList n)
specifier|public
specifier|static
name|List
argument_list|<
name|Node
argument_list|>
name|asList
parameter_list|(
name|NodeList
name|n
parameter_list|)
block|{
return|return
name|n
operator|.
name|getLength
argument_list|()
operator|==
literal|0
condition|?
name|Collections
operator|.
name|emptyList
argument_list|()
else|:
operator|new
name|NodeListWrapper
argument_list|(
name|n
argument_list|)
return|;
block|}
comment|/** * Gets the content of a subnode. * For example, *<item> *<nodeName>content</nodeName> *</item> */
DECL|method|getNodeContent (Node item, String nodeName)
specifier|public
specifier|static
name|Optional
argument_list|<
name|String
argument_list|>
name|getNodeContent
parameter_list|(
name|Node
name|item
parameter_list|,
name|String
name|nodeName
parameter_list|)
block|{
if|if
condition|(
name|item
operator|.
name|getNodeType
argument_list|()
operator|!=
name|Node
operator|.
name|ELEMENT_NODE
condition|)
block|{
return|return
name|Optional
operator|.
name|empty
argument_list|()
return|;
block|}
name|NodeList
name|metadata
init|=
operator|(
operator|(
name|Element
operator|)
name|item
operator|)
operator|.
name|getElementsByTagName
argument_list|(
name|nodeName
argument_list|)
decl_stmt|;
if|if
condition|(
name|metadata
operator|.
name|getLength
argument_list|()
operator|==
literal|1
condition|)
block|{
return|return
name|Optional
operator|.
name|ofNullable
argument_list|(
name|metadata
operator|.
name|item
argument_list|(
literal|0
argument_list|)
operator|.
name|getTextContent
argument_list|()
argument_list|)
return|;
block|}
else|else
block|{
return|return
name|Optional
operator|.
name|empty
argument_list|()
return|;
block|}
block|}
comment|/** * Gets the content of an attribute. * For example, *<item attributeName="content" /> */
DECL|method|getAttributeContent (Node item, String attributeName)
specifier|public
specifier|static
name|Optional
argument_list|<
name|String
argument_list|>
name|getAttributeContent
parameter_list|(
name|Node
name|item
parameter_list|,
name|String
name|attributeName
parameter_list|)
block|{
name|NamedNodeMap
name|attributes
init|=
name|item
operator|.
name|getAttributes
argument_list|()
decl_stmt|;
return|return
name|Optional
operator|.
name|ofNullable
argument_list|(
name|attributes
operator|.
name|getNamedItem
argument_list|(
name|attributeName
argument_list|)
argument_list|)
operator|.
name|map
argument_list|(
name|Node
operator|::
name|getTextContent
argument_list|)
return|;
block|}
comment|/** * Gets a list of subnodes with the specified tag name. * For example, *<item> *<node>first hit</node> *<node>second hit</node> *</item> */
DECL|method|getNodesByName (Node item, String nodeName)
specifier|public
specifier|static
name|List
argument_list|<
name|Node
argument_list|>
name|getNodesByName
parameter_list|(
name|Node
name|item
parameter_list|,
name|String
name|nodeName
parameter_list|)
block|{
if|if
condition|(
name|item
operator|.
name|getNodeType
argument_list|()
operator|!=
name|Node
operator|.
name|ELEMENT_NODE
condition|)
block|{
return|return
name|Collections
operator|.
name|emptyList
argument_list|()
return|;
block|}
name|NodeList
name|nodes
init|=
operator|(
operator|(
name|Element
operator|)
name|item
operator|)
operator|.
name|getElementsByTagName
argument_list|(
name|nodeName
argument_list|)
decl_stmt|;
return|return
name|asList
argument_list|(
name|nodes
argument_list|)
return|;
block|}
comment|/** * Gets a the first subnode with the specified tag name. * For example, *<item> *<node>hit</node> *<node>second hit, but not returned</node> *</item> */
DECL|method|getNode (Node item, String nodeName)
specifier|public
specifier|static
name|Optional
argument_list|<
name|Node
argument_list|>
name|getNode
parameter_list|(
name|Node
name|item
parameter_list|,
name|String
name|nodeName
parameter_list|)
block|{
return|return
name|getNodesByName
argument_list|(
name|item
argument_list|,
name|nodeName
argument_list|)
operator|.
name|stream
argument_list|()
operator|.
name|findFirst
argument_list|()
return|;
block|}
comment|// Wrapper to make NodeList iterable,
comment|// taken from<a href="http://stackoverflow.com/questions/19589231/can-i-iterate-through-a-nodelist-using-for-each-in-java">StackOverflow Answer</a>.
DECL|class|NodeListWrapper
specifier|private
specifier|static
specifier|final
class|class
name|NodeListWrapper
extends|extends
name|AbstractList
argument_list|<
name|Node
argument_list|>
implements|implements
name|RandomAccess
block|{
DECL|field|list
specifier|private
specifier|final
name|NodeList
name|list
decl_stmt|;
DECL|method|NodeListWrapper (NodeList list)
name|NodeListWrapper
parameter_list|(
name|NodeList
name|list
parameter_list|)
block|{
name|this
operator|.
name|list
operator|=
name|list
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|get (int index)
specifier|public
name|Node
name|get
parameter_list|(
name|int
name|index
parameter_list|)
block|{
return|return
name|list
operator|.
name|item
argument_list|(
name|index
argument_list|)
return|;
block|}
annotation|@
name|Override
DECL|method|size ()
specifier|public
name|int
name|size
parameter_list|()
block|{
return|return
name|list
operator|.
name|getLength
argument_list|()
return|;
block|}
block|}
block|}
end_class
end_unit
| 14.191702 | 198 | 0.787298 |
78d0b4eda12c7abd34596cada2c7a2769a369319 | 4,954 | /*
* Copyright 2018 VetsEZ Inc, Sagebits 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.
*/
package sh.isaac.api.convert.differ;
import java.io.File;
import java.util.UUID;
import org.jvnet.hk2.annotations.Contract;
import sh.isaac.api.LookupService;
import sh.isaac.api.Status;
import sh.isaac.api.task.TimedTaskWithProgressTracker;
/**
* An abstract base class to allow useage of this API into the mojo projects, and to not break isaac
* when the actual implementation of the diff tooling isn't included on the classpath.
*
* @author <a href="mailto:[email protected]">Dan Armbrust</a>
*/
@Contract
public abstract class IBDFDiffTool extends TimedTaskWithProgressTracker<Void>
{
public static IBDFDiffTool getInstance(File outputDirectory, File initialStateIBDF, File newStateIBDF, UUID author, long time, boolean ignoreTimeInCompare,
boolean ignoreSiblingModules, boolean generateRetiresForMissingModuleMetadata) throws IllegalStateException
{
IBDFDiffTool idt = LookupService.get().getService(IBDFDiffTool.class);
if (idt == null)
{
throw new IllegalStateException("No implementation of an IBDFDiffTool is available on the classpath");
}
else
{
idt.init(outputDirectory, initialStateIBDF, newStateIBDF, author, time, ignoreTimeInCompare, ignoreSiblingModules, generateRetiresForMissingModuleMetadata);
return idt;
}
}
/**
* @param outputDirectory - The folder where to write the resulting IBDF diff file (and any other debug files)
* @param initialStateIBDF - The starting point IBDF file to examine
* @param newStateIBDF - The new state IBDF file to examine
* @param author - The author to use for any component retirements
* @param time - The time to use for any component retirements
* @param ignoreTimeInCompare - in certain cases, the source content doesn't provide a time, so the IBDF converter invents a time.
* In these cases, we don't want to compare on time. This is only allowed when the incoming file only has one version per chronology.
* Also, metadata is usually generated with the terminology change time, which is usually different on each import.
* @param ignoreSiblingModules - When processing version 8 of something, against version 7, typically, the module is specified
* as a version-specific module - 7 or 8. But both 7 and 8 will share an unversioned 'parent' module. If true, we will ignore
* module differences, as long as the parent module of each module is the same. If false, the module must be identical.
* @param generateRetiresForMissingModuleMetadata - if true, we treat the version specific module concept as if it were any other concept,
* and generate retirements for it, if it isn't present in the new IBDF file (which it usually wouldn't be). If false, we won't
* generate retire diffs for any sibling module concepts, or their attached semantics.
* TODO when alias commits are better supported, perhaps we also produce alias's to put the content on both versioned modules...
*/
public abstract void init(File outputDirectory, File initialStateIBDF, File newStateIBDF, UUID author, long time, boolean ignoreTimeInCompare,
boolean ignoreSiblingModules, boolean generateRetiresForMissingModuleMetadata);
/**
* @return The count of new chronology objects that were found while running the diff (and will be present in the output diff file)
*/
public abstract long getAddedChronologies();
/**
* @return The count of chronology objects that were present in the starting IBDF file, but not present in the new state file.
*/
public abstract long getRemovedChronologies();
/**
* @return The count of {@link Status#INACTIVE} version objects that were created to properly process the {@link #getRemovedChronologies()}
*/
public abstract long getRemovedChronologiesVersionsCreated();
/**
* @return The count of chronologies that had at least one version which differed from an existing version
*/
public abstract long getChangedChronologies();
/**
* @return the total number of changed chronology versions passed into the diff file
*/
public abstract long getChangedChronologyVersions();
/**
* @return the total number of module metadata components that were retained, even though they were not present in the
* new IBDF file
*/
public abstract int getRetainedModuleMetadataComponents();
} | 49.049505 | 159 | 0.756964 |
c95a7b9c8576b732285d0bb67760488878759a8e | 57 |
package Reportes;
public class Reportes {
}
| 8.142857 | 24 | 0.596491 |
c024a6e90cbe7ec8d4892544486572069fe81c32 | 4,990 | package conflux.dex;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.TimeZone;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import conflux.dex.blockchain.CfxBuilder;
import conflux.dex.blockchain.crypto.Domain;
import conflux.dex.common.BusinessException;
import conflux.dex.common.SignatureValidator;
import conflux.dex.common.Validators;
import conflux.dex.common.channel.Channel;
import conflux.dex.config.ConfigRefresh;
import conflux.dex.config.ConfigService;
import conflux.dex.controller.metric.MetricsServlet;
import conflux.dex.dao.DexDao;
import conflux.dex.worker.ticker.DefaultTickGranularity;
import conflux.web3j.Cfx;
import conflux.web3j.types.RawTransaction;
@SpringBootApplication
@EnableScheduling
public class Application {
private static String lockFilename = ".dex.lock";
private static Logger logger = LoggerFactory.getLogger(Application.class);
@Autowired
private ApplicationContext context;
@Value("${repository.inmemory:false}")
private boolean inMemoryRepository;
@Autowired
private ConfigService configService;
@Value("${system.timezone.id}")
private String timezoneId;
@Value("${user.signature.ignore:false}")
private boolean signatureIgnored;
@Value("${user.signature.disabled:false}")
private boolean signatureDisabled;
private static final String CFX_BEAN_NAME = "cfxBean";
@Bean
@Primary
public DexDao getDao() {
if (this.inMemoryRepository) {
return DexDao.newInMemory();
}
return DexDao.newSpringJDBC(this.context);
}
@Bean
public Channel<Object> getObjectChannel() {
return Channel.create();
}
@Bean(destroyMethod = "shutdownNow")
@Primary
public ExecutorService commonThreadPool() {
return Executors.newCachedThreadPool();
}
@Bean(destroyMethod = "close", name = CFX_BEAN_NAME)
@ConfigRefresh
public Cfx cfx() {
String cfxUrl = configService.cfxUrl;
int cfxRetry = configService.cfxRetry;
long cfxIntervalMillis = configService.cfxIntervalMillis;
logger.info("Create CFX, url = {}, retry = {}, intervalMillis = {}",
cfxUrl, cfxRetry, cfxIntervalMillis);
Cfx cfx = new CfxBuilder(cfxUrl)
.withRetry(cfxRetry, cfxIntervalMillis)
.withCallTimeout(configService.cfxCallTimeoutMillis)
.build();
configService.hook(CFX_BEAN_NAME, "cfxUrl", "cfxRetry", "cfxIntervalMillis");
BigInteger chainId = cfx.getStatus().sendAndGet().getChainId();
Domain.defaultChainId = chainId.longValueExact();
RawTransaction.setDefaultChainId(chainId);
return cfx;
}
@Bean
public TimeZone getSystemTimeZone() {
TimeZone timeZone = TimeZone.getTimeZone(this.timezoneId);
if (timeZone.getID().equals("GMT")) {
throw BusinessException.internalError("invalid timezone configured");
}
DefaultTickGranularity.zoneId = timeZone.toZoneId();
return timeZone;
}
@Bean
public SignatureValidator getSignatureValidator() {
if (this.signatureIgnored) {
SignatureValidator.DEFAULT.setIgnored(true);
}
if (this.signatureDisabled) {
SignatureValidator.DEFAULT.setDisabled(true);
}
return SignatureValidator.DEFAULT;
}
// enable WebSocket
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
@Bean
public ServletRegistrationBean<MetricsServlet> registerMetricsServlet() {
return new ServletRegistrationBean<MetricsServlet>(new MetricsServlet(), "/system/metrics/*");
}
@Autowired
public void setDefaultTimeDrift(@Value("${user.signature.timestamp.drift.millis:180000}") long millis) {
Validators.defaultTimeDriftMillis = millis;
}
public static void main(String[] args) throws IOException{
Path path = Paths.get(lockFilename);
FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
// Exclusive lock, will be released after JAVA VM destroyed.
// Note that it could prevent overlapping locking but not reading/writing/deletion.
FileLock fileLock = channel.tryLock();
if (fileLock == null) {
logger.error("Can not acquire lock.");
return;
}
SpringApplication.run(Application.class, args);
}
}
| 30.242424 | 105 | 0.782365 |
d525f1c106f54d56b70eb4c4915af919920e7c81 | 5,747 | /*
* Copyright 2006 The National Library of New Zealand
*
* 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.webcurator.domain.model.core;
import java.util.Date;
import java.lang.Comparable;
import org.webcurator.domain.model.auth.User;
/**
* An audited note attached to an object.
* @author nwaight
* @hibernate.class table="ANNOTATIONS" lazy="false"
* @hibernate.query name="org.webcurator.domain.model.core.Annotation.getNotesForObject" query="from org.webcurator.domain.model.core.Annotation an where an.objectType = :type and an.objectOid = :oid"
*/
public class Annotation implements Comparable {
/** The name of the get annotations for object query. */
public static final String QRY_GET_NOTES = "org.webcurator.domain.model.core.Annotation.getNotesForObject";
/** name of the object type query parameter. */
public static final String PARAM_TYPE = "type";
/** name of the object oid query parameter. */
public static final String PARAM_OID = "oid";
/** the primary key for the annotation. */
private Long oid;
/** The date for the annotation was created. */
private Date date;
/** the annotation text. */
private String note;
/** the user that added the annotation. */
private User user;
/** the type of the annotations parent object. */
private String objectType;
/** the oid of the annotations parent object. */
private Long objectOid;
/** Is this annotation alertable */
private boolean alertable;
/**
* No-arg constructor.
*/
public Annotation() {
}
/**
* Create a new annotation.
* @param date The date/time of the annotation.
* @param note The message string.
*/
public Annotation(Date date, String note) {
this.date = date;
this.note = note;
}
/**
* Create a new annotation.
* @param aDate The date/time of the annotaiton.
* @param aNote The message string.
* @param aUser The user that created the annotation.
* @param aObjectOid The OID of the associated object.
* @param aObjectType
* @param alertable
*/
public Annotation(Date aDate, String aNote, User aUser, Long aObjectOid, String aObjectType, boolean alertable) {
this.date = aDate;
this.note = aNote;
this.user = aUser;
this.objectOid = aObjectOid;
this.objectType = aObjectType;
this.alertable = alertable;
}
/**
* @return the date the annotation was created.
* @hibernate.property column="AN_DATE" not-null="true" type="timestamp"
*/
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
/**
*
* @hibernate.property column="AN_NOTE" not-null="true" length="1000"
*/
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
/**
* @return the user
* @hibernate.many-to-one not-null="true" class="org.webcurator.domain.model.auth.User" column="AN_USER_OID" foreign-key="FK_NOTE_USER_OID"
*/
public User getUser() {
return user;
}
/**
* @param user the user to set
*/
public void setUser(User user) {
this.user = user;
}
/**
* @return the objectOid
* @hibernate.property column="AN_OBJ_OID" not-null="true"
*/
public Long getObjectOid() {
return objectOid;
}
/**
* @param objectOid the objectOid to set
*/
public void setObjectOid(Long objectOid) {
this.objectOid = objectOid;
}
/**
* @return the objectType
* @hibernate.property column="AN_OBJ_TYPE" not-null="true" length="500"
*/
public String getObjectType() {
return objectType;
}
/**
* Set the object type of the annotation. This should be set to the
* classname returned by <code>ClassName.class.getName()</code>.
* @param objectType the objectType to set
*/
public void setObjectType(String objectType) {
this.objectType = objectType;
}
/**
* Returns true if this annotation is alertable.
* @return true if alertable; otherwise false.
* @hibernate.property column="AN_ALERTABLE"
*/
public boolean isAlertable() {
return alertable;
}
/**
* Sets whether this is annotation is alertable.
* @param alertable true to make this the annotation alertable; otherwise false.
*/
public void setAlertable(boolean alertable) {
this.alertable = alertable;
}
/**
* Retrieve the OID of the Annotation.
* @return the oid
* @hibernate.id column="AN_OID" generator-class="org.hibernate.id.MultipleHiLoPerTableGenerator"
* @hibernate.generator-param name="table" value="ID_GENERATOR"
* @hibernate.generator-param name="primary_key_column" value="IG_TYPE"
* @hibernate.generator-param name="value_column" value="IG_VALUE"
* @hibernate.generator-param name="primary_key_value" value="Annotation"
*/
public Long getOid() {
return oid;
}
/**
* Set the oid of the annotations.
* @param oid the oid to set
*/
public void setOid(Long oid) {
this.oid = oid;
}
public int compareTo(Object other)
{
if(other != null)
{
if(other instanceof Annotation)
{
//sort newest first
return ((Annotation)other).date.compareTo(this.date);
}
else {
throw new java.lang.IllegalArgumentException("Invalid comparison with type: "+other.getClass().getName());
}
}
else
{
throw new java.lang.NullPointerException();
}
}
}
| 26.730233 | 200 | 0.695841 |
7001fd6c38062c55eda8561a6b1bea7ee2819390 | 16,952 | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.indexing.v3;
/**
* Service definition for Indexing (v3).
*
* <p>
* Notifies Google when your web pages change.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://developers.google.com/search/apis/indexing-api/" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link IndexingRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class Indexing extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15,
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.15 of google-api-client to run version " +
"1.26.0 of the Indexing API library.", com.google.api.client.googleapis.GoogleUtils.VERSION);
}
/**
* The default encoded root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_ROOT_URL = "https://indexing.googleapis.com/";
/**
* The default encoded service path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_SERVICE_PATH = "";
/**
* The default encoded batch path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.23
*/
public static final String DEFAULT_BATCH_PATH = "batch";
/**
* The default encoded base URL of the service. This is determined when the library is generated
* and normally should not be changed.
*/
public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH;
/**
* Constructor.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Indexing(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
this(new Builder(transport, jsonFactory, httpRequestInitializer));
}
/**
* @param builder builder
*/
Indexing(Builder builder) {
super(builder);
}
@Override
protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException {
super.initialize(httpClientRequest);
}
/**
* An accessor for creating requests from the UrlNotifications collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Indexing indexing = new Indexing(...);}
* {@code Indexing.UrlNotifications.List request = indexing.urlNotifications().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public UrlNotifications urlNotifications() {
return new UrlNotifications();
}
/**
* The "urlNotifications" collection of methods.
*/
public class UrlNotifications {
/**
* Gets metadata about a Web Document. This method can _only_ be used to query URLs that were
* previously seen in successful Indexing API notifications. Includes the latest `UrlNotification`
* received via this API.
*
* Create a request for the method "urlNotifications.getMetadata".
*
* This request holds the parameters needed by the indexing server. After setting any optional
* parameters, call the {@link GetMetadata#execute()} method to invoke the remote operation.
*
* @return the request
*/
public GetMetadata getMetadata() throws java.io.IOException {
GetMetadata result = new GetMetadata();
initialize(result);
return result;
}
public class GetMetadata extends IndexingRequest<com.google.api.services.indexing.v3.model.UrlNotificationMetadata> {
private static final String REST_PATH = "v3/urlNotifications/metadata";
/**
* Gets metadata about a Web Document. This method can _only_ be used to query URLs that were
* previously seen in successful Indexing API notifications. Includes the latest `UrlNotification`
* received via this API.
*
* Create a request for the method "urlNotifications.getMetadata".
*
* This request holds the parameters needed by the the indexing server. After setting any
* optional parameters, call the {@link GetMetadata#execute()} method to invoke the remote
* operation. <p> {@link
* GetMetadata#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @since 1.13
*/
protected GetMetadata() {
super(Indexing.this, "GET", REST_PATH, null, com.google.api.services.indexing.v3.model.UrlNotificationMetadata.class);
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public GetMetadata set$Xgafv(java.lang.String $Xgafv) {
return (GetMetadata) super.set$Xgafv($Xgafv);
}
@Override
public GetMetadata setAccessToken(java.lang.String accessToken) {
return (GetMetadata) super.setAccessToken(accessToken);
}
@Override
public GetMetadata setAlt(java.lang.String alt) {
return (GetMetadata) super.setAlt(alt);
}
@Override
public GetMetadata setCallback(java.lang.String callback) {
return (GetMetadata) super.setCallback(callback);
}
@Override
public GetMetadata setFields(java.lang.String fields) {
return (GetMetadata) super.setFields(fields);
}
@Override
public GetMetadata setKey(java.lang.String key) {
return (GetMetadata) super.setKey(key);
}
@Override
public GetMetadata setOauthToken(java.lang.String oauthToken) {
return (GetMetadata) super.setOauthToken(oauthToken);
}
@Override
public GetMetadata setPrettyPrint(java.lang.Boolean prettyPrint) {
return (GetMetadata) super.setPrettyPrint(prettyPrint);
}
@Override
public GetMetadata setQuotaUser(java.lang.String quotaUser) {
return (GetMetadata) super.setQuotaUser(quotaUser);
}
@Override
public GetMetadata setUploadType(java.lang.String uploadType) {
return (GetMetadata) super.setUploadType(uploadType);
}
@Override
public GetMetadata setUploadProtocol(java.lang.String uploadProtocol) {
return (GetMetadata) super.setUploadProtocol(uploadProtocol);
}
/** URL that is being queried. */
@com.google.api.client.util.Key
private java.lang.String url;
/** URL that is being queried.
*/
public java.lang.String getUrl() {
return url;
}
/** URL that is being queried. */
public GetMetadata setUrl(java.lang.String url) {
this.url = url;
return this;
}
@Override
public GetMetadata set(String parameterName, Object value) {
return (GetMetadata) super.set(parameterName, value);
}
}
/**
* Notifies that a URL has been updated or deleted.
*
* Create a request for the method "urlNotifications.publish".
*
* This request holds the parameters needed by the indexing server. After setting any optional
* parameters, call the {@link Publish#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.indexing.v3.model.UrlNotification}
* @return the request
*/
public Publish publish(com.google.api.services.indexing.v3.model.UrlNotification content) throws java.io.IOException {
Publish result = new Publish(content);
initialize(result);
return result;
}
public class Publish extends IndexingRequest<com.google.api.services.indexing.v3.model.PublishUrlNotificationResponse> {
private static final String REST_PATH = "v3/urlNotifications:publish";
/**
* Notifies that a URL has been updated or deleted.
*
* Create a request for the method "urlNotifications.publish".
*
* This request holds the parameters needed by the the indexing server. After setting any
* optional parameters, call the {@link Publish#execute()} method to invoke the remote operation.
* <p> {@link
* Publish#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.indexing.v3.model.UrlNotification}
* @since 1.13
*/
protected Publish(com.google.api.services.indexing.v3.model.UrlNotification content) {
super(Indexing.this, "POST", REST_PATH, content, com.google.api.services.indexing.v3.model.PublishUrlNotificationResponse.class);
}
@Override
public Publish set$Xgafv(java.lang.String $Xgafv) {
return (Publish) super.set$Xgafv($Xgafv);
}
@Override
public Publish setAccessToken(java.lang.String accessToken) {
return (Publish) super.setAccessToken(accessToken);
}
@Override
public Publish setAlt(java.lang.String alt) {
return (Publish) super.setAlt(alt);
}
@Override
public Publish setCallback(java.lang.String callback) {
return (Publish) super.setCallback(callback);
}
@Override
public Publish setFields(java.lang.String fields) {
return (Publish) super.setFields(fields);
}
@Override
public Publish setKey(java.lang.String key) {
return (Publish) super.setKey(key);
}
@Override
public Publish setOauthToken(java.lang.String oauthToken) {
return (Publish) super.setOauthToken(oauthToken);
}
@Override
public Publish setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Publish) super.setPrettyPrint(prettyPrint);
}
@Override
public Publish setQuotaUser(java.lang.String quotaUser) {
return (Publish) super.setQuotaUser(quotaUser);
}
@Override
public Publish setUploadType(java.lang.String uploadType) {
return (Publish) super.setUploadType(uploadType);
}
@Override
public Publish setUploadProtocol(java.lang.String uploadProtocol) {
return (Publish) super.setUploadProtocol(uploadProtocol);
}
@Override
public Publish set(String parameterName, Object value) {
return (Publish) super.set(parameterName, value);
}
}
}
/**
* Builder for {@link Indexing}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
DEFAULT_ROOT_URL,
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link Indexing}. */
@Override
public Indexing build() {
return new Indexing(this);
}
@Override
public Builder setRootUrl(String rootUrl) {
return (Builder) super.setRootUrl(rootUrl);
}
@Override
public Builder setServicePath(String servicePath) {
return (Builder) super.setServicePath(servicePath);
}
@Override
public Builder setBatchPath(String batchPath) {
return (Builder) super.setBatchPath(batchPath);
}
@Override
public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
return (Builder) super.setHttpRequestInitializer(httpRequestInitializer);
}
@Override
public Builder setApplicationName(String applicationName) {
return (Builder) super.setApplicationName(applicationName);
}
@Override
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
return (Builder) super.setSuppressPatternChecks(suppressPatternChecks);
}
@Override
public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) {
return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks);
}
@Override
public Builder setSuppressAllChecks(boolean suppressAllChecks) {
return (Builder) super.setSuppressAllChecks(suppressAllChecks);
}
/**
* Set the {@link IndexingRequestInitializer}.
*
* @since 1.12
*/
public Builder setIndexingRequestInitializer(
IndexingRequestInitializer indexingRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(indexingRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
| 35.170124 | 148 | 0.679094 |
79bc25d1758b8710f79f09bcedb7d77f34614074 | 1,817 | /*
* Copyright 2019 Treu Techologies
*
* 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 com.treutec.kaypher.parser.tree;
import static org.hamcrest.Matchers.is;
import org.hamcrest.FeatureMatcher;
import org.hamcrest.Matcher;
public final class JoinMatchers {
private JoinMatchers() {
}
public static Matcher<Join> hasLeft(final Relation relationship) {
return hasLeft(is(relationship));
}
public static Matcher<Join> hasLeft(final Matcher<? super Relation> relationship) {
return new FeatureMatcher<Join, Relation>
(relationship, "left relationship", "left") {
@Override
protected Relation featureValueOf(final Join actual) {
return actual.getLeft();
}
};
}
public static Matcher<Join> hasRight(final Relation relationship) {
return hasRight(is(relationship));
}
public static Matcher<Join> hasRight(final Matcher<? super Relation> relationship) {
return new FeatureMatcher<Join, Relation>
(relationship, "right relationship", "right") {
@Override
protected Relation featureValueOf(final Join actual) {
return actual.getRight();
}
};
}
}
| 31.327586 | 86 | 0.718767 |
11a9773bce3b974730424d275f67f2b14cb53e92 | 81,512 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.lint.checks.infrastructure;
import static com.android.SdkConstants.ANDROID_URI;
import static com.android.SdkConstants.ATTR_ID;
import static com.android.SdkConstants.DOT_KT;
import static com.android.SdkConstants.FD_GEN_SOURCES;
import static com.android.SdkConstants.FN_ANDROID_MANIFEST_XML;
import static com.android.SdkConstants.FN_ANNOTATIONS_JAR;
import static com.android.SdkConstants.FN_ANNOTATIONS_ZIP;
import static com.android.SdkConstants.NEW_ID_PREFIX;
import static com.android.ide.common.rendering.api.ResourceNamespace.RES_AUTO;
import static com.android.tools.lint.checks.infrastructure.KotlinClasspathKt.findKotlinStdlibPath;
import static com.android.tools.lint.checks.infrastructure.LintTestUtils.checkTransitiveComparator;
import static java.io.File.separatorChar;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.ide.common.rendering.api.ResourceNamespace;
import com.android.ide.common.resources.MergingException;
import com.android.ide.common.resources.ResourceFile;
import com.android.ide.common.resources.ResourceItem;
import com.android.ide.common.resources.ResourceMerger;
import com.android.ide.common.resources.ResourceMergerItem;
import com.android.ide.common.resources.ResourceRepositories;
import com.android.ide.common.resources.ResourceRepository;
import com.android.ide.common.resources.ResourceSet;
import com.android.ide.common.resources.TestResourceRepository;
import com.android.ide.common.util.PathString;
import com.android.resources.ResourceType;
import com.android.sdklib.IAndroidTarget;
import com.android.support.AndroidxNameUtils;
import com.android.tools.lint.LintCliClient;
import com.android.tools.lint.LintCliFlags;
import com.android.tools.lint.LintCliXmlParser;
import com.android.tools.lint.LintFixPerformer;
import com.android.tools.lint.LintResourceRepository;
import com.android.tools.lint.LintStats;
import com.android.tools.lint.Reporter;
import com.android.tools.lint.TextReporter;
import com.android.tools.lint.XmlFileType;
import com.android.tools.lint.XmlReader;
import com.android.tools.lint.XmlWriter;
import com.android.tools.lint.client.api.CircularDependencyException;
import com.android.tools.lint.client.api.Configuration;
import com.android.tools.lint.client.api.ConfigurationHierarchy;
import com.android.tools.lint.client.api.IssueRegistry;
import com.android.tools.lint.client.api.LintClient;
import com.android.tools.lint.client.api.LintDriver;
import com.android.tools.lint.client.api.LintListener;
import com.android.tools.lint.client.api.LintRequest;
import com.android.tools.lint.client.api.LintXmlConfiguration;
import com.android.tools.lint.client.api.ResourceRepositoryScope;
import com.android.tools.lint.client.api.UastParser;
import com.android.tools.lint.client.api.XmlParser;
import com.android.tools.lint.detector.api.Context;
import com.android.tools.lint.detector.api.Desugaring;
import com.android.tools.lint.detector.api.GradleContext;
import com.android.tools.lint.detector.api.Incident;
import com.android.tools.lint.detector.api.Issue;
import com.android.tools.lint.detector.api.JavaContext;
import com.android.tools.lint.detector.api.Lint;
import com.android.tools.lint.detector.api.LintFix;
import com.android.tools.lint.detector.api.LintModelModuleProject;
import com.android.tools.lint.detector.api.Location;
import com.android.tools.lint.detector.api.Position;
import com.android.tools.lint.detector.api.Project;
import com.android.tools.lint.detector.api.Severity;
import com.android.tools.lint.detector.api.TextFormat;
import com.android.tools.lint.model.LintModelExternalLibrary;
import com.android.tools.lint.model.LintModelLibrary;
import com.android.tools.lint.model.LintModelLintOptions;
import com.android.tools.lint.model.LintModelMavenName;
import com.android.tools.lint.model.LintModelModule;
import com.android.tools.lint.model.LintModelModuleType;
import com.android.tools.lint.model.LintModelSourceProvider;
import com.android.tools.lint.model.LintModelVariant;
import com.android.utils.ILogger;
import com.android.utils.NullLogger;
import com.android.utils.PositionXmlParser;
import com.android.utils.SdkUtils;
import com.android.utils.StdLogger;
import com.android.utils.XmlUtils;
import com.google.common.base.Charsets;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.intellij.openapi.util.Computable;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.PsiElement;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import kotlin.Pair;
import kotlin.io.FilesKt;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.uast.UFile;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* A {@link LintClient} class for use in lint unit tests.
*
* <p><b>NOTE: This is not a public or final API; if you rely on this be prepared to adjust your
* code for the next tools release.</b>
*/
public class TestLintClient extends LintCliClient {
protected final StringWriter writer = new StringWriter();
protected File incrementalCheck;
/** Managed by the {@link TestLintTask} */
@SuppressWarnings({"NotNullFieldNotInitialized"})
@NonNull
TestLintTask task;
/** Used to test PSI read lock issues. */
private boolean insideReadAction = false;
private TextReporter reporter;
public TestLintClient() {
this(CLIENT_UNIT_TESTS);
}
public TestLintClient(String clientName) {
this(new LintCliFlags(), clientName);
}
public TestLintClient(LintCliFlags flags) {
this(flags, CLIENT_UNIT_TESTS);
}
public TestLintClient(LintCliFlags flags, String clientName) {
super(flags, clientName);
reporter = new TextReporter(this, flags, writer, false);
reporter.setForwardSlashPaths(true); // stable tests
flags.getReporters().add(reporter);
}
@Override
public String getClientDisplayName() {
return "Lint Unit Tests";
}
public void setLintTask(@Nullable TestLintTask task) {
if (task != null && task.optionSetter != null) {
task.optionSetter.set(getFlags());
}
if (task != null) {
reporter.setFormat(task.textFormat);
reporter.setIncludeSecondaryLineContent(task.showSecondaryLintContent);
}
// Client should not be used outside of the check process
//noinspection ConstantConditions
this.task = task;
//noinspection VariableNotUsedInsideIf
if (task != null && !task.allowMissingSdk) {
ensureSdkExists(this);
}
}
static void ensureSdkExists(@NonNull LintClient client) {
File sdkHome = client.getSdkHome();
String message;
if (sdkHome == null) {
message = "No SDK configured. ";
} else if (!sdkHome.isDirectory()) {
message = sdkHome + " is not a directory. ";
} else {
return;
}
message =
"This test requires an Android SDK: "
+ message
+ "\n"
+ "If this test does not really need an SDK, set "
+ "TestLintTask#allowMissingSdk(). Otherwise, make sure an SDK is "
+ "available either by specifically pointing to one via "
+ "TestLintTask#sdkHome(File), or configure $ANDROID_HOME in the "
+ "environment";
fail(message);
}
/**
* Normally having $ANDROID_BUILD_TOP set when running lint is a bad idea (because it enables
* some special support in lint for checking code in AOSP itself.) However, some lint tests
* (particularly custom lint checks) may not care about this.
*/
@SuppressWarnings("MethodMayBeStatic")
protected boolean allowAndroidBuildEnvironment() {
return true;
}
@Nullable
private File findIncrementalProject(@NonNull List<File> files) {
// Multiple projects: assume the project names were included in the incremental
// task names
String incrementalFileName = task.incrementalFileName;
if (incrementalFileName == null) {
if (files.size() == 1) {
assert false : "Need to specify incremental file name if more than one project";
} else {
return files.get(0);
}
}
if (files.size() > 1) {
for (File dir : files) {
File root = dir.getParentFile(); // Allow the project name to be part of the name
File current = new File(root, incrementalFileName.replace('/', separatorChar));
if (current.exists()) {
// Try to match project directory exactly
int index = incrementalFileName.indexOf('/');
if (index != -1) {
File path = new File(root, task.incrementalFileName.substring(0, index));
if (path.exists()) {
return path;
}
}
return dir;
}
}
}
for (File dir : files) {
File current = new File(dir, incrementalFileName.replace('/', separatorChar));
if (current.exists()) {
return dir;
}
}
for (File dir : files) {
File current = new File(dir, "../" + incrementalFileName.replace('/', separatorChar));
if (current.exists()) {
return dir;
}
}
// Just using basename? Search among all files
for (File root : files) {
for (File relative : getFilesRecursively(root)) {
if (relative.getName().equals(incrementalFileName)) {
// Turn the basename into a full relative name
task.incrementalFileName = relative.getPath();
return root;
}
}
}
return null;
}
protected TestResultState checkLint(
@NonNull File rootDir,
@NonNull List<File> files,
@NonNull List<Issue> issues,
@NonNull TestMode mode)
throws Exception {
String incrementalFileName = task.incrementalFileName;
if (incrementalFileName != null) {
boolean found = false;
File dir = findIncrementalProject(files);
if (dir != null) {
// may be reassigned by findIncrementalProject if using just a basename
incrementalFileName = task.incrementalFileName;
File current = new File(dir, incrementalFileName.replace('/', separatorChar));
if (!current.exists()) {
// Specified the project name as part of the name to disambiguate
current =
new File(
dir.getParentFile(),
incrementalFileName.replace('/', separatorChar));
}
if (current.exists()) {
setIncremental(current);
found = true;
}
}
if (!found) {
List<File> allFiles = new ArrayList<>();
for (File file : files) {
allFiles.addAll(getFilesRecursively(file));
}
String all = allFiles.toString();
fail(
"Could not find incremental file "
+ incrementalFileName
+ " in the test project folders; did you mean one of "
+ all);
}
}
if (!allowAndroidBuildEnvironment() && System.getenv("ANDROID_BUILD_TOP") != null) {
fail(
"Don't run the lint tests with $ANDROID_BUILD_TOP set; that enables lint's "
+ "special support for detecting AOSP projects (looking for .class "
+ "files in $ANDROID_HOST_OUT etc), and this confuses lint.");
}
String result =
mode == TestMode.PARTIAL
? analyzeAndReportProvisionally(rootDir, files, issues)
: analyze(rootDir, files, issues);
Throwable firstThrowable = task.runner.getFirstThrowable();
return new TestResultState(this, rootDir, result, getDefiniteIncidents(), firstThrowable);
}
private static List<File> getFilesRecursively(File root) {
List<File> result = new ArrayList<>();
addFilesUnder(result, root, root.getPath());
return result;
}
private static void addFilesUnder(List<File> result, File file, String skipPrefix) {
if (file.isFile()) {
String path = file.getPath();
if (path.startsWith(skipPrefix)) {
int length = skipPrefix.length();
if (path.length() > length && path.charAt(length) == separatorChar) {
length++;
}
path = path.substring(length);
}
result.add(new File(path));
} else if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
Arrays.sort(files, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()));
for (File child : files) {
addFilesUnder(result, child, skipPrefix);
}
}
}
}
@Nullable
@Override
public File getSdkHome() {
if (task.sdkHome != null) {
return task.sdkHome;
}
return super.getSdkHome();
}
@NonNull
@Override
protected Project createProject(@NonNull File dir, @NonNull File referenceDir) {
if (getProjectDirs().contains(dir)) {
throw new CircularDependencyException(
"Circular library dependencies; check your project.properties files carefully");
}
getProjectDirs().add(dir);
ProjectDescription description;
try {
description = task.dirToProjectDescription.get(dir.getCanonicalFile());
} catch (IOException ignore) {
description = task.dirToProjectDescription.get(dir);
}
GradleModelMocker mocker;
try {
mocker = task.projectMocks.get(dir.getCanonicalFile());
} catch (IOException ignore) {
mocker = task.projectMocks.get(dir);
}
LintCliFlags flags = getFlags();
if (mocker != null) {
if (mocker.getPrimary()) {
mocker.syncFlagsTo(flags);
flags.setFatalOnly(task.vital);
String variantName = null;
if (description != null && description.getVariantName() != null) {
variantName = description.getVariantName();
} else if (task.variantName != null) {
variantName = task.variantName;
}
if (variantName != null) {
mocker.setVariantName(variantName);
}
} else if (description != null && description.getVariantName() != null) {
mocker.setVariantName(description.getVariantName());
}
}
if (task.baselineFile != null) {
flags.setBaselineFile(task.baselineFile);
}
if (task.overrideConfigFile != null) {
flags.setOverrideLintConfig(task.overrideConfigFile);
}
if (mocker != null && description != null && (mocker.hasJavaOrJavaLibraryPlugin())) {
description.type(ProjectDescription.Type.JAVA);
}
if (description != null
&& task.reportFrom != null
&& !(task.reportFrom.isUnder(description)
|| description.isUnder(task.reportFrom))) {
if (task.reportFrom != description) {
referenceDir =
ProjectDescription.Companion.getProjectDirectory(
task.reportFrom, referenceDir);
} else {
referenceDir = dir;
}
}
Project project = new TestProject(this, dir, referenceDir, description, mocker);
// Try to use the real lint model project instead, if possible
LintModelVariant buildVariant = project.getBuildVariant();
if (buildVariant != null && !task.useTestProject) {
// Make sure the test folders exist; this prevents the common mistake where you
// add a gradle() test model but leave the source files in the old src/ and res/
// folders instead of the required src/main/java, src/main/res, src/test/java, etc
// locations
if (hasOldDirectoryLayout(dir)) {
fail(
"Warning: This test uses a gradle model mocker but doesn't have a main "
+ "source set (src/main/java); that's suspicious; check that the test "
+ "file is in (for example) src/main/res/ rather than res/.\n"
+ "Alternatively, set useTestProjectImplementation(true) on the "
+ "lint task.");
}
Project oldProject = project;
project = new LintModelModuleProject(this, dir, referenceDir, buildVariant, null);
project.setDirectLibraries(oldProject.getDirectLibraries());
}
registerProject(dir, project);
return project;
}
private static boolean hasOldDirectoryLayout(File dir) {
if (new File(dir, "res").exists()) {
// Should probably be src/main/res/
return true;
}
if (new File(dir, "src").exists()
&& !(new File(dir, "src/main").exists())
&& !(new File(dir, "src/test").exists())) {
return true;
}
File[] srcs = new File(dir, "src/main").listFiles();
if (srcs != null) {
for (File child : srcs) {
String name = child.getName();
if (name.startsWith("lint-")) {
continue;
}
switch (name) {
case FN_ANDROID_MANIFEST_XML:
case "res":
case "java":
case "kotlin":
case "lint.xml":
break;
default:
return true;
}
}
}
return false;
}
@Override
public void storeState(@NonNull Project project) {
super.storeState(project);
// Make sure we don't have any absolute paths in the serialization files, if any,
// as well as checking that all XML files are well-formed while we're at it.
String absProjectPath = project.getDir().getAbsolutePath();
String absTestRootPath = task.tempDir.getPath();
String absHomePrefix = System.getProperty("user.home");
String absProjectCanonicalPath = absProjectPath;
String absTestRootCanonicalPath = absTestRootPath;
try {
absProjectCanonicalPath = project.getDir().getCanonicalPath();
absTestRootCanonicalPath = task.tempDir.getCanonicalPath();
} catch (IOException ignore) {
}
for (XmlFileType type : XmlFileType.values()) {
File serializationFile = getSerializationFile(project, type);
if (serializationFile.exists()) {
String xml = FilesKt.readText(serializationFile, Charsets.UTF_8);
if (type != XmlFileType.RESOURCE_REPOSITORY) {
// Skipping RESOURCE_REPOSITORY because these are not real
// XML files, but we're going to replace these soon so not
// worth going to the trouble of changing the file format
Document document = XmlUtils.parseDocumentSilently(xml, false);
assertNotNull("Not valid XML", document);
}
// Make sure we don't have any absolute paths to the test root or project
// directories or home directories in the XML
if (type.isPersistenceFile() || !getFlags().isFullPath()) {
assertFalse(xml, xml.contains(absProjectPath));
assertFalse(xml, xml.contains(absProjectCanonicalPath));
assertFalse(xml, xml.contains(absTestRootPath));
assertFalse(xml, xml.contains(absTestRootCanonicalPath));
assertFalse(xml, xml.contains(absHomePrefix));
}
}
}
}
@Nullable
@Override
public File getCacheDir(@Nullable String name, boolean create) {
File cacheDir;
//noinspection ConstantConditions
if (task != null && task.tempDir != null) {
cacheDir = new File(task.tempDir, "lint-cache/" + name);
} else {
cacheDir = super.getCacheDir(name, create);
// Separate test caches from user's normal caches
cacheDir = new File(cacheDir, "unit-tests/" + name);
}
if (create) {
//noinspection ResultOfMethodCallIgnored
cacheDir.mkdirs();
}
return cacheDir;
}
@NonNull
@Override
public String getDisplayPath(
@NonNull File file, @Nullable Project project, @NonNull TextFormat format) {
String path = super.getDisplayPath(file, project, format);
return path.replace(separatorChar, '/'); // stable tests
}
@Override
public String getClientRevision() {
return "unittest"; // Hardcode version to keep unit test output stable
}
@SuppressWarnings("StringBufferField")
private final StringBuilder output = new StringBuilder();
private interface LintTestAnalysis {
void analyze(LintDriver driver);
}
public String analyze(File rootDir, List<File> files, List<Issue> issues) throws Exception {
return analyze(rootDir, files, issues, LintDriver::analyze);
}
public String analyzeAndReportProvisionally(
@NonNull File rootDir, @NonNull List<File> files, @NonNull List<Issue> issues)
throws Exception {
for (File dir : files) {
// We don't want to share client instances between the analysis of each module
// and the final report generation.
TestLintClient client = task.runner.createClient();
client.incrementalCheck = incrementalCheck;
client.analyze(
rootDir, Collections.singletonList(dir), issues, LintDriver::analyzeOnly);
}
// This isn't expressing it right; I want to be able to say "load the graph from all of
// these" but focus the report on one in particular
return analyze(rootDir, files, issues, LintDriver::mergeOnly);
}
public String analyze(
@NonNull File rootDir,
@NonNull List<File> files,
@NonNull List<Issue> issues,
@NonNull LintTestAnalysis work)
throws Exception {
// We'll sync lint options to flags later when the project is created, but try
// to do it early before the driver is initialized
if (!files.isEmpty()) {
GradleModelMocker mocker = task.projectMocks.get(files.get(0));
if (mocker != null && mocker.getPrimary()) {
mocker.syncFlagsTo(getFlags());
}
}
LintRequest request = createLintRequest(files);
if (task.customScope != null) {
request = request.setScope(task.customScope);
}
if (task.platforms != null) {
request.setPlatform(task.platforms);
}
if (files.size() > 1) {
request.setSrcRoot(rootDir);
}
if (incrementalCheck != null) {
File projectDir = findIncrementalProject(files);
assert projectDir != null;
assertTrue(isProjectDirectory(projectDir));
Project project = createProject(projectDir, projectDir);
project.addFile(incrementalCheck);
List<Project> projects = singletonList(project);
request.setProjects(projects);
project.setReportIssues(true);
}
driver = createDriver(new TestIssueRegistry(issues), request);
if (task.driverConfigurator != null) {
task.driverConfigurator.configure(driver);
}
for (LintListener listener : task.listeners) {
driver.addLintListener(listener);
}
validateIssueIds();
work.analyze(driver);
// Check compare contract
Incident prev = null;
List<Incident> incidents = getDefiniteIncidents();
for (Incident incident : incidents) {
if (prev != null) {
boolean equals = incident.equals(prev);
assertEquals(equals, prev.equals(incident));
int compare = incident.compareTo(prev);
assertEquals(equals, compare == 0);
assertEquals(-compare, prev.compareTo(incident));
}
prev = incident;
}
Collections.sort(incidents);
if (task.reportFrom != null) {
useProjectRelativePaths(task.reportFrom);
} else {
useRootRelativePaths();
}
// Check compare contract and transitivity
Incident prev2 = prev;
prev = null;
for (Incident incident : incidents) {
if (prev != null && prev2 != null) {
assertTrue(incident.compareTo(prev) >= 0);
assertTrue(prev.compareTo(prev2) >= 0);
assertTrue(incident.compareTo(prev2) >= 0);
assertTrue(prev.compareTo(incident) <= 0);
assertTrue(prev2.compareTo(prev) <= 0);
assertTrue(prev2.compareTo(incident) <= 0);
}
prev2 = prev;
prev = incident;
}
String result = writeOutput(incidents);
for (LintListener listener : task.listeners) {
driver.removeLintListener(listener);
}
return result;
}
@NonNull
@Override
protected LintRequest createLintRequest(@NonNull List<? extends File> files) {
TestLintRequest request = new TestLintRequest(this, files);
configureLintRequest(request);
return request;
}
public static class TestLintRequest extends LintRequest {
Project mainProject = null;
public TestLintRequest(@NonNull LintClient client, @NonNull List<? extends File> files) {
super(client, files);
}
@NonNull
@Override
public Project getMainProject(@NonNull Project project) {
if (mainProject != null) {
return mainProject;
}
for (Project main : project.getClient().getKnownProjects()) {
if (main.getType() == LintModelModuleType.APP
&& project.getAllLibraries().contains(project)) {
return main;
}
}
return super.getMainProject(project);
}
}
public String writeOutput(List<Incident> incidents) throws IOException {
LintStats stats = LintStats.Companion.create(getErrorCount(), getWarningCount());
for (Reporter reporter : getFlags().getReporters()) {
reporter.write(stats, incidents);
}
output.append(writer.toString());
if (output.length() == 0) {
output.append("No warnings.");
}
String result = output.toString();
if (result.equals("No issues found.\n")) {
result = "No warnings.";
}
result = cleanup(result);
return result;
}
@NonNull
@Override
protected LintDriver createDriver(
@NonNull IssueRegistry registry, @NonNull LintRequest request) {
LintDriver driver = super.createDriver(registry, request);
driver.setFatalOnlyMode(task.vital);
return driver;
}
@Override
public boolean isProjectDirectory(@NonNull File dir) {
if (task.dirToProjectDescription.containsKey(dir)) {
return true;
}
return super.isProjectDirectory(dir);
}
protected void addCleanupDir(@NonNull File dir) {
cleanupDirs.add(dir);
try {
cleanupDirs.add(dir.getCanonicalFile());
} catch (IOException e) {
fail(e.getLocalizedMessage());
}
cleanupDirs.add(dir.getAbsoluteFile());
}
protected final Set<File> cleanupDirs = Sets.newHashSet();
protected String cleanup(String result) {
List<File> sorted = new ArrayList<>(cleanupDirs);
// Process dirs in order such that we match longest substrings first
sorted.sort(
(file1, file2) -> {
String path1 = file1.getPath();
String path2 = file2.getPath();
int delta = path2.length() - path1.length();
if (delta != 0) {
return delta;
} else {
return path1.compareTo(path2);
}
});
for (File dir : sorted) {
result = task.stripRoot(dir, result);
}
return result;
}
public String getErrors() {
return writer.toString();
}
@NonNull
@Override
public XmlParser getXmlParser() {
//noinspection ConstantConditions
if (task != null && !task.allowCompilationErrors) {
return new LintCliXmlParser(this) {
@Override
public Document parseXml(@NonNull CharSequence xml, @Nullable File file) {
try {
return PositionXmlParser.parse(xml.toString());
} catch (Exception e) {
String message =
e.getCause() != null
? e.getCause().getLocalizedMessage()
: e.getLocalizedMessage();
fail(
message
+ " : Failure processing source "
+ file
+ ".\n"
+ "If you want your test to work with broken XML sources, add "
+ "`allowCompilationErrors()` on the TestLintTask.\n");
return null;
}
}
};
} else {
return super.getXmlParser();
}
}
@NonNull
@Override
public UastParser getUastParser(@Nullable Project project) {
return new LintCliUastParser(project) {
@Override
public boolean prepare(
@NonNull List<? extends JavaContext> contexts,
@Nullable LanguageLevel javaLanguageLevel,
@Nullable LanguageVersionSettings kotlinLanguageLevel) {
boolean ok = super.prepare(contexts, javaLanguageLevel, kotlinLanguageLevel);
if (task.forceSymbolResolutionErrors) {
ok = false;
}
return ok;
}
@Nullable
@Override
public UFile parse(@NonNull JavaContext context) {
UFile file = super.parse(context);
if (!task.allowCompilationErrors) {
ResolveCheckerKt.checkFile(context, file, task);
}
return file;
}
};
}
@Override
public void runReadAction(@NonNull Runnable runnable) {
boolean prev = insideReadAction;
insideReadAction = true;
try {
super.runReadAction(runnable);
} finally {
insideReadAction = prev;
}
}
@Override
public <T> T runReadAction(@NonNull Computable<T> computable) {
boolean prev = insideReadAction;
insideReadAction = true;
try {
return super.runReadAction(computable);
} finally {
insideReadAction = prev;
}
}
@Override
public boolean supportsPartialAnalysis() {
return driver.getMode() != LintDriver.DriverMode.GLOBAL;
}
@Override
protected void mergeIncidents(
@NonNull Project library,
@NonNull Project main,
@NonNull Context mainContext,
@NonNull Map<Project, List<Incident>> definiteMap,
@NonNull Map<Project, List<Incident>> provisionalMap) {
// Some basic validity checks to make sure test projects aren't set up correctly;
// normally AGP manifest merging enforces this
// We have to initialize the manifest because these projects haven't been loaded
// and processed
if (library.getMinSdk() <= 1 && !library.getManifestFiles().isEmpty()) {
String xml = FilesKt.readText(library.getManifestFiles().get(0), Charsets.UTF_8);
Document document = XmlUtils.parseDocumentSilently(xml, true);
if (document != null) {
library.readManifest(document);
}
}
if (main.getMinSdk() <= 1 && !main.getManifestFiles().isEmpty()) {
String xml = FilesKt.readText(main.getManifestFiles().get(0), Charsets.UTF_8);
Document document = XmlUtils.parseDocumentSilently(xml, true);
if (document != null) {
main.readManifest(document);
}
}
int libraryMinSdk = library.getMinSdk() == -1 ? 1 : library.getMinSdk();
int mainMinSdk = main.getMinSdk() == -1 ? 1 : main.getMinSdk();
if (libraryMinSdk > mainMinSdk) {
fail(
"Library project minSdkVersion ("
+ libraryMinSdk
+ ") cannot be higher than consuming project's minSdkVersion ("
+ mainMinSdk
+ ")");
}
ProjectDescription reportFrom = task.reportFrom;
if (reportFrom != null) {
setIncidentProjects(reportFrom, definiteMap);
setIncidentProjects(reportFrom, provisionalMap);
}
super.mergeIncidents(library, main, mainContext, definiteMap, provisionalMap);
}
private void setIncidentProjects(ProjectDescription project, Map<Project, List<Incident>> map) {
for (List<Incident> incidents : map.values()) {
useProjectRelativePaths(project, incidents);
}
}
@Override
public void report(
@NonNull Context context, @NonNull Incident incident, @NonNull TextFormat format) {
Location location = incident.getLocation();
LintFix fix = incident.getFix();
Issue issue = incident.getIssue();
assertNotNull(location);
// Ensure that we're inside a read action if we might need access to PSI.
// This is one heuristic; we could add more assertions elsewhere as needed.
if (context instanceof JavaContext
|| context instanceof GradleContext
|| location.getSource() instanceof PsiElement) {
assertTrue(
"LintClient.report accessing a PSI element should "
+ "always be called inside a runReadAction",
insideReadAction);
}
if (issue == IssueRegistry.LINT_ERROR) {
if (!task.allowSystemErrors) {
return;
}
// We don't care about this error message from lint tests; we don't compile
// test project files
if (incident.getMessage().startsWith("No `.class` files were found in project")) {
return;
}
}
if (task.messageChecker != null
// Don't run this if there's an internal failure instead; this is just going
// to be confusing and we want to reach the final report comparison instead which
// will show the lint error
&& !(!task.allowExceptions
&& issue == IssueRegistry.LINT_ERROR
&& fix instanceof LintFix.DataMap
&& ((LintFix.DataMap) fix).getThrowable(LintDriver.KEY_THROWABLE)
!= null)) {
task.messageChecker.checkReportedError(
context,
incident.getIssue(),
incident.getSeverity(),
incident.getLocation(),
format.convertTo(incident.getMessage(), TextFormat.TEXT),
fix);
}
if (incident.getSeverity() == Severity.FATAL) {
// Treat fatal errors like errors in the golden files.
incident.setSeverity(Severity.ERROR);
}
// For messages into all secondary locations to ensure they get
// specifically included in the text report
if (location.getSecondary() != null) {
Location l = location.getSecondary();
if (l == location) {
fail("Location link cycle");
}
while (l != null) {
if (l.getMessage() == null) {
l.setMessage("<No location-specific message>");
}
if (l == l.getSecondary()) {
fail("Location link cycle");
}
l = l.getSecondary();
}
}
if (!task.allowExceptions) {
Throwable throwable = LintFix.getThrowable(fix, LintDriver.KEY_THROWABLE);
if (throwable != null && task.runner.getFirstThrowable() == null) {
task.runner.setFirstThrowable(throwable);
}
}
incident = checkIncidentSerialization(incident);
if (fix != null) {
checkFix(fix, incident);
}
super.report(context, incident, format);
// Make sure errors are unique! See documentation for #allowDuplicates.
List<Incident> incidents = getDefiniteIncidents();
int incidentCount = incidents.size();
if (incidentCount > 1) {
Incident prev = incidents.get(incidentCount - 2);
if (incident.equals(prev)) {
if (task.allowDuplicates) {
// If we allow duplicates, don't list them multiple times.
incidents.remove(incidentCount - 1);
if (incident.getSeverity().isError()) {
setErrorCount(getErrorCount() - 1);
} else if (incident.getSeverity() == Severity.WARNING) {
// Don't count informational as a warning
setWarningCount(getWarningCount() - 1);
}
} else {
TestMode mode = task.runner.getCurrentTestMode();
String field = mode.getFieldName();
String prologue =
""
+ "java.lang.AssertionError: Incident (message, location) reported more\n"
+ "than once";
if (mode != TestMode.DEFAULT) {
prologue += "in test mode " + field;
}
prologue +=
"; this typically "
+ "means that your detector is incorrectly reaching the same element "
+ "twice (for example, visiting each call of a method and reporting the "
+ "error on the method itself), or that you should incorporate more "
+ "details in your error message such as specific names of methods or "
+ "variables to make each message unique if overlapping errors are "
+ "expected.\n"
+ "\n";
if (mode != TestMode.DEFAULT) {
prologue +=
""
+ "To debug the unit test in this test mode, add the following to the"
+ "lint() test task: testModes("
+ field
+ ")\n"
+ "\n";
}
prologue = SdkUtils.wrap(prologue.substring(prologue.indexOf(':') + 2), 72, "");
String interlogue = "";
if (driver.getMode() == LintDriver.DriverMode.MERGE) {
interlogue =
""
+ "This error happened while merging in provisional results; a common\n"
+ "cause for this is that your detector is\tusing the merged manifest from\n"
+ "each project to report problems. This means that these same errors are\n"
+ "reported repeatedly, from each sub project,\tinstead\tof only\tbeing\n"
+ "reported on the\tmain/app project. To fix this, consider\tadding a check\n"
+ "for (context.project == context.mainProject).\n"
+ "\n";
}
String epilogue =
""
+ "If you *really* want to allow this, add .allowDuplicates() to the test\n"
+ "task.\n"
+ "\n"
+ "Identical incident encountered at the same location more than once:\n"
+ incident;
fail(prologue + interlogue + epilogue);
}
}
}
}
private Incident checkIncidentSerialization(@NonNull Incident incident) {
// Check persistence: serialize and deserialize the issue metadata and continue using the
// deserialized version. It also catches cases where a detector modifies the incident
// after reporting it.
try {
File xmlFile = File.createTempFile("incident", ".xml");
XmlWriter xmlWriter =
new XmlWriter(this, XmlFileType.INCIDENTS, new FileWriter(xmlFile));
xmlWriter.writeIncidents(Collections.singletonList(incident), emptyList());
// Read it back
List<Issue> issueList = singletonList(incident.getIssue());
//noinspection MissingVendor
IssueRegistry registry =
new IssueRegistry() {
@NonNull
@Override
public List<Issue> getIssues() {
return issueList;
}
};
XmlReader xmlReader = new XmlReader(this, registry, incident.getProject(), xmlFile);
incident = xmlReader.getIncidents().get(0);
//noinspection ResultOfMethodCallIgnored
xmlFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
return incident;
}
/** Validity checks for the quickfix associated with the given incident */
private void checkFix(@NonNull LintFix fix, @NonNull Incident incident) {
if (fix instanceof LintFix.ReplaceString) {
LintFix.ReplaceString replaceFix = (LintFix.ReplaceString) fix;
String oldPattern = replaceFix.getOldPattern();
Location range = replaceFix.getRange();
String oldString = replaceFix.getOldString();
Location rangeLocation = range != null ? range : incident.getLocation();
String contents = readFile(rangeLocation.getFile()).toString();
Position start = rangeLocation.getStart();
Position end = rangeLocation.getEnd();
assert start != null;
assert end != null;
String locationRange = contents.substring(start.getOffset(), end.getOffset());
if (oldString != null) {
int startIndex = contents.indexOf(oldString, start.getOffset());
if (startIndex == -1 || startIndex > end.getOffset()) {
if (!(oldString.equals(LintFix.ReplaceString.INSERT_BEGINNING)
|| oldString.equals(LintFix.ReplaceString.INSERT_END))) {
fail(
"Did not find \""
+ oldString
+ "\" in \""
+ locationRange
+ "\" as suggested in the quickfix for issue "
+ incident.getIssue()
+ " (text in range was \""
+ locationRange
+ "\")");
}
}
} else if (oldPattern != null) {
Pattern pattern = Pattern.compile(oldPattern);
if (!pattern.matcher(locationRange).find()) {
fail(
"Did not match pattern \""
+ oldPattern
+ "\" in \""
+ locationRange
+ "\" as suggested in the quickfix for issue "
+ incident.getIssue());
}
}
File file = range != null ? range.getFile() : incident.getLocation().getFile();
if (!file.isFile()) {
fail(file + " is not a file. Use fix().createFile instead of fix().replace.");
}
} else if (fix instanceof LintFix.CreateFileFix) {
LintFix.CreateFileFix createFix = (LintFix.CreateFileFix) fix;
File file = createFix.getFile();
if (createFix.getDelete()) {
assertTrue(file + " cannot be deleted; does not exist", file.exists());
} else if (file.exists()) {
fail("Cannot create file " + file + ": already exists");
}
}
// Make sure any source files referenced by the quick fixes are loaded
// for subsequent quickfix verifications (since those run after the
// test projects have been deleted)
readFixFiles(incident, fix);
}
private void readFixFiles(Incident incident, LintFix fix) {
if (fix instanceof LintFix.LintFixGroup) {
for (LintFix f : ((LintFix.LintFixGroup) fix).getFixes()) {
readFixFiles(incident, f);
}
} else {
Location location = LintFixPerformer.Companion.getLocation(incident, fix);
File file = location.getFile();
if (file.isFile()) {
String displayName = fix.getDisplayName();
assertTrue(
"Quickfix file paths must be absolute: "
+ file
+ " from "
+ (displayName != null
? displayName
: fix.getClass().getSimpleName()),
file.isAbsolute());
getSourceText(file);
}
}
}
@Override
protected void sortResults() {
super.sortResults();
// Make sure Incident comparator is correct. (See also IncidentTest#testComparator)
checkTransitiveComparator(getDefiniteIncidents());
}
/**
* If the test results are spread across more than one project, use root relative rather than
* project relative paths
*/
private void useRootRelativePaths() {
boolean multipleProjects = false;
Iterator<Incident> iterator = getDefiniteIncidents().iterator();
if (iterator.hasNext()) {
Incident prev = iterator.next();
Project firstProject = prev.getProject();
while (iterator.hasNext()) {
Incident incident = iterator.next();
if (firstProject != incident.getProject()) {
multipleProjects = true;
break;
}
}
}
if (multipleProjects) {
// Null out projects on incidents such that it won't print project
// local paths
for (Incident incident : getDefiniteIncidents()) {
incident.setProject(null);
}
}
}
/**
* If the tests are configured to provide reporting from a specific project, set things up such
* that all the paths are relative to that project's directory.
*/
private void useProjectRelativePaths(ProjectDescription from) {
useProjectRelativePaths(from, getDefiniteIncidents());
}
private void useProjectRelativePaths(ProjectDescription from, List<Incident> incidents) {
if (incidents.isEmpty()) {
return;
}
Project project = findProject(from);
for (Incident incident : incidents) {
Project incidentProject = incident.getProject();
if (incidentProject != null && incidentProject != project) {
File dir = incidentProject.getDir();
Location location = ensureAbsolutePaths(dir, incident.getLocation());
incident.setLocation(location);
if (project != null) {
incident.setProject(project);
}
// TODO: Handle secondary
}
}
}
/** Returns the project instance for the given project description */
@Nullable
private Project findProject(ProjectDescription description) {
for (Map.Entry<File, ProjectDescription> entry : task.dirToProjectDescription.entrySet()) {
if (entry.getValue() == description) {
return getDirToProject().get(entry.getKey());
}
}
return null;
}
private static Location ensureAbsolutePaths(@NonNull File base, @NonNull Location location) {
// Recurse to normalize all paths in the secondary linked list too
Location secondary =
location.getSecondary() != null
? ensureAbsolutePaths(base, location.getSecondary())
: null;
File file = location.getFile();
if (!file.isAbsolute() || file.getPath().startsWith("../")) {
String relative = file.getPath();
File absolute = new File(base, relative);
Position start = location.getStart();
Position end = location.getEnd();
location =
start != null && end != null
? Location.create(absolute, start, end)
: Location.create(absolute);
}
if (secondary != null) {
location.setSecondary(secondary);
}
return location;
}
@Override
public void log(Throwable exception, String format, @NonNull Object... args) {
if (exception != null) {
if (task.runner.getFirstThrowable() == null) {
task.runner.setFirstThrowable(exception);
}
exception.printStackTrace();
}
StringBuilder sb = new StringBuilder();
if (format != null) {
sb.append(String.format(format, args));
}
if (exception != null) {
sb.append(exception);
}
System.err.println(sb);
if (exception != null) {
// Ensure that we get the full cause
// fail(exception.toString());
throw new RuntimeException(exception);
}
}
@NonNull
@Override
public Configuration getConfiguration(
@NonNull com.android.tools.lint.detector.api.Project project,
@Nullable final LintDriver driver) {
if (!task.useTestConfiguration) {
return super.getConfiguration(project, driver);
}
return getConfigurations()
.getConfigurationForProject(
project,
(file, defaultConfiguration) ->
createConfiguration(project, defaultConfiguration));
}
private Configuration createConfiguration(
@NonNull com.android.tools.lint.detector.api.Project project,
@NonNull Configuration defaultConfiguration) {
// Ensure that we have a fallback configuration which disables everything
// except the relevant issues
if (task.overrideConfigFile != null) {
ConfigurationHierarchy configurations = getConfigurations();
if (configurations.getOverrides() == null) {
Configuration config =
LintXmlConfiguration.create(configurations, task.overrideConfigFile);
configurations.addGlobalConfigurations(null, config);
}
}
LintModelModule model = project.getBuildModule();
final ConfigurationHierarchy configurations = getConfigurations();
if (model != null) {
LintModelLintOptions options = model.getLintOptions();
return configurations.createLintOptionsConfiguration(
project,
options,
false,
defaultConfiguration,
() ->
new TestLintOptionsConfiguration(
task, project, configurations, options, false));
} else {
return configurations.createChainedConfigurations(
project,
null,
() -> new TestConfiguration(task, configurations),
() -> {
File lintConfigXml =
ConfigurationHierarchy.Companion.getLintXmlFile(project.getDir());
if (lintConfigXml.isFile()) {
LintXmlConfiguration configuration =
LintXmlConfiguration.create(configurations, lintConfigXml);
configuration.setFileLevel(false);
return configuration;
} else {
return null;
}
});
}
}
@Override
protected boolean addBootClassPath(
@NonNull Collection<? extends Project> knownProjects, Set<File> files) {
boolean ok = super.addBootClassPath(knownProjects, files);
// Also add in the kotlin standard libraries if applicable
if (hasKotlin(knownProjects)) {
for (String path : findKotlinStdlibPath()) {
files.add(new File(path));
}
}
return ok;
}
private static boolean hasKotlin(Collection<? extends Project> projects) {
for (Project project : projects) {
for (File dir : project.getJavaSourceFolders()) {
if (hasKotlin(dir)) {
return true;
}
}
}
return false;
}
private static boolean hasKotlin(File dir) {
if (dir.getPath().endsWith(DOT_KT)) {
return true;
} else if (dir.isDirectory()) {
File[] files = dir.listFiles();
if (files != null) {
for (File sub : files) {
if (hasKotlin(sub)) {
return true;
}
}
}
}
return false;
}
@NonNull
@Override
public List<File> findGlobalRuleJars() {
// Don't pick up random custom rules in ~/.android/lint when running unit tests
return Collections.emptyList();
}
public void setIncremental(File currentFile) {
incrementalCheck = currentFile;
}
@NonNull
@Override
public ResourceRepository getResources(
@NonNull Project project, @NonNull ResourceRepositoryScope scope) {
task.requestedResourceRepository = true;
// In special test mode requesting to check resource repositories
// (default vs ~AGP one) ?
if (!task.forceAgpResourceRepository) {
// Default lint resource repository, used in production.
// Instead of just returning the resource repository computed by super,
// we'll compute it, then clear the in-memory caches, then call it again;
// this will test the persistence mechanism as well which helps verify
// correct serialization
super.getResources(project, scope);
LintResourceRepository.Companion.clearCaches(this, project);
return super.getResources(project, scope);
}
ResourceNamespace namespace = project.getResourceNamespace();
List<Project> projects = new ArrayList<>();
projects.add(project);
if (scope.includesDependencies()) {
for (Project dep : project.getAllLibraries()) {
if (!dep.isExternalLibrary()) {
projects.add(dep);
}
}
}
List<Pair<String, List<File>>> resourceSets = new ArrayList<>();
for (Project p : projects) {
List<File> resFolders = p.getResourceFolders();
resourceSets.add(new Pair<>(project.getName(), resFolders));
}
// TODO: Allow TestLintTask pass libraryName (such as getProjectResourceLibraryName())
return getResources(namespace, null, resourceSets, true);
}
/**
* Create a test resource repository given a list of resource sets, where each resource set is a
* resource set name and a list of resource folders
*/
public static ResourceRepository getResources(
@NonNull ResourceNamespace namespace,
@Nullable String libraryName,
@NonNull List<Pair<String, List<File>>> resourceSets,
boolean reportErrors) {
TestResourceRepository repository = new TestResourceRepository(RES_AUTO);
ILogger logger = reportErrors ? new StdLogger(StdLogger.Level.INFO) : new NullLogger();
ResourceMerger merger = new ResourceMerger(0);
try {
for (Pair<String, List<File>> pair : resourceSets) {
String projectName = pair.getFirst();
List<File> resFolders = pair.getSecond();
ResourceSet resourceSet =
new ResourceSet(projectName, namespace, libraryName, true, null) {
@Override
protected void checkItems() {
// No checking in ProjectResources; duplicates can happen, but
// the project resources shouldn't abort initialization
}
};
for (File res : resFolders) {
resourceSet.addSource(res);
}
resourceSet.loadFromFiles(logger);
merger.addDataSet(resourceSet);
}
repository.update(merger);
// Make tests stable: sort the item lists!
for (ListMultimap<String, ResourceItem> map : repository.getResourceTable().values()) {
ResourceRepositories.sortItemLists(map);
}
// Workaround: The repository does not insert ids from layouts! We need
// to do that here.
Map<ResourceType, ListMultimap<String, ResourceItem>> items =
repository.getResourceTable().row(ResourceNamespace.TODO());
ListMultimap<String, ResourceItem> layouts = items.get(ResourceType.LAYOUT);
if (layouts != null) {
for (ResourceItem item : layouts.values()) {
PathString source = item.getSource();
if (source == null) {
continue;
}
File file = source.toFile();
if (file == null) {
continue;
}
String xml = FilesKt.readText(file, Charsets.UTF_8);
Document document = XmlUtils.parseDocumentSilently(xml, true);
assertNotNull(document);
Set<String> ids = Sets.newHashSet();
addIds(ids, document);
if (!ids.isEmpty()) {
ListMultimap<String, ResourceItem> idMap =
items.computeIfAbsent(
ResourceType.ID, k -> ArrayListMultimap.create());
for (String id : ids) {
ResourceMergerItem idItem =
new ResourceMergerItem(
id,
ResourceNamespace.TODO(),
ResourceType.ID,
null,
null,
null);
String qualifiers = source.getParentFileName();
if (qualifiers == null) {
qualifiers = "";
} else if (qualifiers.startsWith("layout-")) {
qualifiers = qualifiers.substring("layout-".length());
} else if (qualifiers.equals("layout")) {
qualifiers = "";
}
// Creating the resource file will set the source of
// idItem.
//noinspection ResultOfObjectAllocationIgnored
ResourceFile.createSingle(file, idItem, qualifiers);
idMap.put(id, idItem);
}
}
}
}
} catch (MergingException e) {
if (reportErrors) {
throw new RuntimeException(e);
}
}
return repository;
}
private static void addIds(Set<String> ids, Node node) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String id = element.getAttributeNS(ANDROID_URI, ATTR_ID);
if (id != null && !id.isEmpty()) {
ids.add(Lint.stripIdPrefix(id));
}
NamedNodeMap attributes = element.getAttributes();
for (int i = 0, n = attributes.getLength(); i < n; i++) {
Attr attribute = (Attr) attributes.item(i);
String value = attribute.getValue();
if (value.startsWith(NEW_ID_PREFIX)) {
ids.add(value.substring(NEW_ID_PREFIX.length()));
}
}
}
NodeList children = node.getChildNodes();
for (int i = 0, n = children.getLength(); i < n; i++) {
Node child = children.item(i);
addIds(ids, child);
}
}
@Nullable
@Override
public IAndroidTarget getCompileTarget(@NonNull Project project) {
IAndroidTarget compileTarget = super.getCompileTarget(project);
if (compileTarget == null) {
if (task.requireCompileSdk && project.getBuildTargetHash() != null) {
fail(
"Could not find SDK to compile with ("
+ project.getBuildTargetHash()
+ "). "
+ "Either allow the test to use any installed SDK (it defaults to the "
+ "highest version) via TestLintTask#requireCompileSdk(false), or make "
+ "sure the SDK being used is the right one via "
+ "TestLintTask#sdkHome(File) or $ANDROID_HOME and that the actual SDK "
+ "platform (platforms/"
+ project.getBuildTargetHash()
+ " is installed "
+ "there");
}
}
return compileTarget;
}
@NonNull
@Override
public Set<Desugaring> getDesugaring(@NonNull Project project) {
if (task.desugaring != null) {
return task.desugaring;
}
return super.getDesugaring(project);
}
@NonNull
@Override
public List<File> getTestSourceFolders(@NonNull Project project) {
List<File> testSourceFolders = super.getTestSourceFolders(project);
File tests = new File(project.getDir(), "test");
if (tests.exists()) {
List<File> all = Lists.newArrayList(testSourceFolders);
all.add(tests);
testSourceFolders = all;
}
return testSourceFolders;
}
@NonNull
@Override
public List<File> getExternalAnnotations(@NonNull Collection<? extends Project> projects) {
List<File> externalAnnotations = Lists.newArrayList(super.getExternalAnnotations(projects));
for (Project project : projects) {
File annotationsZip = new File(project.getDir(), FN_ANNOTATIONS_ZIP);
if (annotationsZip.isFile()) {
externalAnnotations.add(annotationsZip);
}
File annotationsJar = new File(project.getDir(), FN_ANNOTATIONS_JAR);
if (annotationsJar.isFile()) {
externalAnnotations.add(annotationsJar);
}
}
return externalAnnotations;
}
@Nullable
@Override
public URLConnection openConnection(@NonNull URL url, int timeout) throws IOException {
if (task.mockNetworkData != null) {
String query = url.toExternalForm();
byte[] bytes = task.mockNetworkData.get(query);
if (bytes != null) {
return new URLConnection(url) {
@Override
public void connect() {}
@Override
public InputStream getInputStream() {
return new ByteArrayInputStream(bytes);
}
};
}
}
if (!task.allowNetworkAccess) {
fail(
"Lint detector test attempted to read from the network. Normally this means "
+ "that you have forgotten to set up mock data (calling networkData() on the "
+ "lint task) or the URL no longer matches. The URL encountered was "
+ url);
}
return super.openConnection(url, timeout);
}
public static class TestProject extends Project {
@Nullable public final GradleModelMocker mocker;
private final ProjectDescription projectDescription;
public TestProject(
@NonNull LintClient client,
@NonNull File dir,
@NonNull File referenceDir,
@Nullable ProjectDescription projectDescription,
@Nullable GradleModelMocker mocker) {
super(client, dir, referenceDir);
this.projectDescription = projectDescription;
this.mocker = mocker;
// In the old days merging was opt in, but we're almost exclusively using/supporting
// Gradle projects now, so make this the default behavior for test projects too, even
// if they don't explicitly opt into Gradle features like mocking during the test.
// E.g. a simple project like
// ManifestDetectorTest#testUniquePermissionsPrunedViaManifestRemove
// which simply registers library and app manifests (no build files) should exhibit
// manifest merging.
this.mergeManifests = true;
}
@Override
public boolean isGradleProject() {
return mocker != null || super.isGradleProject();
}
@Override
public boolean isLibrary() {
if (mocker != null && mocker.isLibrary()) {
return true;
}
return super.isLibrary()
|| projectDescription != null
&& projectDescription.getType() == ProjectDescription.Type.LIBRARY;
}
@Override
public boolean isAndroidProject() {
if (mocker != null && (mocker.hasJavaOrJavaLibraryPlugin())) {
return false;
}
return projectDescription == null
|| projectDescription.getType() != ProjectDescription.Type.JAVA;
}
@Nullable
@Override
public Boolean dependsOn(@NonNull String artifact) {
artifact = AndroidxNameUtils.getCoordinateMapping(artifact);
LintModelVariant variant = getBuildVariant();
if (mocker != null && variant != null) {
// Simulate what the Gradle integration does
// TODO: Do this more effectively; we have direct library lookup
for (LintModelLibrary lib : variant.getMainArtifact().getDependencies().getAll()) {
if (libraryMatches(artifact, lib)) {
return true;
}
}
}
return super.dependsOn(artifact);
}
private static boolean libraryMatches(@NonNull String artifact, LintModelLibrary lib) {
if (!(lib instanceof LintModelExternalLibrary)) {
return false;
}
LintModelMavenName coordinates =
((LintModelExternalLibrary) lib).getResolvedCoordinates();
String c = coordinates.getGroupId() + ':' + coordinates.getArtifactId();
c = AndroidxNameUtils.getCoordinateMapping(c);
return artifact.equals(c);
}
@Override
public int getBuildSdk() {
if (mocker != null) {
Integer buildSdk = mocker.getBuildSdk();
if (buildSdk != null) {
return buildSdk;
}
}
return super.getBuildSdk();
}
@Nullable
@Override
public String getBuildTargetHash() {
if (mocker != null) {
String buildTargetHash = mocker.getBuildTargetHash();
if (buildTargetHash != null) {
return buildTargetHash;
}
}
return super.getBuildTargetHash();
}
@Override
public boolean getReportIssues() {
if (projectDescription != null && !projectDescription.getReport()) {
return false;
}
return super.getReportIssues();
}
@Nullable
@Override
public LintModelVariant getBuildVariant() {
if (cachedLintVariant != null) {
return cachedLintVariant;
}
if (mocker != null) {
cachedLintVariant = mocker.getLintVariant();
}
return cachedLintVariant;
}
@Nullable private LintModelVariant cachedLintVariant = null;
private List<LintModelSourceProvider> mProviders;
private List<LintModelSourceProvider> getSourceProviders() {
if (mProviders == null) {
LintModelVariant variant = getBuildVariant();
if (variant == null) {
mProviders = Collections.emptyList();
} else {
mProviders = variant.getSourceProviders();
}
}
return mProviders;
}
@NonNull
@Override
public List<File> getManifestFiles() {
if (manifestFiles == null) {
//noinspection VariableNotUsedInsideIf
if (mocker != null) {
for (LintModelSourceProvider provider : getSourceProviders()) {
File manifestFile = provider.getManifestFile();
if (manifestFile.exists()) { // model returns path whether or not it exists
if (manifestFiles == null) {
manifestFiles = Lists.newArrayList();
}
manifestFiles.add(manifestFile);
}
}
}
if (manifestFiles == null) {
manifestFiles = super.getManifestFiles();
}
}
return manifestFiles;
}
@NonNull
@Override
public List<File> getResourceFolders() {
if (resourceFolders == null) {
//noinspection VariableNotUsedInsideIf
if (mocker != null) {
for (LintModelSourceProvider provider : getSourceProviders()) {
Collection<File> list = provider.getResDirectories();
for (File file : list) {
if (file.exists()) { // model returns path whether or not it exists
if (resourceFolders == null) {
resourceFolders = Lists.newArrayList();
}
resourceFolders.add(file);
}
}
}
}
if (resourceFolders == null) {
resourceFolders = super.getResourceFolders();
}
}
return resourceFolders;
}
@NonNull
@Override
public List<File> getJavaSourceFolders() {
if (javaSourceFolders == null) {
//noinspection VariableNotUsedInsideIf
if (mocker != null) {
List<File> list = Lists.newArrayList();
for (LintModelSourceProvider provider : getSourceProviders()) {
Collection<File> srcDirs = provider.getJavaDirectories();
// model returns path whether or not it exists
for (File srcDir : srcDirs) {
if (srcDir.exists()) {
list.add(srcDir);
}
}
}
javaSourceFolders = list;
}
if (javaSourceFolders == null || javaSourceFolders.isEmpty()) {
javaSourceFolders = super.getJavaSourceFolders();
}
}
return javaSourceFolders;
}
@NonNull
@Override
public List<File> getGeneratedSourceFolders() {
// In the tests the only way to mark something as generated is "gen" or "generated"
if (generatedSourceFolders == null) {
//noinspection VariableNotUsedInsideIf
if (mocker != null) {
generatedSourceFolders =
mocker.getGeneratedSourceFolders().stream()
.filter(File::exists)
.collect(Collectors.toList());
}
if (generatedSourceFolders == null || generatedSourceFolders.isEmpty()) {
generatedSourceFolders = super.getGeneratedSourceFolders();
if (generatedSourceFolders.isEmpty()) {
File generated = new File(dir, "generated");
if (generated.isDirectory()) {
generatedSourceFolders = singletonList(generated);
} else {
generated = new File(dir, FD_GEN_SOURCES);
if (generated.isDirectory()) {
generatedSourceFolders = singletonList(generated);
}
}
}
return generatedSourceFolders;
}
}
return generatedSourceFolders;
}
@NonNull
@Override
public List<File> getGeneratedResourceFolders() {
// In the tests the only way to mark something as generated is "gen" or "generated"
if (generatedResourceFolders == null) {
//noinspection VariableNotUsedInsideIf
if (mocker != null) {
generatedResourceFolders =
mocker.getGeneratedSourceFolders().stream()
.filter(File::exists)
.collect(Collectors.toList());
}
if (generatedResourceFolders == null || generatedResourceFolders.isEmpty()) {
generatedResourceFolders = super.getGeneratedResourceFolders();
}
}
return generatedResourceFolders;
}
@NonNull
@Override
public List<File> getTestSourceFolders() {
if (testSourceFolders == null) {
LintModelVariant variant = getBuildVariant();
if (mocker != null && variant != null) {
testSourceFolders = Lists.newArrayList();
for (LintModelSourceProvider provider : variant.getTestSourceProviders()) {
Collection<File> srcDirs = provider.getJavaDirectories();
// model returns path whether or not it exists
for (File srcDir : srcDirs) {
if (srcDir.exists()) {
testSourceFolders.add(srcDir);
}
}
}
}
if (testSourceFolders == null || testSourceFolders.isEmpty()) {
testSourceFolders = super.getTestSourceFolders();
}
}
return testSourceFolders;
}
public void setReferenceDir(File dir) {
this.referenceDir = dir;
}
}
}
| 39.781357 | 118 | 0.543822 |
17991990a8a804c3d706b9389cd3544c0550641a | 902 | package com.tzj.garvel.core.dep.api.parser;
import java.util.ArrayList;
import java.util.List;
public class Versions {
private String latestVersion;
private String releaseVersion;
private List<String> availableVersions;
public Versions() {
this.availableVersions = new ArrayList<>();
}
public String getLatestVersion() {
return latestVersion;
}
public void setLatestVersion(final String latestVersion) {
this.latestVersion = latestVersion;
}
public String getReleaseVersion() {
return releaseVersion;
}
public void setReleaseVersion(final String releaseVersion) {
this.releaseVersion = releaseVersion;
}
public List<String> getAvailableVersions() {
return availableVersions;
}
public void addAvailableVersion(final String version) {
availableVersions.add(version);
}
}
| 23.128205 | 64 | 0.689579 |
cbc29311e64169e2558a646c1c4f7607165e1189 | 104 | package rs.math.oop1.z090402.solid.z06.dobarOPovrsine;
public interface Mera {
double povrsina();
}
| 17.333333 | 54 | 0.759615 |
3104f3aafca34ea682ef1b6e68d33a40de2b3cfd | 2,064 | /*
* Copyright © Zhenjie Yan
*
* 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.yanzhenjie.andserver.processor.util;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.processing.Messager;
import javax.tools.Diagnostic;
/**
* Created by Zhenjie Yan on 2018/2/5.
*/
public class Logger {
private Messager mMessager;
public Logger(Messager messager) {
this.mMessager = messager;
}
public void i(CharSequence info) {
if (StringUtils.isNotEmpty(info)) {
mMessager.printMessage(Diagnostic.Kind.NOTE, info);
}
}
public void e(CharSequence error) {
if (StringUtils.isNotEmpty(error)) {
mMessager.printMessage(Diagnostic.Kind.ERROR, "An exception is encountered, " + error);
}
}
public void e(Throwable error) {
if (null != error) {
mMessager.printMessage(Diagnostic.Kind.ERROR,
"An exception is encountered, " + error.getMessage() + "\n" + formatStackTrace(error.getStackTrace()));
}
}
public void w(CharSequence warning) {
if (StringUtils.isNotEmpty(warning)) {
mMessager.printMessage(Diagnostic.Kind.WARNING, warning);
}
}
private String formatStackTrace(StackTraceElement[] stackTrace) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement element : stackTrace) {
sb.append(" at ").append(element.toString());
sb.append("\n");
}
return sb.toString();
}
} | 30.352941 | 119 | 0.657946 |
31e1e83465efd271b1d4bd8ee2530f1cad36b45d | 279 | package br.edu.utfpr.cp.emater.midmipsystem.repository.base;
import org.springframework.data.jpa.repository.JpaRepository;
import br.edu.utfpr.cp.emater.midmipsystem.entity.base.MacroRegion;
public interface MacroRegionRepository extends JpaRepository<MacroRegion, Long> { }
| 31 | 83 | 0.835125 |
a4a901d8778597db9d7bb805717e0bff80e915ad | 7,702 | package br.com.californiamobile.youfood.activitys;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.mancj.materialsearchbar.MaterialSearchBar;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import br.com.californiamobile.youfood.R;
import br.com.californiamobile.youfood.interfaces.ItemClickListener;
import br.com.californiamobile.youfood.model.Food;
import br.com.californiamobile.youfood.viewHolder.FoodViewHolder;
public class FoodListActivity extends AppCompatActivity {
//Atributos
private RecyclerView recyclerView;
private FirebaseDatabase database;
private DatabaseReference foodList;
private String categoryId = "";
//Configurcao RecyclerView
RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Food,FoodViewHolder> adapter;
//Configuracao do Search
FirebaseRecyclerAdapter<Food,FoodViewHolder> searchAdapter;
List<String> sugestaoList = new ArrayList<>();
MaterialSearchBar materialSearchBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_list);
//FindViewByIds
//Firebase
database = FirebaseDatabase.getInstance();
foodList = database.getReference("Foods");
//RecyclerView
recyclerView = findViewById(R.id.recycler_food);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Pegando a intent
if(getIntent() != null){
categoryId = getIntent().getStringExtra("CategoryId");
}
if(!categoryId.isEmpty() && categoryId != null){
loadListFood(categoryId);
}
//Search
materialSearchBar = findViewById(R.id.searchBar);
materialSearchBar.setHint("Pesquisar prato");
//materialSearchBar.setSpeechMode(false); ja definimos no xml
loadSugestoes();
materialSearchBar.setLastSuggestions(sugestaoList);
materialSearchBar.setCardViewElevation(10);
materialSearchBar.addTextChangeListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
List<String> sugestao = new ArrayList<>();
for(String search:sugestaoList){
if(search.toLowerCase().contains(materialSearchBar.getText().toLowerCase())){
sugestao.add(search);
}
}
materialSearchBar.setLastSuggestions(sugestao);
}
@Override
public void afterTextChanged(Editable editable) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
@Override
public void onSearchStateChanged(boolean enabled) {
if(!enabled)
recyclerView.setAdapter(adapter);
}
@Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text);
}
@Override
public void onButtonClicked(int buttonCode) {
}
});
}
private void startSearch(CharSequence text) {
searchAdapter = new FirebaseRecyclerAdapter<Food, FoodViewHolder>(
Food.class,
R.layout.food_item,
FoodViewHolder.class,
foodList.orderByChild("Name").equalTo(text.toString())
) {
@Override
protected void populateViewHolder(FoodViewHolder viewHolder, Food model, int position) {
viewHolder.food_name.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage())
.into(viewHolder.food_image);
final Food local = model;
viewHolder.setItemClickListener(new ItemClickListener() {
@Override
public void onClick(View view, int position, boolean isLongClick) {
//Toast.makeText(FoodListActivity.this, "" + local.getName(), Toast.LENGTH_SHORT).show();
//Start new Activity
Intent foodDetailIntent = new Intent (FoodListActivity.this, FoodDetailActivity.class);
//Enviando o id para a nova Activity
foodDetailIntent.putExtra("FoodId", searchAdapter.getRef(position).getKey());
startActivity(foodDetailIntent);
}
});
}
};
recyclerView.setAdapter(searchAdapter);
}
private void loadSugestoes() {
foodList.orderByChild("MenuId").equalTo(categoryId)
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapShot:dataSnapshot.getChildren() ){
Food item = postSnapShot.getValue(Food.class);
sugestaoList.add(item.getName());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void loadListFood(String categoryId) {
adapter = new FirebaseRecyclerAdapter<Food, FoodViewHolder>(Food.class,
R.layout.food_item,
FoodViewHolder.class,
foodList.orderByChild("MenuId").equalTo(categoryId)) {
@Override
protected void populateViewHolder(FoodViewHolder viewHolder, Food model, int position) {
viewHolder.food_name.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage())
.into(viewHolder.food_image);
final Food local = model;
viewHolder.setItemClickListener(new ItemClickListener() {
@Override
public void onClick(View view, int position, boolean isLongClick) {
//Toast.makeText(FoodListActivity.this, "" + local.getName(), Toast.LENGTH_SHORT).show();
//Start new Activity
Intent foodDetailIntent = new Intent (FoodListActivity.this, FoodDetailActivity.class);
//Enviando o id para a nova Activity
foodDetailIntent.putExtra("FoodId", adapter.getRef(position).getKey());
startActivity(foodDetailIntent);
}
});
}
};
//Set Adapter
recyclerView.setAdapter(adapter);
}
}
| 36.159624 | 113 | 0.614905 |
7fa76823a54a546b8698f11e700be2f64cb53847 | 347 | package com.heritago.heritandroid.helpers;
/**
* Created by onurtokoglu on 14/05/2017.
*/
public class LoginHelper {
public static final LoginHelper shared = new LoginHelper();
private LoginHelper() {
}
public boolean isLoggedIn(){
return false;
}
public String getUsername(){
return "suzan";
}
}
| 17.35 | 63 | 0.642651 |
c5db5df9e8469500cf918cac669056c1116dd814 | 76 | package models;
public interface ItemInquiryStatusType {
int code();
}
| 12.666667 | 40 | 0.736842 |
2e93a0629d5c93087597c177c97623c2be5eee1d | 4,727 | /**
* 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 com.twitter.distributedlog.client.proxy;
import com.twitter.distributedlog.thrift.service.BulkWriteResponse;
import com.twitter.distributedlog.thrift.service.ClientInfo;
import com.twitter.distributedlog.thrift.service.DistributedLogService;
import com.twitter.distributedlog.thrift.service.HeartbeatOptions;
import com.twitter.distributedlog.thrift.service.ServerInfo;
import com.twitter.distributedlog.thrift.service.WriteContext;
import com.twitter.distributedlog.thrift.service.WriteResponse;
import com.twitter.util.Future;
import java.nio.ByteBuffer;
import java.util.List;
public class MockDistributedLogServices {
static class MockBasicService implements DistributedLogService.ServiceIface {
@Override
public Future<ServerInfo> handshake() {
return Future.value(new ServerInfo());
}
@Override
public Future<ServerInfo> handshakeWithClientInfo(ClientInfo clientInfo) {
return Future.value(new ServerInfo());
}
@Override
public Future<WriteResponse> heartbeat(String stream, WriteContext ctx) {
return Future.value(new WriteResponse());
}
@Override
public Future<WriteResponse> heartbeatWithOptions(String stream,
WriteContext ctx,
HeartbeatOptions options) {
return Future.value(new WriteResponse());
}
@Override
public Future<WriteResponse> write(String stream,
ByteBuffer data) {
return Future.value(new WriteResponse());
}
@Override
public Future<WriteResponse> writeWithContext(String stream,
ByteBuffer data,
WriteContext ctx) {
return Future.value(new WriteResponse());
}
@Override
public Future<BulkWriteResponse> writeBulkWithContext(String stream,
List<ByteBuffer> data,
WriteContext ctx) {
return Future.value(new BulkWriteResponse());
}
@Override
public Future<WriteResponse> truncate(String stream,
String dlsn,
WriteContext ctx) {
return Future.value(new WriteResponse());
}
@Override
public Future<WriteResponse> release(String stream,
WriteContext ctx) {
return Future.value(new WriteResponse());
}
@Override
public Future<WriteResponse> create(String stream, WriteContext ctx) {
return Future.value(new WriteResponse());
}
@Override
public Future<WriteResponse> delete(String stream,
WriteContext ctx) {
return Future.value(new WriteResponse());
}
@Override
public Future<Void> setAcceptNewStream(boolean enabled) {
return Future.value(null);
}
}
public static class MockServerInfoService extends MockBasicService {
protected ServerInfo serverInfo;
public MockServerInfoService() {
serverInfo = new ServerInfo();
}
public void updateServerInfo(ServerInfo serverInfo) {
this.serverInfo = serverInfo;
}
@Override
public Future<ServerInfo> handshake() {
return Future.value(serverInfo);
}
@Override
public Future<ServerInfo> handshakeWithClientInfo(ClientInfo clientInfo) {
return Future.value(serverInfo);
}
}
}
| 35.810606 | 85 | 0.603766 |
3e050226bc53d288fcb40b292a67cb1e1392a181 | 32,049 | package be.naturalsciences.bmdc.ears.ontology.gui;
import be.naturalsciences.bmdc.ears.entities.CurrentVessel;
import be.naturalsciences.bmdc.ears.ontology.Individuals;
import be.naturalsciences.bmdc.ears.ontology.entities.FakeConcept;
import be.naturalsciences.bmdc.ears.ontology.entities.Tool;
import be.naturalsciences.bmdc.ears.ontology.entities.ToolCategory;
import be.naturalsciences.bmdc.ears.ontology.entities.Vessel;
import be.naturalsciences.bmdc.ears.utils.Message;
import be.naturalsciences.bmdc.ears.utils.Messaging;
import be.naturalsciences.bmdc.ontology.AsConceptEvent;
import be.naturalsciences.bmdc.ontology.AsConceptEventListener;
import be.naturalsciences.bmdc.ontology.ConceptHierarchy;
import be.naturalsciences.bmdc.ontology.EarsException;
import be.naturalsciences.bmdc.ontology.IAsConceptFactory;
import be.naturalsciences.bmdc.ontology.IIndividuals;
import be.naturalsciences.bmdc.ontology.IOntologyModel;
import be.naturalsciences.bmdc.ontology.entities.AsConcept;
import be.naturalsciences.bmdc.ontology.entities.EarsTermLabel;
import be.naturalsciences.bmdc.ontology.entities.IAction;
import be.naturalsciences.bmdc.ontology.entities.IEarsTerm;
import be.naturalsciences.bmdc.ontology.entities.IProcess;
import be.naturalsciences.bmdc.ontology.entities.IProperty;
import be.naturalsciences.bmdc.ontology.entities.ITool;
import be.naturalsciences.bmdc.ontology.entities.IToolCategory;
import be.naturalsciences.bmdc.ontology.entities.Term;
import gnu.trove.set.hash.THashSet;
import java.awt.Image;
import java.awt.datatransfer.Transferable;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Set;
import javax.swing.Action;
import org.netbeans.core.multiview.MultiViewTopComponent;
import org.openide.ErrorManager;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.nodes.NodeEvent;
import org.openide.nodes.NodeListener;
import org.openide.nodes.NodeMemberEvent;
import org.openide.nodes.NodeReorderEvent;
import org.openide.nodes.PropertySupport;
import org.openide.nodes.Sheet;
import org.openide.util.ImageUtilities;
import org.openide.util.Utilities;
import org.openide.util.actions.SystemAction;
import org.openide.util.datatransfer.PasteType;
import org.openide.util.lookup.Lookups;
import org.openide.windows.TopComponent;
/**
*
* @author Thomas Vandenberghe
*/
public class AsConceptNode extends AbstractNode implements NodeListener, AsConceptEventListener {
public static String CHILD_ADDED = "CHILD_ADDED";
@Override
public void propertyChange(PropertyChangeEvent evt) {
/* if ("prefLabel".equals(evt.getPropertyName())) {
this.fireDisplayNameChange(null, getDisplayName());
//this.getConcept().getTermRef().getEarsTermLabel().setPrefLabel((String) evt.getNewValue());
PropertyChangeEvent evt2 = new PropertyChangeEvent(this, "prefLabel", evt.getOldValue(), evt.getNewValue());
IIndividuals individuals = childFactory.getOntModel().getIndividuals();
individuals.change(evt2);
individuals.refresh();
}*/
}
@Override
public void childrenAdded(NodeMemberEvent nme) {
IIndividuals individuals = childFactory.getOntModel().getIndividuals();
if (individuals != null) {
individuals.add(nme);
individuals.refresh();
}
}
@Override
public void childrenRemoved(NodeMemberEvent nme) {
IIndividuals individuals = childFactory.getOntModel().getIndividuals();
if (individuals != null) {
individuals.remove(nme);
individuals.refresh();
}
}
@Override
public void childrenReordered(NodeReorderEvent nre) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void nodeDestroyed(NodeEvent ne) {
IIndividuals individuals = childFactory.getOntModel().getIndividuals();
individuals.remove(ne);
individuals.refresh();
}
@Override
public void nodeRenamed(AsConceptEvent ace) {
IIndividuals individuals = childFactory.getOntModel().getIndividuals();
individuals.change(ace);
individuals.refresh();
}
@Override
public void nodeAdded(AsConceptEvent ace) {
IIndividuals individuals = childFactory.getOntModel().getIndividuals();
individuals.add(ace);
individuals.refresh();
}
@Override
public void nodeDestroyed(AsConceptEvent ace) {
IIndividuals individuals = childFactory.getOntModel().getIndividuals();
individuals.remove(ace);
individuals.refresh();
}
public static class ContextBehaviour {
public boolean moveFromWithin;
public boolean moveToOther;
public boolean moveFromOther;
public IAsConceptFactory factory;
public PropertyChangeListener pcListener;
public NodeListener nListener;
private ContextBehaviour(boolean moveFromWithin, boolean moveToOther, boolean moveFromOther, PropertyChangeListener pcListener, NodeListener nListener) {
this.moveFromWithin = moveFromWithin;
this.moveToOther = moveToOther;
this.moveFromOther = moveFromOther;
this.nListener = nListener;
this.pcListener = pcListener;
}
private ContextBehaviour(boolean moveFromWithin, boolean moveToOther, boolean moveFromOther) {
this(moveFromWithin, moveToOther, moveFromOther, null, null);
}
}
public List<PropertyChangeListener> pcListenerList;
public List<NodeListener> nodeListenerList;
public static final ContextBehaviour BROWSE_BEHAVIOUR = new ContextBehaviour(false, true, false, null, null);
public static final ContextBehaviour EDIT_BEHAVIOUR = new ContextBehaviour(true, false, true);
private AsConcept concept;
public AsConceptNode parentNode;
private ContextBehaviour behaviour;
private AsConceptChildFactory childFactory;
ConceptHierarchy ConceptHierarchy;
public AsConceptChildFactory getChildFactory() {
return childFactory;
}
public AsConcept getConcept() {
return concept;
}
public void setConcept(AsConcept concept) {
this.concept = concept;
}
public ContextBehaviour getBehaviour() {
return behaviour;
}
public void addPropertyChangeListenerUseThis(PropertyChangeListener pcl) {
if (this.pcListenerList == null) {
this.pcListenerList = new ArrayList();
}
pcListenerList.add(pcl);
this.addPropertyChangeListener(pcl);
}
public void addNodeListenerUseThis(NodeListener nl) {
if (this.nodeListenerList == null) {
this.nodeListenerList = new ArrayList();
}
nodeListenerList.add(nl);
this.addNodeListener(nl);
}
public void removeNodeListeners() {
this.nodeListenerList.clear();
}
protected AsConceptNode(AsConceptNode parent, AsConcept obj, IOntologyModel ontModel, ContextBehaviour behaviour) { //InstanceContent ic,
super(Children.create(new AsConceptChildFactory(), true), Lookups.singleton(obj));
this.parentNode = parent;
this.concept = obj;
this.behaviour = behaviour;
this.ConceptHierarchy = new ConceptHierarchy(this.getParentsAsConcept());
this.childFactory = new AsConceptChildFactory(parent, obj, this.ConceptHierarchy, ontModel, behaviour);
if (childFactory.hasChildren()) {
this.setChildren(Children.create(childFactory, true));
} else {
this.setChildren(Children.LEAF);
}
this.setValue("nodeDescription", getShortDescription());
this.setShortDescription(getShortDescription());
/* if (obj.getTermRef() != null) {
EarsTermLabel label = obj.getTermRef().getEarsTermLabel(IEarsTerm.Language.en);
label.addPropertyChangeListener(WeakListeners.propertyChange(this, label));
label.addPropertyChangeListener(WeakListeners.propertyChange(behaviour.pcListener, label));
}*/
this.addPropertyChangeListenerUseThis(this.behaviour.pcListener);
this.addNodeListenerUseThis(this); //listen to my own changes
}
/**
* *
* Constructor for a root node
*
* @param ontModel
* @param behaviour
*/
public AsConceptNode(IOntologyModel ontModel, ContextBehaviour behaviour) {
super(Children.create(new AsConceptChildFactory(), true));
this.parentNode = null;
this.concept = new FakeConcept("Root", "Root", "Nothing to see here", true, ontModel.getNodes());
this.behaviour = behaviour;
setName("root");
this.ConceptHierarchy = new ConceptHierarchy();
this.childFactory = new AsConceptChildFactory(null, this.concept, this.ConceptHierarchy, ontModel, behaviour);
this.setChildren(Children.create(childFactory, true));
this.addNodeListenerUseThis(this); //listen to my own changes
}
@Override
public String toString() {
return this.getDisplayName();
}
public Collection<AsConceptNode> getParents() {
Collection<AsConceptNode> ca = this.getParents(new HashSet());
ca.remove(this);
return ca;
}
public final Collection<AsConcept> getParentsAsConcept() {
Collection<AsConcept> sa = new THashSet();
Collection<AsConceptNode> ca = this.getParents();
for (AsConceptNode conceptNode : ca) {
sa.add(conceptNode.getConcept());
}
return sa;
}
private Collection<AsConceptNode> getParents(Collection l) {
if (this.parentNode == null) { //if (this.getParentNode() == null) {
l.add(this);
} else {
l.add(this);
l.addAll(((AsConceptNode) this.parentNode).getParents(l)); //l.addAll(((AsConceptNode) this.getParentNode()).getParents(l));
}
return l;
}
public static Set<Node> getAllChildren(Node thisNode) {
Set<Node> nodes = new THashSet();
// ignore root -- root acts as a container
Node node;
if (thisNode.getChildren().getNodes().length > 0) {
node = thisNode.getChildren().getNodes()[0];
} else {
return nodes;
}
while (node != null && node.getParentNode() != null) {
// print node information
//System.out.println(node. + "=" + node.getNodeValue());
nodes.add(node);
if (node.getChildren().getNodesCount() > 0) {//node.hasChildren() //branch
node = node.getChildren().getNodes()[0]; //node = node.getFirstChild();
} else { // leaf
// find the parent level
Node nodeParent = node.getParentNode();
int siblings = 0;
try {
siblings = nodeParent.getChildren().getNodesCount() - 1;
} catch (Exception e) {
int a = 5;
}
int nodeIndex = getNodeIndex(nodeParent, node);
int remainingSiblings = siblings - nodeIndex;
//for (int i = 1; i < siblings; i++) {
//Node nextSibling =
//Arrays.asList(nodeParent.getChildren().getNodes()).remove().iterator().next();
//}
while (remainingSiblings == 0 && node != thisNode) //while (node.getNextSibling() == null && node != rootNode) // use child-parent link to get to the parent level
{
node = node.getParentNode();
}
if (nodeIndex < siblings) {
try {
node = nodeParent.getChildren().getNodes()[nodeIndex + 1]; //node = node.getNextSibling();
} catch (Exception e) {
int a = 5;
}
} else {
node = null;
}
}
}
return nodes;
}
private static int getNodeIndex(Node parentNode, Node ofNode) {
int c = 0;
try {
c = parentNode.getChildren().getNodesCount();
} catch (Exception e) {
int a = 5;
}
for (int i = 0; i < c; i++) {
if (parentNode.getChildren().getNodes()[i].equals(ofNode)) {
return i;
}
}
return -1;
}
@Override
public String getHtmlDisplayName() {
if (this.concept instanceof IToolCategory) {
return "<font color='#0B486B'>" + getDisplayName() + "</font>";
} else if (this.concept instanceof ITool) {
return "<font color='#02779E'>" + getDisplayName() + "</font>";
} else if (this.concept instanceof IProcess) {
return "<font color='#DC4B40'>" + getDisplayName() + "</font>";
} else if (this.concept instanceof IAction) {
return "<font color='#F59E03'>" + getDisplayName() + "</font>";
} else if (this.concept instanceof IProperty) {
return "<font color='#EB540A'>" + getDisplayName() + "</font>";
} else {
return "<font color='#2C3539'>" + getDisplayName() + "</font>";
}
}
@Override
public String getDisplayName() {
if (isRoot()) {
return "root";
} else if (concept != null && concept.getTermRef() != null) {
return concept.getTermRef().getEarsTermLabel().getPrefLabel();
} else {
return "root";
}
}
public boolean isRoot() {
if (this.concept instanceof FakeConcept) {
FakeConcept c = (FakeConcept) this.concept;
return c.isIsRoot();
} else {
return false;
}
}
@Override
public final String getShortDescription() {
if (concept != null && concept.getTermRef() != null) {
if (concept.getTermRef().getEarsTermLabel().getDefinition() != null) {
return concept.getKind() + ": " + concept.getTermRef().getEarsTermLabel().getDefinition().replace("><", "> <");
} else {
return concept.getKind();
}
}
return "";
}
@Override
public Image getIcon(int type) {
if (this.concept instanceof IToolCategory) {
return ImageUtilities.loadImage("be/naturalsciences/bmdc/ears/ontology/treeviewer/toolcategory.png"); //flaticon
} else if (this.concept instanceof ITool) {
return ImageUtilities.loadImage("be/naturalsciences/bmdc/ears/ontology/treeviewer/tool.png"); //flaticon
} else if (this.concept instanceof IProcess) {
return ImageUtilities.loadImage("be/naturalsciences/bmdc/ears/ontology/treeviewer/process.png"); //flaticon
} else if (this.concept instanceof IAction) {
return ImageUtilities.loadImage("be/naturalsciences/bmdc/ears/ontology/treeviewer/action.png"); //flaticon
} else if (this.concept instanceof IProperty) {
return ImageUtilities.loadImage("be/naturalsciences/bmdc/ears/ontology/treeviewer/property.png"); //flaticon
} else if (this.isRoot()) {
return ImageUtilities.loadImage("be/naturalsciences/bmdc/ears/ontology/treeviewer/root.png"); //flaticon
} else {
return ImageUtilities.loadImage("be/naturalsciences/bmdc/ears/ontology/treeviewer/unknown.png"); //flaticon
}
}
@Override
public Image getOpenedIcon(int i) {
return getIcon(i);
}
@Override
public Action[] getActions(boolean context) {
// Action a = SystemAction.get(ExpandNodeAction.class);
if (this.behaviour == EDIT_BEHAVIOUR) {
return new Action[]{
SystemAction.get(DeleteNodeAction.class),
SystemAction.get(ExpandNodeAction.class),
//SystemAction.get(CollapseNodeAction.class),
SystemAction.get(CreateChildNodeAction.class), //After discussion during ODIP 2 in October 2017 in Galway it was decided to only allow creating new tools or properties.
SystemAction.get(CreateEventAction.class)};
} else {
return new Action[]{
SystemAction.get(ExpandNodeAction.class),
//SystemAction.get(CollapseNodeAction.class),
SystemAction.get(CreateEventAction.class)};
}
}
@Override
public PasteType getDropType(Transferable t, int arg1, int arg2) {
if (behaviour == AsConceptNode.EDIT_BEHAVIOUR && t instanceof AsConcept) {
AsConcept transferred = AsConceptChildFactory.getTransferData(t);
boolean dropPermission = AsConceptChildFactory.isDropPermitted(t, concept, transferred);
if (dropPermission) {
return new PasteType() {
@Override
public Transferable paste() throws IOException {
AsConcept transferredCopy = null;
boolean removePreviousBottomUpAssociations = true;
TopComponent originalTopcomponent = TopComponent.getRegistry().getActivated();
AsConceptNode originalNode = originalTopcomponent.getLookup().lookup(AsConceptNode.class);
try {
transferredCopy = transferred.clone(new IdentityHashMap());
} catch (CloneNotSupportedException ex) {
Messaging.report("Could not clone the dragged object " + transferred.getUri(), ex, this.getClass(), true);
}
if (originalTopcomponent instanceof MultiViewTopComponent) { //ugly hack
removePreviousBottomUpAssociations = false;
}
if (transferredCopy != null) {
if (transferredCopy instanceof ToolCategory) {
ToolCategory child = (ToolCategory) transferredCopy;
try {
child.reduceGevsToSevs(AsConceptNode.this.behaviour.factory);
} catch (EarsException ex) {
throw new RuntimeException(ex);
}
}
if (transferredCopy instanceof Tool) {
Tool child = (Tool) transferredCopy;
child.setToolIdentifier(null);
child.setSerialNumber(null);
}
addAsChild(transferredCopy, removePreviousBottomUpAssociations, originalNode); //:false should be dependent on whether the donor is the same instance as the reciever.
}
return null; //We put nothing in the clipboard
}
};
} else {
return null;
}
} else { //open the node
return null;
}
}
private void addAsChild(AsConcept newChild, boolean removePreviousBottomUpAssociations, AsConceptNode originalNode) {
if (originalNode != null) {
concept.addToChildren(ConceptHierarchy, newChild, removePreviousBottomUpAssociations, originalNode.ConceptHierarchy, this.behaviour.factory);
} else {
concept.addToChildren(ConceptHierarchy, newChild, removePreviousBottomUpAssociations, null, this.behaviour.factory);
}
if (concept instanceof FakeConcept && newChild instanceof ToolCategory) {
childFactory.getOntModel().getNodes().getNodes().add(newChild);
}
if (isLeaf()) {
setChildren(Children.create(childFactory, true));
}
addNodeListenerUseThis(behaviour.nListener);
childFactory.refresh();
}
@Override
public boolean canCut() {
return false;
}
@Override
public boolean canCopy() {
return true;
}
@Override
public Transferable drag() {
if (this.concept instanceof ToolCategory) {
ToolCategory c = (ToolCategory) this.concept;
return c;
} else if (this.concept instanceof Tool) {
Tool c = (Tool) this.concept;
return c;
} else if (this.concept instanceof Vessel) {
Vessel c = (Vessel) this.concept;
return c;
} else if (this.concept instanceof be.naturalsciences.bmdc.ears.ontology.entities.Process) {
be.naturalsciences.bmdc.ears.ontology.entities.Process c = (be.naturalsciences.bmdc.ears.ontology.entities.Process) this.concept;
return c;
} else if (this.concept instanceof be.naturalsciences.bmdc.ears.ontology.entities.Action) {
be.naturalsciences.bmdc.ears.ontology.entities.Action c = (be.naturalsciences.bmdc.ears.ontology.entities.Action) this.concept;
return c;
} else if (this.concept instanceof be.naturalsciences.bmdc.ears.ontology.entities.Property) {
be.naturalsciences.bmdc.ears.ontology.entities.Property c = (be.naturalsciences.bmdc.ears.ontology.entities.Property) this.concept;
return c;
} else {
return null;
}
}
public void delete() {
concept.delete(this.ConceptHierarchy);
addNodeListenerUseThis(behaviour.nListener);
fireNodeDestroyed();
/* IIndividuals individuals = childFactory.getOntModel().getIndividuals();
individuals.remove(concept);
individuals.refresh();*/
}
public void createNewChild() {
AsConcept newChild = null;
try {
newChild = this.behaviour.factory.buildChild(concept);
if (newChild != null) {
/*IIndividuals individuals = childFactory.getOntModel().getIndividuals(); //TODO replaced by event
individuals.add(newChild);
individuals.refresh();*/
addAsChild(newChild, false, null);
}
} catch (EarsException ex) {
Messaging.report("Could not create a child node", ex, this.getClass(), true);
}
}
public class EarsTermRenamer {
private EarsTermLabel termLabel;
public EarsTermLabel getTermLabel() {
return termLabel;
}
public void setTermLabel(EarsTermLabel termLabel) {
this.termLabel = termLabel;
}
public EarsTermRenamer(EarsTermLabel termLabel) {
this.termLabel = termLabel;
}
public String getPrefLabel() {
return termLabel.getPrefLabel();
}
public void setPrefLabel(String label) {
String nameExists = Individuals.nameExists(label);
if (nameExists != null) {
Messaging.report(nameExists, Message.State.BAD, ClassChildren.class, true);
} else {
//IIndividuals individuals = childFactory.getOntModel().getIndividuals();
//individuals.remove(concept);
String oldPrefLabel = this.termLabel.getPrefLabel();
this.termLabel.setPrefLabel(label);
PropertyChangeEvent evt2 = new PropertyChangeEvent(AsConceptNode.this, "prefLabel", oldPrefLabel, label);
AsConceptNode.this.fireDisplayNameChange(null, getDisplayName());
for (PropertyChangeListener pcl : AsConceptNode.this.pcListenerList) {
pcl.propertyChange(evt2);
}
IIndividuals individuals = childFactory.getOntModel().getIndividuals();
individuals.change(evt2);
individuals.refresh();
// individuals.change(concept);
//individuals.refresh();
}
}
public String getDefinition() {
return termLabel.getDefinition();
}
public void setDefinition(String definition) {
this.termLabel.setDefinition(definition);
IIndividuals individuals = childFactory.getOntModel().getIndividuals();
individuals.refresh();
}
}
@Override
protected Sheet createSheet() {
Sheet sheet = Sheet.createDefault();
if (!(this.concept instanceof FakeConcept)) {
Sheet.Set set = Sheet.createPropertiesSet();
if (this.concept != null) {
IOntologyModel currentModel = childFactory.getOntModel();
Term term = this.concept.getTermRef();
if (term != null) {
URI uri = term.getUri();
be.naturalsciences.bmdc.ears.ontology.entities.Property infoProperty = null;
Tool infoTool = null;
EarsTermLabel label = term.getEarsTermLabel(IEarsTerm.Language.en);
EarsTermRenamer termRenamer = new EarsTermRenamer(label);
if (this.concept instanceof be.naturalsciences.bmdc.ears.ontology.entities.Property) {
infoProperty = (be.naturalsciences.bmdc.ears.ontology.entities.Property) this.concept;
}
if (this.concept instanceof Tool) {
infoTool = (Tool) this.concept;
}
try {
Property nameProp = null;
Property altNameProp = null;
Property defProp = null;
Property mandatoryPropertyProp = null;
Property multiplePropertyProp = null;
Property serialNumberProp = null;
Property toolIdentifierProp = null;
CurrentVessel currentVessel = Utilities.actionsGlobalContext().lookup(CurrentVessel.class);
String currentVesselCode = null;
if (currentVessel != null && currentVessel.getConcept() != null) {
currentVesselCode = currentVessel.getConcept().getCode();
}
if (currentVesselCode != null && this.behaviour == EDIT_BEHAVIOUR && currentModel.isEditable() && concept.getTermRef().isOwnTerm(currentVesselCode)) {
nameProp = new PropertySupport.Reflection(termRenamer, String.class, "getPrefLabel", "setPrefLabel");
altNameProp = new PropertySupport.Reflection(label, String.class, "altLabel");
defProp = new PropertySupport.Reflection(termRenamer, String.class, "getDefinition", "setDefinition");
if (infoProperty != null) {
mandatoryPropertyProp = new PropertySupport.Reflection(infoProperty, Boolean.class, "isMultiple", "setMultiple");
multiplePropertyProp = new PropertySupport.Reflection(infoProperty, Boolean.class, "isMandatory", "setMandatory");
mandatoryPropertyProp.setName("is mandatory");
multiplePropertyProp.setName("can occur multiple times");
set.put(mandatoryPropertyProp);
set.put(multiplePropertyProp);
}
} else {
nameProp = new PropertySupport.Reflection(label, String.class, "getPrefLabel", null);
altNameProp
= new PropertySupport.Reflection(label, String.class, "getAltLabel", null);
defProp
= new PropertySupport.Reflection(label, String.class, "getDefinition", null);
if (infoProperty != null) {
mandatoryPropertyProp = new PropertySupport.Reflection(infoProperty, Boolean.class, "isMultiple", null);
multiplePropertyProp = new PropertySupport.Reflection(infoProperty, Boolean.class, "isMandatory", null);
mandatoryPropertyProp.setName("is mandatory");
multiplePropertyProp.setName("can occur multiple times");
set.put(mandatoryPropertyProp);
set.put(multiplePropertyProp);
}
}
/*if (currentVesselCode != null && this.behaviour == editBehaviour && currentModel.isEditable() && infoTool != null) {
serialNumberProp = new PropertySupport.Reflection(infoTool, String.class, "getSerialNumber", "setSerialNumber");
serialNumberProp.setName("tool serial number");
toolIdentifierProp = new PropertySupport.Reflection(infoTool, String.class, "getToolIdentifier", "setToolIdentifier");
toolIdentifierProp.setName("tool identifier");
}*/
Property kindProp = new PropertySupport.Reflection(this.concept, String.class, "getKind", null);
Property uriProp = new PropertySupport.Reflection(uri, String.class, "toASCIIString", null);
Property urnProp = new PropertySupport.Reflection(term, String.class, "getIdentifierUrn", null);
Property statusProp = new PropertySupport.Reflection(term, String.class, "getStatusName", null);
Property creationDateProp = new PropertySupport.Reflection(term, Date.class, "getCreationDate", null);
Property toStringProp = new PropertySupport.Reflection(this.concept, String.class, "toString", null);
//Property printProp = new PropertySupport.Reflection(this.concept, String.class, "print", null);
nameProp.setName("label");
altNameProp.setName("alt label");
defProp.setName("definition");
kindProp.setName("kind");
uriProp.setName("uri");
urnProp.setName("urn");
statusProp.setName("status");
creationDateProp.setName("creation date");
toStringProp.setName("internal details");
//printProp.setName("relations");
set.put(nameProp);
set.put(altNameProp);
set.put(defProp);
set.put(kindProp);
/*if (serialNumberProp != null) {
set.put(serialNumberProp);
}
if (toolIdentifierProp != null) {
set.put(toolIdentifierProp);
}*/
set.put(uriProp);
set.put(urnProp);
set.put(statusProp);
set.put(creationDateProp);
set.put(toStringProp);
//set.put(printProp);
} catch (NoSuchMethodException ex) {
ErrorManager.getDefault();
}
sheet.put(set);
}
}
}
return sheet;
}
}
| 42.903614 | 194 | 0.597523 |
6870161134414f2c4bcae9f83810e72af6136987 | 14,954 | import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.swing.JTextArea;
/**
* @author Ubaby The MIT License (MIT) Copyright (c)
*
* <2016><Gintaras Koncevicius>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
public class SlowMachine extends FastMachine {
private JTextArea infoArea = null;
public SlowMachine(SettingsBox settings) {
super(settings);
}
public BestSettingsBox findBestSettings(List<VectorBox> learnData, List<VectorBox> predictData) {
learnMap = new HashMap<Integer, VectorBox>();
for (int l = 0; l < learnData.size(); l++) {
learnMap.put(new Integer(learnData.get(l).hashCode()), learnData.get(l));
}
loadLabelPairs(learnData);
List<OneVsOtherBox> labelPairs = getLabelPairs();
SettingsBox currentSettings = getCurrentSettings();
List<BestSettingsBox> bestSettings = new ArrayList<BestSettingsBox>();
loadBestSettings(labelPairs, currentSettings);
for (int i = 0; i < labelPairs.size(); i++) {
OneVsOtherBox labelPair = labelPairs.get(i);
List<SettingsBox> closests = labelPair.getBestClosestSettings();
for (int j = 0; j < closests.size(); j++) {
SettingsBox closest = closests.get(j);
List<SettingsBox> furthests = labelPair.getBestFurthestSettings();
for (int k = 0; k < furthests.size(); k++) {
SettingsBox furthest = furthests.get(k);
SimilaritySettingsBox closestSetting, furthestSetting, predictionSetting;
closestSetting = closest.getClosestSimilaritySetting();
furthestSetting = furthest.getFurthestSimilaritySetting();
loadClosestFurthest(labelPairs, closestSetting, furthestSetting);
resetDataLabels(predictData);
predictionSetting = tryPredict(labelPairs, predictData, learnData, currentSettings);
bestSettings.add(new BestSettingsBox(predictionSetting.getPrecision(), closestSetting, furthestSetting, predictionSetting));
addDisplayInfo("Trying to find best setting: " + "One Vs. Other Label Pair: " + (i + 1) + " Tries: " + (i + 1) * (j + 1) + " Settings: " + (i + 1) * (j + 1) * (k + 1));
}
}
}
Collections.sort(bestSettings);
return bestSettings.get(bestSettings.size() - 1);
}
public void addDisplayInfo(String info) {
if (infoArea != null) {
int w = info.length();
int s = 6;
int width = w * s;
infoArea.setPreferredSize(new Dimension(width, (int) infoArea.getSize().getHeight()));
infoArea.setText(info);
infoArea.setText(info);
}
}
public void loadBestSettings(List<OneVsOtherBox> labelPairs, SettingsBox currentSettings) {
for (int i = 0; i < labelPairs.size(); i++) {
OneVsOtherBox labelPair = labelPairs.get(i);
List<VectorBox> one = labelPair.getOne();
List<VectorBox> other = labelPair.getOther();
List<SettingsBox> bestClosestSettings = tryFindSettings(one, other, currentSettings, true);
resetClosestOrFurthest(one, other, true);
resetClosestOrFurthest(one, other, false);
List<SettingsBox> bestFurthestSettings = tryFindFurthestSettings(one, other, bestClosestSettings, currentSettings);
labelPair.setBestClosestSettings(bestClosestSettings);
labelPair.setBestFurthestSettings(bestFurthestSettings);
}
}
public void loadClosestFurthest(List<OneVsOtherBox> labelPairs, SimilaritySettingsBox closest, SimilaritySettingsBox furthest) {
for (int i = 0; i < labelPairs.size(); i++) {
OneVsOtherBox labelPair = labelPairs.get(i);
findClosestAndFurthest(labelPair, closest, furthest);
}
}
public SimilaritySettingsBox tryPredict(List<OneVsOtherBox> labelPairs, List<VectorBox> data, List<VectorBox> existing, SettingsBox currentSettings) {
List<SimilaritySettingsBox> randomSettings = getRandomSimilaritySettings(currentSettings);
int size = randomSettings.size();
double[] precisions = new double[size];
SimilaritySettingsBox bestSetting = getRandomSimilaritySetting("g");
double bestPrecision = 0;
for (int i = 0; i < size; i++) {
SimilaritySettingsBox randomSetting = randomSettings.get(i);
for (int j = 0; j < labelPairs.size(); j++) {
OneVsOtherBox labelPair = labelPairs.get(j);
for (int k = 0; k < data.size(); k++) {
VectorBox unknownLabel = data.get(k);
assignLabel(unknownLabel, labelPair, randomSetting, labelPair.getOneLabel());
}
}
precisions[i] = predictonPrecision(data, existing);
resetDataLabels(data);
if (bestPrecision < precisions[i]) {
bestPrecision = precisions[i];
bestSetting = randomSetting;
bestSetting.setPrecision(bestPrecision);
}
}
return bestSetting;
}
public String getMostCommonLabel(List<VectorBox> data, String[] labels) {
List<LabelDataBox> labelData = new ArrayList<LabelDataBox>();
for (int i = 0; i < labels.length; i++) {
int count = 0;
for (int j = 0; j < data.size(); j++) {
if (data.get(j).equals(labels[i])) {
count++;
}
}
labelData.add(new LabelDataBox(count, labels[i]));
}
Collections.sort(labelData);
return labelData.get(labelData.size() - 1).getLabel();
}
public void findAllClosestAndFurthest(List<OneVsOtherBox> labelPairs, SimilaritySettingsBox closest, SimilaritySettingsBox furthest) {
for (int i = 0; i < labelPairs.size(); i++) {
OneVsOtherBox labelPair = labelPairs.get(i);
findClosestAndFurthest(labelPair, closest, furthest);
}
}
public double findBestPredictionSensitivity(List<VectorBox> predictData, List<VectorBox> withLabelsForComparison, SettingsBox bestSetting, int attempts) {
List<OneVsOtherBox> labelPairs = getLabelPairs();
SettingsBox currentSettings = getCurrentSettings();
loadClosestFurthest(labelPairs, bestSetting.getClosestSimilaritySetting(), bestSetting.getFurthestSimilaritySetting());
double bestSensitivity = 1;
double bestPrecision = 0;
int count = attempts * 100;
double limit = (double) count;
for (int i = 1; i < count; i++) {
double predictionSearchSensitivity = 1 / (limit / (double) i);
currentSettings.setPredictionSearchSensitivity(predictionSearchSensitivity);
resetDataLabels(predictData);
List<VectorBox> predicted = predict(predictData, currentSettings);
double precision = predictonPrecision(predicted, withLabelsForComparison);
if (precision > bestPrecision) {
addDisplayInfo("Trying to find best closest sensitivity: " + "Try: " + (i + 1) + ", Sensitivity: " + predictionSearchSensitivity + ", Prediction: " + precision);
bestPrecision = precision;
bestSensitivity = predictionSearchSensitivity;
}
}
return bestSensitivity;
}
public void resetDataLabels(List<VectorBox> data) {
for (int i = 0; i < data.size(); i++) {
VectorBox v = data.get(i);
v.setNominalLabel("unknown");
}
}
public double predictonPrecision(List<VectorBox> predicted, List<VectorBox> existing) {
int len = predicted.size();
double good = len;
for (int i = 0; i < len; i++) {
// String existingLabel = existing.get(i).getNominalLabel();
String predictedLabel = predicted.get(i).getNominalLabel();
int pH = predicted.get(i).hashCode();
// int eH=existing.get(i).hashCode();
if (!learnMap.get(new Integer(pH)).getNominalLabel().equals(predictedLabel)) {
good -= 1;
}
// if (!existingLabel.equals(predictedLabel)) {
// good -= 1;
// }
}
double pct = (100 * good) / len;
pct = extraMath.round(pct, 3);
return pct;
}
public List<SettingsBox> tryFindFurthestSettings(List<VectorBox> one, List<VectorBox> other, List<SettingsBox> settingsList, SettingsBox settings) {
List<List<SettingsBox>> furthestSettingsMatrix = new ArrayList<List<SettingsBox>>();
for (int i = 0; i < settingsList.size(); i++) {
SimilaritySettingsBox currentClosestSimilarity = settingsList.get(i).getClosestSimilaritySetting();
List<VectorBox> closestOne = find(other, one, currentClosestSimilarity, true);
List<VectorBox> closestOther = find(one, other, currentClosestSimilarity, true);
List<SettingsBox> current = tryFindSettings(closestOne, closestOther, settings, false);
furthestSettingsMatrix.add(current);
}
return furthestSettingsList(furthestSettingsMatrix);
}
public List<SettingsBox> furthestSettingsList(List<List<SettingsBox>> furthestSettingsMatrix) {
Collections.sort(furthestSettingsMatrix, new Comparator<List<SettingsBox>>() {
public int compare(List<SettingsBox> o1, List<SettingsBox> o2) {
int totala = 0;
int totalb = 0;
for (int i = 0; i < o1.size(); i++) {
SettingsBox s = o1.get(i);
totala += s.getOne() + s.getOther();
}
for (int i = 0; i < o2.size(); i++) {
SettingsBox s = o2.get(i);
totalb += s.getOne() + s.getOther();
}
return totalb - totala;
}
});
return furthestSettingsMatrix.get(0);
}
public List<SettingsBox> tryFindSettings(List<VectorBox> one, List<VectorBox> other, SettingsBox settings, boolean closest) {
String[] similarityFormulas = settings.getSimilarityFormulas();
int attempts = settings.getAttemptsForBestSearching();
int maxAmountOfVectors = settings.getLeastClosestVectors();
List<SettingsBox> listOfSettings = new ArrayList<SettingsBox>();
List<VectorBox> closestOrFurthestOne;
List<VectorBox> closestOrFurthestOther;
for (int i = 0; i < similarityFormulas.length; i++) {
for (int j = 0; j < attempts; j++) {
SimilaritySettingsBox similaritySettings = getRandomSimilaritySetting(similarityFormulas[i]);
if (closest) {
resetClosestOrFurthest(one, other, true);
closestOrFurthestOne = find(other, one, similaritySettings, true);
closestOrFurthestOther = find(one, other, similaritySettings, true);
listOfSettings.add(new SettingsBox(closestOrFurthestOne.size(), closestOrFurthestOther.size(), similaritySettings, true));
} else {
resetClosestOrFurthest(one, other, true);
resetClosestOrFurthest(one, other, false);
closestOrFurthestOne = find(other, one, similaritySettings, false);
closestOrFurthestOther = find(one, other, similaritySettings, false);
listOfSettings.add(new SettingsBox(closestOrFurthestOne.size(), closestOrFurthestOther.size(), similaritySettings, false));
}
}
}
List<SettingsBox> filtered = filterSimilaritySettings(listOfSettings, maxAmountOfVectors);
return filtered;
}
public List<SettingsBox> filterSimilaritySettings(List<SettingsBox> listOfSettings, int tolerance) {
Collections.sort(listOfSettings);
List<SettingsBox> lowest = new ArrayList<SettingsBox>();
int ones = 0;
int others = 0;
boolean set = false;
for (int i = 0; i < listOfSettings.size(); i++) {
SettingsBox cur = listOfSettings.get(i);
if (cur.getOne() > 0 && cur.getOther() > 0) {
if (!set) {
ones = cur.getOne();
others = cur.getOther();
set = true;
}
if (cur.getOne() <= ones + (tolerance - 1) && cur.getOther() <= others + (tolerance - 1)) {
lowest.add(cur);
}
}
}
return lowest;
}
public SimilaritySettingsBox getRandomSimilaritySetting(String similarityFormula) {
MathHelper v = extraMath;
double p = v.normalize(new Random().nextInt(100), 0, 100, 0, 1);
double q = v.normalize(new Random().nextInt(100), 0, 100, 0, 1);
double ro = v.normalize(new Random().nextInt(100), 0, 100, 0, 1);
double gamma = v.normalize(new Random().nextInt(100), 0, 100, 0, 200);
double delta = v.normalize(new Random().nextInt(100), 0, 100, 0, 1);
double k = v.normalize(new Random().nextInt(100), 0, 100, 0, 1);
return new SimilaritySettingsBox(similarityFormula, p, q, ro, gamma, delta, k);
}
public List<SimilaritySettingsBox> getRandomSimilaritySettings(SettingsBox s) {
String[] sf = s.getSimilarityFormulas();
List<SimilaritySettingsBox> similaritySettings = new ArrayList<SimilaritySettingsBox>();
for (int i = 0; i < sf.length; i++) {
similaritySettings.add(getRandomSimilaritySetting(sf[i]));
}
return similaritySettings;
}
public JTextArea getInfoArea() {
return infoArea;
}
public void setInfoArea(JTextArea infoArea) {
this.infoArea = infoArea;
}
public List<VectorBox> tryFindBestTrainSet(List<VectorBox> learn, List<VectorBox> predict, SettingsBox s, int times, int subsetSize) {
List<List<VectorBox>> randomSubsets = getRandomSubsets(learn, times, subsetSize);
double[] results = new double[times];
double high = 0;
for (int i = 0; i < times; i++) {
List<VectorBox> randomSubset = randomSubsets.get(i);
FastMachine lss = new FastMachine(s);
lss.learn(randomSubset);
resetDataLabels(predict);
List<VectorBox> predicted = lss.predict(predict);
results[i] = predictonPrecision(predicted, learn);
if (results[i] > high) {
high = results[i];
addDisplayInfo("Trying to find best learning subset: " + "Try: " + (i + 1) + " Prediction: " + high + "%");
}
}
double highest = results[0];
List<VectorBox> bestTrainingSubset = randomSubsets.get(0);
for (int i = 0; i < results.length; i++) {
if (highest < results[i]) {
highest = results[i];
bestTrainingSubset = randomSubsets.get(i);
}
}
return bestTrainingSubset;
}
public List<List<VectorBox>> getRandomSubsets(List<VectorBox> list, int howMany, int howBig) {
List<List<VectorBox>> randomSubsets = new ArrayList<List<VectorBox>>();
for (int i = 0; i < howMany; i++) {
randomSubsets.add(randomSubset(list, howBig));
}
return randomSubsets;
}
private List<VectorBox> randomSubset(List<VectorBox> list, int howBig) {
List<VectorBox> randomized = new ArrayList<VectorBox>();
for (int i = 0; i < howBig; i++) {
int r = new Random().nextInt(list.size() - 1);
randomized.add(list.get(r));
}
return randomized;
}
} | 40.746594 | 174 | 0.699813 |
0900e8140cda2120ccf0436f8ea8649d0ed4043e | 2,554 | package ristogo.common.net;
import ristogo.common.entities.Customer;
import ristogo.common.entities.Entity;
import ristogo.common.entities.Owner;
import ristogo.common.entities.Reservation;
import ristogo.common.entities.Restaurant;
import ristogo.common.entities.User;
/**
* Represents a request message, sent from the client to the server.
*/
public class RequestMessage extends Message
{
private static final long serialVersionUID = 6989601732466426604L;
protected final ActionRequest action;
/**
* Creates a new request message, with optional entities attached.
* @param action The type of action requested.
* @param entities The list of entities to attach.
*/
public RequestMessage(ActionRequest action, Entity... entities)
{
super(entities);
this.action = action;
}
/**
* Returns the type of action requested.
* @return The type of action.
*/
public ActionRequest getAction()
{
return action;
}
/**
* Checks whether this message is valid (properly formed).
* @return True if valid; False otherwise.
*/
public boolean isValid()
{
boolean hasOwner = false;
boolean hasRestaurant = false;
boolean hasReservation = false;
switch(action) {
case LOGIN:
return getEntityCount() == 1 && getEntity() instanceof User;
case REGISTER:
if (getEntityCount() == 1 && getEntity() instanceof Customer)
return true;
if (getEntityCount() != 2)
return false;
for (Entity entity: getEntities())
if (entity instanceof Owner)
hasOwner = true;
else if (entity instanceof Restaurant)
hasRestaurant = true;
return hasOwner && hasRestaurant;
case EDIT_RESTAURANT:
case DELETE_RESTAURANT:
case LIST_RESERVATIONS:
return getEntityCount() == 1 && getEntity() instanceof Restaurant;
case EDIT_RESERVATION:
case DELETE_RESERVATION:
return getEntityCount() == 1 && getEntity() instanceof Reservation;
case RESERVE:
case CHECK_SEATS:
if (getEntityCount() < 1 || getEntityCount() > 2)
return false;
for (Entity entity: getEntities())
if (entity instanceof Reservation)
hasReservation = true;
else if (entity instanceof Restaurant)
hasRestaurant = true;
return (getEntityCount() == 2 && hasReservation && hasRestaurant) || (getEntityCount() == 1 && hasReservation);
case LIST_RESTAURANTS:
return (getEntityCount() == 0) || (getEntityCount() == 1 && getEntity() instanceof Restaurant);
case LOGOUT:
case GET_OWN_RESTAURANT:
case LIST_OWN_RESERVATIONS:
return getEntityCount() == 0;
default:
return false;
}
}
}
| 28.065934 | 114 | 0.71574 |
76df810c44ea5082931a44921412f015f1bf4618 | 2,040 | package Simulation;
public class DetermineStrength {
/**
* Add
* @param teams
* @return
*/
public static Team[] SOS(Team[] teams){
// normalize values
teams = NormalizeValues(teams);
// get defensive strength
teams = GetDefStrength(teams);
return teams;
}
public static Team[] NormalizeValues(Team[] teams){
// loop though the teams
for(int i=0; i < teams.length; i++) {
// if the spot is not empty
if(teams[i] != null){
// normalize the values
teams[i].poss /= teams[i].games_played;
teams[i].typical_scoring /= teams[i].games_played;
teams[i].turnover_propensity /= teams[i].games_played;
teams[i].turnover_causing /= teams[i].games_played;
teams[i].foul_rate /= teams[i].games_played;
teams[i].fouled_rate /= teams[i].games_played;
teams[i].off_rebound_rate /= teams[i].games_played;
teams[i].def_rebound_rate /= teams[i].games_played;
// otherwise
} else {
// exit the loop
break;
}
}
return teams;
}
public static Team[] GetDefStrength(Team[] teams){
// loop though teams
for(int i=0; i < teams.length; i++){
// if the teams spot is not empty
if(teams[i] != null){
// loop though the teams played
for(int j=0; j < teams[i].teams_played.length; j++) {
// if there is an opponant to calculate
if(teams[i].teams_played[j] != null) {
// add difference between opponant's typically allowed and team's typical scoring
teams[i].defense_strength += teams[i].typical_allowed.get(j) - teams[i].teams_played[j].typical_scoring;
// if there are no more opponants
} else {
// normalize defensive strength
teams[i].defense_strength /= teams[i].games_played;
teams[i].defense_strength /= teams[i].poss;
// exit the loop
break;
}
}
// if at the end of the teams list
} else {
// exit the loop
break;
}
}
return teams;
}
}
| 20.19802 | 110 | 0.59951 |
2351cfdd66e9dadbe40124cdea06d5269caf12f0 | 8,295 | /*
* Copyright 2017 Align Technology, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aligntech.cs.jmeter.signalfx;
import com.google.common.base.Throwables;
import com.signalfx.endpoint.SignalFxEndpoint;
import com.signalfx.metrics.auth.StaticAuthToken;
import com.signalfx.metrics.connection.HttpDataPointProtobufReceiverFactory;
import com.signalfx.metrics.connection.HttpEventProtobufReceiverFactory;
import com.signalfx.metrics.errorhandler.MetricError;
import com.signalfx.metrics.errorhandler.MetricErrorType;
import com.signalfx.metrics.errorhandler.OnSendErrorHandler;
import com.signalfx.metrics.flush.AggregateMetricSender;
import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
import java.net.URI;
import java.util.*;
import static com.signalfx.metrics.errorhandler.MetricErrorType.DATAPOINT_SEND_ERROR;
import static com.signalfx.metrics.errorhandler.MetricErrorType.EVENT_SEND_ERROR;
public class SignalFxMetricsSenderImpl implements SignalFxMetricsSender, OnSendErrorHandler {
private static final Logger log = LoggingManager.getLoggerForClass();
private final AggregateMetricSender sender;
private final List<SignalFxProtocolBuffers.Dimension> dimensions;
private final Map<String, String> eventDimensions;
public SignalFxMetricsSenderImpl(String endpoint, String authToken,
Map<String, String> dimensions,
Map<String, String> eventDimensions, int timeout) {
URI uri = toUri(endpoint);
sender = new AggregateMetricSender("jmeter",
new HttpDataPointProtobufReceiverFactory(new SignalFxEndpoint(uri.getScheme(), uri.getHost(), uri.getPort())).setTimeoutMs(timeout),
new HttpEventProtobufReceiverFactory(new SignalFxEndpoint(uri.getScheme(), uri.getHost(), uri.getPort())).setTimeoutMs(timeout),
new StaticAuthToken(authToken), Collections.singletonList(this));
this.dimensions = new ArrayList<>(dimensions.size());
for (Map.Entry<String, String> d : dimensions.entrySet()) {
this.dimensions.add(dimension(d).build());
}
this.eventDimensions = eventDimensions;
}
private URI toUri(String endpoint) {
try {
return new URI(endpoint);
} catch (Exception ex) {
throw Throwables.propagate(ex);
}
}
@Override
public void addEvent(String event, String details) {
AggregateMetricSender.Session session = sender.createSession();
SignalFxProtocolBuffers.Event.Builder builder = SignalFxProtocolBuffers.Event.newBuilder()
.setEventType("Jmeter: " + event)
.setCategory(SignalFxProtocolBuffers.EventCategory.USER_DEFINED)
.setTimestamp(System.currentTimeMillis())
.addDimensions(
dimension("source", "jmeter"))
.addProperties(
SignalFxProtocolBuffers.Property.newBuilder()
.setKey("details")
.setValue(
SignalFxProtocolBuffers.PropertyValue.newBuilder()
.setStrValue(details)
.build())
.build());
for (Map.Entry<String, String> eventDimensions : eventDimensions.entrySet()) {
builder.addDimensions(dimension(eventDimensions));
}
session.setEvent(builder.build());
closeQuitely(session);
}
private SignalFxProtocolBuffers.Dimension.Builder dimension(Map.Entry<String, String> entry) {
return dimension(entry.getKey(), entry.getValue());
}
private SignalFxProtocolBuffers.Dimension.Builder dimension(String key, String value) {
return SignalFxProtocolBuffers.Dimension.newBuilder().setKey(key).setValue(value);
}
@Override
public MetricCollector startCollection() {
return new MetricCollectorImpl(sender.createSession(), dimensions);
}
@Override
public void writeAndSendMetrics(MetricCollector collector) {
if (!(collector instanceof MetricCollectorImpl)) {
throw new IllegalArgumentException("This sender can work only with " + MetricCollectorImpl.class);
}
closeQuitely(((MetricCollectorImpl) collector).session);
}
private void closeQuitely(AggregateMetricSender.Session session) {
try {
session.close();
} catch (Exception ex) {
//to be handled in handleError(MetricError) method
}
}
@Override
public void destroy() {
log.debug("Destroing signalfx sender");
}
@Override
public void handleError(MetricError metricError) {
Set<MetricErrorType> warnErrors = EnumSet.of(DATAPOINT_SEND_ERROR,
EVENT_SEND_ERROR);
if (warnErrors.contains(metricError.getMetricErrorType())) {
log.warn(metricError.getMessage(), metricError.getException());
} else {
log.error(metricError.getMessage(), metricError.getException());
}
}
private static class MetricCollectorImpl implements MetricCollector {
private final long timestamp;
private final AggregateMetricSender.Session session;
private final List<SignalFxProtocolBuffers.Dimension> dimensions;
public MetricCollectorImpl(AggregateMetricSender.Session session, List<SignalFxProtocolBuffers.Dimension> dimensions) {
this.session = session;
this.timestamp = System.currentTimeMillis();
this.dimensions = dimensions;
}
@Override
public void addGauge(String contextName, String measurement, int value) {
session.setDatapoint(metric(contextName, measurement)
.setMetricType(SignalFxProtocolBuffers.MetricType.GAUGE)
.setValue(SignalFxProtocolBuffers.Datum.newBuilder().setIntValue(value))
.build()
);
}
@Override
public void addGauge(String contextName, String measurement, double value) {
if (Double.isInfinite(value) || Double.isNaN(value)) {
return;
}
session.setDatapoint(metric(contextName, measurement)
.setMetricType(SignalFxProtocolBuffers.MetricType.GAUGE)
.setValue(SignalFxProtocolBuffers.Datum.newBuilder().setDoubleValue(value))
.build()
);
}
@Override
public void addCounter(String contextName, String measurement, int value) {
session.setDatapoint(metric(contextName, measurement)
.setMetricType(SignalFxProtocolBuffers.MetricType.COUNTER)
.setValue(SignalFxProtocolBuffers.Datum.newBuilder().setIntValue(normalizeValue(value)))
.build()
);
}
/**
* Normalization of integer value. For some reason passing of value without multiplication results in
* strange graphed values
*/
private int normalizeValue(int value) {
return value * 10;
}
private SignalFxProtocolBuffers.DataPoint.Builder metric(String contextName, String measurement) {
return SignalFxProtocolBuffers.DataPoint.newBuilder()
.setTimestamp(timestamp)
.setSource("jmeter")
.setMetric("jmeter." + contextName + "." + measurement)
.addAllDimensions(dimensions);
}
}
}
| 41.893939 | 148 | 0.655214 |
b03986775eeb6cce1cca419a847fb13a70da24b0 | 397 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Commands;
/**
*
* @author Eugene
*/
public abstract class Command {
public Object DoAction(Object[] params) throws Exception
{
throw new Exception("Not Implemented Yet");
}
}
| 20.894737 | 79 | 0.68262 |
13b65950664ebc5dc89d0be7b1bd4e944b9684e7 | 1,071 | import java.util.Arrays;
public class question6 {
public static int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int res = 0x3f3f3f3f;
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && (nums[i] == nums[i - 1])) {
continue;
}
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right] + nums[i];
if (Math.abs(sum - target) < Math.abs(res - target)) {
res = sum;
}
if (sum == target) {
return target;
} else if (sum < target) {
left += 1;
} else if (sum > target){
right -= 1;
}
}
}
return res;
}
public static void main(String[] args) {
int[] example = {9, 1, 2, 3, 3, 4, 5};
int target = 3;
int res = threeSumClosest(example, target);
}
}
| 28.945946 | 70 | 0.405229 |
1e09150080b9a2311db779a98fea1b52dea98122 | 379 | package org.singledog.dogmall.pms.mapper;
import org.singledog.dogmall.pms.entity.SpuDescEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* spu信息介绍
*
* @author Zheming Liu
* @email [email protected]
* @date 2022-04-23 19:43:11
*/
@Mapper
public interface SpuDescMapper extends BaseMapper<SpuDescEntity> {
}
| 21.055556 | 66 | 0.765172 |
02e9071d3442516c8f70c3b4181fc60f11262752 | 1,177 | package com.github.etienneZink.model.sudoku.framework.checker;
import com.github.etienneZink.model.sudoku.framework.boards.ClassicSudoku;
import com.github.etienneZink.model.sudoku.framework.fields.SudokuField;
import com.github.etienneZink.model.sudoku.framework.interfaces.Checker;
/**
* Class to check if a ClassicSudoku is solved or not.
*
* @see ClassicSudoku
*/
public final class SudokuChecker implements Checker {
private ClassicSudoku sudoku;
// constructors
public SudokuChecker(ClassicSudoku sudoku) {
this.sudoku = sudoku;
}
// non-static methods
@Override
public boolean isSolved() {
SudokuField field;
for (int row = 0; row < sudoku.BOARD_SIZE; ++row) {
for (int column = 0; column < sudoku.BOARD_SIZE; ++column) {
field = (SudokuField) sudoku.getFieldAt(row, column);
if (field.isSet()) {
if (sudoku.checkValue(row, column, field.getValue())) {
return false;
}
} else {
return false;
}
}
}
return true;
}
} | 28.707317 | 75 | 0.597281 |
f63cf6fd0eb577a0d73fb3e6cf09b6b19a190930 | 667 | package com.dragontalker.exercise;
public class CustomerTest {
public static void main(String[] args) {
Customer customer = new Customer("Jane", "Smith");
Account account = new Account(1000, 2000, 1.23);
customer.setAccount(account);
customer.getAccount().deposit(100);
customer.getAccount().withdraw(960);
customer.getAccount().withdraw(2000);
System.out.println("Customer[" + customer.getLastName() + ", "
+ customer.getFirstName() + "] has an account: with ID: " +
"Annual Interest Rate: " + customer.getAccount().getAnnualInterestRate() +
"%");
}
}
| 37.055556 | 90 | 0.605697 |
bc25b76fd1644277d8fad75702ae8cadbd81c4e8 | 724 | package co.bantamstudio.streamie.auth.twitch.connect;
import org.springframework.social.oauth2.AbstractOAuth2ServiceProvider;
import org.springframework.social.oauth2.OAuth2Template;
import co.bantamstudio.streamie.auth.twitch.api.Twitch;
import co.bantamstudio.streamie.auth.twitch.api.impl.TwitchTemplate;
class TwitchServiceProvider extends
AbstractOAuth2ServiceProvider<Twitch> {
public TwitchServiceProvider(String clientId, String clientSecret) {
super(new OAuth2Template(clientId,
clientSecret,
"https://api.twitch.tv/kraken/oauth2/authorize",
"https://api.twitch.tv/kraken/oauth2/token"));
}
@Override
public Twitch getApi(String accessToken) {
return new TwitchTemplate(accessToken);
}
} | 31.478261 | 71 | 0.805249 |
7abd6526fbaaa9f6ff998c437e023bed505c7462 | 4,200 | package studio.xiaoyun.app.web;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import reactor.bus.EventBus;
import reactor.spring.context.annotation.Consumer;
import reactor.spring.context.annotation.Selector;
import studio.xiaoyun.app.convert.tool.FileTool;
import studio.xiaoyun.config.SystemConfig;
import studio.xiaoyun.config.XiaoyunWebConfig;
import studio.xiaoyun.core.exception.XyException;
import studio.xiaoyun.event.event.ArticleDeleteEvent;
import studio.xiaoyun.event.event.ArticleReleaseEvent;
import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;
/**
* 更新网站首页
*/
@Consumer
@Component
public class HomeUpdateHandler {
private Logger logger = LoggerFactory.getLogger(HomeUpdateHandler.class);
@Resource
private EventBus eventBus;
@Resource
private SystemConfig systemConfig;
@Resource
private XiaoyunWebConfig webConfig;
/**
* 记录最后一次的更新时间,防止更新太频繁
*/
private AtomicLong lastUpdateTime = new AtomicLong();
/**
* 两次更新的最小间隔时间
*/
private final static long interval = 10*60*1000;
/**
* 发布文章
* @param event 事件
*/
@Selector(ArticleReleaseEvent.EVENT_NAME)
public void articleRelease(ArticleReleaseEvent event) {
try{
updateHome(true);
}catch(Exception e){
logger.error(e.getMessage(),e);
}
}
/**
* 删除文章
* @param event 事件
*/
@Selector(ArticleDeleteEvent.EVENT_NAME)
public void articleDelete(ArticleDeleteEvent event) {
try{
updateHome(true);
}catch(Exception e){
logger.error(e.getMessage(),e);
}
}
/**
* 更新首页
* @param isInterval 是否考虑间隔时间
*/
private void updateHome(boolean isInterval){
if(!webConfig.isUpdateHomeEnabled()){
return;
}
logger.debug("开始更新首页");
long date = new Date().getTime();
if (!isInterval || date - lastUpdateTime.longValue() > interval) {
lastUpdateTime.set(date);
try{
String text = getText(webConfig.getXiaoyunWebUrl());
Path path = getHomePath();
if(Files.notExists(path.getParent())){
Files.createDirectories(path.getParent());
}
if(Files.exists(path)){
Files.delete(path);
}
FileTool.writeFile(path,text);
}catch (IOException e){
throw new XyException("更新首页失败,"+e.getMessage(),e);
}
}
}
/**
* 更新首页
*/
public void updateHome() {
updateHome(false);
}
/**
*
* @return 首页文件的路径
*/
public Path getHomePath(){
return systemConfig.getFilePath().resolve(systemConfig.getArticlePath()).resolve("home").resolve("index.html");
}
/**
* 根据url获得数据
* @param url url
* @return url的数据
*/
String getText(String url) throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
HttpGet httpGet = new HttpGet(url);
response = client.execute(httpGet);
if (response.getStatusLine().getStatusCode() < 400) {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, "utf-8");
}else{
throw new XyException("获取网页数据失败,状态码:"+response.getStatusLine().getStatusCode());
}
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
}
}
| 28.571429 | 119 | 0.613571 |
5e553f54702f6554c4ea3346c2e17a8f2be37c5e | 888 | package edu.bpb.oops.pattern.ch11.observer;
import edu.bpb.oops.pattern.ch11.observer.model.Article;
/**
* An {@code Observable} is an entity that wraps content and allows to observer the content.<br>
* The implementation must override the notifyObservers method to notify the registered {@code Observer} about any changes
*
* @author Lalit Mehra
* @since Dec 20, 2019
* @see Observer
*
*/
public interface Observable {
/**
* Adds an observer to the registration list. <br>
* Once added the new observer will be notified of all the changes.
* @param observer
*/
public void registerObserver(Observer observer);
/**
* Remove an observer from the registration list
* @param observer
*/
public void deregisterObserver(Observer observer);
/**
* Notify observers about the new article
* @param txn
*/
public void notifyObservers(Article article);
}
| 24.666667 | 122 | 0.724099 |
e8c592de1796d104c5c9bf29abff20bcda4ce7f5 | 347 | package it.polimi.deib.se.ex05.concurrent.ballo;
/**
* @author Alessandro Rizzi, Mattia Salnitri
*
*/
public class Dama {
private final int id;
/**
* costruttore della classe
* @param id
*/
public Dama(int id) {
this.id = id;
}
/**
* getter dell'id della dama
*
* @return
*/
public int getId(){
return id;
}
}
| 11.965517 | 48 | 0.599424 |
db0b8f63a3927a2fa574e744c49bf8a801fdf587 | 1,033 | /*
* Copyright 2014. AppDynamics LLC and its affiliates.
* All Rights Reserved.
* This is unpublished proprietary source code of AppDynamics LLC and its affiliates.
* The copyright notice above does not evidence any actual or intended publication of such source code.
*/
package com.appdynamics.extensions.sslcertificate;
import com.appdynamics.extensions.sslcertificate.common.SystemUtilTest;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import java.io.IOException;
@RunWith(Suite.class)
@Suite.SuiteClasses({
SystemUtilTest.class,
ProcessExecutorTest.class,
SslCertificateProcessorTest.class
})
public class SslCertificateMonitorTestSuite {
@BeforeClass
public static void setup() throws IOException {
String path = SslCertificateMonitorTestSuite.class.getResource("/cmd").getPath();
System.out.println("Changing the file permissions.");
Runtime.getRuntime().exec(new String[]{"chmod", "-R","+x",path});
}
}
| 32.28125 | 104 | 0.747338 |
824bc61b016367280d10e5b2ffa29f5db36a4c24 | 853 | package com.inepex.ineFrame.client.auth;
import com.inepex.ineFrame.client.auth.AbstractAuthManager.AuthActionCallback;
import com.inepex.ineFrame.shared.auth.AuthStatusResultBase;
public interface AuthManager {
public abstract void checkAuthStatus(final AuthActionCallback callback);
public abstract void doLogin(
String userName,
String password,
String captchaAnswer,
AuthActionCallback callback);
public abstract AuthStatusResultBase getLastAuthStatusResult();
public abstract void doLogout(AuthActionCallback callback);
public abstract boolean isUserLoggedIn();
public abstract boolean doUserHaveAnyOfRoles(String... roles);
public abstract void doGoogleLogin(String googleLoginToken, AuthActionCallback callback);
public abstract void setLoginProductType(int typeOrdinal);
} | 32.807692 | 93 | 0.786635 |
cea0a70bc8baff8740fe8b8ee95509373b6c76b0 | 6,928 | /*
* 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.directory.api.ldap.codec.controls.search.pagedSearch;
import org.apache.directory.api.asn1.DecoderException;
import org.apache.directory.api.asn1.ber.grammar.AbstractGrammar;
import org.apache.directory.api.asn1.ber.grammar.Grammar;
import org.apache.directory.api.asn1.ber.grammar.GrammarAction;
import org.apache.directory.api.asn1.ber.grammar.GrammarTransition;
import org.apache.directory.api.asn1.ber.tlv.BerValue;
import org.apache.directory.api.asn1.ber.tlv.IntegerDecoder;
import org.apache.directory.api.asn1.ber.tlv.IntegerDecoderException;
import org.apache.directory.api.asn1.ber.tlv.UniversalTag;
import org.apache.directory.api.i18n.I18n;
import org.apache.directory.api.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class implements the PagedSearchControl. All the actions are declared in
* this class. As it is a singleton, these declaration are only done once.
*
* The decoded grammar is the following :
*
* realSearchControlValue ::= SEQUENCE {
* size INTEGER,
* cookie OCTET STRING,
* }
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
public final class PagedResultsGrammar extends AbstractGrammar<PagedResultsContainer>
{
/** The logger */
static final Logger LOG = LoggerFactory.getLogger( PagedResultsGrammar.class );
/** The instance of grammar. PagedSearchControlGrammar is a singleton */
private static Grammar<?> instance = new PagedResultsGrammar();
/**
* Creates a new PagedSearchControlGrammar object.
*/
@SuppressWarnings("unchecked")
private PagedResultsGrammar()
{
setName( PagedResultsGrammar.class.getName() );
// Create the transitions table
super.transitions = new GrammarTransition[PagedResultsStates.LAST_PAGED_SEARCH_STATE.ordinal()][256];
/**
* Transition from initial state to PagedSearch sequence
* realSearchControlValue ::= SEQUENCE OF {
* ...
*
* Nothing to do
*/
super.transitions[PagedResultsStates.START_STATE.ordinal()][UniversalTag.SEQUENCE.getValue()] =
new GrammarTransition<PagedResultsContainer>( PagedResultsStates.START_STATE,
PagedResultsStates.PAGED_SEARCH_SEQUENCE_STATE,
UniversalTag.SEQUENCE.getValue(), null );
/**
* Transition from PagedSearch sequence to size
*
* realSearchControlValue ::= SEQUENCE OF {
* size INTEGER, -- INTEGER (0..maxInt),
* ...
*
* Stores the size value
*/
super.transitions[PagedResultsStates.PAGED_SEARCH_SEQUENCE_STATE.ordinal()][UniversalTag.INTEGER.getValue()] =
new GrammarTransition<PagedResultsContainer>( PagedResultsStates.PAGED_SEARCH_SEQUENCE_STATE,
PagedResultsStates.SIZE_STATE,
UniversalTag.INTEGER.getValue(),
new GrammarAction<PagedResultsContainer>( "Set PagedSearchControl size" )
{
public void action( PagedResultsContainer container ) throws DecoderException
{
BerValue value = container.getCurrentTLV().getValue();
try
{
// Check that the value is into the allowed interval
int size = IntegerDecoder.parse( value, Integer.MIN_VALUE, Integer.MAX_VALUE );
// We allow negative value to absorb a bug in some M$ client.
// Those negative values will be transformed to Integer.MAX_VALUE.
if ( size < 0 )
{
size = Integer.MAX_VALUE;
}
if ( LOG.isDebugEnabled() )
{
LOG.debug( I18n.msg( I18n.MSG_05303_SIZE, size ) );
}
container.getDecorator().setSize( size );
}
catch ( IntegerDecoderException ide )
{
String msg = I18n.err( I18n.ERR_05306_PAGED_SEARCH_SIZE_DECODING_ERROR );
LOG.error( msg, ide );
throw new DecoderException( msg, ide );
}
}
} );
/**
* Transition from size to cookie
* realSearchControlValue ::= SEQUENCE OF {
* ...
* cookie OCTET STRING
* }
*
* Stores the cookie flag
*/
super.transitions[PagedResultsStates.SIZE_STATE.ordinal()][UniversalTag.OCTET_STRING.getValue()] =
new GrammarTransition<PagedResultsContainer>( PagedResultsStates.SIZE_STATE,
PagedResultsStates.COOKIE_STATE, UniversalTag.OCTET_STRING.getValue(),
new GrammarAction<PagedResultsContainer>( "Set PagedSearchControl cookie" )
{
public void action( PagedResultsContainer container )
{
BerValue value = container.getCurrentTLV().getValue();
if ( container.getCurrentTLV().getLength() == 0 )
{
container.getDecorator().setCookie( Strings.EMPTY_BYTES );
}
else
{
container.getDecorator().setCookie( value.getData() );
}
// We can have an END transition
container.setGrammarEndAllowed( true );
}
} );
}
/**
* This class is a singleton.
*
* @return An instance on this grammar
*/
public static Grammar<?> getInstance()
{
return instance;
}
}
| 39.816092 | 118 | 0.587471 |
0355f1301e506fffbd3027188a9f1d68b8760bdc | 3,186 | package fossilsarcheology.server.entity.utility;
import fossilsarcheology.server.entity.monster.EntityFriendlyPigZombie;
import net.minecraft.entity.Entity;
import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.entity.passive.EntityPig;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.SoundEvents;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import java.util.List;
public class EntityAncientLightning extends EntityLightningBolt {
public long boltVertex;
private int lightningState = 2;
private int boltLivingTime;
public EntityAncientLightning(World var1, double var2, double var4, double var6) {
super(var1, var2, var4, var6, false);
this.boltLivingTime = this.rand.nextInt(3) + 1;
}
@Override
public void onUpdate() {
super.onUpdate();
if (this.lightningState == 2) {
this.world.playSound(null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_LIGHTNING_THUNDER, SoundCategory.WEATHER, 10000.0F, 0.8F + this.rand.nextFloat() * 0.2F);
this.world.playSound(null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_LIGHTNING_IMPACT, SoundCategory.WEATHER, 2.0F, 0.5F + this.rand.nextFloat() * 0.2F);
}
--this.lightningState;
if (this.lightningState < 0) {
if (this.boltLivingTime == 0) {
this.setDead();
} else if (this.lightningState < -this.rand.nextInt(10)) {
--this.boltLivingTime;
this.lightningState = 1;
this.boltVertex = this.rand.nextLong();
if (this.world.isAreaLoaded(new BlockPos(MathHelper.floor(this.posX), MathHelper.floor(this.posY), MathHelper.floor(this.posZ)), 10)) {
int var1 = MathHelper.floor(this.posX);
int var2 = MathHelper.floor(this.posY);
int var3 = MathHelper.floor(this.posZ);
BlockPos pos = new BlockPos(var1, var2, var3);
if (this.world.isAirBlock(pos) && Blocks.FIRE.canPlaceBlockAt(this.world, pos)) {
this.world.setBlockState(pos, Blocks.FIRE.getDefaultState());
}
}
}
}
if (this.lightningState >= 0) {
double var6 = 3.0D;
List var7 = this.world.getEntitiesWithinAABBExcludingEntity(this, new AxisAlignedBB(this.posX - var6, this.posY - var6, this.posZ - var6, this.posX + var6, this.posY + 6.0D + var6, this.posZ + var6));
for (Object aVar7 : var7) {
Entity var5 = (Entity) aVar7;
if (!(var5 instanceof EntityPlayer) && !(var5 instanceof EntityFriendlyPigZombie) && !(var5 instanceof EntityPig)) {
var5.onStruckByLightning(new EntityLightningBolt(this.world, this.posX, this.posY, this.posZ, false));
}
}
this.world.setLastLightningBolt(2);
}
}
}
| 41.921053 | 212 | 0.638418 |
46ab5c89456d268cf35509a9472a8c26cabd78bd | 1,073 | package four;
import four.classes.Banco;
import four.classes.Correntista;
import four.classes.Movimentacoes;
public class Main {
public static void main(String[] args) {
Banco banco = new Banco();
Correntista correntistas[] = {
new Correntista("123456789", 5000),
new Correntista("987654321", 1000),
new Correntista("331331331", 99999.5f),
new Correntista("111222111", 50.5f),
new Correntista("959595955", 0f),
new Correntista("141414141", -50f)
};
Movimentacoes movimentacoes[] = {
new Movimentacoes("123456789", -5000),
new Movimentacoes("987654321", 1),
new Movimentacoes("331331331", -999.5f),
new Movimentacoes("111222111", -20.5f),
new Movimentacoes("959595955", 50f),
new Movimentacoes("141414141", 150f)
};
Correntista.realizaMovimentacao(correntistas, movimentacoes, banco);
for (Correntista corrente : correntistas) {
System.out.println(corrente);
}
}
}
| 32.515152 | 76 | 0.609506 |
b846ec4e7d383517a77cce04b4ee84525fbaf140 | 2,203 | package com.erayerdin.primitivefxmvc.alerts;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* An Alert that is especially for any Throwable.
* Default AlertType is ERROR.
*
* @param <T> Any throwable
* @see java.lang.Throwable
* @see javafx.scene.control.Alert
*/
public class ExceptionAlert <T extends Throwable> extends Alert {
private String stackTraceString;
private T throwable;
public ExceptionAlert(T throwable) {
super(AlertType.ERROR);
this.throwable = throwable;
this.setTitle(throwable.getClass().getSimpleName());
this.setHeaderText(throwable.getMessage());
// Content Setter
// REF http://code.makery.ch/blog/javafx-dialogs-official/
Label label = new Label("Error details:");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
this.stackTraceString = sw.toString();
TextArea exceptionTextArea = new TextArea(this.stackTraceString);
exceptionTextArea.setEditable(false);
exceptionTextArea.setWrapText(true);
exceptionTextArea.setPrefSize(this.getDialogPane().getWidth()-20, this.getDialogPane().getHeight());
GridPane.setVgrow(exceptionTextArea, Priority.ALWAYS);
GridPane.setHgrow(exceptionTextArea, Priority.ALWAYS);
GridPane expContent = new GridPane();
expContent.setMaxWidth(Double.MAX_VALUE);
expContent.add(label, 0, 0);
expContent.add(exceptionTextArea, 0, 1);
this.getDialogPane().setExpandableContent(expContent);
this.getDialogPane().setMinHeight(300);
}
public String getStackTraceString() {
return stackTraceString;
}
public void setStackTraceString(String stackTraceString) {
this.stackTraceString = stackTraceString;
}
public T getThrowable() {
return throwable;
}
public void setThrowable(T throwable) {
this.throwable = throwable;
}
}
| 30.178082 | 108 | 0.695869 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.