repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
chanil1218/elasticsearch | src/main/java/org/elasticsearch/index/search/geo/GeoUtils.java | 1341 | /*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch 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.elasticsearch.index.search.geo;
/**
*/
public class GeoUtils {
public static double normalizeLon(double lon) {
return centeredModulus(lon, 360);
}
public static double normalizeLat(double lat) {
return centeredModulus(lat, 180);
}
private static double centeredModulus(double dividend, double divisor) {
double rtn = dividend % divisor;
if (rtn <= 0)
rtn += divisor;
if (rtn > divisor/2)
rtn -= divisor;
return rtn;
}
}
| apache-2.0 |
denisneuling/apitrary.jar | apitrary-orm/apitrary-orm-core/src/test/java/com/apitrary/orm/core/marshalling/dumb/DumbEntity.java | 1421 | /*
* Copyright 2012-2013 Denis Neuling
*
* 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.apitrary.orm.core.marshalling.dumb;
import com.apitrary.orm.core.annotations.Codec;
import com.apitrary.orm.core.annotations.Column;
import com.apitrary.orm.core.annotations.Entity;
import com.apitrary.orm.core.annotations.Id;
/**
* @author Denis Neuling (denisneuling@gmail.com)
*
*/
@Entity
public class DumbEntity {
@Id
private String id;
@Column
private String a;
@Column
@Codec(DumbCodec.class)
private String b;
public DumbEntity() {
}
public DumbEntity(String a, String b) {
this.a = a;
this.b = b;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
} | apache-2.0 |
cloudera/director-aws-plugin | provider/src/main/java/com/cloudera/director/aws/ec2/EC2Retryer.java | 3227 | // (c) Copyright 2017 Cloudera, 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.cloudera.director.aws.ec2;
import com.cloudera.director.aws.AWSExceptions;
import com.github.rholder.retry.RetryException;
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import com.google.common.annotations.VisibleForTesting;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.Interval;
public class EC2Retryer {
// backoff not resulted from contention, so fixed interval
private static final Duration DEFAULT_BACKOFF = Duration.standardSeconds(5);
private static final Duration DEFAULT_TIMEOUT = Duration.millis(Long.MAX_VALUE);
private EC2Retryer() {
throw new IllegalStateException("static class");
}
public static <T> T retryUntil(Callable<T> func)
throws InterruptedException, RetryException, ExecutionException {
return retryUntil(func, DEFAULT_TIMEOUT);
}
public static <T> T retryUntil(Callable<T> func, DateTime timeout)
throws InterruptedException, RetryException, ExecutionException {
return retryUntil(func, timeout, DEFAULT_BACKOFF);
}
public static <T> T retryUntil(Callable<T> func, Duration timeout)
throws InterruptedException, RetryException, ExecutionException {
return retryUntil(func, timeout, DEFAULT_BACKOFF);
}
public static <T> T retryUntil(Callable<T> func, DateTime timeout, Duration backoff)
throws InterruptedException, RetryException, ExecutionException {
return retryUntil(func, getTimeout(timeout), backoff);
}
public static <T> T retryUntil(Callable<T> func, Duration timeout, Duration backoff)
throws InterruptedException, RetryException, ExecutionException {
Retryer<T> retryer = RetryerBuilder.<T>newBuilder()
.withWaitStrategy(WaitStrategies.fixedWait(backoff.getMillis(), TimeUnit.MILLISECONDS))
.withStopStrategy(StopStrategies.stopAfterDelay(timeout.getMillis(), TimeUnit.MILLISECONDS))
.retryIfException(AWSExceptions::isNotFound)
.build();
try {
return retryer.call(func);
} catch (RetryException e) {
if (Thread.interrupted()) {
throw new InterruptedException();
}
throw e;
}
}
@VisibleForTesting
static Duration getTimeout(DateTime timeout) {
DateTime now = DateTime.now();
if (timeout.isBefore(now)) {
return Duration.ZERO;
}
return new Interval(now, timeout).toDuration();
}
}
| apache-2.0 |
simonjupp/java-skos-api | skos-core/src/main/java/org/semanticweb/skos/properties/SKOSNarrowMatchProperty.java | 1321 | package org.semanticweb.skos.properties;
import org.semanticweb.skos.SKOSObjectProperty;
/*
* Copyright (C) 2007, University of Manchester
*
* Modifications to the initial code base are copyright of their
* respective authors, or their employers as appropriate. Authorship
* of the modifications may be determined from the ChangeLog placed at
* the end of this file.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library 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
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* Author: Simon Jupp<br>
* Date: Apr 21, 2008<br>
* The University of Manchester<br>
* Bio-Health Informatics Group<br>
*/
public interface SKOSNarrowMatchProperty extends SKOSObjectProperty {
}
| apache-2.0 |
citlab/vs.msc.ws14 | flink-0-7-custom/flink-core/src/main/java/org/apache/flink/api/common/InvalidProgramException.java | 1599 | /*
* 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.flink.api.common;
/**
* An exception thrown to indicate that the composed program is invalid. Examples of invalid programs are
* operations where crucial parameters are omitted, or functions where the input type and the type signature
* do not match.
*/
public class InvalidProgramException extends RuntimeException {
private static final long serialVersionUID = 3119881934024032887L;
/**
* Creates a new exception with no message.
*/
public InvalidProgramException() {
super();
}
/**
* Creates a new exception with the given message.
*
* @param message The exception message.
*/
public InvalidProgramException(String message) {
super(message);
}
public InvalidProgramException(String message, Throwable e) {
super(message, e);
}
}
| apache-2.0 |
blusechen/venus | venus-commons/venus-common-exception/src/main/java/com/meidusa/venus/exception/ServiceInactiveException.java | 715 | /**
*
*/
package com.meidusa.venus.exception;
import com.meidusa.venus.annotations.RemoteException;
import com.meidusa.venus.annotations.RemoteException.Level;
/**
* thrown when service not available.
*
* @author Sun Ning
* @since 2010-3-16
*/
@RemoteException(errorCode=VenusExceptionCodeConstant.SERVICE_INACTIVE_EXCEPTION,level=Level.ERROR)
public class ServiceInactiveException extends AbstractVenusException {
private static final long serialVersionUID = 1L;
public ServiceInactiveException(String msg) {
super("ServiceUnavailableException:" + msg);
}
@Override
public int getErrorCode() {
return VenusExceptionCodeConstant.SERVICE_INACTIVE_EXCEPTION;
}
}
| apache-2.0 |
eldevanjr/helianto | helianto-core/src/main/java/org/helianto/core/repository/PublicAddressRepository.java | 564 | package org.helianto.core.repository;
import java.io.Serializable;
import org.helianto.core.domain.Operator;
import org.helianto.core.domain.PublicAddress;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Public address repository.
*
* @author mauriciofernandesdecastro
*/
public interface PublicAddressRepository extends JpaRepository<PublicAddress, Serializable> {
/**
* Find by natural key.
*
* @param operator
* @param postalCode
*/
PublicAddress findByOperatorAndPostalCode(Operator operator, String postalCode);
}
| apache-2.0 |
lvweiwolf/poi-3.16 | src/testcases/org/apache/poi/ss/formula/ptg/TestUnionPtg.java | 1638 | /* ====================================================================
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.poi.ss.formula.ptg;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* Tests for {@link UnionPtg}.
*
* @author Daniel Noll (daniel at nuix dot com dot au)
*/
public final class TestUnionPtg extends AbstractPtgTestCase {
/**
* Tests reading a file containing this ptg.
*/
public void testReading() {
HSSFWorkbook workbook = loadWorkbook("UnionPtg.xls");
HSSFCell cell = workbook.getSheetAt(0).getRow(4).getCell(2);
assertEquals("Wrong cell value", 24.0, cell.getNumericCellValue(), 0.0);
assertEquals("Wrong cell formula", "SUM(A1:B2,B2:C3)", cell.getCellFormula());
}
}
| apache-2.0 |
ayyoob/carbon-device-mgt-plugins | components/device-mgt/org.wso2.carbon.device.mgt.mobile.impl/src/main/java/org/wso2/carbon/device/mgt/mobile/dao/impl/MobileOperationPropertyDAOImpl.java | 8567 | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.device.mgt.mobile.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.dao.MobileOperationPropertyDAO;
import org.wso2.carbon.device.mgt.mobile.dao.util.MobileDeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.mobile.dto.MobileOperationProperty;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Implementation of MobileOperationPropertyDAO.
*/
public class MobileOperationPropertyDAOImpl implements MobileOperationPropertyDAO {
private DataSource dataSource;
private static final Log log = LogFactory.getLog(MobileOperationPropertyDAOImpl.class);
public MobileOperationPropertyDAOImpl(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public boolean addMobileOperationProperty(MobileOperationProperty mblOperationProperty)
throws MobileDeviceManagementDAOException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = this.getConnection();
String createDBQuery =
"INSERT INTO AD_OPERATION_PROPERTY(OPERATION_ID, PROPERTY, VALUE) " +
"VALUES ( ?, ?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setInt(1, mblOperationProperty.getOperationId());
stmt.setString(2, mblOperationProperty.getProperty());
stmt.setString(3, mblOperationProperty.getValue());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Added a new MobileOperationProperty " + mblOperationProperty.getProperty() +
" to MDM database.");
}
}
} catch (SQLException e) {
String msg =
"Error occurred while adding mobile operation property to MBL_OPERATION_PROPERTY " +
"table";
log.error(msg, e);
throw new MobileDeviceManagementDAOException(msg, e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
}
return status;
}
@Override
public boolean updateMobileOperationProperty(
MobileOperationProperty mblOperationProperty)
throws MobileDeviceManagementDAOException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = this.getConnection();
String createDBQuery =
"UPDATE AD_OPERATION_PROPERTY SET VALUE = ? WHERE OPERATION_ID = ? AND " +
"PROPERTY = ?";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, mblOperationProperty.getValue());
stmt.setInt(2, mblOperationProperty.getOperationId());
stmt.setString(3, mblOperationProperty.getProperty());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Updated MobileOperationProperty " + mblOperationProperty.getProperty() +
" to MDM database.");
}
}
} catch (SQLException e) {
String msg =
"Error occurred while updating the mobile operation property in" +
" MBL_OPERATION_PROPERTY table.";
log.error(msg, e);
throw new MobileDeviceManagementDAOException(msg, e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
}
return status;
}
@Override
public boolean deleteMobileOperationProperties(int mblOperationId)
throws MobileDeviceManagementDAOException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = this.getConnection();
String deleteDBQuery =
"DELETE FROM AD_OPERATION_PROPERTY WHERE OPERATION_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setInt(1, mblOperationId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Deleted MobileOperationProperties of operation-id " +
mblOperationId +
" from MDM database.");
}
}
} catch (SQLException e) {
String msg =
"Error occurred while deleting MBL_OPERATION_PROPERTY entry with operation Id - ";
log.error(msg, e);
throw new MobileDeviceManagementDAOException(msg, e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
}
return status;
}
@Override
public MobileOperationProperty getMobileOperationProperty(int mblOperationId,
String property)
throws MobileDeviceManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
MobileOperationProperty mobileOperationProperty = null;
try {
conn = this.getConnection();
String selectDBQuery =
"SELECT OPERATION_ID, PROPERTY, VALUE FROM AD_OPERATION_PROPERTY WHERE " +
"OPERATION_ID = ? AND PROPERTY = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setInt(1, mblOperationId);
stmt.setString(2, property);
ResultSet resultSet = stmt.executeQuery();
if (resultSet.next()) {
mobileOperationProperty = new MobileOperationProperty();
mobileOperationProperty.setOperationId(resultSet.getInt(1));
mobileOperationProperty.setProperty(resultSet.getString(2));
mobileOperationProperty.setValue(resultSet.getString(3));
if (log.isDebugEnabled()) {
log.debug("Fetched MobileOperationProperty of Operation-id : " +
mblOperationId +
" Property : " + property + " from MDM database.");
}
}
} catch (SQLException e) {
String msg =
"Error occurred while fetching the mobile operation property of Operation_id : " +
mblOperationId + " and Property : " + property;
log.error(msg, e);
throw new MobileDeviceManagementDAOException(msg, e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
}
return mobileOperationProperty;
}
@Override
public List<MobileOperationProperty> getAllMobileOperationPropertiesOfOperation(
int mblOperationId) throws MobileDeviceManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
MobileOperationProperty mobileOperationProperty;
List<MobileOperationProperty> properties = new ArrayList<MobileOperationProperty>();
try {
conn = this.getConnection();
String selectDBQuery =
"SELECT OPERATION_ID, PROPERTY, VALUE FROM AD_OPERATION_PROPERTY WHERE " +
"OPERATION_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setInt(1, mblOperationId);
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
mobileOperationProperty = new MobileOperationProperty();
mobileOperationProperty.setOperationId(resultSet.getInt(1));
mobileOperationProperty.setProperty(resultSet.getString(2));
mobileOperationProperty.setValue(resultSet.getString(3));
properties.add(mobileOperationProperty);
}
if (log.isDebugEnabled()) {
log.debug("Fetched all MobileOperationProperties of Operation-id : " +
mblOperationId +
" from MDM database.");
}
} catch (SQLException e) {
String msg =
"Error occurred while fetching the mobile operation properties of Operation_id " +
mblOperationId;
log.error(msg, e);
throw new MobileDeviceManagementDAOException(msg, e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
}
return properties;
}
private Connection getConnection() throws MobileDeviceManagementDAOException {
try {
return dataSource.getConnection();
} catch (SQLException e) {
String msg = "Error occurred while obtaining a connection from the mobile device " +
"management metadata repository datasource.";
log.error(msg, e);
throw new MobileDeviceManagementDAOException(msg, e);
}
}
}
| apache-2.0 |
alibaba/fastjson | src/test/java/com/alibaba/json/bvt/JSONFieldDefaultValueTest.java | 6296 | package com.alibaba.json.bvt;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import junit.framework.TestCase;
public class JSONFieldDefaultValueTest extends TestCase {
public void test_default_value() throws Exception {
Model m = new Model();
String s = JSON.toJSONString(m);
System.out.println(s);
Model m2 = JSON.parseObject(s, Model.class);
assertEquals("string", m2.getString());
assertEquals(false, m2.getaBoolean());
assertEquals(true, m2.getaBoolean2().booleanValue());
assertEquals(0, m2.getAnInt());
assertEquals(888, m2.getInteger().intValue());
assertEquals(0, m2.getaShort());
assertEquals(88, m2.getaShort2().shortValue());
assertEquals('\u0000', m2.getaChar());
assertEquals('J', m2.getCharacter().charValue());
assertEquals(0, m2.getaByte());
assertEquals(8, m2.getaByte2().byteValue());
assertEquals(0, m2.getaLong());
assertEquals(8888, m2.getaLong2().longValue());
assertEquals("0.0", "" + m2.getaFloat());
assertEquals("8.8", "" + m2.getaFloat2());
assertEquals("0.0", "" + m2.getaDouble());
assertEquals("88.88", "" + m2.getaDouble2());
}
public void test_not_null() throws Exception {
Model m = new Model("test", true, 888, (short)88, 'J', (byte)8, 8888L, 8.8F, 88.88, false, 999, (short)99, 'C', (byte)9, 9999L, 9.9F, 99.99);
String s = JSON.toJSONString(m);
System.out.println(s);
Model m2 = JSON.parseObject(s, Model.class);
assertEquals("test", m2.getString());
assertEquals(true, m2.getaBoolean());
assertEquals(false, m2.getaBoolean2().booleanValue());
assertEquals(888, m2.getAnInt());
assertEquals(999, m2.getInteger().intValue());
assertEquals(88, m2.getaShort());
assertEquals(99, m2.getaShort2().shortValue());
assertEquals('J', m2.getaChar());
assertEquals('C', m2.getCharacter().charValue());
assertEquals(8, m2.getaByte());
assertEquals(9, m2.getaByte2().byteValue());
assertEquals(8888, m2.getaLong());
assertEquals(9999, m2.getaLong2().longValue());
assertEquals("8.8", "" + m2.getaFloat());
assertEquals("9.9", "" + m2.getaFloat2());
assertEquals("88.88", "" + m2.getaDouble());
assertEquals("99.99", "" + m2.getaDouble2());
}
public static class Model {
@JSONField(defaultValue = "string")
private String string;
@JSONField(defaultValue = "true") //shouldn't work
private boolean aBoolean;
@JSONField(defaultValue = "888") //shouldn't work
private int anInt;
@JSONField(defaultValue = "88") //shouldn't work
private short aShort;
@JSONField(defaultValue = "J") //shouldn't work
private char aChar;
@JSONField(defaultValue = "8") //shouldn't work
private byte aByte;
@JSONField(defaultValue = "8888") //shouldn't work
private long aLong;
@JSONField(defaultValue = "8.8") //shouldn't work
private float aFloat;
@JSONField(defaultValue = "88.88") //shouldn't work
private double aDouble;
@JSONField(defaultValue = "true")
private Boolean aBoolean2;
@JSONField(defaultValue = "888")
private Integer integer;
@JSONField(defaultValue = "88")
private Short aShort2;
@JSONField(defaultValue = "J")
private Character character;
@JSONField(defaultValue = "8")
private Byte aByte2;
@JSONField(defaultValue = "8888")
private Long aLong2;
@JSONField(defaultValue = "8.8")
private Float aFloat2;
@JSONField(defaultValue = "88.88")
private Double aDouble2;
public Model(String string, boolean aBoolean, int anInt, short aShort, char aChar,
byte aByte, long aLong, float aFloat, double aDouble,
Boolean aBoolean2, Integer integer, Short aShort2, Character character,
Byte aByte2, Long aLong2, Float aFloat2, Double aDouble2) {
this.string = string;
this.aBoolean = aBoolean;
this.anInt = anInt;
this.aShort = aShort;
this.aChar = aChar;
this.aByte = aByte;
this.aLong = aLong;
this.aFloat = aFloat;
this.aDouble = aDouble;
this.aBoolean2 = aBoolean2;
this.integer = integer;
this.aShort2 = aShort2;
this.character = character;
this.aByte2 = aByte2;
this.aLong2 = aLong2;
this.aFloat2 = aFloat2;
this.aDouble2 = aDouble2;
}
public Model() {
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public boolean getaBoolean() {
return aBoolean;
}
public void setaBoolean(boolean aBoolean) {
this.aBoolean = aBoolean;
}
public int getAnInt() {
return anInt;
}
public void setAnInt(int anInt) {
this.anInt = anInt;
}
public short getaShort() {
return aShort;
}
public void setaShort(short aShort) {
this.aShort = aShort;
}
public char getaChar() {
return aChar;
}
public void setaChar(char aChar) {
this.aChar = aChar;
}
public byte getaByte() {
return aByte;
}
public void setaByte(byte aByte) {
this.aByte = aByte;
}
public long getaLong() {
return aLong;
}
public void setaLong(long aLong) {
this.aLong = aLong;
}
public float getaFloat() {
return aFloat;
}
public void setaFloat(float aFloat) {
this.aFloat = aFloat;
}
public double getaDouble() {
return aDouble;
}
public void setaDouble(double aDouble) {
this.aDouble = aDouble;
}
public Boolean getaBoolean2() {
return aBoolean2;
}
public void setaBoolean2(Boolean aBoolean2) {
this.aBoolean2 = aBoolean2;
}
public Integer getInteger() {
return integer;
}
public void setInteger(Integer integer) {
this.integer = integer;
}
public Short getaShort2() {
return aShort2;
}
public void setaShort2(Short aShort2) {
this.aShort2 = aShort2;
}
public Character getCharacter() {
return character;
}
public void setCharacter(Character character) {
this.character = character;
}
public Byte getaByte2() {
return aByte2;
}
public void setaByte2(Byte aByte2) {
this.aByte2 = aByte2;
}
public Long getaLong2() {
return aLong2;
}
public void setaLong2(Long aLong2) {
this.aLong2 = aLong2;
}
public Float getaFloat2() {
return aFloat2;
}
public void setaFloat2(Float aFloat2) {
this.aFloat2 = aFloat2;
}
public Double getaDouble2() {
return aDouble2;
}
public void setaDouble2(Double aDouble2) {
this.aDouble2 = aDouble2;
}
}
}
| apache-2.0 |
Max2817/stolen-bike-android | app/src/main/java/com/majateam/bikespot/MainActivity.java | 24881 | package com.majateam.bikespot;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.akexorcist.googledirection.DirectionCallback;
import com.akexorcist.googledirection.GoogleDirection;
import com.akexorcist.googledirection.constant.TransportMode;
import com.akexorcist.googledirection.constant.Unit;
import com.akexorcist.googledirection.model.Direction;
import com.akexorcist.googledirection.model.Info;
import com.akexorcist.googledirection.util.DirectionConverter;
import com.crashlytics.android.Crashlytics;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.maps.android.clustering.ClusterItem;
import com.google.maps.android.clustering.ClusterManager;
import com.majateam.bikespot.helper.DateHelper;
import com.majateam.bikespot.helper.MapHelper;
import com.majateam.bikespot.model.Bike;
import com.majateam.bikespot.model.Dock;
import com.majateam.bikespot.provider.LocationProvider;
import com.majateam.bikespot.renderer.BikeRenderer;
import com.majateam.bikespot.service.LocationService;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.fabric.sdk.android.Fabric;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
public class MainActivity extends BaseActivity implements LocationProvider.LocationCallback, GoogleMap.OnMarkerClickListener, GoogleMap.OnMapClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String BIKES_LIST = "bikesList";
private static final String DOCKS_LIST = "docksList";
private static final int BIKES = 10;
private static final int DOCKS = 20;
private static final String CHOICE = "choice";
private static final String MENU_VISIBILITY = "menu_visibility";
private static final String CURRENT_LATITUDE = "currentLatitude";
private static final String CURRENT_LONGITUDE = "currentLongitude";
private static final int UNSAFE_SPOT = 30;
private static final int NEUTRAL_SPOT = 40;
private static final int LOADING_SPOT = 50;
private static final String SPOT = "spot";
private static final int NEUTRAL_DISTANCE = 300;
@Bind(R.id.sub_menu)
LinearLayout mSubMenu;
@Bind(R.id.display_choice)
TextView mDisplayChoice;
@Bind(R.id.show_choice_txt)
TextView mShowChoice;
@Bind(R.id.choice_icon)
ImageView mChoiceIcon;
@Bind(R.id.show_icon)
ImageView mShowIcon;
@Bind(R.id.bike_spot_status_layout)
LinearLayout mBikeSpotStatusLayout;
@Bind(R.id.bike_spot_status)
TextView mBikeSpotStatus;
@Bind(R.id.bike_spot_title)
TextView mBikeSpotTitle;
@Bind(R.id.bike_spot_description)
TextView mBikeSpotDescription;
@Bind(R.id.bike_spot_brand)
TextView mBikeSpotBrand;
@Bind(R.id.map_user_location)
FloatingActionButton mLocateUser;
@Bind(R.id.empty_container)
LinearLayout mEmptyContainer;
@Bind(R.id.empty_icon)
ImageView mEmptyIcon;
@Bind(R.id.empty_title)
TextView mEmptyTitle;
@Bind(R.id.empty_subtitle)
TextView mEmptySubtitle;
@Bind(R.id.container)
FrameLayout mContainer;
@Bind(R.id.wrapper_coordinator)
CoordinatorLayout mCoordinatorLayout;
private LocationProvider mLocationProvider;
private ArrayList<Bike> mBikes = null;
private ArrayList<Dock> mDocks = null;
private ArrayList<ClusterItem> mClusterItems = null;
private ClusterManager<ClusterItem> mClusterManager;
private int mChoice;
private double mCurrentLatitude;
private double mCurrentLongitude;
private List<Polyline> mPolylines;
private int mSpot = LOADING_SPOT;
private Marker mUserMarker = null;
private Circle mCircle = null;
private boolean mLocationHandledFirst = false;
private BikeRenderer mBikeRenderer;
Snackbar mSnackBar;
private boolean mInternetConnected = true;
private Integer mConnectivityStatus = null;
private Boolean mFirstTime;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
Fabric.with(this, new Crashlytics());
initEmptyContainer();
//set default choice
if(savedInstanceState != null) {
mCurrentLatitude = savedInstanceState.getDouble(CURRENT_LATITUDE);
mCurrentLongitude = savedInstanceState.getDouble(CURRENT_LONGITUDE);
mBikes = savedInstanceState.getParcelableArrayList(BIKES_LIST);
mDocks = savedInstanceState.getParcelableArrayList(DOCKS_LIST);
mChoice = savedInstanceState.getInt(CHOICE);
mSubMenu.setVisibility((savedInstanceState.getInt(MENU_VISIBILITY) == View.VISIBLE) ? View.VISIBLE : View.GONE);
setChoice();
mSpot = savedInstanceState.getInt(SPOT);
}else{
mChoice = BIKES;
mShowChoice.setText(com.majateam.bikespot.R.string.show_docks);
mDisplayChoice.setText(com.majateam.bikespot.R.string.bikes);
mChoiceIcon.setImageResource(R.drawable.ic_legend_stolen);
mShowIcon.setImageResource(R.drawable.ic_legend_dock);
mBikes = new ArrayList<>();
mDocks = new ArrayList<>();
}
//init polylines array
mPolylines = new ArrayList<>();
//First time the app is launched
mFirstTime = true;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(CHOICE, mChoice);
outState.putInt(MENU_VISIBILITY, mSubMenu.getVisibility());
outState.putInt(SPOT, mSpot);
outState.putDouble(CURRENT_LATITUDE, mCurrentLatitude);
outState.putDouble(CURRENT_LONGITUDE, mCurrentLongitude);
outState.putParcelableArrayList(BIKES_LIST, mBikes);
outState.putParcelableArrayList(DOCKS_LIST, mDocks);
if(mClusterManager != null) {
mClusterManager.clearItems();
}
}
@OnClick(R.id.card_view)
public void showPopup() {
mSubMenu.setVisibility((mSubMenu.getVisibility() == View.VISIBLE) ? View.GONE : View.VISIBLE);
}
@OnClick(R.id.show_choice)
public void showChoice() {
updateChoice();
showPopup();
removeDestination();
}
private void updateChoice(){
if(mChoice == BIKES){
mChoice = DOCKS;
mShowChoice.setText(com.majateam.bikespot.R.string.show_bikes);
mDisplayChoice.setText(com.majateam.bikespot.R.string.docks);
mChoiceIcon.setImageResource(R.drawable.ic_legend_dock);
mShowIcon.setImageResource(R.drawable.ic_legend_stolen);
}else{
mChoice = BIKES;
mShowChoice.setText(com.majateam.bikespot.R.string.show_docks);
mDisplayChoice.setText(com.majateam.bikespot.R.string.bikes);
mChoiceIcon.setImageResource(R.drawable.ic_legend_stolen);
mShowIcon.setImageResource(R.drawable.ic_legend_dock);
}
setClusterItems(mChoice);
}
private void setChoice(){
if(mChoice == BIKES){
mChoice = BIKES;
mShowChoice.setText(com.majateam.bikespot.R.string.show_docks);
mDisplayChoice.setText(com.majateam.bikespot.R.string.bikes);
mChoiceIcon.setImageResource(R.drawable.ic_legend_stolen);
mShowIcon.setImageResource(R.drawable.ic_legend_dock);
}else{
mChoice = DOCKS;
mShowChoice.setText(com.majateam.bikespot.R.string.show_bikes);
mDisplayChoice.setText(com.majateam.bikespot.R.string.docks);
mChoiceIcon.setImageResource(R.drawable.ic_legend_dock);
mShowIcon.setImageResource(R.drawable.ic_legend_stolen);
}
setClusterItems(mChoice);
}
private void setSpotStatus(){
// Get back the mutable Circle
if(mBikeSpotTitle.getVisibility() != View.VISIBLE) {
if (mSpot == UNSAFE_SPOT) {
mBikeSpotStatusLayout.setBackgroundResource(R.color.red);
mBikeSpotStatus.setText(R.string.bike_unsafe_spot);
} else if (mSpot == NEUTRAL_SPOT) {
mBikeSpotStatusLayout.setBackgroundResource(R.color.green);
mBikeSpotStatus.setText(R.string.bike_neutral_spot);
} else {
mBikeSpotStatusLayout.setBackgroundResource(R.color.grey);
mBikeSpotStatus.setText(R.string.loading);
}
}
if (mSpot == UNSAFE_SPOT) {
// Instantiates a new CircleOptions object and defines the center and radius
if(mCircle == null) {
// Instantiates a new CircleOptions object and defines the center and radius
CircleOptions circleOptions = new CircleOptions()
.center(new LatLng(mCurrentLatitude, mCurrentLongitude))
.radius(NEUTRAL_DISTANCE)
.strokeColor(ContextCompat.getColor(this, R.color.transparent))
.fillColor(ContextCompat.getColor(this, R.color.red_transparent)); // In meters
mCircle = getMap().addCircle(circleOptions);
}else{
mCircle.setCenter(new LatLng(mCurrentLatitude, mCurrentLongitude));
}
}else{
if(mCircle != null){
mCircle.remove();
}
}
}
private void initEmptyContainer() {
mEmptyIcon.setImageResource(R.drawable.ic_wifi_black_48dp);
mEmptyTitle.setText(R.string.empty_no_internet_connection);
mEmptySubtitle.setText(getString(R.string.empty_please_connect));
}
@Override
protected void onResume() {
super.onResume();
if(getConnectivityStatus(this) != TYPE_NOT_CONNECTED) {
mContainer.setVisibility(View.VISIBLE);
mEmptyContainer.setVisibility(View.GONE);
setSpotStatus();
if (mLocationProvider != null) {
mLocationProvider.connect();
if (mBikes == null || mBikes.size() == 0 || mDocks == null || mDocks.size() == 0) {
callData();
}
}
//
if(!mFirstTime && getMap() != null && mUserMarker != null) {
mUserMarker.remove();
mUserMarker = null;
}else{
mFirstTime = false;
}
}else{
mContainer.setVisibility(View.GONE);
mEmptyContainer.setVisibility(View.VISIBLE);
}
}
@Override
public boolean onMarkerClick(Marker marker) {
if(mChoice == DOCKS && !marker.getPosition().equals(new LatLng(mCurrentLatitude, mCurrentLongitude))) {
LatLng destPosition = marker.getPosition();
drawDestination(destPosition, marker);
}else if(mChoice == BIKES && !marker.getPosition().equals(new LatLng(mCurrentLatitude, mCurrentLongitude))){
marker.showInfoWindow();
if (mBikeRenderer != null) {
HashMap<String, ClusterItem> clusterItemMarkerMap = mBikeRenderer.getmMarkerClusterItemMap();
Bike bike = (Bike) clusterItemMarkerMap.get(marker.getId());
if (bike != null) {
mBikeSpotTitle.setVisibility(View.VISIBLE);
mBikeSpotTitle.setText(bike.getTitle());
mBikeSpotDescription.setVisibility(View.VISIBLE);
mBikeSpotDescription.setText(bike.getDescription());
mBikeSpotBrand.setVisibility(View.VISIBLE);
String brand = getString(R.string.brand) + " : " + bike.getBrand();
mBikeSpotBrand.setText(brand);
mBikeSpotStatus.setVisibility(View.GONE);
mLocateUser.setVisibility(View.GONE);
mBikeSpotStatusLayout.setBackgroundResource(R.color.green);
}
}
}else{
removeDestination();
hideMarkerInfo();
}
return true;
}
private void drawDestination(LatLng destination, final Marker marker){
//if it already exists a polyline we remove it
removeDestination();
//Then we draw the new polyline and display it
String serverKey = "AIzaSyDNtlRTiYN4cNhjmO3Zzzghg0I7mV5i9bc";
LatLng origin = new LatLng(mCurrentLatitude, mCurrentLongitude);
GoogleDirection.withServerKey(serverKey)
.from(origin)
.to(destination)
.transportMode(TransportMode.BICYCLING)
.unit(Unit.METRIC)
.execute(new DirectionCallback() {
@Override
public void onDirectionSuccess(Direction direction) {
// Do something here
//String status = direction.getStatus();
Info durationInfo = direction.getRouteList().get(0).getLegList().get(0).getDuration();
marker.setTitle(durationInfo.getText());
marker.showInfoWindow();
if (direction.isOK()) {
ArrayList<LatLng> directionPositionList = direction.getRouteList().get(0).getLegList().get(0).getDirectionPoint();
PolylineOptions polylineOptions = DirectionConverter.createPolyline(MainActivity.this, directionPositionList, 5, Color.BLACK);
GoogleMap map = getMap();
LatLngBounds.Builder builder = new LatLngBounds.Builder();
mPolylines.add(map.addPolyline(polylineOptions));
for (LatLng latLng : polylineOptions.getPoints()) {
builder.include(latLng);
}
LatLngBounds bounds = builder.build();
map.animateCamera(CameraUpdateFactory.newLatLng(bounds.getCenter()));
}
Log.v(TAG, "direction is ok : " + direction.isOK());
}
@Override
public void onDirectionFailure(Throwable t) {
// Do something here
}
});
}
private void removeDestination(){
if(mPolylines.size() > 0) {
for (Polyline line : mPolylines) {
line.remove();
}
mPolylines.clear();
}
}
@Override
protected void startApp() {
GoogleMap map = getMap();
if(mLocationProvider == null)
mLocationProvider = new LocationProvider(this, this);
if(mClusterManager == null)
mClusterManager = new ClusterManager<>(this, map);
if(mBikeRenderer == null)
mBikeRenderer = new BikeRenderer(getApplicationContext(), map, mClusterManager);
mClusterManager.setRenderer(mBikeRenderer);
map.setOnCameraChangeListener(mClusterManager);
map.setOnMarkerClickListener(this);
map.setOnMapClickListener(this);
//commented code used with Android emulator, uncomment to use it
//setFalseUserLocation();
callData();
}
private void callData(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Global.ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.build();
final LocationService service = retrofit.create(LocationService.class);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1); // to get previous year add -1
Call<List<Bike>> callBikes = service.listBikes(Global.BIKES_URL, String.valueOf(cal.getTime().getTime()/1000));
callBikes.enqueue(new Callback<List<Bike>>() {
@Override
public void onResponse(Response<List<Bike>> response, Retrofit retrofit) {
if (response.body() != null) {
mBikes.clear();
mBikes.addAll(response.body());
}
Call<List<Dock>> callDocks = service.listDocks(Global.DOCKS_URL);
callDocks.enqueue(new Callback<List<Dock>>() {
@Override
public void onResponse(Response<List<Dock>> response, Retrofit retrofit) {
if (response.body() != null) {
mDocks.clear();
mDocks.addAll(response.body());
}
setClusterItems(mChoice);
//Update location if we get the data after the location is handled
if (mLocationHandledFirst) {
mLocationProvider.callNewLocation();
mLocationHandledFirst = false;
}
}
@Override
public void onFailure(Throwable t) {
// you should handle errors, too
}
});
}
@Override
public void onFailure(Throwable t) {
// you should handle errors, too
}
});
}
/**
* False user location used only for android emulator
*/
private void setFalseUserLocation(){
mCurrentLatitude = 45.5486;
mCurrentLongitude = -73.5788;
GoogleMap map = getMap();
LatLng latLng = new LatLng(mCurrentLatitude, mCurrentLongitude);
MarkerOptions options = new MarkerOptions().position(latLng)
.icon(BitmapDescriptorFactory.fromResource(com.majateam.bikespot.R.drawable.ic_user_location));
mUserMarker = map.addMarker(options);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mCurrentLatitude, mCurrentLongitude), 15.0f));
}
private void setClusterItems(int type) {
if(mClusterManager == null){
GoogleMap map = getMap();
mClusterManager = new ClusterManager<>(this, map);
mBikeRenderer = new BikeRenderer(getApplicationContext(), map, mClusterManager);
mClusterManager.setRenderer(mBikeRenderer);
map.setOnCameraChangeListener(mClusterManager);
}
mClusterManager.clearItems();
if(mClusterItems == null){
mClusterItems = new ArrayList<>();
}else{
mClusterItems.clear();
}
if (type == BIKES && mBikes != null) {
mClusterItems.addAll(mBikes);
}else if(mDocks != null){
mClusterItems.addAll(mDocks);
}
if(mClusterItems != null && mClusterItems.size() > 0){
mClusterManager.addItems(mClusterItems);
}
mClusterManager.cluster();
}
@Override
protected void onPause() {
super.onPause();
mLocationProvider.disconnect();
}
public void handleNewLocation(Location location) {
mCurrentLatitude = location.getLatitude();
mCurrentLongitude = location.getLongitude();
LatLng latLng = new LatLng(mCurrentLatitude, mCurrentLongitude);
GoogleMap map = getMap();
if(mUserMarker == null){
MarkerOptions options = new MarkerOptions().position(latLng)
.icon(BitmapDescriptorFactory.fromResource(com.majateam.bikespot.R.drawable.ic_user_location));
mUserMarker = map.addMarker(options);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mCurrentLatitude, mCurrentLongitude), 15.0f));
}else{
mUserMarker.setPosition(latLng);
}
//check if there is any recent stolen bike (< 6 months) around me 300m
if(mChoice == BIKES){
if(mBikes != null && mBikes.size() > 0) {
long todayMinusSixMonths = DateHelper.getDateMonthsAgo(6).getTime();
mSpot = NEUTRAL_SPOT;
for (Bike bike : mBikes) {
if (bike.getRawDate()*1000 >= todayMinusSixMonths && MapHelper.distFrom((float) mCurrentLatitude, (float) mCurrentLongitude, Float.valueOf(bike.getLat()), Float.valueOf(bike.getLng())) <= NEUTRAL_DISTANCE) {
mSpot = UNSAFE_SPOT;
break;
}
}
setSpotStatus();
}else{
if(mCircle != null){
mCircle.remove();
}
mLocationHandledFirst = true;
}
}
}
@OnClick(R.id.map_user_location)
public void showUserLocation() {
GoogleMap map = getMap();
if(map != null) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mCurrentLatitude, mCurrentLongitude), 15.0f));
}
}
public void onRequestPermissionsResult(int requestCode,
String[] permissions,
int[] grantResults) {
if(mLocationProvider != null){
mLocationProvider.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
@Override
public void onMapClick(LatLng latLng) {
removeDestination();
hideMarkerInfo();
}
private void hideMarkerInfo(){
if(mBikeSpotTitle.getVisibility() == View.VISIBLE){
mBikeSpotTitle.setVisibility(View.GONE);
mBikeSpotDescription.setVisibility(View.GONE);
mBikeSpotBrand.setVisibility(View.GONE);
mBikeSpotStatus.setVisibility(View.VISIBLE);
mLocateUser.setVisibility(View.VISIBLE);
setSpotStatus();
}
}
@Override
protected void setSnackbarMessage() {
String internetStatus;
int connectionStatusCode = getConnectivityStatus(this);
if (connectionStatusCode != TYPE_NOT_CONNECTED) {
internetStatus = getString(R.string.internet_connected);
} else {
internetStatus = getString(R.string.lost_internet_connection);
}
mSnackBar = Snackbar
.make(mCoordinatorLayout, internetStatus, Snackbar.LENGTH_LONG)
.setAction("X", new View.OnClickListener() {
@Override
public void onClick(View view) {
mSnackBar.dismiss();
}
});
// Changing message text color
mSnackBar.setActionTextColor(Color.BLACK);
// Changing action button text color
View sbView = mSnackBar.getView();
sbView.setBackgroundColor(ContextCompat.getColor(this, android.R.color.white));
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.BLACK);
if (connectionStatusCode == TYPE_NOT_CONNECTED) {
if (mInternetConnected) {
mSnackBar.show();
mInternetConnected = false;
}
} else {
if (!mInternetConnected) {
mInternetConnected = true;
mSnackBar.show();
}
}
}
@Override
protected void onNetworkConnectionUpdated(Integer connectivityCode){
if (mConnectivityStatus != null && mConnectivityStatus == TYPE_NOT_CONNECTED && connectivityCode != TYPE_NOT_CONNECTED && mEmptyContainer.getVisibility() == View.VISIBLE) {
//refresh if we are now connected
onResume();
}
mConnectivityStatus = connectivityCode;
}
}
| apache-2.0 |
futureskywei/whale | src/main/java/com/jy/common/utils/echarts/data/RangeData.java | 3698 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.jy.common.utils.echarts.data;
import java.io.Serializable;
/**
* 描述信息
*
*
* @since 2015-06-29
*/
public class RangeData implements Serializable {
private static final long serialVersionUID = 1L;
private Integer start;
private Integer end;
private String label;
private Object color;
/**
* 构造函数
*/
public RangeData() {
}
/**
* 构造函数,参数:start,end
*
* @param start
* @param end
*/
public RangeData(Integer start, Integer end) {
this.start = start;
this.end = end;
}
/**
* 设置start值
*
* @param start
*/
public RangeData start(Integer start) {
this.start = start;
return this;
}
/**
* 获取start值
*/
public Integer start() {
return this.start;
}
/**
* 设置end值
*
* @param end
*/
public RangeData end(Integer end) {
this.end = end;
return this;
}
/**
* 获取end值
*/
public Integer end() {
return this.end;
}
/**
* 设置label值
*
* @param label
*/
public RangeData label(String label) {
this.label = label;
return this;
}
/**
* 获取label值
*/
public String label() {
return this.label;
}
/**
* 设置color值
*
* @param color
*/
public RangeData color(Object color) {
this.color = color;
return this;
}
/**
* 获取color值
*/
public Object color() {
return this.color;
}
/**
* 获取start值
*/
public Integer getStart() {
return start;
}
/**
* 设置start值
*
* @param start
*/
public void setStart(Integer start) {
this.start = start;
}
/**
* 获取end值
*/
public Integer getEnd() {
return end;
}
/**
* 设置end值
*
* @param end
*/
public void setEnd(Integer end) {
this.end = end;
}
/**
* 获取label值
*/
public String getLabel() {
return label;
}
/**
* 设置label值
*
* @param label
*/
public void setLabel(String label) {
this.label = label;
}
/**
* 获取color值
*/
public Object getColor() {
return color;
}
/**
* 设置color值
*
* @param color
*/
public void setColor(Object color) {
this.color = color;
}
}
| apache-2.0 |
vovagrechka/fucking-everything | phizdets/phizdets-idea/eclipse-src/org.eclipse.php.ui/src/org/eclipse/php/internal/ui/editor/contentassist/PHPCompletionProposalLabelProvider.java | 14700 | /*******************************************************************************
* Copyright (c) 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Zend Technologies
*******************************************************************************/
package org.eclipse.php.internal.ui.editor.contentassist;
import org.eclipse.core.runtime.Assert;
import org.eclipse.dltk.core.*;
import org.eclipse.dltk.internal.core.ArchiveProjectFragment;
import org.eclipse.dltk.ui.DLTKPluginImages;
import org.eclipse.dltk.ui.ScriptElementLabels;
import org.eclipse.dltk.ui.text.completion.CompletionProposalLabelProvider;
import org.eclipse.dltk.ui.text.completion.ICompletionProposalLabelProviderExtension;
import org.eclipse.dltk.ui.text.completion.ScriptCompletionProposalCollector;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.php.core.compiler.IPHPModifiers;
import org.eclipse.php.core.compiler.PHPFlags;
import org.eclipse.php.core.compiler.ast.nodes.NamespaceReference;
import org.eclipse.php.internal.core.codeassist.AliasField;
import org.eclipse.php.internal.core.codeassist.AliasMethod;
import org.eclipse.php.internal.core.codeassist.AliasType;
import org.eclipse.php.internal.core.typeinference.FakeConstructor;
import org.eclipse.php.internal.ui.Logger;
import org.eclipse.php.internal.ui.PHPUiPlugin;
import org.eclipse.php.internal.ui.preferences.PreferenceConstants;
import org.eclipse.php.internal.ui.util.PHPModelLabelProvider;
import org.eclipse.php.ui.PHPElementLabels;
public class PHPCompletionProposalLabelProvider extends CompletionProposalLabelProvider
implements ICompletionProposalLabelProviderExtension {
private static final PHPModelLabelProvider fLabelProvider = new PHPModelLabelProvider();
private static final String ENCLOSING_TYPE_SEPARATOR = String.valueOf(NamespaceReference.NAMESPACE_SEPARATOR);
@Override
protected String createMethodProposalLabel(CompletionProposal methodProposal) {
return createStyledMethodProposalLabel(methodProposal).toString();
}
@Override
protected String createOverrideMethodProposalLabel(CompletionProposal methodProposal) {
return createStyledOverrideMethodProposalLabel(methodProposal).toString();
}
protected StyledString createStyledOverrideMethodProposalLabel(CompletionProposal methodProposal) {
StyledString nameBuffer = new StyledString();
IMethod method = (IMethod) methodProposal.getModelElement();
if (method instanceof FakeConstructor && method.getParent() instanceof AliasType) {
AliasType aliasType = (AliasType) method.getParent();
nameBuffer.append(aliasType.getAlias());
} else if (method instanceof AliasMethod) {
AliasMethod aliasMethod = (AliasMethod) method;
nameBuffer.append(aliasMethod.getAlias());
} else {
nameBuffer.append(method.getElementName());
}
// parameters
nameBuffer.append('(');
appendStyledParameterList(nameBuffer, methodProposal);
nameBuffer.append(')'); // $NON-NLS-1$
appendMethodType(nameBuffer, methodProposal);
appendQualifier(nameBuffer, method.getParent());
return nameBuffer;
}
protected void appendMethodType(StyledString nameBuffer, CompletionProposal methodProposal) {
if (showMethodReturnType()) {
IMethod method = (IMethod) methodProposal.getModelElement();
if (method instanceof AliasMethod) {
method = (IMethod) ((AliasMethod) method).getMethod();
}
if (method == null) {
return;
}
try {
if (method.isConstructor() || !method.exists()) {
return;
}
nameBuffer.append(getReturnTypeSeparator(), StyledString.DECORATIONS_STYLER);
if (PHPFlags.isNullable(method.getFlags())) {
nameBuffer.append("?", StyledString.DECORATIONS_STYLER); //$NON-NLS-1$
}
String type = method.getType();
if (type == null) {
if ((method.getFlags() & IPHPModifiers.AccReturn) != 0) {
type = "mixed"; //$NON-NLS-1$
} else {
type = "void"; //$NON-NLS-1$
}
}
nameBuffer.append(type, StyledString.DECORATIONS_STYLER);
} catch (ModelException e) {
Logger.logException(e);
}
}
}
protected void appendFieldType(StyledString nameBuffer, CompletionProposal methodProposal) {
IField element = (IField) methodProposal.getModelElement();
if (element instanceof AliasField) {
element = (IField) ((AliasField) element).getField();
}
if (element == null) {
return;
}
try {
if (!element.exists()) {
return;
}
String type = element.getType();
if (type != null) {
nameBuffer.append(getReturnTypeSeparator(), StyledString.DECORATIONS_STYLER);
nameBuffer.append(type, StyledString.DECORATIONS_STYLER);
}
} catch (ModelException e) {
Logger.logException(e);
}
}
private boolean showMethodReturnType() {
return PHPUiPlugin.getDefault().getPreferenceStore()
.getBoolean(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE);
}
@Override
public String createTypeProposalLabel(CompletionProposal typeProposal) {
return createStyledTypeProposalLabel(typeProposal).toString();
}
protected String createLabelWithTypeAndDeclaration(CompletionProposal proposal) {
StringBuilder nameBuffer = new StringBuilder();
nameBuffer.append(proposal.getName());
IField field = (IField) proposal.getModelElement();
if (field.getParent() != null) {
nameBuffer.append(" - "); //$NON-NLS-1$
IModelElement parent = field.getParent();
nameBuffer.append(parent.getElementName());
}
return nameBuffer.toString();
}
@Override
protected String createTypeProposalLabel(String fullName) {
return super.createTypeProposalLabel(fullName);
}
@Override
public ImageDescriptor createImageDescriptor(CompletionProposal proposal) {
if (proposal.getModelElement() instanceof ArchiveProjectFragment) {
return DLTKPluginImages.DESC_OBJS_JAR;
}
ImageDescriptor imageDescriptor = fLabelProvider.getImageDescriptor(proposal.getModelElement(),
PHPModelLabelProvider.DEFAULT_IMAGEFLAGS);
if (imageDescriptor != null) {
return imageDescriptor;
}
return super.createImageDescriptor(proposal);
}
@Override
public ImageDescriptor createTypeImageDescriptor(CompletionProposal proposal) {
ImageDescriptor imageDescriptor = fLabelProvider.getImageDescriptor(proposal.getModelElement(),
PHPModelLabelProvider.DEFAULT_IMAGEFLAGS);
if (imageDescriptor != null) {
return imageDescriptor;
}
return super.createTypeImageDescriptor(proposal);
}
@Override
public String createFieldProposalLabel(CompletionProposal proposal) {
return createStyledFieldProposalLabel(proposal).toString();
}
@Override
public ImageDescriptor createFieldImageDescriptor(CompletionProposal proposal) {
ImageDescriptor imageDescriptor = fLabelProvider.getImageDescriptor(proposal.getModelElement(),
PHPModelLabelProvider.DEFAULT_IMAGEFLAGS);
if (imageDescriptor != null) {
return imageDescriptor;
}
return super.createFieldImageDescriptor(proposal);
}
@Override
public ImageDescriptor createMethodImageDescriptor(CompletionProposal proposal) {
ImageDescriptor imageDescriptor = fLabelProvider.getImageDescriptor(proposal.getModelElement(),
PHPModelLabelProvider.DEFAULT_IMAGEFLAGS);
if (imageDescriptor != null) {
return imageDescriptor;
}
return super.createMethodImageDescriptor(proposal);
}
@Override
public StyledString createStyledFieldProposalLabel(CompletionProposal proposal) {
StyledString buffer = new StyledString();
if (proposal.getModelElement() instanceof AliasField) {
AliasField aliasField = (AliasField) proposal.getModelElement();
buffer.append(aliasField.getAlias());
} else {
buffer.append(proposal.getName());
}
IModelElement element = proposal.getModelElement();
if (element != null && element.getElementType() == IModelElement.FIELD) {
appendFieldType(buffer, proposal);
if (!proposal.getName().startsWith("$")) { //$NON-NLS-1$
appendQualifier(buffer, element.getParent());
}
}
return buffer;
}
@Override
public StyledString createStyledLabel(CompletionProposal proposal) {
switch (proposal.getKind()) {
case CompletionProposal.METHOD_NAME_REFERENCE:
case CompletionProposal.METHOD_REF:
case CompletionProposal.POTENTIAL_METHOD_DECLARATION:
return createStyledMethodProposalLabel(proposal);
case CompletionProposal.METHOD_DECLARATION:
return createStyledOverrideMethodProposalLabel(proposal);
case CompletionProposal.TYPE_REF:
return createStyledTypeProposalLabel(proposal);
case CompletionProposal.FIELD_REF:
return createStyledFieldProposalLabel(proposal);
case CompletionProposal.LOCAL_VARIABLE_REF:
case CompletionProposal.VARIABLE_DECLARATION:
return createStyledSimpleLabelWithType(proposal);
case CompletionProposal.KEYWORD:
return createStyledKeywordLabel(proposal);
case CompletionProposal.PACKAGE_REF:
case CompletionProposal.LABEL_REF:
return createStyledSimpleLabel(proposal);
default:
Assert.isTrue(false);
return null;
}
}
protected StyledString createStyledMethodProposalLabel(CompletionProposal methodProposal) {
StyledString nameBuffer = new StyledString();
boolean isAlias = methodProposal.getModelElement() instanceof AliasMethod;
// method name
if (isAlias) {
AliasMethod aliasMethod = (AliasMethod) methodProposal.getModelElement();
nameBuffer.append(aliasMethod.getAlias());
} else {
nameBuffer.append(methodProposal.getName());
}
// parameters
nameBuffer.append('(');
appendStyledParameterList(nameBuffer, methodProposal);
nameBuffer.append(')');
appendMethodType(nameBuffer, methodProposal);
if (isAlias) {
return nameBuffer;
}
IModelElement method = methodProposal.getModelElement();
appendQualifier(nameBuffer, method.getParent());
return nameBuffer;
}
protected StyledString appendStyledParameterList(StyledString buffer, CompletionProposal methodProposal) {
String[] parameterNames = methodProposal.findParameterNames(null);
IMethod method = (IMethod) methodProposal.getModelElement();
if (method instanceof AliasMethod) {
method = (IMethod) ((AliasMethod) method).getMethod();
}
IParameter[] parameters = null;
boolean isVariadic = false;
try {
if (method != null) {
parameters = method.getParameters();
if (PHPFlags.isVariadic(method.getFlags())) {
isVariadic = true;
}
}
} catch (ModelException e) {
Logger.logException(e);
}
if (parameterNames != null) {
final Integer paramLimit = (Integer) methodProposal
.getAttribute(ScriptCompletionProposalCollector.ATTR_PARAM_LIMIT);
if (paramLimit != null) {
for (int i = 0; i < parameterNames.length; i++) {
if (i >= paramLimit.intValue()) {
break;
}
if (i > 0) {
buffer.append(',');
buffer.append(' ');
}
if (parameters != null && i < parameters.length && PHPFlags.isReference(parameters[i].getFlags())) {
buffer.append(PHPElementLabels.REFERENCE_STRING);
}
if (isVariadic && i + 1 == parameterNames.length) {
buffer.append(ScriptElementLabels.ELLIPSIS_STRING); // $NON-NLS-1$
}
buffer.append(parameterNames[i]);
}
return buffer;
}
}
return appendStyledParameterSignature(buffer, parameterNames, parameters, isVariadic);
}
protected StyledString appendStyledParameterSignature(StyledString buffer, String[] parameterNames,
IParameter[] parameters, boolean isVariadic) {
if (parameterNames != null) {
for (int i = 0; i < parameterNames.length; i++) {
if (i > 0) {
buffer.append(',');
buffer.append(' ');
}
if (parameters != null && i < parameters.length && PHPFlags.isReference(parameters[i].getFlags())) {
buffer.append(PHPElementLabels.REFERENCE_STRING);
}
if (isVariadic && i + 1 == parameterNames.length) {
buffer.append(ScriptElementLabels.ELLIPSIS_STRING);
}
buffer.append(parameterNames[i]);
}
}
return buffer;
}
@Override
public String createLabel(CompletionProposal proposal) {
return createStyledLabel(proposal).toString();
}
@Override
public StyledString createStyledKeywordLabel(CompletionProposal proposal) {
return new StyledString(proposal.getName());
}
@Override
public StyledString createStyledSimpleLabel(CompletionProposal proposal) {
return new StyledString(proposal.getName());
}
@Override
public StyledString createStyledTypeProposalLabel(CompletionProposal typeProposal) {
StyledString nameBuffer = new StyledString();
IType type = (IType) typeProposal.getModelElement();
if (type instanceof AliasType) {
AliasType aliasType = (AliasType) type;
nameBuffer.append(aliasType.getAlias());
} else {
nameBuffer.append(typeProposal.getName());
}
boolean isNamespace = false;
try {
isNamespace = PHPFlags.isNamespace(type.getFlags());
} catch (ModelException e) {
Logger.logException(e);
}
if (!isNamespace) {
appendQualifier(nameBuffer, type);
if (type.getParent() != null) {
nameBuffer.append(" - ", StyledString.DECORATIONS_STYLER); //$NON-NLS-1$
nameBuffer.append(type.getParent().getElementName(), StyledString.QUALIFIER_STYLER);
}
}
return nameBuffer;
}
@Override
public StyledString createStyledSimpleLabelWithType(CompletionProposal proposal) {
StyledString buffer = new StyledString(proposal.getName());
IModelElement element = proposal.getModelElement();
if (element != null && element.getElementType() == IModelElement.LOCAL_VARIABLE && element.exists()) {
final ILocalVariable var = (ILocalVariable) element;
String type = var.getType();
if (type != null) {
buffer.append(getReturnTypeSeparator(), StyledString.DECORATIONS_STYLER);
buffer.append(type, StyledString.QUALIFIER_STYLER);
}
}
return buffer;
}
@Override
protected String createSimpleLabelWithType(CompletionProposal proposal) {
return createStyledSimpleLabelWithType(proposal).toString();
}
protected void appendQualifier(StyledString buffer, IModelElement modelElement) {
if (modelElement == null) {
return;
}
buffer.append(" - ", StyledString.QUALIFIER_STYLER); //$NON-NLS-1$
if (modelElement instanceof IType) {
IType type = (IType) modelElement;
buffer.append(type.getTypeQualifiedName(ENCLOSING_TYPE_SEPARATOR), StyledString.QUALIFIER_STYLER); // $NON-NLS-1$
} else {
buffer.append(modelElement.getElementName(), StyledString.QUALIFIER_STYLER);
}
}
}
| apache-2.0 |
TheTemportalist/CountryGamer_PEforPC | Blocks/BlockNetherCore.java | 11127 | package CountryGamer_PEforPC.Blocks;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityMobSpawner;
import net.minecraft.util.Icon;
import net.minecraft.world.World;
import CountryGamer_Core.Blocks.BlockContainerBase;
import CountryGamer_PEforPC.PEforPC;
import CountryGamer_PEforPC.Blocks.TileEnt.TileEntityReactor;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class BlockNetherCore extends BlockContainerBase {
public static int maximumCharge = 5;// 45;
public BlockNetherCore(int id, Material mat, String modid, String name) {
super(id, mat, modid, name);
this.setResistance(4000.0F);
}
@SideOnly(Side.CLIENT)
private Icon[] icons;
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister iconRegister) {
this.icons = new Icon[3];
String textureName = this.getUnlocalizedName().substring(
this.getUnlocalizedName().indexOf(".") + 1);
this.icons[1] = iconRegister.registerIcon(this.modid + ":"
+ textureName + "_Full");
this.icons[2] = iconRegister.registerIcon(this.modid + ":"
+ textureName + "_Active");
this.icons[0] = iconRegister.registerIcon(this.modid + ":"
+ textureName + "_Drained");
}
@SideOnly(Side.CLIENT)
/**
* @param side
* @param metadata
*/
public Icon getIcon(int side, int metadata) {
if (metadata < 0)
metadata = 0;
if (metadata == 0) // Drained
return this.icons[0];
else if (metadata == BlockNetherCore.maximumCharge + 1) // Active
return this.icons[2];
else
// Between 0 & MaxCharge; Charged
return this.icons[1];
}
public int damageDropped(int meta) {
return 1;
}
public void onBlockDestroyedByPlayer(World world, int x, int y, int z,
int meta) {
TileEntity tEnt = world.getBlockTileEntity(x, y, z);
if (tEnt instanceof TileEntityReactor) {
TileEntityReactor tileEnt = (TileEntityReactor) tEnt;
if (meta > BlockNetherCore.maximumCharge) {
super.onBlockDestroyedByPlayer(world, x, y, x, tileEnt.charge);
}
}
}
public TileEntity createNewTileEntity(World world) {
return new TileEntityReactor();
}
private void setBlockNew(World world, int coreX, int coreY, int coreZ,
int x, int y, int z, int blockiD) {
this.setBlockMetaWithNotifyNew(world, coreX, coreY, coreZ, x, y, z,
blockiD, 0, 3);
}
private void setBlockMetaWithNotifyNew(World world, int coreX, int coreY,
int coreZ, int x, int y, int z, int blockiD, int meta, int flag) {
Random rand = new Random();
boolean degrate = rand.nextInt(100) % 5 == 0;
if (degrate) {
TileEntity tEnt = world.getBlockTileEntity(coreX, coreY, coreZ);
if (tEnt != null) {
if (tEnt instanceof TileEntityReactor) {
// PEforPC.log.info("Setting Degration");
((TileEntityReactor) tEnt).setBlockDegrate(x, y, z);
}
} else {
// PEforPC.log.info("No Tile Ent");
}
}
world.setBlock(x, y, z, blockiD, meta, flag);
}
public boolean onBlockActivated(World world, int x, int y, int z,
EntityPlayer player, int side, float par7, float par8, float par9) {
if (!world.isRemote) {
if (player.isSneaking())
return false;
TileEntity tEnt = world.getBlockTileEntity(x, y, z);
if (tEnt instanceof TileEntityReactor) {
TileEntityReactor tileEnt = (TileEntityReactor) tEnt;
if (world.getBlockMetadata(x, y, z) <= 0)
tileEnt.isExhausted = true;
PEforPC.log.info("isActive: " + tileEnt.isActive);
PEforPC.log.info("isExhausted: " + tileEnt.isExhausted);
if (!tileEnt.isActive && !tileEnt.isExhausted) {
if (this.structureCheck(world, x, y, z)) {
PEforPC.log.info("Making Spire");
this.createSpire(world, x, y, z);
tileEnt.isActive = true;
return true;
}
}
}
}
return false;
}
private boolean structureCheck(World world, int x, int y, int z) {
int cobble = Block.cobblestone.blockID;
int gold = Block.blockGold.blockID;
boolean bottomGold = world.getBlockId(x - 1, y - 1, z - 1) == gold
&& world.getBlockId(x + 1, y - 1, z - 1) == gold
&& world.getBlockId(x - 1, y - 1, z + 1) == gold
&& world.getBlockId(x + 1, y - 1, z + 1) == gold;
boolean cobble1 = world.getBlockId(x - 1, y - 1, z - 0) == cobble
&& world.getBlockId(x - 0, y - 1, z - 1) == cobble
&& world.getBlockId(x + 1, y - 1, z - 0) == cobble
&& world.getBlockId(x - 0, y - 1, z + 1) == cobble
&& world.getBlockId(x - 0, y - 1, z - 0) == cobble;
boolean cobble2 = world.getBlockId(x - 1, y - 0, z - 1) == cobble
&& world.getBlockId(x + 1, y - 0, z - 1) == cobble
&& world.getBlockId(x - 1, y - 0, z + 1) == cobble
&& world.getBlockId(x + 1, y - 0, z + 1) == cobble;
boolean cobble3 = world.getBlockId(x - 1, y + 1, z - 0) == cobble
&& world.getBlockId(x - 0, y + 1, z - 1) == cobble
&& world.getBlockId(x + 1, y + 1, z - 0) == cobble
&& world.getBlockId(x - 0, y + 1, z + 1) == cobble
&& world.getBlockId(x - 0, y + 1, z - 0) == cobble;
return bottomGold && cobble1 && cobble2 && cobble3;
}
private void createSpire(World world, int x, int y, int z) {
int block = Block.netherrack.blockID;
int radiusFromCore = 7;
int baseofSpire = y - 2;
int spireBoxHeight = 1 + 5 + 1 + 5;// floor+4+floor+4+spire
// hollow it out
this.spireHollowInterior(world, x, z, baseofSpire, radiusFromCore, y
+ spireBoxHeight + 40);
// floors of spire
this.spireFloor(world, x, y, z, baseofSpire, block, radiusFromCore);
this.spireFloor(world, x, y, z, baseofSpire + 6, block, radiusFromCore);
this.spireFloor(world, x, y, z, baseofSpire + 12, block, radiusFromCore);
// ~~~~~~~~~~~~~~~
// Walls
// +X
int wallX = x + radiusFromCore + 1;
for (int j = baseofSpire; j <= baseofSpire + spireBoxHeight; j++) {
for (int k = z - radiusFromCore - 1; k <= z + radiusFromCore + 1; k++) {
if (!this.isValidSpireWall(world.getBlockId(wallX, j, k))) {
// world.destroyBlock(wallX, j, k, true);
this.setBlockNew(world, x, y, z, wallX, j, k, block);
}
}
}
// -X
wallX = x - radiusFromCore - 1;
for (int j = baseofSpire; j <= baseofSpire + spireBoxHeight; j++) {
for (int k = z - radiusFromCore - 1; k <= z + radiusFromCore + 1; k++) {
if (!this.isValidSpireWall(world.getBlockId(wallX, j, k))) {
// world.destroyBlock(wallX, j, k, true);
this.setBlockNew(world, x, y, z, wallX, j, k, block);
}
}
}
// +Z
int wallZ = z + radiusFromCore + 1;
for (int j = baseofSpire; j <= baseofSpire + spireBoxHeight; j++) {
for (int i = x - radiusFromCore - 1; i <= x + radiusFromCore + 1; i++) {
if (!this.isValidSpireWall(world.getBlockId(i, j, wallZ))) {
// world.destroyBlock(i, j, wallZ, true);
this.setBlockNew(world, x, y, z, i, j, wallZ, block);
}
}
}
// -Z
wallZ = z - radiusFromCore - 1;
for (int j = baseofSpire; j <= baseofSpire + spireBoxHeight; j++) {
for (int i = x - radiusFromCore - 1; i <= x + radiusFromCore + 1; i++) {
if (!this.isValidSpireWall(world.getBlockId(i, j, wallZ))) {
// world.destroyBlock(i, j, wallZ, true);
this.setBlockNew(world, x, y, z, i, j, wallZ, block);
}
}
}
// ~~~~~~~~~~~~~~~
// spire
// this.spire(world, x, z, baseofSpire + 12, block, radiusFromCore);
// ~~~~~~~~~~~~~~~
// Lighting
// this.spireLight(world, x, z, baseofSpire, Block.glowStone.blockID,
// radiusFromCore);
block = PEforPC.glowObsidian.blockID;
for (int i = x - 1; i <= x + 1; i++) {
for (int k = z - 1; k <= z + 1; k++) {
world.setBlock(i, y - 1, k, block);
}
}
world.setBlock(x - 1, y - 0, z - 1, block);
world.setBlock(x + 1, y - 0, z - 1, block);
world.setBlock(x - 1, y - 0, z + 1, block);
world.setBlock(x + 1, y - 0, z + 1, block);
world.setBlock(x + 1, y + 1, z - 0, block);
world.setBlock(x - 1, y + 1, z - 0, block);
world.setBlock(x - 0, y + 1, z - 0, block);
world.setBlock(x - 0, y + 1, z + 1, block);
world.setBlock(x - 0, y + 1, z - 1, block);
// ~~~~~~~~~~~~~~~
// Spawner
world.setBlock(x, y + 5, z, Block.mobSpawner.blockID, 0, 2);
TileEntityMobSpawner tileentitymobspawner = (TileEntityMobSpawner) world
.getBlockTileEntity(x, y + 5, z);
if (tileentitymobspawner != null) {
tileentitymobspawner.getSpawnerLogic().setMobID("Blaze");
}
}
private boolean isValidSpireWall(int blockiD) {
return blockiD == Block.netherrack.blockID
|| blockiD == Block.netherBrick.blockID
|| blockiD == Block.bedrock.blockID
|| blockiD == Block.obsidian.blockID
|| blockiD == Block.glowStone.blockID;
}
private void spireFloor(World world, int coreX, int coreY, int coreZ,
int floorY, int blockiD, int radiusFromCore) {
for (int i = coreX - radiusFromCore - 1; i <= coreX + radiusFromCore
+ 1; i++) {
for (int k = coreZ - radiusFromCore - 1; k <= coreZ
+ radiusFromCore + 1; k++) {
if (!this.isValidSpireWall(world.getBlockId(i, floorY, k))) {
// world.destroyBlock(i, floorY, k, true);
this.setBlockNew(world, coreX, coreY, coreZ, i, floorY, k,
blockiD);
}
}
}
}
private void spireLight(World world, int coreX, int coreZ, int floorY,
int blockiD, int radiusFromCore) {
for (int layer = floorY; layer <= floorY + 5; layer += 5) {
world.setBlock(coreX - 3, layer, coreZ - 3, blockiD);
world.setBlock(coreX + 3, layer, coreZ - 3, blockiD);
world.setBlock(coreX - 3, layer, coreZ + 3, blockiD);
world.setBlock(coreX + 3, layer, coreZ + 3, blockiD);
}
}
private void spireHollowInterior(World world, int coreX, int coreZ,
int spireBase, int radiusFromCore, int height) {
int minWallY = spireBase;
int maxWallY = height;
int minWallX = coreX - radiusFromCore - 1;
int maxWallX = coreX + radiusFromCore + 1;
int minWallZ = coreZ - radiusFromCore - 1;
int maxWallZ = coreZ + radiusFromCore + 1;
for (int j = maxWallY; j >= minWallY; j--) {
for (int i = minWallX; i <= maxWallX; i++) {
for (int k = minWallZ; k <= maxWallZ; k++) {
if (world.getBlockId(i, j, k) != this.blockID) {
// world.destroyBlock(i, j, k, true);
world.setBlock(i, j, k, 0);
}
}
}
}
}
private void spire(World world, int coreX, int coreZ, int floorY,
int blockiD, int radiusFromCore) {
int maxWallX = coreX + radiusFromCore + 1;
int maxWallZ = coreZ + radiusFromCore + 1;
int minWallX = coreX - radiusFromCore - 1;
int minWallZ = coreZ - radiusFromCore - 1;
int yLayer = floorY;
int i, k;
k = minWallZ;
while (k <= maxWallZ - 3) {
yLayer++;
k += 2;
for (int i1 = maxWallX; i1 >= maxWallX - 2; i1--) {
for (int k1 = k; k1 <= maxWallZ; k1++) {
world.setBlock(i1, yLayer, k1, blockiD);
}
}
}
i = maxWallX;
while (i >= minWallX + 3) {
yLayer++;
i -= 2;
for (int k1 = maxWallZ; k1 >= maxWallZ - 2; k1--) {
for (int i1 = i; i1 >= minWallX; i1--) {
world.setBlock(i1, yLayer, k1, blockiD);
}
}
}
}
}
| apache-2.0 |
mocc/bookkeeper-lab | bookkeeper-server/src/test/java/org/apache/bookkeeper/client/TestFencing.java | 13930 | package org.apache.bookkeeper.client;
/*
*
* 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.
*
*/
import org.junit.*;
import java.net.InetSocketAddress;
import java.util.Enumeration;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.CountDownLatch;
import org.apache.bookkeeper.conf.ClientConfiguration;
import org.apache.bookkeeper.client.LedgerHandle;
import org.apache.bookkeeper.client.LedgerEntry;
import org.apache.bookkeeper.client.BookKeeper;
import org.apache.bookkeeper.client.BookKeeperAdmin;
import org.apache.bookkeeper.client.BKException;
import org.apache.bookkeeper.client.BookKeeper.DigestType;
import org.apache.bookkeeper.test.BaseTestCase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This unit test tests ledger fencing;
*
*/
public class TestFencing extends BaseTestCase {
static Logger LOG = LoggerFactory.getLogger(TestFencing.class);
DigestType digestType;
public TestFencing(DigestType digestType) {
super(10);
this.digestType = digestType;
}
/**
* Basic fencing test. Create ledger, write to it,
* open ledger, write again (should fail).
*/
@Test(timeout=60000)
public void testBasicFencing() throws Exception {
/*
* Create ledger.
*/
LedgerHandle writelh = null;
writelh = bkc.createLedger(digestType, "password".getBytes());
String tmp = "BookKeeper is cool!";
for (int i = 0; i < 10; i++) {
writelh.addEntry(tmp.getBytes());
}
/*
* Try to open ledger.
*/
LedgerHandle readlh = bkc.openLedger(writelh.getId(), digestType, "password".getBytes());
// should have triggered recovery and fencing
try {
writelh.addEntry(tmp.getBytes());
LOG.error("Should have thrown an exception");
fail("Should have thrown an exception when trying to write");
} catch (BKException.BKLedgerFencedException e) {
// correct behaviour
}
/*
* Check if has recovered properly.
*/
assertTrue("Has not recovered correctly: " + readlh.getLastAddConfirmed()
+ " original " + writelh.getLastAddConfirmed(),
readlh.getLastAddConfirmed() == writelh.getLastAddConfirmed());
}
private static int threadCount = 0;
class LedgerOpenThread extends Thread {
private final long ledgerId;
private long lastConfirmedEntry = 0;
private final DigestType digestType;
private final CyclicBarrier barrier;
LedgerOpenThread (DigestType digestType, long ledgerId, CyclicBarrier barrier)
throws Exception {
super("TestFencing-LedgerOpenThread-" + threadCount++);
this.ledgerId = ledgerId;
this.digestType = digestType;
this.barrier = barrier;
}
@Override
public void run() {
LedgerHandle lh = null;
BookKeeper bk = null;
try {
barrier.await();
while(true) {
try {
bk = new BookKeeper(new ClientConfiguration(baseClientConf), bkc.getZkHandle());
lh = bk.openLedger(ledgerId,
digestType, "".getBytes());
lastConfirmedEntry = lh.getLastAddConfirmed();
lh.close();
break;
} catch (BKException.BKMetadataVersionException zke) {
LOG.info("Contention with someone else recovering");
} catch (BKException.BKLedgerRecoveryException bkre) {
LOG.info("Contention with someone else recovering");
} finally {
if (lh != null) {
lh.close();
}
if (bk != null) {
bk.close();
bk = null;
}
}
}
} catch (Exception e) {
// just exit, test should spot bad last add confirmed
LOG.error("Exception occurred ", e);
}
LOG.info("Thread exiting, lastConfirmedEntry = " + lastConfirmedEntry);
}
long getLastConfirmedEntry() {
return lastConfirmedEntry;
}
}
/**
* Try to open a ledger many times in parallel.
* All opens should result in a ledger with an equals number of
* entries.
*/
@Test(timeout=60000)
public void testManyOpenParallel() throws Exception {
/*
* Create ledger.
*/
final LedgerHandle writelh = bkc.createLedger(digestType, "".getBytes());
final int numRecovery = 10;
final String tmp = "BookKeeper is cool!";
final CountDownLatch latch = new CountDownLatch(numRecovery);
Thread writethread = new Thread() {
public void run() {
try {
while (true) {
writelh.addEntry(tmp.getBytes());
latch.countDown();
}
} catch (Exception e) {
LOG.info("Exception adding entry", e);
}
}
};
writethread.start();
CyclicBarrier barrier = new CyclicBarrier(numRecovery+1);
LedgerOpenThread threads[] = new LedgerOpenThread[numRecovery];
for (int i = 0; i < numRecovery; i++) {
threads[i] = new LedgerOpenThread(digestType, writelh.getId(), barrier);
threads[i].start();
}
latch.await();
barrier.await(); // should trigger threads to go
writethread.join();
long lastConfirmed = writelh.getLastAddConfirmed();
for (int i = 0; i < numRecovery; i++) {
threads[i].join();
assertTrue("Added confirmed is incorrect",
lastConfirmed <= threads[i].getLastConfirmedEntry());
}
}
/**
* Test that opening a ledger in norecovery mode
* doesn't fence off a ledger
*/
@Test(timeout=60000)
public void testNoRecoveryOpen() throws Exception {
/*
* Create ledger.
*/
LedgerHandle writelh = null;
writelh = bkc.createLedger(digestType, "".getBytes());
String tmp = "BookKeeper is cool!";
final int numEntries = 10;
for (int i = 0; i < numEntries; i++) {
writelh.addEntry(tmp.getBytes());
}
/*
* Try to open ledger.
*/
LedgerHandle readlh = bkc.openLedgerNoRecovery(writelh.getId(),
digestType, "".getBytes());
// should not have triggered recovery and fencing
writelh.addEntry(tmp.getBytes());
long numReadable = readlh.getLastAddConfirmed();
LOG.error("numRead " + numReadable);
Enumeration<LedgerEntry> entries = readlh.readEntries(1, numReadable);
try {
readlh.readEntries(numReadable+1, numReadable+1);
fail("Shouldn't have been able to read this far");
} catch (BKException.BKReadException e) {
// all is good
}
writelh.addEntry(tmp.getBytes());
long numReadable2 = readlh.getLastAddConfirmed();
assertEquals("Number of readable entries hasn't changed", numReadable2, numReadable);
readlh.close();
writelh.addEntry(tmp.getBytes());
writelh.close();
}
/**
* create a ledger and write entries.
* kill a bookie in the ensemble. Recover.
* Fence the ledger. Kill another bookie. Recover.
*/
@Test(timeout=60000)
public void testFencingInteractionWithBookieRecovery() throws Exception {
System.setProperty("digestType", digestType.toString());
System.setProperty("passwd", "testPasswd");
BookKeeperAdmin admin = new BookKeeperAdmin(zkUtil.getZooKeeperConnectString());
LedgerHandle writelh = bkc.createLedger(digestType, "testPasswd".getBytes());
String tmp = "Foobar";
final int numEntries = 10;
for (int i = 0; i < numEntries; i++) {
writelh.addEntry(tmp.getBytes());
}
InetSocketAddress bookieToKill
= writelh.getLedgerMetadata().getEnsemble(numEntries).get(0);
killBookie(bookieToKill);
// write entries to change ensemble
for (int i = 0; i < numEntries; i++) {
writelh.addEntry(tmp.getBytes());
}
admin.recoverBookieData(bookieToKill, null);
for (int i = 0; i < numEntries; i++) {
writelh.addEntry(tmp.getBytes());
}
LedgerHandle readlh = bkc.openLedger(writelh.getId(),
digestType, "testPasswd".getBytes());
try {
writelh.addEntry(tmp.getBytes());
LOG.error("Should have thrown an exception");
fail("Should have thrown an exception when trying to write");
} catch (BKException.BKLedgerFencedException e) {
// correct behaviour
}
readlh.close();
try {
writelh.close();
fail("Should fail trying to update metadata");
} catch (BKException.BKMetadataVersionException e) {
// correct behaviour
}
}
/**
* create a ledger and write entries.
* Fence the ledger. Kill a bookie. Recover.
* Ensure that recover doesn't reallow adding
*/
@Test(timeout=60000)
public void testFencingInteractionWithBookieRecovery2() throws Exception {
System.setProperty("digestType", digestType.toString());
System.setProperty("passwd", "testPasswd");
BookKeeperAdmin admin = new BookKeeperAdmin(zkUtil.getZooKeeperConnectString());
LedgerHandle writelh = bkc.createLedger(digestType, "testPasswd".getBytes());
String tmp = "Foobar";
final int numEntries = 10;
for (int i = 0; i < numEntries; i++) {
writelh.addEntry(tmp.getBytes());
}
LedgerHandle readlh = bkc.openLedger(writelh.getId(),
digestType, "testPasswd".getBytes());
// should be fenced by now
InetSocketAddress bookieToKill
= writelh.getLedgerMetadata().getEnsemble(numEntries).get(0);
killBookie(bookieToKill);
admin.recoverBookieData(bookieToKill, null);
try {
writelh.addEntry(tmp.getBytes());
LOG.error("Should have thrown an exception");
fail("Should have thrown an exception when trying to write");
} catch (BKException.BKLedgerFencedException e) {
// correct behaviour
}
readlh.close();
try {
writelh.close();
fail("Should fail trying to update metadata");
} catch (BKException.BKMetadataVersionException e) {
// correct behaviour
}
}
/**
* Test that fencing doesn't work with a bad password
*/
@Test(timeout=60000)
public void testFencingBadPassword() throws Exception {
/*
* Create ledger.
*/
LedgerHandle writelh = null;
writelh = bkc.createLedger(digestType, "password1".getBytes());
String tmp = "BookKeeper is cool!";
for (int i = 0; i < 10; i++) {
writelh.addEntry(tmp.getBytes());
}
/*
* Try to open ledger.
*/
try {
LedgerHandle readlh = bkc.openLedger(writelh.getId(), digestType, "badPassword".getBytes());
fail("Should not have been able to open with a bad password");
} catch (BKException.BKUnauthorizedAccessException uue) {
// correct behaviour
}
// should have triggered recovery and fencing
writelh.addEntry(tmp.getBytes());
}
@Test
public void testFencingAndRestartBookies() throws Exception {
LedgerHandle writelh = null;
writelh = bkc.createLedger(digestType, "password".getBytes());
String tmp = "BookKeeper is cool!";
for (int i = 0; i < 10; i++) {
writelh.addEntry(tmp.getBytes());
}
/*
* Try to open ledger.
*/
LedgerHandle readlh = bkc.openLedger(writelh.getId(), digestType,
"password".getBytes());
restartBookies();
try {
writelh.addEntry(tmp.getBytes());
LOG.error("Should have thrown an exception");
fail("Should have thrown an exception when trying to write");
} catch (BKException.BKLedgerFencedException e) {
// correct behaviour
}
readlh.close();
}
}
| apache-2.0 |
xhoong/incubator-calcite | core/src/main/java/org/apache/calcite/adapter/enumerable/ReflectiveCallNotNullImplementor.java | 2868 | /*
* 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.calcite.adapter.enumerable;
import org.apache.calcite.linq4j.tree.Expression;
import org.apache.calcite.linq4j.tree.Expressions;
import org.apache.calcite.rex.RexCall;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
/**
* Implementation of
* {@link org.apache.calcite.adapter.enumerable.NotNullImplementor}
* that calls a given {@link java.lang.reflect.Method}.
*
* <p>When method is not static, a new instance of the required class is
* created.
*/
public class ReflectiveCallNotNullImplementor implements NotNullImplementor {
protected final Method method;
/**
* Constructor of {@link ReflectiveCallNotNullImplementor}
* @param method method that is used to implement the call
*/
public ReflectiveCallNotNullImplementor(Method method) {
this.method = method;
}
public Expression implement(RexToLixTranslator translator,
RexCall call, List<Expression> translatedOperands) {
translatedOperands =
EnumUtils.fromInternal(method.getParameterTypes(), translatedOperands);
final Expression callExpr;
if ((method.getModifiers() & Modifier.STATIC) != 0) {
callExpr = Expressions.call(method, translatedOperands);
} else {
// The UDF class must have a public zero-args constructor.
// Assume that the validator checked already.
final Expression target =
Expressions.new_(method.getDeclaringClass());
callExpr = Expressions.call(target, method, translatedOperands);
}
if (!containsCheckedException(method)) {
return callExpr;
}
return translator.handleMethodCheckedExceptions(callExpr);
}
private boolean containsCheckedException(Method method) {
Class[] exceptions = method.getExceptionTypes();
if (exceptions == null || exceptions.length == 0) {
return false;
}
for (Class clazz : exceptions) {
if (!RuntimeException.class.isAssignableFrom(clazz)) {
return true;
}
}
return false;
}
}
// End ReflectiveCallNotNullImplementor.java
| apache-2.0 |
asdf2014/yuzhouwan | yuzhouwan-hacker/src/main/java/com/yuzhouwan/hacker/algorithms/array/CircularBufferSimple.java | 559 | package com.yuzhouwan.hacker.algorithms.array;
/**
* Copyright @ 2020 yuzhouwan.com
* All right reserved.
* Function:Simple Circular Buffer
*
* @author Benedict Jin
* @since 2017/02/28
*/
public class CircularBufferSimple {
private int len, index;
private int[] buffer;
public CircularBufferSimple(int len) {
this.len = len;
this.buffer = new int[len];
}
public void buffer(int input) {
index++;
buffer[index % len] = input;
}
public int[] getBuffer() {
return buffer;
}
}
| apache-2.0 |
skunkiferous/PingPong | src/com/blockwithme/pingpong/latency/impl/kilim/KilimPinger.java | 3718 | /*
* Copyright (C) 2013 Sebastien Diot.
*
* 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.blockwithme.pingpong.latency.impl.kilim;
import kilim.Mailbox;
import kilim.Pausable;
import kilim.Task;
/**
* The Pinger's job is to hammer the Ponger with ping() request.
* Implemented using Kilim Tasks.
*/
public class KilimPinger extends Task {
/** A Hammer request, targeted at Pinger. */
private static class HammerRequest {
/** The number of exchanges to do. */
private final int count;
/** The request result will be returned to that Mailbox. */
private final Mailbox<Integer> callerMB;
/** Creates a hammer request, with the targeted Ponger. */
public HammerRequest(final int _count, final Mailbox<Integer> _callerMB) {
count = _count;
callerMB = _callerMB;
}
/** Process the hammer request. */
public void processRequest(final KilimPinger pinger) throws Exception {
pinger.count = count;
pinger.callerMB = callerMB;
}
}
private final Mailbox<Object> pingerMB;
private final KilimPonger ponger;
private Mailbox<Integer> callerMB;
/** Number of replies received. */
private int pongs;
/** The number of exchanges to do. */
private int count;
public KilimPinger(final Mailbox<Object> _pingerMB,
final KilimPonger _ponger) {
pingerMB = _pingerMB;
ponger = _ponger;
}
@Override
public void execute() throws Pausable, Exception {
while (true) {
final Object msg = pingerMB.get();
if (msg instanceof HammerRequest) {
final HammerRequest req = (HammerRequest) msg;
try {
req.processRequest(this);
// Sends the first ping
ponger.ping(0);
} catch (final Exception e) {
e.printStackTrace();
return;
}
} else if (msg instanceof Integer) {
final Integer response = (Integer) msg;
pongs++;
if (response.intValue() != pongs) {
throw new IllegalStateException("Expected " + pongs
+ " but got " + response);
}
if (pongs < count) {
try {
ponger.ping(pongs);
} catch (final Exception e) {
e.printStackTrace();
return;
}
} else {
callerMB.put(pongs);
}
} else {
new Exception("Expceted HammerRequest but got "
+ msg.getClass()).printStackTrace();
return;
}
}
}
/** Tells the pinger to hammer the Ponger. Blocks and returns the result. */
public Integer hammer(final int _count) throws Pausable, Exception {
final Mailbox<Integer> callerMB = new Mailbox<Integer>();
pingerMB.put(new HammerRequest(_count, callerMB));
return callerMB.get();
}
}
| apache-2.0 |
80998062/Yuk | app/src/main/java/com/sinyuk/yuk/utils/lists/OnLoadMoreListener.java | 2231 | package com.sinyuk.yuk.utils.lists;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
/**
* Created by Sinyuk on 16.2.11.
*/
@Deprecated
public abstract class OnLoadMoreListener extends RecyclerView.OnScrollListener {
private int PRELOAD_SIZE = 1;
private StaggeredGridLayoutManager mStaggeredGridLayoutManager;
private LinearLayoutManager mLinearLayoutManager;
private boolean mIsFirstTimeTouchBottom = true;
public void setPreloadSize(int PreloadSize) {
this.PRELOAD_SIZE = PreloadSize;
}
public int getPreloadSize() {
return PRELOAD_SIZE;
}
public OnLoadMoreListener(@NonNull StaggeredGridLayoutManager staggeredGridLayoutManager) {
this.mStaggeredGridLayoutManager = staggeredGridLayoutManager;
}
public OnLoadMoreListener(@NonNull LinearLayoutManager linearLayout) {
this.mLinearLayoutManager = linearLayout;
}
@Override
public void onScrolled(RecyclerView rv, int dx, int dy) {
if (mStaggeredGridLayoutManager != null) {
boolean isBottom =
mStaggeredGridLayoutManager.findLastCompletelyVisibleItemPositions(
new int[2])[1] >=
rv.getAdapter().getItemCount() -
PRELOAD_SIZE;
if (isBottom) {
if (!mIsFirstTimeTouchBottom) {
onLoadMore();
} else {
mIsFirstTimeTouchBottom = false;
}
}
}else if(mLinearLayoutManager != null){
boolean isBottom =
mLinearLayoutManager.findLastCompletelyVisibleItemPosition() >= rv.getAdapter().getItemCount() - PRELOAD_SIZE;
if (isBottom) {
if (!mIsFirstTimeTouchBottom) {
onLoadMore();
} else {
mIsFirstTimeTouchBottom = false;
}
}
}
}
public abstract void onLoadMore();
}
| apache-2.0 |
hejingit/Skybird-WorkSpace | demo-boot/src/main/java/com/xe/demo/model/AuthOperation.java | 2129 | package com.xe.demo.model;
import javax.persistence.*;
@Table(name = "auth_operation")
public class AuthOperation {
/**
* 主键
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer opid;
/**
* 权限值
*/
private String opcode;
/**
* 权限名称
*/
private String opname;
/**
* 权限操作链接
*/
private String ophref;
/**
* 显示顺序
*/
private Integer opseq;
/**
* 获取主键
*
* @return id - 主键
*/
public Integer getOpid() {
return opid;
}
/**
* 设置主键
*
* @param id 主键
*/
public void setOpid(Integer opid) {
this.opid = opid;
}
/**
* 获取权限值
*
* @return opcode - 权限值
*/
public String getOpcode() {
return opcode;
}
/**
* 设置权限值
*
* @param opcode 权限值
*/
public void setOpcode(String opcode) {
this.opcode = opcode;
}
/**
* 获取权限名称
*
* @return opname - 权限名称
*/
public String getOpname() {
return opname;
}
/**
* 设置权限名称
*
* @param opname 权限名称
*/
public void setOpname(String opname) {
this.opname = opname;
}
/**
* 获取权限操作链接
*
* @return ophref - 权限操作链接
*/
public String getOphref() {
return ophref;
}
/**
* 设置权限操作链接
*
* @param ophref 权限操作链接
*/
public void setOphref(String ophref) {
this.ophref = ophref;
}
/**
* 获取显示顺序
*
* @return opseq - 显示顺序
*/
public Integer getOpseq() {
return opseq;
}
/**
* 设置显示顺序
*
* @param opseq 显示顺序
*/
public void setOpseq(Integer opseq) {
this.opseq = opseq;
}
} | apache-2.0 |
tallycheck/data-support | data-service-base/src/main/java/com/taoswork/tallycheck/dataservice/io/response/NewInstanceResponse.java | 161 | package com.taoswork.tallycheck.dataservice.io.response;
/**
* Created by gaoyuan on 7/1/16.
*/
public class NewInstanceResponse extends InstanceResponse {
}
| apache-2.0 |
iskenxan/MMA-TODAY | MMATODAY/app/src/main/java/space/samatov/mmatoday/model/interfaces/NewsFeedItemClicked.java | 138 | package space.samatov.mmatoday.model.interfaces;
public interface NewsFeedItemClicked {
void OnNewsFeedItemClicked(int position);
}
| apache-2.0 |
nitlang/alterner | t/sav/comb2.java.alt/comb2.1alt1.2alt3.alt2.java | 63 | a1//alt1
//1alt11a1
//alt21a2
2a1//2alt1
2a2//2alt2
//2alt32a3
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/GetUserPoolMfaConfigRequest.java | 3484 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.cognitoidp.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/GetUserPoolMfaConfig" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetUserPoolMfaConfigRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The user pool ID.
* </p>
*/
private String userPoolId;
/**
* <p>
* The user pool ID.
* </p>
*
* @param userPoolId
* The user pool ID.
*/
public void setUserPoolId(String userPoolId) {
this.userPoolId = userPoolId;
}
/**
* <p>
* The user pool ID.
* </p>
*
* @return The user pool ID.
*/
public String getUserPoolId() {
return this.userPoolId;
}
/**
* <p>
* The user pool ID.
* </p>
*
* @param userPoolId
* The user pool ID.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetUserPoolMfaConfigRequest withUserPoolId(String userPoolId) {
setUserPoolId(userPoolId);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getUserPoolId() != null)
sb.append("UserPoolId: ").append(getUserPoolId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetUserPoolMfaConfigRequest == false)
return false;
GetUserPoolMfaConfigRequest other = (GetUserPoolMfaConfigRequest) obj;
if (other.getUserPoolId() == null ^ this.getUserPoolId() == null)
return false;
if (other.getUserPoolId() != null && other.getUserPoolId().equals(this.getUserPoolId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getUserPoolId() == null) ? 0 : getUserPoolId().hashCode());
return hashCode;
}
@Override
public GetUserPoolMfaConfigRequest clone() {
return (GetUserPoolMfaConfigRequest) super.clone();
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-iotthingsgraph/src/main/java/com/amazonaws/services/iotthingsgraph/model/transform/DeprecateSystemTemplateRequestMarshaller.java | 2077 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.iotthingsgraph.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.iotthingsgraph.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DeprecateSystemTemplateRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeprecateSystemTemplateRequestMarshaller {
private static final MarshallingInfo<String> ID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("id").build();
private static final DeprecateSystemTemplateRequestMarshaller instance = new DeprecateSystemTemplateRequestMarshaller();
public static DeprecateSystemTemplateRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(DeprecateSystemTemplateRequest deprecateSystemTemplateRequest, ProtocolMarshaller protocolMarshaller) {
if (deprecateSystemTemplateRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deprecateSystemTemplateRequest.getId(), ID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
chaordic/cassandra | src/java/org/apache/cassandra/utils/FBUtilities.java | 27992 | /*
* 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.cassandra.utils;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.*;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.zip.Adler32;
import java.util.zip.Checksum;
import com.google.common.base.Joiner;
import com.google.common.collect.AbstractIterator;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.auth.IAuthenticator;
import org.apache.cassandra.auth.IAuthorizer;
import org.apache.cassandra.auth.IRoleManager;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.io.IVersionedSerializer;
import org.apache.cassandra.io.compress.CompressionParameters;
import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.io.util.DataOutputBufferFixed;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.net.AsyncOneResponse;
import org.apache.thrift.*;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.map.ObjectMapper;
public class FBUtilities
{
private static final Logger logger = LoggerFactory.getLogger(FBUtilities.class);
private static final ObjectMapper jsonMapper = new ObjectMapper(new JsonFactory());
public static final BigInteger TWO = new BigInteger("2");
private static final String DEFAULT_TRIGGER_DIR = "triggers";
private static final String OPERATING_SYSTEM = System.getProperty("os.name").toLowerCase();
private static final boolean IS_WINDOWS = OPERATING_SYSTEM.contains("windows");
private static final boolean HAS_PROCFS = !IS_WINDOWS && (new File(File.separator + "proc")).exists();
private static volatile InetAddress localInetAddress;
private static volatile InetAddress broadcastInetAddress;
public static int getAvailableProcessors()
{
if (System.getProperty("cassandra.available_processors") != null)
return Integer.parseInt(System.getProperty("cassandra.available_processors"));
else
return Runtime.getRuntime().availableProcessors();
}
private static final ThreadLocal<MessageDigest> localMD5Digest = new ThreadLocal<MessageDigest>()
{
@Override
protected MessageDigest initialValue()
{
return newMessageDigest("MD5");
}
@Override
public MessageDigest get()
{
MessageDigest digest = super.get();
digest.reset();
return digest;
}
};
public static final int MAX_UNSIGNED_SHORT = 0xFFFF;
public static MessageDigest threadLocalMD5Digest()
{
return localMD5Digest.get();
}
public static MessageDigest newMessageDigest(String algorithm)
{
try
{
return MessageDigest.getInstance(algorithm);
}
catch (NoSuchAlgorithmException nsae)
{
throw new RuntimeException("the requested digest algorithm (" + algorithm + ") is not available", nsae);
}
}
/**
* Please use getBroadcastAddress instead. You need this only when you have to listen/connect.
*/
public static InetAddress getLocalAddress()
{
if (localInetAddress == null)
try
{
localInetAddress = DatabaseDescriptor.getListenAddress() == null
? InetAddress.getLocalHost()
: DatabaseDescriptor.getListenAddress();
}
catch (UnknownHostException e)
{
throw new RuntimeException(e);
}
return localInetAddress;
}
public static InetAddress getBroadcastAddress()
{
if (broadcastInetAddress == null)
broadcastInetAddress = DatabaseDescriptor.getBroadcastAddress() == null
? getLocalAddress()
: DatabaseDescriptor.getBroadcastAddress();
return broadcastInetAddress;
}
public static Collection<InetAddress> getAllLocalAddresses()
{
Set<InetAddress> localAddresses = new HashSet<InetAddress>();
try
{
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
if (nets != null)
{
while (nets.hasMoreElements())
localAddresses.addAll(Collections.list(nets.nextElement().getInetAddresses()));
}
}
catch (SocketException e)
{
throw new AssertionError(e);
}
return localAddresses;
}
/**
* Given two bit arrays represented as BigIntegers, containing the given
* number of significant bits, calculate a midpoint.
*
* @param left The left point.
* @param right The right point.
* @param sigbits The number of bits in the points that are significant.
* @return A midpoint that will compare bitwise halfway between the params, and
* a boolean representing whether a non-zero lsbit remainder was generated.
*/
public static Pair<BigInteger,Boolean> midpoint(BigInteger left, BigInteger right, int sigbits)
{
BigInteger midpoint;
boolean remainder;
if (left.compareTo(right) < 0)
{
BigInteger sum = left.add(right);
remainder = sum.testBit(0);
midpoint = sum.shiftRight(1);
}
else
{
BigInteger max = TWO.pow(sigbits);
// wrapping case
BigInteger distance = max.add(right).subtract(left);
remainder = distance.testBit(0);
midpoint = distance.shiftRight(1).add(left).mod(max);
}
return Pair.create(midpoint, remainder);
}
public static int compareUnsigned(byte[] bytes1, byte[] bytes2, int offset1, int offset2, int len1, int len2)
{
return FastByteOperations.compareUnsigned(bytes1, offset1, len1, bytes2, offset2, len2);
}
public static int compareUnsigned(byte[] bytes1, byte[] bytes2)
{
return compareUnsigned(bytes1, bytes2, 0, 0, bytes1.length, bytes2.length);
}
/**
* @return The bitwise XOR of the inputs. The output will be the same length as the
* longer input, but if either input is null, the output will be null.
*/
public static byte[] xor(byte[] left, byte[] right)
{
if (left == null || right == null)
return null;
if (left.length > right.length)
{
byte[] swap = left;
left = right;
right = swap;
}
// left.length is now <= right.length
byte[] out = Arrays.copyOf(right, right.length);
for (int i = 0; i < left.length; i++)
{
out[i] = (byte)((left[i] & 0xFF) ^ (right[i] & 0xFF));
}
return out;
}
public static byte[] hash(ByteBuffer... data)
{
MessageDigest messageDigest = localMD5Digest.get();
for (ByteBuffer block : data)
{
if (block.hasArray())
messageDigest.update(block.array(), block.arrayOffset() + block.position(), block.remaining());
else
messageDigest.update(block.duplicate());
}
return messageDigest.digest();
}
public static BigInteger hashToBigInteger(ByteBuffer data)
{
return new BigInteger(hash(data)).abs();
}
@Deprecated
public static void serialize(TSerializer serializer, TBase struct, DataOutput out)
throws IOException
{
assert serializer != null;
assert struct != null;
assert out != null;
byte[] bytes;
try
{
bytes = serializer.serialize(struct);
}
catch (TException e)
{
throw new RuntimeException(e);
}
out.writeInt(bytes.length);
out.write(bytes);
}
@Deprecated
public static void deserialize(TDeserializer deserializer, TBase struct, DataInput in)
throws IOException
{
assert deserializer != null;
assert struct != null;
assert in != null;
byte[] bytes = new byte[in.readInt()];
in.readFully(bytes);
try
{
deserializer.deserialize(struct, bytes);
}
catch (TException ex)
{
throw new IOException(ex);
}
}
public static void sortSampledKeys(List<DecoratedKey> keys, Range<Token> range)
{
if (range.left.compareTo(range.right) >= 0)
{
// range wraps. have to be careful that we sort in the same order as the range to find the right midpoint.
final Token right = range.right;
Comparator<DecoratedKey> comparator = new Comparator<DecoratedKey>()
{
public int compare(DecoratedKey o1, DecoratedKey o2)
{
if ((right.compareTo(o1.getToken()) < 0 && right.compareTo(o2.getToken()) < 0)
|| (right.compareTo(o1.getToken()) > 0 && right.compareTo(o2.getToken()) > 0))
{
// both tokens are on the same side of the wrap point
return o1.compareTo(o2);
}
return o2.compareTo(o1);
}
};
Collections.sort(keys, comparator);
}
else
{
// unwrapped range (left < right). standard sort is all we need.
Collections.sort(keys);
}
}
public static String resourceToFile(String filename) throws ConfigurationException
{
ClassLoader loader = FBUtilities.class.getClassLoader();
URL scpurl = loader.getResource(filename);
if (scpurl == null)
throw new ConfigurationException("unable to locate " + filename);
return new File(scpurl.getFile()).getAbsolutePath();
}
public static File cassandraTriggerDir()
{
File triggerDir = null;
if (System.getProperty("cassandra.triggers_dir") != null)
{
triggerDir = new File(System.getProperty("cassandra.triggers_dir"));
}
else
{
URL confDir = FBUtilities.class.getClassLoader().getResource(DEFAULT_TRIGGER_DIR);
if (confDir != null)
triggerDir = new File(confDir.getFile());
}
if (triggerDir == null || !triggerDir.exists())
{
logger.warn("Trigger directory doesn't exist, please create it and try again.");
return null;
}
return triggerDir;
}
public static String getReleaseVersionString()
{
try (InputStream in = FBUtilities.class.getClassLoader().getResourceAsStream("org/apache/cassandra/config/version.properties"))
{
if (in == null)
{
return System.getProperty("cassandra.releaseVersion", "Unknown");
}
Properties props = new Properties();
props.load(in);
return props.getProperty("CassandraVersion");
}
catch (Exception e)
{
JVMStabilityInspector.inspectThrowable(e);
logger.warn("Unable to load version.properties", e);
return "debug version";
}
}
public static long timestampMicros()
{
// we use microsecond resolution for compatibility with other client libraries, even though
// we can't actually get microsecond precision.
return System.currentTimeMillis() * 1000;
}
public static int nowInSeconds()
{
return (int)(System.currentTimeMillis() / 1000);
}
public static void waitOnFutures(Iterable<Future<?>> futures)
{
for (Future f : futures)
waitOnFuture(f);
}
public static <T> T waitOnFuture(Future<T> future)
{
try
{
return future.get();
}
catch (ExecutionException ee)
{
throw new RuntimeException(ee);
}
catch (InterruptedException ie)
{
throw new AssertionError(ie);
}
}
public static void waitOnFutures(List<AsyncOneResponse> results, long ms) throws TimeoutException
{
for (AsyncOneResponse result : results)
result.get(ms, TimeUnit.MILLISECONDS);
}
public static IPartitioner newPartitioner(String partitionerClassName) throws ConfigurationException
{
if (!partitionerClassName.contains("."))
partitionerClassName = "org.apache.cassandra.dht." + partitionerClassName;
return FBUtilities.instanceOrConstruct(partitionerClassName, "partitioner");
}
public static IAuthorizer newAuthorizer(String className) throws ConfigurationException
{
if (!className.contains("."))
className = "org.apache.cassandra.auth." + className;
return FBUtilities.construct(className, "authorizer");
}
public static IAuthenticator newAuthenticator(String className) throws ConfigurationException
{
if (!className.contains("."))
className = "org.apache.cassandra.auth." + className;
return FBUtilities.construct(className, "authenticator");
}
public static IRoleManager newRoleManager(String className) throws ConfigurationException
{
if (!className.contains("."))
className = "org.apache.cassandra.auth." + className;
return FBUtilities.construct(className, "role manager");
}
/**
* @return The Class for the given name.
* @param classname Fully qualified classname.
* @param readable Descriptive noun for the role the class plays.
* @throws ConfigurationException If the class cannot be found.
*/
public static <T> Class<T> classForName(String classname, String readable) throws ConfigurationException
{
try
{
return (Class<T>)Class.forName(classname);
}
catch (ClassNotFoundException | NoClassDefFoundError e)
{
throw new ConfigurationException(String.format("Unable to find %s class '%s'", readable, classname), e);
}
}
/**
* Constructs an instance of the given class, which must have a no-arg or default constructor.
* @param classname Fully qualified classname.
* @param readable Descriptive noun for the role the class plays.
* @throws ConfigurationException If the class cannot be found.
*/
public static <T> T instanceOrConstruct(String classname, String readable) throws ConfigurationException
{
Class<T> cls = FBUtilities.classForName(classname, readable);
try
{
Field instance = cls.getField("instance");
return cls.cast(instance.get(null));
}
catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e)
{
// Could not get instance field. Try instantiating.
return construct(cls, classname, readable);
}
}
/**
* Constructs an instance of the given class, which must have a no-arg or default constructor.
* @param classname Fully qualified classname.
* @param readable Descriptive noun for the role the class plays.
* @throws ConfigurationException If the class cannot be found.
*/
public static <T> T construct(String classname, String readable) throws ConfigurationException
{
Class<T> cls = FBUtilities.classForName(classname, readable);
return construct(cls, classname, readable);
}
private static <T> T construct(Class<T> cls, String classname, String readable) throws ConfigurationException
{
try
{
return cls.newInstance();
}
catch (IllegalAccessException e)
{
throw new ConfigurationException(String.format("Default constructor for %s class '%s' is inaccessible.", readable, classname));
}
catch (InstantiationException e)
{
throw new ConfigurationException(String.format("Cannot use abstract class '%s' as %s.", classname, readable));
}
catch (Exception e)
{
// Catch-all because Class.newInstance() "propagates any exception thrown by the nullary constructor, including a checked exception".
if (e.getCause() instanceof ConfigurationException)
throw (ConfigurationException)e.getCause();
throw new ConfigurationException(String.format("Error instantiating %s class '%s'.", readable, classname), e);
}
}
public static <T> NavigableSet<T> singleton(T column, Comparator<? super T> comparator)
{
NavigableSet<T> s = new TreeSet<T>(comparator);
s.add(column);
return s;
}
public static <T> NavigableSet<T> emptySortedSet(Comparator<? super T> comparator)
{
return new TreeSet<T>(comparator);
}
public static String toString(Map<?,?> map)
{
Joiner.MapJoiner joiner = Joiner.on(", ").withKeyValueSeparator(":");
return joiner.join(map);
}
/**
* Used to get access to protected/private field of the specified class
* @param klass - name of the class
* @param fieldName - name of the field
* @return Field or null on error
*/
public static Field getProtectedField(Class klass, String fieldName)
{
try
{
Field field = klass.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
}
catch (Exception e)
{
throw new AssertionError(e);
}
}
public static <T> CloseableIterator<T> closeableIterator(Iterator<T> iterator)
{
return new WrappedCloseableIterator<T>(iterator);
}
public static Map<String, String> fromJsonMap(String json)
{
try
{
return jsonMapper.readValue(json, Map.class);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
public static List<String> fromJsonList(String json)
{
try
{
return jsonMapper.readValue(json, List.class);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
public static String json(Object object)
{
try
{
return jsonMapper.writeValueAsString(object);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
public static String prettyPrintMemory(long size)
{
if (size >= 1 << 30)
return String.format("%.3fGiB", size / (double) (1 << 30));
if (size >= 1 << 20)
return String.format("%.3fMiB", size / (double) (1 << 20));
return String.format("%.3fKiB", size / (double) (1 << 10));
}
/**
* Starts and waits for the given @param pb to finish.
* @throws java.io.IOException on non-zero exit code
*/
public static void exec(ProcessBuilder pb) throws IOException
{
Process p = pb.start();
try
{
int errCode = p.waitFor();
if (errCode != 0)
{
try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream())))
{
String lineSep = System.getProperty("line.separator");
StringBuilder sb = new StringBuilder();
String str;
while ((str = in.readLine()) != null)
sb.append(str).append(lineSep);
while ((str = err.readLine()) != null)
sb.append(str).append(lineSep);
throw new IOException("Exception while executing the command: "+ StringUtils.join(pb.command(), " ") +
", command error Code: " + errCode +
", command output: "+ sb.toString());
}
}
}
catch (InterruptedException e)
{
throw new AssertionError(e);
}
}
public static void updateChecksumInt(Checksum checksum, int v)
{
checksum.update((v >>> 24) & 0xFF);
checksum.update((v >>> 16) & 0xFF);
checksum.update((v >>> 8) & 0xFF);
checksum.update((v >>> 0) & 0xFF);
}
private static Method directUpdate;
static
{
try
{
directUpdate = Adler32.class.getDeclaredMethod("update", new Class[]{ByteBuffer.class});
directUpdate.setAccessible(true);
} catch (NoSuchMethodException e)
{
logger.warn("JVM doesn't support Adler32 byte buffer access");
directUpdate = null;
}
}
private static final ThreadLocal<byte[]> threadLocalScratchBuffer = new ThreadLocal<byte[]>()
{
@Override
protected byte[] initialValue()
{
return new byte[CompressionParameters.DEFAULT_CHUNK_LENGTH];
}
};
public static byte[] getThreadLocalScratchBuffer()
{
return threadLocalScratchBuffer.get();
}
//Java 7 has this method but it's private till Java 8. Thanks JDK!
public static boolean supportsDirectChecksum()
{
return directUpdate != null;
}
public static void directCheckSum(Adler32 checksum, ByteBuffer bb)
{
if (directUpdate != null)
{
try
{
directUpdate.invoke(checksum, bb);
return;
}
catch (IllegalAccessException e)
{
directUpdate = null;
logger.warn("JVM doesn't support Adler32 byte buffer access");
}
catch (InvocationTargetException e)
{
throw new RuntimeException(e);
}
}
//Fallback
byte[] buffer = getThreadLocalScratchBuffer();
int remaining;
while ((remaining = bb.remaining()) > 0)
{
remaining = Math.min(remaining, buffer.length);
ByteBufferUtil.arrayCopy(bb, bb.position(), buffer, 0, remaining);
bb.position(bb.position() + remaining);
checksum.update(buffer, 0, remaining);
}
}
public static long abs(long index)
{
long negbit = index >> 63;
return (index ^ negbit) - negbit;
}
private static final class WrappedCloseableIterator<T>
extends AbstractIterator<T> implements CloseableIterator<T>
{
private final Iterator<T> source;
public WrappedCloseableIterator(Iterator<T> source)
{
this.source = source;
}
protected T computeNext()
{
if (!source.hasNext())
return endOfData();
return source.next();
}
public void close() {}
}
public static <T> byte[] serialize(T object, IVersionedSerializer<T> serializer, int version)
{
int size = (int) serializer.serializedSize(object, version);
try (DataOutputBuffer buffer = new DataOutputBufferFixed(size))
{
serializer.serialize(object, buffer, version);
assert buffer.getLength() == size && buffer.getData().length == size
: String.format("Final buffer length %s to accommodate data size of %s (predicted %s) for %s",
buffer.getData().length, buffer.getLength(), size, object);
return buffer.getData();
}
catch (IOException e)
{
// We're doing in-memory serialization...
throw new AssertionError(e);
}
}
public static long copy(InputStream from, OutputStream to, long limit) throws IOException
{
byte[] buffer = new byte[64]; // 64 byte buffer
long copied = 0;
int toCopy = buffer.length;
while (true)
{
if (limit < buffer.length + copied)
toCopy = (int) (limit - copied);
int sofar = from.read(buffer, 0, toCopy);
if (sofar == -1)
break;
to.write(buffer, 0, sofar);
copied += sofar;
if (limit == copied)
break;
}
return copied;
}
public static File getToolsOutputDirectory()
{
File historyDir = new File(System.getProperty("user.home"), ".cassandra");
FileUtils.createDirectory(historyDir);
return historyDir;
}
public static boolean isWindows()
{
return IS_WINDOWS;
}
public static boolean hasProcFS()
{
return HAS_PROCFS;
}
public static void updateWithShort(MessageDigest digest, int val)
{
digest.update((byte) ((val >> 8) & 0xFF));
digest.update((byte) (val & 0xFF));
}
public static void updateWithByte(MessageDigest digest, int val)
{
digest.update((byte) (val & 0xFF));
}
public static void updateWithInt(MessageDigest digest, int val)
{
digest.update((byte) ((val >>> 24) & 0xFF));
digest.update((byte) ((val >>> 16) & 0xFF));
digest.update((byte) ((val >>> 8) & 0xFF));
digest.update((byte) ((val >>> 0) & 0xFF));
}
public static void updateWithLong(MessageDigest digest, long val)
{
digest.update((byte) ((val >>> 56) & 0xFF));
digest.update((byte) ((val >>> 48) & 0xFF));
digest.update((byte) ((val >>> 40) & 0xFF));
digest.update((byte) ((val >>> 32) & 0xFF));
digest.update((byte) ((val >>> 24) & 0xFF));
digest.update((byte) ((val >>> 16) & 0xFF));
digest.update((byte) ((val >>> 8) & 0xFF));
digest.update((byte) ((val >>> 0) & 0xFF));
}
public static void updateWithBoolean(MessageDigest digest, boolean val)
{
updateWithByte(digest, val ? 0 : 1);
}
public static void closeAll(List<? extends AutoCloseable> l) throws Exception
{
Exception toThrow = null;
for (AutoCloseable c : l)
{
try
{
c.close();
}
catch (Exception e)
{
if (toThrow == null)
toThrow = e;
else
toThrow.addSuppressed(e);
}
}
if (toThrow != null)
throw toThrow;
}
}
| apache-2.0 |
GerritCodeReview/gerrit | java/com/google/gerrit/entities/LabelType.java | 10614 | // Copyright (C) 2008 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.google.gerrit.entities;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.gerrit.common.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
@AutoValue
public abstract class LabelType {
public static final boolean DEF_ALLOW_POST_SUBMIT = true;
public static final boolean DEF_CAN_OVERRIDE = true;
public static final boolean DEF_COPY_ALL_SCORES_IF_LIST_OF_FILES_DID_NOT_CHANGE = false;
public static final boolean DEF_COPY_ALL_SCORES_IF_NO_CHANGE = true;
public static final boolean DEF_COPY_ALL_SCORES_IF_NO_CODE_CHANGE = false;
public static final boolean DEF_COPY_ALL_SCORES_ON_TRIVIAL_REBASE = false;
public static final boolean DEF_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE = false;
public static final boolean DEF_COPY_ANY_SCORE = false;
public static final boolean DEF_COPY_MAX_SCORE = false;
public static final boolean DEF_COPY_MIN_SCORE = false;
public static final ImmutableList<Short> DEF_COPY_VALUES = ImmutableList.of();
public static final boolean DEF_IGNORE_SELF_APPROVAL = false;
public static LabelType withDefaultValues(String name) {
checkName(name);
List<LabelValue> values = new ArrayList<>(2);
values.add(LabelValue.create((short) 0, "Rejected"));
values.add(LabelValue.create((short) 1, "Approved"));
return create(name, values);
}
public static String checkName(String name) throws IllegalArgumentException {
checkNameInternal(name);
if ("SUBM".equals(name)) {
throw new IllegalArgumentException("Reserved label name \"" + name + "\"");
}
return name;
}
public static String checkNameInternal(String name) throws IllegalArgumentException {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("Empty label name");
}
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if ((i == 0 && c == '-')
|| !((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == '-')) {
throw new IllegalArgumentException("Illegal label name \"" + name + "\"");
}
}
return name;
}
private static ImmutableList<LabelValue> sortValues(List<LabelValue> values) {
if (values.isEmpty()) {
return ImmutableList.of();
}
values = values.stream().sorted(comparing(LabelValue::getValue)).collect(toList());
short v = values.get(0).getValue();
short i = 0;
ImmutableList.Builder<LabelValue> result = ImmutableList.builder();
// Fill in any missing values with empty text.
while (i < values.size()) {
while (v < values.get(i).getValue()) {
result.add(LabelValue.create(v++, ""));
}
v++;
result.add(values.get(i++));
}
return result.build();
}
public abstract String getName();
public abstract Optional<String> getDescription();
public abstract LabelFunction getFunction();
public abstract boolean isCopyAnyScore();
public abstract boolean isCopyMinScore();
public abstract boolean isCopyMaxScore();
public abstract boolean isCopyAllScoresIfListOfFilesDidNotChange();
public abstract boolean isCopyAllScoresOnMergeFirstParentUpdate();
public abstract boolean isCopyAllScoresOnTrivialRebase();
public abstract boolean isCopyAllScoresIfNoCodeChange();
public abstract boolean isCopyAllScoresIfNoChange();
public abstract ImmutableList<Short> getCopyValues();
public abstract boolean isAllowPostSubmit();
public abstract boolean isIgnoreSelfApproval();
public abstract short getDefaultValue();
public abstract ImmutableList<LabelValue> getValues();
public abstract short getMaxNegative();
public abstract short getMaxPositive();
public abstract boolean isCanOverride();
public abstract Optional<String> getCopyCondition();
@Nullable
public abstract ImmutableList<String> getRefPatterns();
public abstract ImmutableMap<Short, LabelValue> getByValue();
public static LabelType create(String name, List<LabelValue> valueList) {
return LabelType.builder(name, valueList).build();
}
public static LabelType.Builder builder(String name, List<LabelValue> valueList) {
return new AutoValue_LabelType.Builder()
.setName(name)
.setDescription(Optional.empty())
.setValues(valueList)
.setDefaultValue((short) 0)
.setFunction(LabelFunction.MAX_WITH_BLOCK)
.setMaxNegative(Short.MIN_VALUE)
.setMaxPositive(Short.MAX_VALUE)
.setCanOverride(DEF_CAN_OVERRIDE)
.setCopyAllScoresIfListOfFilesDidNotChange(
DEF_COPY_ALL_SCORES_IF_LIST_OF_FILES_DID_NOT_CHANGE)
.setCopyAllScoresIfNoChange(DEF_COPY_ALL_SCORES_IF_NO_CHANGE)
.setCopyAllScoresIfNoCodeChange(DEF_COPY_ALL_SCORES_IF_NO_CODE_CHANGE)
.setCopyAllScoresOnTrivialRebase(DEF_COPY_ALL_SCORES_ON_TRIVIAL_REBASE)
.setCopyAllScoresOnMergeFirstParentUpdate(DEF_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE)
.setCopyAnyScore(DEF_COPY_ANY_SCORE)
.setCopyMaxScore(DEF_COPY_MAX_SCORE)
.setCopyMinScore(DEF_COPY_MIN_SCORE)
.setCopyValues(DEF_COPY_VALUES)
.setAllowPostSubmit(DEF_ALLOW_POST_SUBMIT)
.setIgnoreSelfApproval(DEF_IGNORE_SELF_APPROVAL);
}
public boolean matches(PatchSetApproval psa) {
return psa.labelId().get().equalsIgnoreCase(getName());
}
public LabelValue getMin() {
if (getValues().isEmpty()) {
return null;
}
return getValues().get(0);
}
public LabelValue getMax() {
if (getValues().isEmpty()) {
return null;
}
return getValues().get(getValues().size() - 1);
}
public boolean isMaxNegative(PatchSetApproval ca) {
return getMaxNegative() == ca.value();
}
public boolean isMaxPositive(PatchSetApproval ca) {
return getMaxPositive() == ca.value();
}
public LabelValue getValue(short value) {
return getByValue().get(value);
}
public LabelValue getValue(PatchSetApproval ca) {
return getByValue().get(ca.value());
}
public LabelId getLabelId() {
return LabelId.create(getName());
}
@Override
public final String toString() {
StringBuilder sb = new StringBuilder(getName()).append('[');
LabelValue min = getMin();
LabelValue max = getMax();
if (min != null && max != null) {
sb.append(
new PermissionRange(Permission.forLabel(getName()), min.getValue(), max.getValue())
.toString()
.trim());
} else if (min != null) {
sb.append(min.formatValue().trim());
} else if (max != null) {
sb.append(max.formatValue().trim());
}
sb.append(']');
return sb.toString();
}
public abstract Builder toBuilder();
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder setName(String name);
public abstract Builder setDescription(Optional<String> description);
public abstract Builder setFunction(LabelFunction function);
public abstract Builder setCanOverride(boolean canOverride);
public abstract Builder setAllowPostSubmit(boolean allowPostSubmit);
public abstract Builder setIgnoreSelfApproval(boolean ignoreSelfApproval);
public abstract Builder setRefPatterns(@Nullable List<String> refPatterns);
public abstract Builder setValues(List<LabelValue> values);
public abstract Builder setDefaultValue(short defaultValue);
public abstract Builder setCopyAnyScore(boolean copyAnyScore);
public abstract Builder setCopyCondition(@Nullable String copyCondition);
public abstract Builder setCopyMinScore(boolean copyMinScore);
public abstract Builder setCopyMaxScore(boolean copyMaxScore);
public abstract Builder setCopyAllScoresIfListOfFilesDidNotChange(
boolean copyAllScoresIfListOfFilesDidNotChange);
public abstract Builder setCopyAllScoresOnMergeFirstParentUpdate(
boolean copyAllScoresOnMergeFirstParentUpdate);
public abstract Builder setCopyAllScoresOnTrivialRebase(boolean copyAllScoresOnTrivialRebase);
public abstract Builder setCopyAllScoresIfNoCodeChange(boolean copyAllScoresIfNoCodeChange);
public abstract Builder setCopyAllScoresIfNoChange(boolean copyAllScoresIfNoChange);
public abstract Builder setCopyValues(Collection<Short> copyValues);
public abstract Builder setMaxNegative(short maxNegative);
public abstract Builder setMaxPositive(short maxPositive);
public abstract ImmutableList<LabelValue> getValues();
protected abstract String getName();
protected abstract ImmutableList<Short> getCopyValues();
protected abstract Builder setByValue(ImmutableMap<Short, LabelValue> byValue);
@Nullable
protected abstract ImmutableList<String> getRefPatterns();
protected abstract LabelType autoBuild();
public LabelType build() throws IllegalArgumentException {
setName(checkName(getName()));
if (getRefPatterns() == null || getRefPatterns().isEmpty()) {
// Empty to null
setRefPatterns(null);
}
List<LabelValue> valueList = sortValues(getValues());
setValues(valueList);
if (!valueList.isEmpty()) {
if (valueList.get(0).getValue() < 0) {
setMaxNegative(valueList.get(0).getValue());
}
if (valueList.get(valueList.size() - 1).getValue() > 0) {
setMaxPositive(valueList.get(valueList.size() - 1).getValue());
}
}
ImmutableMap.Builder<Short, LabelValue> byValue = ImmutableMap.builder();
for (LabelValue v : valueList) {
byValue.put(v.getValue(), v);
}
setByValue(byValue.build());
setCopyValues(ImmutableList.sortedCopyOf(getCopyValues()));
return autoBuild();
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-config/src/main/java/com/amazonaws/services/config/model/transform/ConformancePackRuleComplianceJsonUnmarshaller.java | 3482 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.config.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.config.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ConformancePackRuleCompliance JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ConformancePackRuleComplianceJsonUnmarshaller implements Unmarshaller<ConformancePackRuleCompliance, JsonUnmarshallerContext> {
public ConformancePackRuleCompliance unmarshall(JsonUnmarshallerContext context) throws Exception {
ConformancePackRuleCompliance conformancePackRuleCompliance = new ConformancePackRuleCompliance();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("ConfigRuleName", targetDepth)) {
context.nextToken();
conformancePackRuleCompliance.setConfigRuleName(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("ComplianceType", targetDepth)) {
context.nextToken();
conformancePackRuleCompliance.setComplianceType(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Controls", targetDepth)) {
context.nextToken();
conformancePackRuleCompliance.setControls(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))
.unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return conformancePackRuleCompliance;
}
private static ConformancePackRuleComplianceJsonUnmarshaller instance;
public static ConformancePackRuleComplianceJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ConformancePackRuleComplianceJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
treasure-data/digdag | digdag-cli/src/main/java/io/digdag/cli/client/ShowWorkflow.java | 3478 | package io.digdag.cli.client;
import com.beust.jcommander.Parameter;
import com.google.common.base.Optional;
import io.digdag.cli.SystemExitException;
import io.digdag.client.DigdagClient;
import io.digdag.client.api.Id;
import io.digdag.client.api.RestProject;
import io.digdag.client.api.RestWorkflowDefinition;
import javax.ws.rs.NotFoundException;
import java.util.List;
import static io.digdag.cli.SystemExitException.systemExit;
public class ShowWorkflow
extends ClientCommand
{
@Parameter(names = {"--last-id"})
Id lastId = null;
@Parameter(names = {"--count"})
int count = 100;
@Override
public void mainWithClientException()
throws Exception
{
switch (args.size()) {
case 0:
showWorkflows(null);
break;
case 1:
showWorkflows(args.get(0));
break;
case 2:
showWorkflowDetails(args.get(0), args.get(1));
break;
default:
throw usage(null);
}
}
public SystemExitException usage(String error)
{
err.println("Usage: " + programName + " workflows [project-name] [name]");
err.println(" Options:");
err.println(" --count number number of workflows");
err.println(" --last-id id last id of workflow");
showCommonOptions();
return systemExit(error);
}
private void showWorkflows(String projName)
throws Exception
{
DigdagClient client = buildClient();
if (projName != null) {
RestProject proj = client.getProject(projName);
ln(" %s", proj.getName());
for (RestWorkflowDefinition def : client.getWorkflowDefinitions(proj.getId()).getWorkflows()) {
ln(" %s", def.getName());
}
}
else {
List<RestWorkflowDefinition> defs = client.getWorkflowDefinitions(Optional.fromNullable(lastId), count).getWorkflows();
String lastProjName = null;
for (RestWorkflowDefinition def : defs) {
if (!def.getProject().getName().equals(lastProjName)) {
ln(" %s", def.getProject().getName());
lastProjName = def.getProject().getName();
}
ln(" %s", def.getName());
}
}
ln("");
err.println("Use `" + programName + " workflows <project-name> <name>` to show details.");
}
private void showWorkflowDetails(String projName, String defName)
throws Exception
{
DigdagClient client = buildClient();
if (projName != null) {
RestProject proj = client.getProject(projName);
RestWorkflowDefinition def = client.getWorkflowDefinition(proj.getId(), defName);
String yaml = yamlMapper().toYaml(def.getConfig());
ln("%s", yaml);
}
else {
for (RestProject proj : client.getProjects().getProjects()) {
try {
RestWorkflowDefinition def = client.getWorkflowDefinition(proj.getId(), defName);
String yaml = yamlMapper().toYaml(def.getConfig());
ln("%s", yaml);
return;
}
catch (NotFoundException ex) {
}
}
throw systemExit("Workflow definition '" + defName + "' does not exist.");
}
}
}
| apache-2.0 |
HaStr/kieker | kieker-analysis/src-gen/kieker/analysis/model/analysisMetaModel/impl/MAnalysisMetaModelFactory.java | 5165 | /**
*/
package kieker.analysis.model.analysisMetaModel.impl;
import kieker.analysis.model.analysisMetaModel.*;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class MAnalysisMetaModelFactory extends EFactoryImpl implements MIAnalysisMetaModelFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static MIAnalysisMetaModelFactory init() {
try {
MIAnalysisMetaModelFactory theAnalysisMetaModelFactory = (MIAnalysisMetaModelFactory)EPackage.Registry.INSTANCE.getEFactory(MIAnalysisMetaModelPackage.eNS_URI);
if (theAnalysisMetaModelFactory != null) {
return theAnalysisMetaModelFactory;
}
}
catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new MAnalysisMetaModelFactory();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MAnalysisMetaModelFactory() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case MIAnalysisMetaModelPackage.PROJECT: return createProject();
case MIAnalysisMetaModelPackage.INPUT_PORT: return createInputPort();
case MIAnalysisMetaModelPackage.OUTPUT_PORT: return createOutputPort();
case MIAnalysisMetaModelPackage.PROPERTY: return createProperty();
case MIAnalysisMetaModelPackage.FILTER: return createFilter();
case MIAnalysisMetaModelPackage.READER: return createReader();
case MIAnalysisMetaModelPackage.REPOSITORY: return createRepository();
case MIAnalysisMetaModelPackage.DEPENDENCY: return createDependency();
case MIAnalysisMetaModelPackage.REPOSITORY_CONNECTOR: return createRepositoryConnector();
case MIAnalysisMetaModelPackage.DISPLAY: return createDisplay();
case MIAnalysisMetaModelPackage.VIEW: return createView();
case MIAnalysisMetaModelPackage.DISPLAY_CONNECTOR: return createDisplayConnector();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MIProject createProject() {
MProject project = new MProject();
return project;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MIInputPort createInputPort() {
MInputPort inputPort = new MInputPort();
return inputPort;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MIOutputPort createOutputPort() {
MOutputPort outputPort = new MOutputPort();
return outputPort;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MIProperty createProperty() {
MProperty property = new MProperty();
return property;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MIFilter createFilter() {
MFilter filter = new MFilter();
return filter;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MIReader createReader() {
MReader reader = new MReader();
return reader;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MIRepository createRepository() {
MRepository repository = new MRepository();
return repository;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MIDependency createDependency() {
MDependency dependency = new MDependency();
return dependency;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MIRepositoryConnector createRepositoryConnector() {
MRepositoryConnector repositoryConnector = new MRepositoryConnector();
return repositoryConnector;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MIDisplay createDisplay() {
MDisplay display = new MDisplay();
return display;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MIView createView() {
MView view = new MView();
return view;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MIDisplayConnector createDisplayConnector() {
MDisplayConnector displayConnector = new MDisplayConnector();
return displayConnector;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MIAnalysisMetaModelPackage getAnalysisMetaModelPackage() {
return (MIAnalysisMetaModelPackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static MIAnalysisMetaModelPackage getPackage() {
return MIAnalysisMetaModelPackage.eINSTANCE;
}
} //MAnalysisMetaModelFactory
| apache-2.0 |
frank-tan/Super-Duo | football_scores/app/src/main/java/barqsoft/footballscores/data/DatabaseContract.java | 1997 | package barqsoft.footballscores.data;
import android.content.ContentResolver;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Created by yehya khaled on 2/25/2015.
*/
public class DatabaseContract
{
public static final String SCORES_TABLE = "scores_table";
public static final class scores_table implements BaseColumns
{
//Table data
public static final String LEAGUE_COL = "league";
public static final String DATE_COL = "date";
public static final String TIME_COL = "time";
public static final String HOME_COL = "home";
public static final String AWAY_COL = "away";
public static final String HOME_GOALS_COL = "home_goals";
public static final String AWAY_GOALS_COL = "away_goals";
public static final String MATCH_ID = "match_id";
public static final String MATCH_DAY = "match_day";
//public static Uri SCORES_CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH)
//.build();
//Types
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH;
public static final String CONTENT_ITEM_TYPE =
ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH;
public static Uri buildScoreWithLeague()
{
return BASE_CONTENT_URI.buildUpon().appendPath("league").build();
}
public static Uri buildScoreWithId()
{
return BASE_CONTENT_URI.buildUpon().appendPath("id").build();
}
public static Uri buildScoreWithDate()
{
return BASE_CONTENT_URI.buildUpon().appendPath("date").build();
}
}
//URI data
public static final String CONTENT_AUTHORITY = "barqsoft.footballscores";
public static final String PATH = "scores";
public static Uri BASE_CONTENT_URI = Uri.parse("content://"+CONTENT_AUTHORITY);
}
| apache-2.0 |
blusechen/venus | venus-commons/venus-common-exception/src/main/java/com/meidusa/venus/exception/InvocationAbortedException.java | 689 | /**
*
*/
package com.meidusa.venus.exception;
import com.meidusa.venus.annotations.RemoteException;
import com.meidusa.venus.annotations.RemoteException.Level;
/**
*
*
* @author Sun Ning
* @since 2010-3-16
*/
@RemoteException(errorCode=VenusExceptionCodeConstant.SERVICE_UNAVAILABLE_EXCEPTION,level=Level.ERROR)
public class InvocationAbortedException extends AbstractVenusException {
private static final long serialVersionUID = 1L;
public InvocationAbortedException(String msg) {
super("InvocationAbortedException:" + msg);
}
@Override
public int getErrorCode() {
return VenusExceptionCodeConstant.SERVICE_UNAVAILABLE_EXCEPTION;
}
}
| apache-2.0 |
justinsb/cloudata | cloudata-mq/src/main/java/com/cloudata/mq/web/QueueUser.java | 210 | package com.cloudata.mq.web;
public class QueueUser {
final String scope;
public QueueUser(String scope) {
super();
this.scope = scope;
}
public String getScope() {
return scope;
}
}
| apache-2.0 |
bradtm/pulsar | pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java | 49503 | /**
* 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.pulsar.client.impl;
import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.pulsar.checksum.utils.Crc32cChecksum.computeChecksum;
import static org.apache.pulsar.checksum.utils.Crc32cChecksum.resumeChecksum;
import static org.apache.pulsar.common.api.Commands.hasChecksum;
import static org.apache.pulsar.common.api.Commands.readChecksum;
import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import org.apache.pulsar.client.api.CompressionType;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.ProducerConfiguration;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.common.api.Commands;
import org.apache.pulsar.common.api.DoubleByteBuf;
import org.apache.pulsar.common.api.Commands.ChecksumType;
import org.apache.pulsar.common.api.proto.PulsarApi;
import org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata;
import org.apache.pulsar.common.api.proto.PulsarApi.ProtocolVersion;
import org.apache.pulsar.common.compression.CompressionCodec;
import org.apache.pulsar.common.compression.CompressionCodecProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Queues;
import io.netty.buffer.ByteBuf;
import io.netty.util.Recycler;
import io.netty.util.Recycler.Handle;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
public class ProducerImpl extends ProducerBase implements TimerTask {
// Producer id, used to identify a producer within a single connection
private final long producerId;
// Variable is used through the atomic updater
@SuppressWarnings("unused")
private volatile long msgIdGenerator = 0;
private final BlockingQueue<OpSendMsg> pendingMessages;
private final BlockingQueue<OpSendMsg> pendingCallbacks;
private final Semaphore semaphore;
private volatile Timeout sendTimeout = null;
private long createProducerTimeout;
private final int maxNumMessagesInBatch;
private final BatchMessageContainer batchMessageContainer;
// Globally unique producer name
private String producerName;
private String connectionId;
private String connectedSince;
private final int partitionIndex;
private final ProducerStats stats;
private final CompressionCodec compressor;
private static final AtomicLongFieldUpdater<ProducerImpl> msgIdGeneratorUpdater = AtomicLongFieldUpdater
.newUpdater(ProducerImpl.class, "msgIdGenerator");
public ProducerImpl(PulsarClientImpl client, String topic, String producerName, ProducerConfiguration conf,
CompletableFuture<Producer> producerCreatedFuture, int partitionIndex) {
super(client, topic, conf, producerCreatedFuture);
this.producerId = client.newProducerId();
this.producerName = producerName;
this.partitionIndex = partitionIndex;
this.pendingMessages = Queues.newArrayBlockingQueue(conf.getMaxPendingMessages());
this.pendingCallbacks = Queues.newArrayBlockingQueue(conf.getMaxPendingMessages());
this.semaphore = new Semaphore(conf.getMaxPendingMessages(), true);
this.compressor = CompressionCodecProvider
.getCompressionCodec(convertCompressionType(conf.getCompressionType()));
if (conf.getSendTimeoutMs() > 0) {
sendTimeout = client.timer().newTimeout(this, conf.getSendTimeoutMs(), TimeUnit.MILLISECONDS);
}
this.createProducerTimeout = System.currentTimeMillis() + client.getConfiguration().getOperationTimeoutMs();
if (conf.getBatchingEnabled()) {
this.maxNumMessagesInBatch = conf.getBatchingMaxMessages();
this.batchMessageContainer = new BatchMessageContainer(maxNumMessagesInBatch,
convertCompressionType(conf.getCompressionType()), topic, producerName);
} else {
this.maxNumMessagesInBatch = 1;
this.batchMessageContainer = null;
}
if (client.getConfiguration().getStatsIntervalSeconds() > 0) {
stats = new ProducerStats(client, conf, this);
} else {
stats = ProducerStats.PRODUCER_STATS_DISABLED;
}
grabCnx();
}
private boolean isBatchMessagingEnabled() {
return conf.getBatchingEnabled();
}
@Override
public CompletableFuture<MessageId> sendAsync(Message message) {
CompletableFuture<MessageId> future = new CompletableFuture<>();
sendAsync(message, new SendCallback() {
SendCallback nextCallback = null;
long createdAt = System.nanoTime();
@Override
public CompletableFuture<MessageId> getFuture() {
return future;
}
@Override
public SendCallback getNextSendCallback() {
return nextCallback;
}
@Override
public void sendComplete(Exception e) {
if (e != null) {
stats.incrementSendFailed();
future.completeExceptionally(e);
} else {
future.complete(message.getMessageId());
stats.incrementNumAcksReceived(System.nanoTime() - createdAt);
}
while (nextCallback != null) {
SendCallback sendCallback = nextCallback;
if (e != null) {
stats.incrementSendFailed();
sendCallback.getFuture().completeExceptionally(e);
} else {
sendCallback.getFuture().complete(message.getMessageId());
stats.incrementNumAcksReceived(System.nanoTime() - createdAt);
}
nextCallback = nextCallback.getNextSendCallback();
sendCallback = null;
}
}
@Override
public void addCallback(SendCallback scb) {
nextCallback = scb;
}
});
return future;
}
public void sendAsync(Message message, SendCallback callback) {
checkArgument(message instanceof MessageImpl);
if (!isValidProducerState(callback)) {
return;
}
if (!canEnqueueRequest(callback)) {
return;
}
MessageImpl msg = (MessageImpl) message;
MessageMetadata.Builder msgMetadata = msg.getMessageBuilder();
ByteBuf payload = msg.getDataBuffer();
// If compression is enabled, we are compressing, otherwise it will simply use the same buffer
int uncompressedSize = payload.readableBytes();
ByteBuf compressedPayload = payload;
// batch will be compressed when closed
if (!isBatchMessagingEnabled()) {
compressedPayload = compressor.encode(payload);
payload.release();
}
if (!msg.isReplicated() && msgMetadata.hasProducerName()) {
callback.sendComplete(new PulsarClientException.InvalidMessageException("Cannot re-use the same message"));
compressedPayload.release();
return;
}
try {
synchronized (this) {
long sequenceId = msgIdGeneratorUpdater.getAndIncrement(this);
if (!msgMetadata.hasPublishTime()) {
msgMetadata.setPublishTime(System.currentTimeMillis());
checkArgument(!msgMetadata.hasProducerName());
checkArgument(!msgMetadata.hasSequenceId());
msgMetadata.setProducerName(producerName);
msgMetadata.setSequenceId(sequenceId);
if (conf.getCompressionType() != CompressionType.NONE) {
msgMetadata.setCompression(convertCompressionType(conf.getCompressionType()));
msgMetadata.setUncompressedSize(uncompressedSize);
}
}
if (isBatchMessagingEnabled()) {
// handle boundary cases where message being added would exceed
// batch size and/or max message size
if (batchMessageContainer.hasSpaceInBatch(msg)) {
batchMessageContainer.add(msg, callback);
payload.release();
if (batchMessageContainer.numMessagesInBatch == maxNumMessagesInBatch
|| batchMessageContainer.currentBatchSizeBytes >= BatchMessageContainer.MAX_MESSAGE_BATCH_SIZE_BYTES) {
batchMessageAndSend();
}
} else {
doBatchSendAndAdd(msg, callback, payload);
}
} else {
ByteBuf cmd = sendMessage(producerId, sequenceId, 1, msgMetadata.build(), compressedPayload);
msgMetadata.recycle();
final OpSendMsg op = OpSendMsg.create(msg, cmd, sequenceId, callback);
op.setNumMessagesInBatch(1);
op.setBatchSizeByte(payload.readableBytes());
pendingMessages.put(op);
// Read the connection before validating if it's still connected, so that we avoid reading a null
// value
ClientCnx cnx = cnx();
if (isConnected()) {
// If we do have a connection, the message is sent immediately, otherwise we'll try again once a
// new
// connection is established
cmd.retain();
cnx.ctx().channel().eventLoop().execute(WriteInEventLoopCallback.create(this, cnx, op));
stats.updateNumMsgsSent(op.numMessagesInBatch, op.batchSizeByte);
} else {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Connection is not ready -- sequenceId {}", topic, producerName,
sequenceId);
}
}
}
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
semaphore.release();
callback.sendComplete(new PulsarClientException(ie));
} catch (Throwable t) {
semaphore.release();
callback.sendComplete(new PulsarClientException(t));
}
}
private ByteBuf sendMessage(long producerId, long sequenceId, int numMessages, MessageMetadata msgMetadata,
ByteBuf compressedPayload) throws IOException {
ChecksumType checksumType;
if (getClientCnx() == null
|| getClientCnx().getRemoteEndpointProtocolVersion() >= brokerChecksumSupportedVersion()) {
checksumType = ChecksumType.Crc32c;
} else {
checksumType = ChecksumType.None;
}
return Commands.newSend(producerId, sequenceId, numMessages, checksumType, msgMetadata, compressedPayload);
}
private void doBatchSendAndAdd(MessageImpl msg, SendCallback callback, ByteBuf payload) {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Closing out batch to accomodate large message with size {}", topic, producerName,
msg.getDataBuffer().readableBytes());
}
batchMessageAndSend();
batchMessageContainer.add(msg, callback);
payload.release();
}
private boolean isValidProducerState(SendCallback callback) {
switch (getState()) {
case Ready:
// OK
case Connecting:
// We are OK to queue the messages on the client, it will be sent to the broker once we get the connection
return true;
case Closing:
case Closed:
callback.sendComplete(new PulsarClientException.AlreadyClosedException("Producer already closed"));
return false;
case Terminated:
callback.sendComplete(new PulsarClientException.TopicTerminatedException("Topic was terminated"));
return false;
case Failed:
case Uninitialized:
default:
callback.sendComplete(new PulsarClientException.NotConnectedException());
return false;
}
}
private boolean canEnqueueRequest(SendCallback callback) {
try {
if (conf.getBlockIfQueueFull()) {
semaphore.acquire();
} else {
if (!semaphore.tryAcquire()) {
callback.sendComplete(
new PulsarClientException.ProducerQueueIsFullError("Producer send queue is full"));
return false;
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
callback.sendComplete(new PulsarClientException(e));
return false;
}
return true;
}
private static final class WriteInEventLoopCallback implements Runnable {
private ProducerImpl producer;
private ClientCnx cnx;
private OpSendMsg op;
static WriteInEventLoopCallback create(ProducerImpl producer, ClientCnx cnx, OpSendMsg op) {
WriteInEventLoopCallback c = RECYCLER.get();
c.producer = producer;
c.cnx = cnx;
c.op = op;
return c;
}
@Override
public void run() {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Sending message cnx {}, sequenceId {}", producer.topic, producer.producerName, cnx,
op.sequenceId);
}
try {
cnx.ctx().writeAndFlush(op.cmd, cnx.ctx().voidPromise());
} finally {
recycle();
}
}
private void recycle() {
producer = null;
cnx = null;
op = null;
RECYCLER.recycle(this, recyclerHandle);
}
private final Handle recyclerHandle;
private WriteInEventLoopCallback(Handle recyclerHandle) {
this.recyclerHandle = recyclerHandle;
}
private static final Recycler<WriteInEventLoopCallback> RECYCLER = new Recycler<WriteInEventLoopCallback>() {
@Override
protected WriteInEventLoopCallback newObject(Handle handle) {
return new WriteInEventLoopCallback(handle);
}
};
}
@Override
public CompletableFuture<Void> closeAsync() {
final State currentState = getAndUpdateState(state -> {
if (state == State.Closed) {
return state;
}
return State.Closing;
});
if (currentState == State.Closed || currentState == State.Closing) {
return CompletableFuture.completedFuture(null);
}
Timeout timeout = sendTimeout;
if (timeout != null) {
timeout.cancel();
sendTimeout = null;
}
stats.cancelStatsTimeout();
ClientCnx cnx = cnx();
if (cnx == null || currentState != State.Ready) {
log.info("[{}] [{}] Closed Producer (not connected)", topic, producerName);
synchronized (this) {
setState(State.Closed);
client.cleanupProducer(this);
PulsarClientException ex = new PulsarClientException.AlreadyClosedException(
"Producer was already closed");
pendingMessages.forEach(msg -> {
msg.callback.sendComplete(ex);
msg.cmd.release();
msg.recycle();
});
pendingMessages.clear();
}
return CompletableFuture.completedFuture(null);
}
long requestId = client.newRequestId();
ByteBuf cmd = Commands.newCloseProducer(producerId, requestId);
CompletableFuture<Void> closeFuture = new CompletableFuture<>();
cnx.sendRequestWithId(cmd, requestId).handle((v, exception) -> {
cnx.removeProducer(producerId);
if (exception == null || !cnx.ctx().channel().isActive()) {
// Either we've received the success response for the close producer command from the broker, or the
// connection did break in the meantime. In any case, the producer is gone.
synchronized (ProducerImpl.this) {
log.info("[{}] [{}] Closed Producer", topic, producerName);
setState(State.Closed);
pendingMessages.forEach(msg -> {
msg.cmd.release();
msg.recycle();
});
pendingMessages.clear();
}
closeFuture.complete(null);
client.cleanupProducer(this);
} else {
closeFuture.completeExceptionally(exception);
}
return null;
});
return closeFuture;
}
@Override
public boolean isConnected() {
return getClientCnx() != null && (getState() == State.Ready);
}
public boolean isWritable() {
ClientCnx cnx = getClientCnx();
return cnx != null && cnx.channel().isWritable();
}
public void terminated(ClientCnx cnx) {
State previousState = getAndUpdateState(state -> (state == State.Closed ? State.Closed : State.Terminated));
if (previousState != State.Terminated && previousState != State.Closed) {
log.info("[{}] [{}] The topic has been terminated", topic, producerName);
setClientCnx(null);
failPendingMessages(cnx,
new PulsarClientException.TopicTerminatedException("The topic has been terminated"));
}
}
void ackReceived(ClientCnx cnx, long sequenceId, long ledgerId, long entryId) {
OpSendMsg op = null;
boolean callback = false;
synchronized (this) {
op = pendingMessages.peek();
if (op == null) {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Got ack for timed out msg {}", topic, producerName, sequenceId);
}
return;
}
long expectedSequenceId = op.sequenceId;
if (sequenceId > expectedSequenceId) {
log.warn("[{}] [{}] Got ack for msg. expecting: {} - got: {} - queue-size: {}", topic, producerName,
expectedSequenceId, sequenceId, pendingMessages.size());
// Force connection closing so that messages can be retransmitted in a new connection
cnx.channel().close();
} else if (sequenceId < expectedSequenceId) {
// Ignoring the ack since it's referring to a message that has already timed out.
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Got ack for timed out msg {} last-seq: {}", topic, producerName, sequenceId,
expectedSequenceId);
}
} else {
// Message was persisted correctly
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Received ack for msg {} ", topic, producerName, sequenceId);
}
pendingMessages.remove();
semaphore.release(op.numMessagesInBatch);
callback = true;
pendingCallbacks.add(op);
}
}
if (callback) {
op = pendingCallbacks.poll();
if (op != null) {
op.setMessageId(ledgerId, entryId, partitionIndex);
try {
// Need to protect ourselves from any exception being thrown in the future handler from the
// application
op.callback.sendComplete(null);
} catch (Throwable t) {
log.warn("[{}] [{}] Got exception while completing the callback for msg {}:", topic, producerName,
sequenceId, t);
}
ReferenceCountUtil.safeRelease(op.cmd);
op.recycle();
}
}
}
/**
* Checks message checksum to retry if message was corrupted while sending to broker. Recomputes checksum of the
* message header-payload again.
* <ul>
* <li><b>if matches with existing checksum</b>: it means message was corrupt while sending to broker. So, resend
* message</li>
* <li><b>if doesn't match with existing checksum</b>: it means message is already corrupt and can't retry again.
* So, fail send-message by failing callback</li>
* </ul>
*
* @param cnx
* @param sequenceId
*/
protected synchronized void recoverChecksumError(ClientCnx cnx, long sequenceId) {
OpSendMsg op = pendingMessages.peek();
if (op == null) {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Got send failure for timed out msg {}", topic, producerName, sequenceId);
}
} else {
long expectedSequenceId = op.sequenceId;
if (sequenceId == expectedSequenceId) {
boolean corrupted = !verifyLocalBufferIsNotCorrupted(op);
if (corrupted) {
// remove message from pendingMessages queue and fail callback
pendingMessages.remove();
semaphore.release(op.numMessagesInBatch);
try {
op.callback.sendComplete(
new PulsarClientException.ChecksumException("Checksum failded on corrupt message"));
} catch (Throwable t) {
log.warn("[{}] [{}] Got exception while completing the callback for msg {}:", topic,
producerName, sequenceId, t);
}
ReferenceCountUtil.safeRelease(op.cmd);
op.recycle();
return;
} else {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Message is not corrupted, retry send-message with sequenceId {}", topic,
producerName, sequenceId);
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Corrupt message is already timed out {}", topic, producerName, sequenceId);
}
}
}
// as msg is not corrupted : let producer resend pending-messages again including checksum failed message
resendMessages(cnx);
}
/**
* Computes checksum again and verifies it against existing checksum. If checksum doesn't match it means that
* message is corrupt.
*
* @param op
* @return returns true only if message is not modified and computed-checksum is same as previous checksum else
* return false that means that message is corrupted. Returns true if checksum is not present.
*/
protected boolean verifyLocalBufferIsNotCorrupted(OpSendMsg op) {
DoubleByteBuf msg = getDoubleByteBuf(op.cmd);
if (msg != null) {
ByteBuf headerFrame = msg.getFirst();
msg.markReaderIndex();
headerFrame.markReaderIndex();
try {
// skip bytes up to checksum index
headerFrame.skipBytes(4); // skip [total-size]
int cmdSize = (int) headerFrame.readUnsignedInt();
headerFrame.skipBytes(cmdSize);
// verify if checksum present
if (hasChecksum(headerFrame)) {
int checksum = readChecksum(headerFrame).intValue();
// msg.readerIndex is already at header-payload index, Recompute checksum for headers-payload
int metadataChecksum = computeChecksum(headerFrame);
long computedChecksum = resumeChecksum(metadataChecksum, msg.getSecond());
return checksum == computedChecksum;
} else {
log.warn("[{}] [{}] checksum is not present into message with id {}", topic, producerName,
op.sequenceId);
}
} finally {
headerFrame.resetReaderIndex();
msg.resetReaderIndex();
}
return true;
} else {
log.warn("[{}] Failed while casting {} into DoubleByteBuf", producerName, op.cmd.getClass().getName());
return false;
}
}
protected static final class OpSendMsg {
MessageImpl msg;
List<MessageImpl> msgs;
ByteBuf cmd;
SendCallback callback;
long sequenceId;
long createdAt;
long batchSizeByte = 0;
int numMessagesInBatch = 1;
static OpSendMsg create(MessageImpl msg, ByteBuf cmd, long sequenceId, SendCallback callback) {
OpSendMsg op = RECYCLER.get();
op.msg = msg;
op.cmd = cmd;
op.callback = callback;
op.sequenceId = sequenceId;
op.createdAt = System.currentTimeMillis();
return op;
}
static OpSendMsg create(List<MessageImpl> msgs, ByteBuf cmd, long sequenceId, SendCallback callback) {
OpSendMsg op = RECYCLER.get();
op.msgs = msgs;
op.cmd = cmd;
op.callback = callback;
op.sequenceId = sequenceId;
op.createdAt = System.currentTimeMillis();
return op;
}
void recycle() {
msg = null;
msgs = null;
cmd = null;
callback = null;
sequenceId = -1;
createdAt = -1;
RECYCLER.recycle(this, recyclerHandle);
}
void setNumMessagesInBatch(int numMessagesInBatch) {
this.numMessagesInBatch = numMessagesInBatch;
}
void setBatchSizeByte(long batchSizeByte) {
this.batchSizeByte = batchSizeByte;
}
void setMessageId(long ledgerId, long entryId, int partitionIndex) {
if (msg != null) {
msg.setMessageId(new MessageIdImpl(ledgerId, entryId, partitionIndex));
} else {
for (int batchIndex = 0; batchIndex < msgs.size(); batchIndex++) {
msgs.get(batchIndex)
.setMessageId(new BatchMessageIdImpl(ledgerId, entryId, partitionIndex, batchIndex));
}
}
}
private OpSendMsg(Handle recyclerHandle) {
this.recyclerHandle = recyclerHandle;
}
private final Handle recyclerHandle;
private static final Recycler<OpSendMsg> RECYCLER = new Recycler<OpSendMsg>() {
@Override
protected OpSendMsg newObject(Handle handle) {
return new OpSendMsg(handle);
}
};
}
@Override
void connectionOpened(final ClientCnx cnx) {
// we set the cnx reference before registering the producer on the cnx, so if the cnx breaks before creating the
// producer, it will try to grab a new cnx
setClientCnx(cnx);
cnx.registerProducer(producerId, this);
log.info("[{}] [{}] Creating producer on cnx {}", topic, producerName, cnx.ctx().channel());
long requestId = client.newRequestId();
cnx.sendRequestWithId(Commands.newProducer(topic, producerId, requestId, producerName), requestId)
.thenAccept(producerName -> {
// We are now reconnected to broker and clear to send messages. Re-send all pending messages and
// set the cnx pointer so that new messages will be sent immediately
synchronized (ProducerImpl.this) {
if (getState() == State.Closing || getState() == State.Closed) {
// Producer was closed while reconnecting, close the connection to make sure the broker
// drops the producer on its side
cnx.removeProducer(producerId);
cnx.channel().close();
return;
}
resetBackoff();
log.info("[{}] [{}] Created producer on cnx {}", topic, producerName, cnx.ctx().channel());
connectionId = cnx.ctx().channel().toString();
connectedSince = DATE_FORMAT.format(Instant.now());
if (this.producerName == null) {
this.producerName = producerName;
}
if (!producerCreatedFuture.isDone() && isBatchMessagingEnabled()) {
// schedule the first batch message task
client.timer().newTimeout(batchMessageAndSendTask, conf.getBatchingMaxPublishDelayMs(),
TimeUnit.MILLISECONDS);
}
resendMessages(cnx);
}
}).exceptionally((e) -> {
Throwable cause = e.getCause();
cnx.removeProducer(producerId);
if (getState() == State.Closing || getState() == State.Closed) {
// Producer was closed while reconnecting, close the connection to make sure the broker
// drops the producer on its side
cnx.channel().close();
return null;
}
log.error("[{}] [{}] Failed to create producer: {}", topic, producerName,
cause.getMessage());
if (cause instanceof PulsarClientException.ProducerBlockedQuotaExceededException) {
synchronized (this) {
log.warn("[{}] [{}] Topic backlog quota exceeded. Throwing Exception on producer.", topic,
producerName);
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Pending messages: {}", topic, producerName,
pendingMessages.size());
}
PulsarClientException bqe = new PulsarClientException.ProducerBlockedQuotaExceededException(
"Could not send pending messages as backlog exceeded");
failPendingMessages(cnx(), bqe);
}
} else if (cause instanceof PulsarClientException.ProducerBlockedQuotaExceededError) {
log.warn("[{}] [{}] Producer is blocked on creation because backlog exceeded on topic.",
producerName, topic);
}
if (cause instanceof PulsarClientException.TopicTerminatedException) {
setState(State.Terminated);
failPendingMessages(cnx(), (PulsarClientException) cause);
producerCreatedFuture.completeExceptionally(cause);
client.cleanupProducer(this);
} else if (producerCreatedFuture.isDone() || //
(cause instanceof PulsarClientException && isRetriableError((PulsarClientException) cause)
&& System.currentTimeMillis() < createProducerTimeout)) {
// Either we had already created the producer once (producerCreatedFuture.isDone()) or we are
// still within the initial timeout budget and we are dealing with a retriable error
reconnectLater(cause);
} else {
setState(State.Failed);
producerCreatedFuture.completeExceptionally(cause);
client.cleanupProducer(this);
}
return null;
});
}
@Override
void connectionFailed(PulsarClientException exception) {
if (System.currentTimeMillis() > createProducerTimeout
&& producerCreatedFuture.completeExceptionally(exception)) {
log.info("[{}] Producer creation failed for producer {}", topic, producerId);
setState(State.Failed);
}
}
private void resendMessages(ClientCnx cnx) {
cnx.ctx().channel().eventLoop().execute(() -> {
synchronized (this) {
if (getState() == State.Closing || getState() == State.Closed) {
// Producer was closed while reconnecting, close the connection to make sure the broker
// drops the producer on its side
cnx.channel().close();
return;
}
int messagesToResend = pendingMessages.size();
if (messagesToResend == 0) {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] No pending messages to resend {}", topic, producerName, messagesToResend);
}
if (changeToReadyState()) {
producerCreatedFuture.complete(ProducerImpl.this);
return;
} else {
// Producer was closed while reconnecting, close the connection to make sure the broker
// drops the producer on its side
cnx.channel().close();
return;
}
}
log.info("[{}] [{}] Re-Sending {} messages to server", topic, producerName, messagesToResend);
final boolean stripChecksum = cnx.getRemoteEndpointProtocolVersion() < brokerChecksumSupportedVersion();
for (OpSendMsg op : pendingMessages) {
if (stripChecksum) {
stripChecksum(op);
}
op.cmd.retain();
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Re-Sending message in cnx {}, sequenceId {}", topic, producerName,
cnx.channel(), op.sequenceId);
}
cnx.ctx().write(op.cmd, cnx.ctx().voidPromise());
stats.updateNumMsgsSent(op.numMessagesInBatch, op.batchSizeByte);
}
cnx.ctx().flush();
if (!changeToReadyState()) {
// Producer was closed while reconnecting, close the connection to make sure the broker
// drops the producer on its side
cnx.channel().close();
return;
}
}
});
}
/**
* Strips checksum from {@link OpSendMsg} command if present else ignore it.
*
* @param op
*/
private void stripChecksum(OpSendMsg op) {
op.cmd.markReaderIndex();
int totalMsgBufSize = op.cmd.readableBytes();
DoubleByteBuf msg = getDoubleByteBuf(op.cmd);
if (msg != null) {
ByteBuf headerFrame = msg.getFirst();
msg.markReaderIndex();
headerFrame.markReaderIndex();
try {
headerFrame.skipBytes(4); // skip [total-size]
int cmdSize = (int) headerFrame.readUnsignedInt();
// verify if checksum present
headerFrame.skipBytes(cmdSize);
if (!hasChecksum(headerFrame)) {
headerFrame.resetReaderIndex();
return;
}
int headerSize = 4 + 4 + cmdSize; // [total-size] [cmd-length] [cmd-size]
int checksumSize = 4 + 2; // [magic-number] [checksum-size]
int checksumMark = (headerSize + checksumSize); // [header-size] [checksum-size]
int metaPayloadSize = (totalMsgBufSize - checksumMark); // metadataPayload = totalSize - checksumMark
int newTotalFrameSizeLength = 4 + cmdSize + metaPayloadSize; // new total-size without checksum
headerFrame.resetReaderIndex();
int headerFrameSize = headerFrame.readableBytes();
headerFrame.setInt(0, newTotalFrameSizeLength); // rewrite new [total-size]
ByteBuf metadata = headerFrame.slice(checksumMark, headerFrameSize - checksumMark); // sliced only
// metadata
headerFrame.writerIndex(headerSize); // set headerFrame write-index to overwrite metadata over checksum
metadata.readBytes(headerFrame, metadata.readableBytes());
headerFrame.capacity(headerFrameSize - checksumSize); // reduce capacity by removed checksum bytes
headerFrame.resetReaderIndex();
} finally {
op.cmd.resetReaderIndex();
}
} else {
log.warn("[{}] Failed while casting {} into DoubleByteBuf", producerName, op.cmd.getClass().getName());
}
}
public int brokerChecksumSupportedVersion() {
return ProtocolVersion.v6.getNumber();
}
@Override
String getHandlerName() {
return producerName;
}
/**
* Process sendTimeout events
*/
@Override
public void run(Timeout timeout) throws Exception {
if (timeout.isCancelled()) {
return;
}
long timeToWaitMs;
synchronized (this) {
OpSendMsg firstMsg = pendingMessages.peek();
if (firstMsg == null) {
// If there are no pending messages, reset the timeout to the configured value.
timeToWaitMs = conf.getSendTimeoutMs();
} else {
// If there is at least one message, calculate the diff between the message timeout and the current
// time.
long diff = (firstMsg.createdAt + conf.getSendTimeoutMs()) - System.currentTimeMillis();
if (diff <= 0) {
// The diff is less than or equal to zero, meaning that the message has been timed out.
// Set the callback to timeout on every message, then clear the pending queue.
log.info("[{}] [{}] Message send timed out. Failing {} messages", topic, producerName,
pendingMessages.size());
PulsarClientException te = new PulsarClientException.TimeoutException(
"Could not send message to broker within given timeout");
failPendingMessages(cnx(), te);
stats.incrementSendFailed(pendingMessages.size());
// Since the pending queue is cleared now, set timer to expire after configured value.
timeToWaitMs = conf.getSendTimeoutMs();
} else {
// The diff is greater than zero, set the timeout to the diff value
timeToWaitMs = diff;
}
}
}
sendTimeout = client.timer().newTimeout(this, timeToWaitMs, TimeUnit.MILLISECONDS);
}
/**
* This fails and clears the pending messages with the given exception. This method should be called from within the
* ProducerImpl object mutex.
*/
private void failPendingMessages(ClientCnx cnx, PulsarClientException ex) {
if (cnx == null) {
final AtomicInteger releaseCount = new AtomicInteger();
pendingMessages.forEach(op -> {
releaseCount.addAndGet(op.numMessagesInBatch);
try {
// Need to protect ourselves from any exception being thrown in the future handler from the
// application
op.callback.sendComplete(ex);
} catch (Throwable t) {
log.warn("[{}] [{}] Got exception while completing the callback for msg {}:", topic, producerName,
op.sequenceId, t);
}
ReferenceCountUtil.safeRelease(op.cmd);
op.recycle();
});
semaphore.release(releaseCount.get());
pendingMessages.clear();
pendingCallbacks.clear();
if (isBatchMessagingEnabled()) {
failPendingBatchMessages(ex);
}
} else {
// If we have a connection, we schedule the callback and recycle on the event loop thread to avoid any
// race condition since we also write the message on the socket from this thread
cnx.ctx().channel().eventLoop().execute(() -> {
synchronized (ProducerImpl.this) {
failPendingMessages(null, ex);
}
});
}
}
/**
* fail any pending batch messages that were enqueued, however batch was not closed out
*
*/
private void failPendingBatchMessages(PulsarClientException ex) {
if (batchMessageContainer.isEmpty()) {
return;
}
int numMessagesInBatch = batchMessageContainer.numMessagesInBatch;
semaphore.release(numMessagesInBatch);
try {
// Need to protect ourselves from any exception being thrown in the future handler from the application
batchMessageContainer.firstCallback.sendComplete(ex);
} catch (Throwable t) {
log.warn("[{}] [{}] Got exception while completing the callback for msg {}:", topic, producerName,
batchMessageContainer.sequenceId, t);
}
ReferenceCountUtil.safeRelease(batchMessageContainer.getBatchedSingleMessageMetadataAndPayload());
batchMessageContainer.clear();
}
TimerTask batchMessageAndSendTask = new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
if (timeout.isCancelled()) {
return;
}
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Batching the messages from the batch container from timer thread", topic,
producerName);
}
// semaphore acquired when message was enqueued to container
synchronized (ProducerImpl.this) {
batchMessageAndSend();
}
// schedule the next batch message task
client.timer().newTimeout(this, conf.getBatchingMaxPublishDelayMs(), TimeUnit.MILLISECONDS);
}
};
// must acquire semaphore before enqueuing
private void batchMessageAndSend() {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Batching the messages from the batch container with {} messages", topic, producerName,
batchMessageContainer.numMessagesInBatch);
}
OpSendMsg op = null;
int numMessagesInBatch = 0;
try {
if (!batchMessageContainer.isEmpty()) {
numMessagesInBatch = batchMessageContainer.numMessagesInBatch;
ByteBuf compressedPayload = batchMessageContainer.getCompressedBatchMetadataAndPayload();
long sequenceId = batchMessageContainer.sequenceId;
ByteBuf cmd = sendMessage(producerId, sequenceId, batchMessageContainer.numMessagesInBatch,
batchMessageContainer.setBatchAndBuild(), compressedPayload);
op = OpSendMsg.create(batchMessageContainer.messages, cmd, sequenceId,
batchMessageContainer.firstCallback);
op.setNumMessagesInBatch(batchMessageContainer.numMessagesInBatch);
op.setBatchSizeByte(batchMessageContainer.currentBatchSizeBytes);
batchMessageContainer.clear();
pendingMessages.put(op);
if (isConnected()) {
// If we do have a connection, the message is sent immediately, otherwise we'll try again once a new
// connection is established
cmd.retain();
cnx().ctx().channel().eventLoop().execute(WriteInEventLoopCallback.create(this, cnx(), op));
stats.updateNumMsgsSent(numMessagesInBatch, op.batchSizeByte);
} else {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Connection is not ready -- sequenceId {}", topic, producerName,
sequenceId);
}
}
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
semaphore.release(numMessagesInBatch);
if (op != null) {
op.callback.sendComplete(new PulsarClientException(ie));
}
} catch (Throwable t) {
semaphore.release(numMessagesInBatch);
log.warn("[{}] [{}] error while closing out batch -- {}", topic, producerName, t);
if (op != null) {
op.callback.sendComplete(new PulsarClientException(t));
}
}
}
/**
* Casts input cmd to {@link DoubleByteBuf}
*
* Incase if leak-detection level is enabled: pulsar instruments {@link DoubleByteBuf} into LeakAwareByteBuf (type
* of {@link io.netty.buffer.WrappedByteBuf}) So, this method casts input cmd to {@link DoubleByteBuf} else
* retrieves it from LeakAwareByteBuf.
*
* @param cmd
* @return DoubleByteBuf or null in case failed to cast input {@link ByteBuf}
*/
private DoubleByteBuf getDoubleByteBuf(ByteBuf cmd) {
DoubleByteBuf msg = null;
if (cmd instanceof DoubleByteBuf) {
msg = (DoubleByteBuf) cmd;
} else {
try {
msg = (DoubleByteBuf) cmd.unwrap();
} catch (Exception e) {
log.error("[{}] Failed while casting {} into DoubleByteBuf", producerName, cmd.getClass().getName(), e);
}
}
return msg;
}
public long getDelayInMillis() {
OpSendMsg firstMsg = pendingMessages.peek();
if (firstMsg != null) {
return System.currentTimeMillis() - firstMsg.createdAt;
}
return 0L;
}
public String getConnectionId() {
return cnx() != null ? connectionId : null;
}
public String getConnectedSince() {
return cnx() != null ? connectedSince : null;
}
public int getPendingQueueSize() {
return pendingMessages.size();
}
private static DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSZ")
.withZone(ZoneId.systemDefault());
private PulsarApi.CompressionType convertCompressionType(CompressionType compressionType) {
switch (compressionType) {
case NONE:
return PulsarApi.CompressionType.NONE;
case LZ4:
return PulsarApi.CompressionType.LZ4;
case ZLIB:
return PulsarApi.CompressionType.ZLIB;
default:
throw new RuntimeException("Invalid compression type");
}
}
@Override
public ProducerStats getStats() {
if (stats instanceof ProducerStatsDisabled) {
return null;
}
return stats;
}
public String getProducerName() {
return producerName;
}
private static final Logger log = LoggerFactory.getLogger(ProducerImpl.class);
}
| apache-2.0 |
rabidgremlin/Mutters | mutters-templated-intent/src/test/java/com/rabidgremlin/mutters/generate/TestProduct.java | 1117 | /* Licensed under Apache-2.0 */
package com.rabidgremlin.mutters.generate;
import static com.google.common.truth.Truth.assertThat;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class TestProduct
{
@Test
void testProduct()
{
List<String> list1 = Arrays.asList("A", "B");
List<String> list2 = Arrays.asList("1", "2", "3");
List<String> list3 = Arrays.asList("X");
@SuppressWarnings("unchecked")
List<List<String>> product = Product.generate(list1, list2, list3);
assertThat(product).isNotNull();
assertThat(product).hasSize(list1.size() * list2.size() * list3.size());
assertThat(product.get(0)).isEqualTo(Arrays.asList("A", "1", "X"));
assertThat(product.get(1)).isEqualTo(Arrays.asList("A", "2", "X"));
assertThat(product.get(2)).isEqualTo(Arrays.asList("A", "3", "X"));
assertThat(product.get(3)).isEqualTo(Arrays.asList("B", "1", "X"));
assertThat(product.get(4)).isEqualTo(Arrays.asList("B", "2", "X"));
assertThat(product.get(5)).isEqualTo(Arrays.asList("B", "3", "X"));
System.out.println(product);
}
}
| apache-2.0 |
shevek/gradle-jnaerator-plugin | src/main/java/org/anarres/gradle/plugin/jnaerator/JNAeratorPluginExtension.java | 1086 | package org.anarres.gradle.plugin.jnaerator;
import java.io.File;
import javax.annotation.Nonnull;
import org.gradle.api.file.FileCollection;
/**
*
* @author shevek
*/
public class JNAeratorPluginExtension {
public static final String NAME = "jnaerator";
private File outputDir;
private String libraryName;
private String packageName;
private Object[] headerFiles;
public File getOutputDir() {
return outputDir;
}
public void setOutputDir(File outputDir) {
this.outputDir = outputDir;
}
public String getLibraryName() {
return libraryName;
}
public void setLibraryName(@Nonnull String libraryName) {
this.libraryName = libraryName;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public void setHeaderFiles(@Nonnull Object[] headerFiles) {
this.headerFiles = headerFiles;
}
public Object[] getHeaderFiles() {
return headerFiles;
}
} | apache-2.0 |
dbflute-test/dbflute-test-active-hangar | src/main/java/org/docksidestage/hangar/dbflute/bsentity/dbmeta/WhiteCompoundPkRefVirturlDbm.java | 11964 | package org.docksidestage.hangar.dbflute.bsentity.dbmeta;
import java.util.List;
import java.util.Map;
import org.dbflute.Entity;
import org.dbflute.optional.OptionalEntity;
import org.dbflute.dbmeta.AbstractDBMeta;
import org.dbflute.dbmeta.info.*;
import org.dbflute.dbmeta.name.*;
import org.dbflute.dbmeta.property.PropertyGateway;
import org.dbflute.dbway.DBDef;
import org.docksidestage.hangar.dbflute.allcommon.*;
import org.docksidestage.hangar.dbflute.exentity.*;
/**
* The DB meta of WHITE_COMPOUND_PK_REF_VIRTURL. (Singleton)
* @author DBFlute(AutoGenerator)
*/
public class WhiteCompoundPkRefVirturlDbm extends AbstractDBMeta {
// ===================================================================================
// Singleton
// =========
private static final WhiteCompoundPkRefVirturlDbm _instance = new WhiteCompoundPkRefVirturlDbm();
private WhiteCompoundPkRefVirturlDbm() {}
public static WhiteCompoundPkRefVirturlDbm getInstance() { return _instance; }
// ===================================================================================
// Current DBDef
// =============
public String getProjectName() { return DBCurrent.getInstance().projectName(); }
public String getProjectPrefix() { return DBCurrent.getInstance().projectPrefix(); }
public String getGenerationGapBasePrefix() { return DBCurrent.getInstance().generationGapBasePrefix(); }
public DBDef getCurrentDBDef() { return DBCurrent.getInstance().currentDBDef(); }
// ===================================================================================
// Property Gateway
// ================
// -----------------------------------------------------
// Column Property
// ---------------
protected final Map<String, PropertyGateway> _epgMap = newHashMap();
{ xsetupEpg(); }
protected void xsetupEpg() {
setupEpg(_epgMap, et -> ((WhiteCompoundPkRefVirturl)et).getRefFirstId(), (et, vl) -> ((WhiteCompoundPkRefVirturl)et).setRefFirstId(ctl(vl)), "refFirstId");
setupEpg(_epgMap, et -> ((WhiteCompoundPkRefVirturl)et).getRefSecondId(), (et, vl) -> ((WhiteCompoundPkRefVirturl)et).setRefSecondId(ctl(vl)), "refSecondId");
setupEpg(_epgMap, et -> ((WhiteCompoundPkRefVirturl)et).getRefThirdId(), (et, vl) -> ((WhiteCompoundPkRefVirturl)et).setRefThirdId(ctl(vl)), "refThirdId");
setupEpg(_epgMap, et -> ((WhiteCompoundPkRefVirturl)et).getCompoundRefName(), (et, vl) -> ((WhiteCompoundPkRefVirturl)et).setCompoundRefName((String)vl), "compoundRefName");
}
public PropertyGateway findPropertyGateway(String prop)
{ return doFindEpg(_epgMap, prop); }
// -----------------------------------------------------
// Foreign Property
// ----------------
protected final Map<String, PropertyGateway> _efpgMap = newHashMap();
{ xsetupEfpg(); }
@SuppressWarnings("unchecked")
protected void xsetupEfpg() {
setupEfpg(_efpgMap, et -> ((WhiteCompoundPkRefVirturl)et).getWhiteCompoundPk(), (et, vl) -> ((WhiteCompoundPkRefVirturl)et).setWhiteCompoundPk((OptionalEntity<WhiteCompoundPk>)vl), "whiteCompoundPk");
}
public PropertyGateway findForeignPropertyGateway(String prop)
{ return doFindEfpg(_efpgMap, prop); }
// ===================================================================================
// Table Info
// ==========
protected final String _tableDbName = "WHITE_COMPOUND_PK_REF_VIRTURL";
protected final String _tableDispName = "WHITE_COMPOUND_PK_REF_VIRTURL";
protected final String _tablePropertyName = "whiteCompoundPkRefVirturl";
protected final TableSqlName _tableSqlName = new TableSqlName("MAIHAMADB.PUBLIC.WHITE_COMPOUND_PK_REF_VIRTURL", _tableDbName);
{ _tableSqlName.xacceptFilter(DBFluteConfig.getInstance().getTableSqlNameFilter()); }
public String getTableDbName() { return _tableDbName; }
public String getTableDispName() { return _tableDispName; }
public String getTablePropertyName() { return _tablePropertyName; }
public TableSqlName getTableSqlName() { return _tableSqlName; }
// ===================================================================================
// Column Info
// ===========
protected final ColumnInfo _columnRefFirstId = cci("REF_FIRST_ID", "REF_FIRST_ID", null, null, Long.class, "refFirstId", null, true, false, true, "DECIMAL", 16, 0, null, null, false, null, null, "whiteCompoundPk", null, null, false);
protected final ColumnInfo _columnRefSecondId = cci("REF_SECOND_ID", "REF_SECOND_ID", null, null, Long.class, "refSecondId", null, true, false, true, "DECIMAL", 16, 0, null, null, false, null, null, "whiteCompoundPk", null, null, false);
protected final ColumnInfo _columnRefThirdId = cci("REF_THIRD_ID", "REF_THIRD_ID", null, null, Long.class, "refThirdId", null, true, false, true, "DECIMAL", 16, 0, null, null, false, null, null, null, null, null, false);
protected final ColumnInfo _columnCompoundRefName = cci("COMPOUND_REF_NAME", "COMPOUND_REF_NAME", null, null, String.class, "compoundRefName", null, false, false, true, "VARCHAR", 200, 0, null, null, false, null, null, null, null, null, false);
/**
* REF_FIRST_ID: {PK, NotNull, DECIMAL(16), FK to WHITE_COMPOUND_PK}
* @return The information object of specified column. (NotNull)
*/
public ColumnInfo columnRefFirstId() { return _columnRefFirstId; }
/**
* REF_SECOND_ID: {PK, NotNull, DECIMAL(16), FK to WHITE_COMPOUND_PK}
* @return The information object of specified column. (NotNull)
*/
public ColumnInfo columnRefSecondId() { return _columnRefSecondId; }
/**
* REF_THIRD_ID: {PK, NotNull, DECIMAL(16)}
* @return The information object of specified column. (NotNull)
*/
public ColumnInfo columnRefThirdId() { return _columnRefThirdId; }
/**
* COMPOUND_REF_NAME: {NotNull, VARCHAR(200)}
* @return The information object of specified column. (NotNull)
*/
public ColumnInfo columnCompoundRefName() { return _columnCompoundRefName; }
protected List<ColumnInfo> ccil() {
List<ColumnInfo> ls = newArrayList();
ls.add(columnRefFirstId());
ls.add(columnRefSecondId());
ls.add(columnRefThirdId());
ls.add(columnCompoundRefName());
return ls;
}
{ initializeInformationResource(); }
// ===================================================================================
// Unique Info
// ===========
// -----------------------------------------------------
// Primary Element
// ---------------
protected UniqueInfo cpui() {
List<ColumnInfo> ls = newArrayListSized(4);
ls.add(columnRefFirstId());
ls.add(columnRefSecondId());
ls.add(columnRefThirdId());
return hpcpui(ls);
}
public boolean hasPrimaryKey() { return true; }
public boolean hasCompoundPrimaryKey() { return true; }
// ===================================================================================
// Relation Info
// =============
// cannot cache because it uses related DB meta instance while booting
// (instead, cached by super's collection)
// -----------------------------------------------------
// Foreign Property
// ----------------
/**
* WHITE_COMPOUND_PK by my REF_FIRST_ID, REF_SECOND_ID, named 'whiteCompoundPk'.
* @return The information object of foreign property. (NotNull)
*/
public ForeignInfo foreignWhiteCompoundPk() {
Map<ColumnInfo, ColumnInfo> mp = newLinkedHashMapSized(4);
mp.put(columnRefFirstId(), WhiteCompoundPkDbm.getInstance().columnPkFirstId());
mp.put(columnRefSecondId(), WhiteCompoundPkDbm.getInstance().columnPkSecondId());
return cfi("FK_WHITE_COMPOUND_PK_REF_VIRTURL_FIRST_SECOND", "whiteCompoundPk", this, WhiteCompoundPkDbm.getInstance(), mp, 0, org.dbflute.optional.OptionalEntity.class, false, false, false, true, null, null, false, "whiteCompoundPkRefVirturlList", false);
}
// -----------------------------------------------------
// Referrer Property
// -----------------
// ===================================================================================
// Various Info
// ============
// ===================================================================================
// Type Name
// =========
public String getEntityTypeName() { return "org.docksidestage.hangar.dbflute.exentity.WhiteCompoundPkRefVirturl"; }
public String getConditionBeanTypeName() { return "org.docksidestage.hangar.dbflute.cbean.WhiteCompoundPkRefVirturlCB"; }
public String getBehaviorTypeName() { return "org.docksidestage.hangar.dbflute.exbhv.WhiteCompoundPkRefVirturlBhv"; }
// ===================================================================================
// Object Type
// ===========
public Class<WhiteCompoundPkRefVirturl> getEntityType() { return WhiteCompoundPkRefVirturl.class; }
// ===================================================================================
// Object Instance
// ===============
public WhiteCompoundPkRefVirturl newEntity() { return new WhiteCompoundPkRefVirturl(); }
// ===================================================================================
// Map Communication
// =================
public void acceptPrimaryKeyMap(Entity et, Map<String, ? extends Object> mp)
{ doAcceptPrimaryKeyMap((WhiteCompoundPkRefVirturl)et, mp); }
public void acceptAllColumnMap(Entity et, Map<String, ? extends Object> mp)
{ doAcceptAllColumnMap((WhiteCompoundPkRefVirturl)et, mp); }
public Map<String, Object> extractPrimaryKeyMap(Entity et) { return doExtractPrimaryKeyMap(et); }
public Map<String, Object> extractAllColumnMap(Entity et) { return doExtractAllColumnMap(et); }
}
| apache-2.0 |
nortal/spring-mvc-component-web | modules/component-web-jsp/src/main/java/com/nortal/spring/cw/jsp/model/xml/dokument/vorm/XmlVormDokument.java | 1386 | package com.nortal.spring.cw.jsp.model.xml.dokument.vorm;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import com.nortal.spring.cw.core.xml.XmlRootModel;
import com.nortal.spring.cw.jsp.model.xml.dokument.model.GeneralDokumentModel;
/**
* Vormdokumendi XML alus mudel
*
* @author Lauri Lättemäe <lauri.lattemae@nortal.com>
* @since 21.03.2014
*/
@Data
@EqualsAndHashCode(callSuper = true)
@XmlType
public abstract class XmlVormDokument<T extends GeneralDokumentModel> extends XmlRootModel {
private static final long serialVersionUID = 1L;
public static final String DEFAULT_VERSION = "v1";
public static final String ROOT_NAME = "dokument";
@XmlAttribute(required = true)
private String kood;
@XmlAttribute
private String versioon;
public abstract T getSisu();
public abstract void setSisu(T sisu);
@Override
public String getTemplate() {
String result = null;
String targetPackage = getClass().getPackage().getName();
String vdPackage = XmlVormDokument.class.getPackage().getName();
result = StringUtils.removeStart(targetPackage, vdPackage);
result = result.replaceFirst("\\.", "");
result = result.replaceFirst("\\.", "/");
return result;
}
}
| apache-2.0 |
SuperKaitoKid/ModIRCBots-Modules | src/ircmodbot/module/QuoteMod.java | 2900 | package ircmodbot.module;
import ircmodbot.Module;
import ircmodbot.OpHelp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;
import org.jibble.pircbot.Colors;
/**
* Mod to allow SKKBot to output quote like text.
* Used for quoting people.
*
* Format: Keyword Username Message
* @author Charles Chen
*
*/
public class QuoteMod extends Module
{
public QuoteMod()
{
super("QM");
moduleName = "Quoting Mod";
}
public void onMessage(String channel, String sender,
String login, String hostname, String message, ArrayList<String> cmd)
{
if(cmd.size() < 3 )
{
bot.sendMessage(sender, "Invalid formatting");
return;
}
message = OpHelp.subString(message, 3 + sender.length() + 1, message.length());
displayQuote(sender,message,channel);
}
public void onPrivateMessage(String sender, String login,
String hostname, String message, ArrayList<String> cmd)
{
if(cmd.size() < 3 )
{
bot.sendMessage(sender, "Invalid formatting");
return;
}
message = OpHelp.subString(message, 3 + sender.length() + 1, message.length());
displayQuote(sender, message, bot.getChannelName());
}
public void onJoin(String channel,String sender,
String login,String hostname)
{
return ;
}
public void noticeQuote(String sender, String message,String sendTo)
{
int year = Calendar.getInstance().get(Calendar.YEAR);
bot.sendNotice(sendTo, Colors.BOLD + randColor()
+ "\"" + message + "\"" + Colors.NORMAL + " - "
+ sender + ", " + year);
}
public void displayQuote(String sender,String message, String sendTo)
{
int year = Calendar.getInstance().get(Calendar.YEAR);
bot.sendMessage(sendTo, Colors.BOLD + randColor()
+ "\"" + message + "\"" + Colors.NORMAL + " - "
+ sender + ", " + year);
}
public String randColor()
{
Random random = new Random();
int rand = random.nextInt(10 + 1);
String color = "";
switch(rand)
{
case 0:
color = Colors.BLACK;
break;
case 1:
color = Colors.BLUE;
break;
case 2:
color = Colors.BROWN;
break;
case 3:
color = Colors.CYAN;
break;
case 4:
color = Colors.DARK_GRAY;
break;
case 5:
color = Colors.GREEN;
break;
case 6:
color = Colors.BLACK;
break;
case 7:
color = Colors.OLIVE;
break;
case 8:
color = Colors.DARK_BLUE;
case 9:
color = Colors.RED;
case 10:
color = Colors.TEAL;
default:
color = Colors.DARK_BLUE;
break;
}
return color;
}
} | apache-2.0 |
tigline/startui | src/com/tcl/roselauncher/ui/startui/Circle.java | 5176 | /**
*
*/
package com.tcl.roselauncher.ui.startui;
import java.util.ArrayList;
import org.cocos2d.nodes.CCLabel;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.nodes.CCTextureCache;
import org.cocos2d.particlesystem.CCParticleFire;
import org.cocos2d.particlesystem.CCParticleSystem;
import org.cocos2d.types.CGPoint;
import static com.tcl.roselauncher.ui.startui.Constant.*;
/**
* @Project ControlMenu
* @author houxb
* @Date 2015-9-10
* 内容泡泡类
*/
public class Circle extends CCSprite {
/**
* @param string
*/
public boolean runFlag = true;
public float ACC = 0.5f; //
public float SPEED; //
public float MASS = 10;
public float COF = 0.05f;
public float vx = 0 ; //
public float vy = 0 ;
public float BALL_R;
public float xOffset;
public float yOffset;
public float toScale;
public float crScale;
public MicroPhone micPhone;
public boolean firstCreate;
public boolean turn;
public int offsetX = 0;
public int offsetY = 0;
//private static Circle circle;
public Circle(String text, float scale ,float posX, float posY, boolean init ) {
super("launcher/circle4.png");
toScale = scale;
firstCreate = init;
// CGRect rect = getBoundingBox();
CCLabel content = CCLabel.makeLabel( text, "fangzheng.ttf", 36);
setAnchorPoint(CGPoint.ccp(0.5f, 0.5f));
// content.setPosition(getContentSiye().width*scale/2, getContentSiye().height*scale/2);
content.setPosition(getContentSize().width/2, getContentSize().height/2);
addChild(content);
// CCParticleSystem emitter;
// emitter = CCParticleFire.node();
// emitter.setTexture(CCTextureCache.sharedTextureCache().addImage("fire.png"));
// emitter.setPosition(getContentSize().width/2, getContentSize().height/2);
// addChild(emitter);
// Log.e("Circle point", CGRect.width(rect)/2 +" and "+CGRect.height(rect)/2);
if (1.0f == scale) {
runFlag = false;
setScale(scale);
this.setBallR(STANDA_BAll_R/2);
}else{
setScale(0.001f);
this.setBallR(STANDA_BAll_R * 0.001f/2);
}
vx = posX*2.7f;
vy = posY*2.7f;
}
public void setBallR(float ballR){
this.BALL_R = ballR;
}
public float getBallR(){
return this.BALL_R;
}
public void TranslateTo(float dt){
vx = vx * V_TENUATION;
vy = vy * V_TENUATION;
}
public void CheckCollision(ArrayList<Circle> circleList, float dt){
for (int i = 0; i < circleList.size(); i++) {
if (this != circleList.get(i)) {
CollisionUtil.collision(circleList.get(i),this);
//CollisionUtil.collisionS(this, micPhone);
}
}
if (runFlag) {
xOffset = getPosition().x + vx*dt;
yOffset = getPosition().y + vy*dt;
this.setPosition(xOffset, yOffset);
crScale += dt*2.0f;
if (crScale < toScale) {
setScale(crScale);
this.setBallR(STANDA_BAll_R * crScale/2);
}
}
if(this.yOffset< BALL_R ||this.yOffset>(SCREEN_HEIGHT - BALL_R))
{
if (firstCreate) {
offsetY += dt;
if (offsetY > 5.0f ) {
removeFromParentAndCleanup(true);
circleList.remove(this);
}else{
this.vy=-0.8f*this.vy;
this.firstCreate = false;
}
}
else{
removeFromParentAndCleanup(true);
circleList.remove(this);
}
}
// if (this.yOffset< (BALL_R )||this.yOffset>(SCREEN_HEIGHT - BALL_R)) {
//
// }
if(this.xOffset< BALL_R||this.xOffset>(SCREEN_WIDTH - BALL_R))//外围
{
if (firstCreate) {
offsetX += dt;
if (offsetX > 5.0f ) {
removeFromParentAndCleanup(true);
circleList.remove(this);
}else{
this.vx=-0.8f*this.vx;
this.firstCreate = false;
}
}
else{
removeFromParentAndCleanup(true);
circleList.remove(this);
}
}
if (runFlag) {
this.TranslateTo(dt);
}
}
/*
public static Circle getInstance(String text, float scale)
{
if (null == circle)
{
circle = new Circle(text,scale);
}
return circle;
}
@Override
public Boolean touchBegan(CCTouch pTouch)
{
Log.e("Circle", "touchBegan" );
//float x = pTouch.getLocation().x;
//float y = pTouch.getLocation().y;
//setPosition(x, y);
return true;
}
@Override
public void touchMoved(CCTouch pTouch)
{
float x = pTouch.getLocation().x;
float y = pTouch.getLocation().y;
setPosition(x, y);
}
@Override
public void touchEnded(CCTouch pTouch)
{
float x = pTouch.getLocation().x;
float y = pTouch.getLocation().y;
//setPosition(x, y);
}
*/
// public Circle(String image){
//
// //sprite = new CCSprite(image);
// //CCLabelTTF content = new CCLabelTTF(textTure, "fangyheng.ttf", 24);
// //content.setPosition(halo.getContentSize().width/2.5f, halo.getContentSize().height/2.5f);
// //halo.addChild(content);
// //sprite.setPosition(x, y);
//
// }
/*
public static Circle getInstance(String image)
{
if (null == circle)
{
circle = new Circle(image);
}
return circle;
}
/*
public void setLocation(float x, float y){
this.x = x;
this.y = y;
circle.setPosition(x, y);
}
public static Circle getInstance()
{
if (null == parse)
{
parse = new Circle();
}
return parse;
}
public CCPoint getPositon(){
CCPoint point = new CCPoint(x, y);
return point;
}
*/
}
| apache-2.0 |
sgroschupf/katta | modules/katta-core/src/test/java/net/sf/katta/client/NodeProxyManagerTest.java | 4540 | /**
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.katta.client;
import java.lang.reflect.InvocationTargetException;
import java.net.ConnectException;
import net.sf.katta.AbstractTest;
import net.sf.katta.lib.lucene.ILuceneServer;
import net.sf.katta.node.IContentServer;
import org.apache.hadoop.conf.Configuration;
import org.junit.Test;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Matchers.anyString;
import static org.fest.assertions.Assertions.assertThat;
public class NodeProxyManagerTest extends AbstractTest {
private INodeSelectionPolicy _nodeSelectionPolicy = mock(INodeSelectionPolicy.class);
private NodeProxyManager _proxyManager = new NodeProxyManager(ILuceneServer.class, new Configuration(),
_nodeSelectionPolicy);
@Test
public void testProxyFailure() throws Exception {
NodeProxyManager proxyManagerSpy = spy(_proxyManager);
IContentServer contentServer = mock(IContentServer.class);
doReturn(contentServer).when(proxyManagerSpy).createNodeProxy(anyString());
assertThat(proxyManagerSpy.getProxy("node1", true)).isNotNull();
assertThat(proxyManagerSpy.getProxy("node2", true)).isNotNull();
proxyManagerSpy.setSuccessiveProxyFailuresBeforeReestablishing(2);
// node1 failure
reportNodeFailure(proxyManagerSpy, "node1");
verifyNoMoreInteractions(_nodeSelectionPolicy);
assertThat(proxyManagerSpy.getProxy("node1", false)).isNotNull();
assertThat(proxyManagerSpy.getProxy("node2", false)).isNotNull();
// node2 failure
reportNodeFailure(proxyManagerSpy, "node2");
verifyNoMoreInteractions(_nodeSelectionPolicy);
assertThat(proxyManagerSpy.getProxy("node1", false)).isNotNull();
assertThat(proxyManagerSpy.getProxy("node2", false)).isNotNull();
// node1 success
proxyManagerSpy.reportNodeCommunicationSuccess("node1");
// node1 failure
reportNodeFailure(proxyManagerSpy, "node1");
verifyNoMoreInteractions(_nodeSelectionPolicy);
assertThat(proxyManagerSpy.getProxy("node1", false)).isNotNull();
assertThat(proxyManagerSpy.getProxy("node2", false)).isNotNull();
// node2 failure
reportNodeFailure(proxyManagerSpy, "node2");
verify(_nodeSelectionPolicy).removeNode("node2");
verifyNoMoreInteractions(_nodeSelectionPolicy);
assertThat(proxyManagerSpy.getProxy("node1", false)).isNotNull();
assertThat(proxyManagerSpy.getProxy("node2", false)).isNull();
}
@Test
public void testProxyFailure_ConnectionFailure() throws Exception {
NodeProxyManager proxyManagerSpy = spy(_proxyManager);
IContentServer contentServer = mock(IContentServer.class);
doReturn(contentServer).when(proxyManagerSpy).createNodeProxy(anyString());
assertThat(proxyManagerSpy.getProxy("node1", true)).isNotNull();
assertThat(proxyManagerSpy.getProxy("node2", true)).isNotNull();
proxyManagerSpy.setSuccessiveProxyFailuresBeforeReestablishing(2);
// node1 connect failure
reportNodeFailure(proxyManagerSpy, "node1", new InvocationTargetException(new ConnectException()));
verify(_nodeSelectionPolicy).removeNode("node1");
verifyNoMoreInteractions(_nodeSelectionPolicy);
assertThat(proxyManagerSpy.getProxy("node1", false)).isNull();
assertThat(proxyManagerSpy.getProxy("node2", false)).isNotNull();
}
private void reportNodeFailure(NodeProxyManager proxyManagerSpy, String nodeName) {
reportNodeFailure(proxyManagerSpy, nodeName, new RuntimeException());
}
private void reportNodeFailure(NodeProxyManager proxyManagerSpy, String nodeName, Exception exception) {
try {
proxyManagerSpy.reportNodeCommunicationFailure(nodeName, exception);
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("not a proxy instance");
}
}
}
| apache-2.0 |
elsam/drools-planner-old | drools-planner-examples/src/main/java/org/drools/planner/examples/cloudbalancing/domain/CloudProcess.java | 4305 | /*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.planner.examples.cloudbalancing.domain;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.drools.planner.api.domain.entity.PlanningEntity;
import org.drools.planner.api.domain.value.ValueRange;
import org.drools.planner.api.domain.value.ValueRangeType;
import org.drools.planner.api.domain.variable.PlanningVariable;
import org.drools.planner.examples.cloudbalancing.domain.solver.CloudComputerStrengthComparator;
import org.drools.planner.examples.cloudbalancing.domain.solver.CloudProcessDifficultyComparator;
import org.drools.planner.examples.common.domain.AbstractPersistable;
@PlanningEntity(difficultyComparatorClass = CloudProcessDifficultyComparator.class)
@XStreamAlias("CloudProcess")
public class CloudProcess extends AbstractPersistable {
private int requiredCpuPower; // in gigahertz
private int requiredMemory; // in gigabyte RAM
private int requiredNetworkBandwidth; // in gigabyte per hour
// Planning variables: changes during planning, between score calculations.
private CloudComputer computer;
public int getRequiredCpuPower() {
return requiredCpuPower;
}
public void setRequiredCpuPower(int requiredCpuPower) {
this.requiredCpuPower = requiredCpuPower;
}
public int getRequiredMemory() {
return requiredMemory;
}
public void setRequiredMemory(int requiredMemory) {
this.requiredMemory = requiredMemory;
}
public int getRequiredNetworkBandwidth() {
return requiredNetworkBandwidth;
}
public void setRequiredNetworkBandwidth(int requiredNetworkBandwidth) {
this.requiredNetworkBandwidth = requiredNetworkBandwidth;
}
@PlanningVariable(strengthComparatorClass = CloudComputerStrengthComparator.class)
@ValueRange(type = ValueRangeType.FROM_SOLUTION_PROPERTY, solutionProperty = "computerList")
public CloudComputer getComputer() {
return computer;
}
public void setComputer(CloudComputer computer) {
this.computer = computer;
}
// ************************************************************************
// Complex methods
// ************************************************************************
public int getRequiredMultiplicand() {
return requiredCpuPower * requiredMemory * requiredNetworkBandwidth;
}
public String getLabel() {
return "Process " + id;
}
/**
* The normal methods {@link #equals(Object)} and {@link #hashCode()} cannot be used because the rule engine already
* requires them (for performance in their original state).
* @see #solutionHashCode()
*/
public boolean solutionEquals(Object o) {
if (this == o) {
return true;
} else if (o instanceof CloudProcess) {
CloudProcess other = (CloudProcess) o;
return new EqualsBuilder()
.append(id, other.id)
.append(computer, other.computer)
.isEquals();
} else {
return false;
}
}
/**
* The normal methods {@link #equals(Object)} and {@link #hashCode()} cannot be used because the rule engine already
* requires them (for performance in their original state).
* @see #solutionEquals(Object)
*/
public int solutionHashCode() {
return new HashCodeBuilder()
.append(id)
.append(computer)
.toHashCode();
}
@Override
public String toString() {
return getLabel() + "->" + computer;
}
}
| apache-2.0 |
JustBurrow/com | com-service/src/main/java/com/service/web/dao/PageDaoImpl.java | 1513 | package com.service.web.dao;
import com.domain.web.Page;
import com.domain.web.Site;
import com.jpa.entity.web.PageEntity;
import com.jpa.repository.PageRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import static java.lang.String.format;
/**
* @author justburrow
* @since 2017. 4. 10.
*/
@Service class PageDaoImpl implements PageDao {
private static final Logger log = LoggerFactory.getLogger(PageDao.class);
@Autowired
private PageRepository pageRepository;
@Override
public Page create(Page page) {
if (log.isDebugEnabled()) {
log.debug(format("before page : %s", page));
}
page = this.pageRepository.save((PageEntity) page);
if (log.isDebugEnabled()) {
log.debug(format("after page : %s", page));
}
return page;
}
@Override
public Page read(int id) {
if (log.isDebugEnabled()) {
log.debug(format("id=%d", id));
}
Page page = this.pageRepository.findOne(id);
if (log.isDebugEnabled()) {
log.debug(format("page=%s", page));
}
return page;
}
@Override
public Page read(Site site, String path) {
if (log.isDebugEnabled()) {
log.debug(format("site=%s, path=%s", site, path));
}
PageEntity page = this.pageRepository.findOneBySiteAndPath(site, path);
if (log.isDebugEnabled()) {
log.debug(format("page=%s", page));
}
return page;
}
}
| apache-2.0 |
HujiangTechnology/RestVolley | restvolley/src/main/java/com/hujiang/restvolley/webapi/request/GetRequest.java | 571 | /*
* GetRequest 2015-11-24
* Copyright (c) 2015 hujiang Co.Ltd. All right reserved(http://www.hujiang.com).
*
*/
package com.hujiang.restvolley.webapi.request;
import android.content.Context;
import com.android.volley.Request;
/**
* Get method request.
*
* @author simon
* @version 1.0.0
* @since 2015-11-24
*/
public class GetRequest extends RestVolleyRequestWithNoBody<GetRequest> {
/**
* constructor.
* @param context {@link Context}
*/
public GetRequest(Context context) {
super(context, Request.Method.GET);
}
} | apache-2.0 |
agwlvssainokuni/springmvctutorial | src/goods/java/cherry/goods/crypto/Crypto.java | 1045 | /*
* Copyright 2014 agwlvssainokuni
*
* 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 cherry.goods.crypto;
/**
* 暗号化/復号化の機能のインタフェースを規定する。
*/
public interface Crypto {
/**
* 暗号化する。
*
* @param in
* 平文。
* @return 暗号文。
*/
byte[] encrypt(byte[] in);
/**
* 復号化する。
*
* @param in
* 暗号文。
* @return 平文。
*/
byte[] decrypt(byte[] in);
}
| apache-2.0 |
apache/tapestry4 | framework/src/test/org/apache/tapestry/error/BaseErrorTestCase.java | 2196 | // Copyright 2005 The Apache Software Foundation
//
// 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.apache.tapestry.error;
import org.apache.hivemind.test.HiveMindTestCase;
import org.apache.tapestry.IPage;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.error.TestExceptionPresenter.ExceptionFixture;
import org.apache.tapestry.services.ResponseRenderer;
import org.apache.tapestry.test.Creator;
import org.easymock.MockControl;
/**
* Base class for tests of the various error reporting service implementations.
*
* @author Howard M. Lewis Ship
* @since 4.0
*/
public abstract class BaseErrorTestCase extends HiveMindTestCase
{
protected IPage newPage()
{
Creator c = new Creator();
return (IPage) c.newInstance(ExceptionFixture.class);
}
protected IRequestCycle newCycle(String pageName, IPage page)
{
MockControl control = newControl(IRequestCycle.class);
IRequestCycle cycle = (IRequestCycle) control.getMock();
cycle.getPage(pageName);
control.setReturnValue(page);
return cycle;
}
protected ResponseRenderer newRenderer(IRequestCycle cycle, Throwable throwable) throws Exception
{
MockControl control = newControl(ResponseRenderer.class);
ResponseRenderer renderer = (ResponseRenderer) control.getMock();
renderer.renderResponse(cycle);
if (throwable != null)
control.setThrowable(throwable);
return renderer;
}
protected RequestExceptionReporter newReporter()
{
return (RequestExceptionReporter) newMock(RequestExceptionReporter.class);
}
}
| apache-2.0 |
google/nomulus | proxy/src/main/java/google/registry/proxy/metric/BaseMetrics.java | 2534 | // Copyright 2019 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.proxy.metric;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import com.google.monitoring.metrics.CustomFitter;
import com.google.monitoring.metrics.ExponentialFitter;
import com.google.monitoring.metrics.FibonacciFitter;
import com.google.monitoring.metrics.LabelDescriptor;
/** Base class for metrics. */
public abstract class BaseMetrics {
/**
* Labels to register metrics with.
*
* <p>The client certificate hash value is only used for EPP metrics. For WHOIS metrics, it will
* always be {@code "none"}. In order to get the actual registrar name, one can use the {@code
* nomulus} tool:
*
* <pre>
* nomulus -e production list_registrars -f clientCertificateHash | grep $HASH
* </pre>
*/
protected static final ImmutableSet<LabelDescriptor> LABELS =
ImmutableSet.of(
LabelDescriptor.create("protocol", "Name of the protocol."),
LabelDescriptor.create(
"client_cert_hash", "SHA256 hash of the client certificate, if available."));
// Maximum request size is defined in the config file, this is not realistic and we'd be out of
// memory when the size approaches 1 GB.
protected static final CustomFitter DEFAULT_SIZE_FITTER = FibonacciFitter.create(1073741824);
// Maximum 1 hour latency, this is not specified by the spec, but given we have a one hour idle
// timeout, it seems reasonable that maximum latency is set to 1 hour as well. If we are
// approaching anywhere near 1 hour latency, we'd be way out of SLO anyway.
protected static final ExponentialFitter DEFAULT_LATENCY_FITTER =
ExponentialFitter.create(22, 2, 1.0);
/**
* Resets all metrics.
*
* <p>This should only be used in tests to reset states. Production code should not call this
* method.
*/
@VisibleForTesting
abstract void resetMetrics();
}
| apache-2.0 |
flo-gouin/OpenVenturiEngine | org.ove.incubationBox/src/org/ove/incubationbox/testBox/TIFFReader.java | 12561 | package org.ove.incubationbox.testBox;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
public class TIFFReader {
private static final short MAGIC_NUMBER = 42;
private static final short LITTLE_ENDIAN = 0x4949;
private static final short BIG_ENDIAN = 0x4D4D;
private static FileChannel _channel;
private static ByteOrder _byteOrder = ByteOrder.nativeOrder();
public static void read(File file_p) {
FileInputStream fis;
try {
fis = new FileInputStream(file_p);
_channel = fis.getChannel();
ByteBuffer fileheader = ByteBuffer.allocateDirect(4);
_channel.read(fileheader);
fileheader.flip();
// Get File ByteOrder
switch (fileheader.getShort()) {
case LITTLE_ENDIAN:
_byteOrder = ByteOrder.LITTLE_ENDIAN;
break;
case BIG_ENDIAN:
_byteOrder = ByteOrder.BIG_ENDIAN;
break;
default:
System.err.println("Unknown endianess");
return;
}
fileheader.order(_byteOrder);
// Check if the file is a valid TIFF File
if (fileheader.getShort() != MAGIC_NUMBER) {
System.err.println(file_p + " isn't a valid TIFF file");
}
// Get IFD offset
ByteBuffer ifdBuffer = ByteBuffer.allocateDirect(4);
ifdBuffer.order(_byteOrder);
_channel.read(ifdBuffer);
ifdBuffer.flip();
int position = ifdBuffer.getInt();
System.out.println("IFD start position:" + position);
_channel.position(position);
// Get quantity of IFD
ByteBuffer ifdQtyBuffer = ByteBuffer.allocateDirect(2);
ifdQtyBuffer.order(_byteOrder);
_channel.read(ifdQtyBuffer);
ifdQtyBuffer.flip();
int qty = ifdQtyBuffer.getShort();
System.out.println("IFD qty:" + qty);
for (int ifdNum = 1; ifdNum <= qty; ifdNum++) {
ByteBuffer ifdEntryBuffer = ByteBuffer.allocateDirect(12);
ifdEntryBuffer.order(_byteOrder);
_channel.read(ifdEntryBuffer);
ifdEntryBuffer.flip();
short tagId = ifdEntryBuffer.getShort();
short fieldType = ifdEntryBuffer.getShort();
int nbValues = ifdEntryBuffer.getInt();
int value = ifdEntryBuffer.getInt();
System.out.println("IFD #"
+ ifdNum
+ " ["
+ tagId
+ "] -> "
+ nbValues
+ " "
+ decodeType(fieldType)
+ " value(s):");
decode(tagId, fieldType, nbValues, value);
}
ByteBuffer nextIfdOffsetBuffer = ByteBuffer.allocateDirect(4);
nextIfdOffsetBuffer.order(_byteOrder);
_channel.read(nextIfdOffsetBuffer);
nextIfdOffsetBuffer.flip();
System.out.println("Next offset:" + nextIfdOffsetBuffer.getInt());
System.out.println("End of TIFF file reader");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void decode(short tagId_p, short fieldType_p, int nbValues_p, int value_p)
throws IOException {
long backUpPosition = 0;
ByteBuffer buffer;
switch (tagId_p) {
//ImageWidth
case 256:
System.out.println("Width: " + value_p + "px");
break;
//ImageHeight
case 257:
System.out.println("Height: " + value_p + "px");
break;
//BitsPerSample [Grayscale Images]
case 258:
System.out.println("BitsPerSample: " + value_p + " bits"); // Not used with Bilevel images
break;
//Compression
case 259:
decodeCompression(fieldType_p, nbValues_p, value_p);
break;
//PhotometricInterpretation
case 262:
decodeColor(fieldType_p, nbValues_p, value_p);
break;
//StripOffsets
case 273:
backUpPosition = _channel.position();
_channel.position(value_p);
buffer = ByteBuffer.allocateDirect(nbValues_p * 4);
buffer.order(_byteOrder);
_channel.read(buffer);
buffer.flip();
for (int cpt = 0; cpt < nbValues_p; cpt++) {
System.out.println("#" + cpt + " offset: " + buffer.getInt());
}
_channel.position(backUpPosition);
break;
case 274:
decodeOrientation(fieldType_p, nbValues_p, value_p);
break;
//SampesPerPixel [RGB FullColor Images]
case 277:
System.out.println("SamplesPerPixel: " + value_p + " component(s)");
break;
//RowsPerStrip
case 278:
System.out.println("Nb row per strips: " + value_p);
break;
//StripByteCounts
case 279:
backUpPosition = _channel.position();
_channel.position(value_p);
buffer = ByteBuffer.allocateDirect(nbValues_p * 4);
buffer.order(_byteOrder);
_channel.read(buffer);
buffer.flip();
for (int cpt = 0; cpt < nbValues_p; cpt++) {
System.out.println("#" + cpt + " size: " + buffer.getInt());
}
_channel.position(backUpPosition);
break;
//XResolution
case 282:
backUpPosition = _channel.position();
_channel.position(value_p);
buffer = ByteBuffer.allocateDirect(2 * 4);
buffer.order(_byteOrder);
_channel.read(buffer);
buffer.flip();
_channel.position(backUpPosition);
System.out.println("XResolution: " + (buffer.getInt() / (float) (buffer.getInt())));
break;
//YResolution
case 283:
backUpPosition = _channel.position();
_channel.position(value_p);
buffer = ByteBuffer.allocateDirect(2 * 4);
buffer.order(_byteOrder);
_channel.read(buffer);
buffer.flip();
_channel.position(backUpPosition);
System.out.println("YResolution: " + (buffer.getInt() / (float) (buffer.getInt())));
break;
case 284:
decodePlanarConfiguration(fieldType_p, nbValues_p, value_p);
break;
//ResolutionUnit
case 296:
decodeResolutionUnit(fieldType_p, nbValues_p, value_p);
break;
case 315:
//TODO complete this part
break;
//ColorMap [Palette-color Images]
case 320:
System.out.println("Color map: " + value_p); // Specific palette-color Image
default:
System.out.println("<<Unknown Tag [" + tagId_p + "]>>");
break;
}
}
private static void decodePlanarConfiguration(short fieldType_p, int nbValues_p, int value_p) {
switch (value_p) {
case 1: // Default value
System.out.println("Chunky format storage");
break;
case 2:
System.out.println("Planar format storage");
break;
default:
System.out.println("Unknown Value: " + value_p);
break;
}
}
private static void decodeOrientation(short fieldType_p, int nbValues_p, int value_p) {
switch (value_p) {
case 1: // Default value
System.out.println("Top left origin");
break;
case 2:
System.out.println("Top right origin");
break;
case 3:
System.out.println("Bottom right origin");
break;
case 4:
System.out.println("Bottom left origin");
break;
case 5:
System.out.println("x<->y inverted top left origin");
break;
case 6:
System.out.println("x<->y inverted top right origin");
break;
case 7:
System.out.println("x<->y inverted bottom right origin");
break;
case 8:
System.out.println("x<->y inverted bottom left origin");
break;
default:
System.out.println("Unknown Value: " + value_p);
break;
}
}
private static String decodeType(short fieldType_p) {
switch (fieldType_p) {
case 1:
return "byte";
case 2:
return "ASCII";
case 3:
return "short";
case 4:
return "long";
case 5:
return "rational";
case 6:
return "sbyte";
case 7:
return "undefined";
case 8:
return "sshort";
case 9:
return "slong";
case 10:
return "srational";
case 11:
return "float";
case 12:
return "double";
default:
return "unknown(" + fieldType_p + ")";
}
}
private static void decodeResolutionUnit(short fieldType_p, int nbValues_p, int value_p) {
switch (value_p) {
case 1:
System.out.println("No absolute unit");
break;
case 2:
System.out.println("Inch unit"); // Default value
break;
case 3:
System.out.println("Centimeter unit");
break;
default:
System.out.println("Unknown Value: " + value_p);
break;
}
}
private static void decodeColor(short fieldType_p, int nbValues_p, int value_p) {
switch (value_p) {
case 0:
System.out.println("White is zero");
break;
case 1:
System.out.println("Black is zero");
break;
case 2:
System.out.println("RGB");
break;
case 3:
System.out.println("Palette color");
break;
case 4:
System.out.println("Transparency mask");
break;
default:
System.out.println("Unknown Value: " + value_p);
break;
}
}
private static void unpackData(FileChannel channel_p,
long offset_p,
long length_p,
ByteBuffer destinationBuffer_p) throws IOException {
long backUpPosition = _channel.position();
channel_p.position(offset_p);
ByteBuffer headBuffer = ByteBuffer.allocateDirect(1);
headBuffer.order(_byteOrder);
long nbReadBytes = 0;
while (nbReadBytes < length_p) {
headBuffer.clear();
nbReadBytes += channel_p.read(headBuffer);
headBuffer.flip();
byte head = headBuffer.get();
if (head <= Byte.MIN_VALUE) {
continue;
} else if (head > 0) {
ByteBuffer buffer = ByteBuffer.allocateDirect(1 + head);
buffer.order(_byteOrder);
nbReadBytes += channel_p.read(buffer);
buffer.flip();
destinationBuffer_p.put(buffer);
} else {
ByteBuffer buffer = ByteBuffer.allocateDirect(1);
buffer.order(_byteOrder);
nbReadBytes += channel_p.read(buffer);
buffer.flip();
byte data = buffer.get();
for (int cpt = 0; cpt < (1 - head); cpt++) {
destinationBuffer_p.put(data);
}
}
}
_channel.position(backUpPosition);
}
private static void decodeCompression(short fieldType_p, int nbValues_p, int value_p) {
switch (value_p) {
case 1: // Default value
System.out.println("No Compression");
break;
case 2:
System.out.println("Modified Huffman Compression");
break;
case 32773:
System.out.println("PackBits Compression");
break;
default:
System.out.println("Unknown Value: " + value_p);
break;
}
}
}
| apache-2.0 |
thrawn-sh/subversion | src/test/java/de/shadowhunt/subversion/internal/httpv1/v1_3/RepositoryExistsReadOnlyIT.java | 980 | /**
* Copyright © 2013-2018 shadowhunt (dev@shadowhunt.de)
*
* 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 de.shadowhunt.subversion.internal.httpv1.v1_3;
import de.shadowhunt.subversion.internal.AbstractRepositoryExistsIT;
public class RepositoryExistsReadOnlyIT extends AbstractRepositoryExistsIT {
private static final Helper HELPER = new Helper();
public RepositoryExistsReadOnlyIT() {
super(HELPER.getRepositoryReadOnly());
}
}
| apache-2.0 |
iqrfsdk/jsimply | simply-modules/simply-iqrf-dpa30x/simply-iqrf-dpa-v30x/src/main/java/com/microrisc/simply/iqrf/dpa/v30x/types/NodeStatusInfo.java | 5953 | /*
* Copyright 2014 MICRORISC s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microrisc.simply.iqrf.dpa.v30x.types;
import java.util.Arrays;
/**
* Encapsulates status information of node of IQMesh network.
*
* @author Michal Konopa
* @author Rostislav Spinar
*/
public final class NodeStatusInfo {
/** Logical network address of the node. */
private final int address;
/** VRN (Virtual Routing Number). */
private final int vrn;
/** Zone index (zone number + 1) */
private final int zoneIndex;
/** NTW DID variable. */
private final int ntwDID;
/** parent VRN */
private final int parentVrn;
/** 2B user address */
private final int userAddress;
/** Network identification NID0, NID1 */
private final short[] networkId;
/** VRN of the first Node in a given zone */
private final int vrnFirstNodeInZone;
/** Network configuration */
private final int networkConfiguration;
/**
* Flags.
* Bit 0 indicates whether the Node device is bonded.
*/
private final int flags;
/**
* Creates new {@code NodeStatusInfo} object.
* @param address logical network address of the node
* @param vrn VRN (virtual routing number)
* @param zoneIndex zone index
* @param ntwDID {@code ntwDID} variable value
* @param parentVrn parent VRN
* @param userAddress 2B user address
* @param networkId Network identification NID0, NID1
* @param vrnFirstNodeInZone VRN of the first Node in a given zone
* @param networkConfiguration Network configuration
* @param flags flags
*/
public NodeStatusInfo(
int address, int vrn, int zoneIndex, int ntwDID, int parentVrn,
int userAddress, short[] networkId, int vrnFirstNodeInZone,
int networkConfiguration, int flags
) {
this.address = address;
this.vrn = vrn;
this.zoneIndex = zoneIndex;
this.ntwDID = ntwDID;
this.parentVrn = parentVrn;
this.userAddress = userAddress;
this.networkId = networkId;
this.vrnFirstNodeInZone = vrnFirstNodeInZone;
this.networkConfiguration = networkConfiguration;
this.flags = flags;
}
/**
* @return the address
*/
public int getAddress() {
return address;
}
/**
* @return Virtual Routing Number
*/
public int getVrn() {
return vrn;
}
/**
* @return zone index
*/
public int getZoneIndex() {
return zoneIndex;
}
/**
* @return {@code ntwDID} variable value
*/
public int getNtwDID() {
return ntwDID;
}
/**
* @return parent VRN
*/
public int getParentVrn() {
return parentVrn;
}
/**
* @return the user address
*/
public int getUserAddress() {
return userAddress;
}
/**
* @return the network identification
*/
public short[] getNetworkId() {
return networkId;
}
/**
* @return the VRN of the first Node in a given zone
*/
public int getVrnFirstNodeinZone() {
return vrnFirstNodeInZone;
}
/**
* @return the network configuration
*/
public int getNetworkConfiguration() {
return networkConfiguration;
}
/**
* @return flags. Bit 0 indicates whether the Node device is bonded.
*/
public int getFlags() {
return flags;
}
@Override
public String toString() {
StringBuilder strBuilder = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
strBuilder.append(this.getClass().getSimpleName() + " { " + NEW_LINE);
strBuilder.append(" Address: " + address + NEW_LINE);
strBuilder.append(" VRN: " + vrn + NEW_LINE);
strBuilder.append(" Zone index: " + zoneIndex + NEW_LINE);
strBuilder.append(" Parent VRN: " + parentVrn + NEW_LINE);
strBuilder.append(" User address: " + userAddress + NEW_LINE);
strBuilder.append(" Network ID: " + Arrays.toString(networkId) + NEW_LINE);
strBuilder.append(" VRN of the first node in zone: " + vrnFirstNodeInZone + NEW_LINE);
strBuilder.append(" Network configuration: " + networkConfiguration + NEW_LINE);
strBuilder.append(" Flags: " + flags + NEW_LINE);
strBuilder.append("}");
return strBuilder.toString();
}
public String toPrettyFormattedString() {
StringBuilder strBuilder = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
strBuilder.append("Address: " + address + NEW_LINE);
strBuilder.append("VRN: " + vrn + NEW_LINE);
strBuilder.append("Zone index: " + zoneIndex + NEW_LINE);
strBuilder.append("Parent VRN: " + parentVrn + NEW_LINE);
strBuilder.append("User address: " + userAddress + NEW_LINE);
strBuilder.append("Network ID: " + Arrays.toString(networkId) + NEW_LINE);
strBuilder.append("VRN of the first node in zone: " + vrnFirstNodeInZone + NEW_LINE);
strBuilder.append("Network configuration: " + networkConfiguration + NEW_LINE);
strBuilder.append("Flags: " + flags + NEW_LINE);
return strBuilder.toString();
}
}
| apache-2.0 |
ui-icts/spring-utils | src/main/java/edu/uiowa/icts/criterion/IntegerLike.java | 2566 | package edu.uiowa.icts.criterion;
/*
* #%L
* spring-utils
* %%
* Copyright (C) 2010 - 2015 University of Iowa Institute for Clinical and Translational Science (ICTS)
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.engine.spi.TypedValue;
/**
* <p>IntegerLike class.</p>
*
* @author rrlorent
* @date March 20, 2014
* @version $Id: $
*/
public class IntegerLike implements Criterion {
private static final long serialVersionUID = -6821722080754628376L;
private String propertyName;
private String value;
/**
* <p>Constructor for IntegerLike.</p>
*
* @param propertyName a {@link java.lang.String} object.
* @param value a {@link java.lang.String} object.
*/
public IntegerLike( String propertyName, String value ) {
this.propertyName = propertyName;
this.value = value;
}
/**
* {@inheritDoc}
*
* (non-Javadoc)
* @see org.hibernate.criterion.Criterion#toSqlString(org.hibernate.Criteria, org.hibernate.criterion.CriteriaQuery)
*/
@Override
public String toSqlString( Criteria criteria, CriteriaQuery criteriaQuery ) throws HibernateException {
String[] columns = criteriaQuery.getColumnsUsingProjection( criteria, propertyName );
if ( columns.length != 1 ) {
throw new HibernateException( "like may only be used with single-column properties" );
}
return " lower( cast( " + columns[0] + " as varchar ) ) like ? ";
}
/**
* {@inheritDoc}
*
* (non-Javadoc)
* @see org.hibernate.criterion.Criterion#getTypedValues(org.hibernate.Criteria, org.hibernate.criterion.CriteriaQuery)
*/
@Override
public TypedValue[] getTypedValues( Criteria criteria, CriteriaQuery criteriaQuery ) throws HibernateException {
return new TypedValue[] { new TypedValue( new org.hibernate.type.StringType(), MatchMode.START.toMatchString( value.toLowerCase() ) ) };
}
}
| apache-2.0 |
spring-cloud/spring-cloud-contract | spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/builder/Acceptor.java | 729 | /*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.cloud.contract.verifier.builder;
interface Acceptor {
boolean accept();
}
| apache-2.0 |
ContinuITy-Project/ContinuITy | continuity.lib.api/src/test/java/org/continuity/api/entities/artifact/markovbehavior/MarkovChainTest.java | 5558 | package org.continuity.api.entities.artifact.markovbehavior;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.assertj.core.data.Offset;
import org.continuity.api.entities.test.MarkovChainTestInstance;
import org.junit.Test;
public class MarkovChainTest {
@Test
public void testReadWrite() throws IOException {
testReadWrite(MarkovChainTestInstance.SOCK_SHOP);
testReadWrite(MarkovChainTestInstance.SIMPLE);
testReadWrite(MarkovChainTestInstance.SIMPLE_WO_A);
testReadWrite(MarkovChainTestInstance.SIMPLE_INSERT);
testReadWrite(MarkovChainTestInstance.SIMPLE_WITH_INSERT);
}
@Test
public void testSpecialNumbers() throws IOException {
String[][] csv = MarkovChainTestInstance.SPECIAL_NUMBERS.getCsv();
RelativeMarkovChain chain = RelativeMarkovChain.fromCsv(csv);
System.out.println(chain);
}
private void testReadWrite(MarkovChainTestInstance instance) throws IOException {
String[][] csv = instance.getCsv();
RelativeMarkovChain chain = RelativeMarkovChain.fromCsv(csv);
assertThat(chain.toCsv()).isEqualTo(csv);
}
@Test
public void testRemoveState() throws IOException {
String[][] origCsv = MarkovChainTestInstance.SIMPLE.getCsv();
RelativeMarkovChain chain = RelativeMarkovChain.fromCsv(origCsv);
chain.removeState("a", NormalDistribution.ZERO);
String[][] newCsv = MarkovChainTestInstance.SIMPLE_WO_A.getCsv();
assertThat(chain.toCsv()).isEqualTo(newCsv);
}
@Test
public void testRenameState() throws IOException {
testRenameState(MarkovChainTestInstance.SIMPLE, "a");
testRenameState(MarkovChainTestInstance.SIMPLE, "b");
testRenameState(MarkovChainTestInstance.SIMPLE, "c");
testRenameState(MarkovChainTestInstance.SOCK_SHOP, "cartUsingGET");
testRenameState(MarkovChainTestInstance.SOCK_SHOP, "getCatalogueItemUsingGET");
testRenameState(MarkovChainTestInstance.SOCK_SHOP, "loginUsingGET");
testRenameState(MarkovChainTestInstance.SIMPLE, RelativeMarkovChain.INITIAL_STATE);
testRenameState(MarkovChainTestInstance.SIMPLE, RelativeMarkovChain.FINAL_STATE);
testRenameState(MarkovChainTestInstance.SOCK_SHOP, RelativeMarkovChain.INITIAL_STATE);
testRenameState(MarkovChainTestInstance.SOCK_SHOP, RelativeMarkovChain.FINAL_STATE);
}
private void testRenameState(MarkovChainTestInstance instance, String state) throws IOException {
String[][] csv = instance.getCsv();
RelativeMarkovChain chain = RelativeMarkovChain.fromCsv(csv);
chain.renameState(state, state + "2");
chain.renameState(state + "2", state);
assertThat(chain.toCsv()).isEqualTo(csv);
}
@Test
public void testAddSubChain() throws IOException {
String[][] origCsv = MarkovChainTestInstance.SIMPLE.getCsv();
String[][] insertCsv = MarkovChainTestInstance.SIMPLE_INSERT.getCsv();
RelativeMarkovChain chain = RelativeMarkovChain.fromCsv(origCsv);
chain.setId("orig");
RelativeMarkovChain insert = RelativeMarkovChain.fromCsv(insertCsv);
insert.setId("insert");
chain.replaceState("a", insert);
String[][] newCsv = MarkovChainTestInstance.SIMPLE_WITH_INSERT.getCsv();
assertThat(chain.toCsv()).isEqualTo(newCsv);
}
@Test
public void testThinkTimeAfterStateRemoval() throws IOException {
testThinkTimeAfterStateRemovals(MarkovChainTestInstance.SIMPLE, 34.833);
testThinkTimeAfterStateRemovals(MarkovChainTestInstance.SOCK_SHOP, 654368.40);
}
private void testThinkTimeAfterStateRemovals(MarkovChainTestInstance instance, double expectedThinkTime) throws IOException {
String[][] csv = instance.getCsv();
RelativeMarkovChain chain = RelativeMarkovChain.fromCsv(csv);
for (String state : chain.getRequestStates()) {
chain.removeState(state, NormalDistribution.ZERO);
}
assertThat(chain.getRequestStates()).isEmpty();
assertThat(chain.getTransition(RelativeMarkovChain.INITIAL_STATE, RelativeMarkovChain.FINAL_STATE).getThinkTime().getMean()).isEqualTo(expectedThinkTime, Offset.offset(0.01));
}
@Test
public void testThinkTimeWithSubChain() throws IOException {
testThinkTimeWithSubChain(MarkovChainTestInstance.SIMPLE, MarkovChainTestInstance.SIMPLE_INSERT, "a");
testThinkTimeWithSubChain(MarkovChainTestInstance.SOCK_SHOP, MarkovChainTestInstance.SIMPLE, "cartUsingGET");
}
private void testThinkTimeWithSubChain(MarkovChainTestInstance origInstance, MarkovChainTestInstance insertInstance, String state) throws IOException {
String[][] origCsv = origInstance.getCsv();
String[][] insertCsv = insertInstance.getCsv();
RelativeMarkovChain insert = RelativeMarkovChain.fromCsv(insertCsv);
NormalDistribution insertDuration = calculateDuration(insert);
RelativeMarkovChain chain = RelativeMarkovChain.fromCsv(origCsv);
chain.removeState(state, insertDuration);
NormalDistribution origDuration = calculateDuration(chain);
chain = RelativeMarkovChain.fromCsv(origCsv);
chain.setId("orig");
insert = RelativeMarkovChain.fromCsv(insertCsv);
insert.setId("insert");
chain.replaceState(state, insert);
NormalDistribution duration = calculateDuration(chain);
assertThat(duration.getMean()).as("mean").isEqualTo(origDuration.getMean(), Offset.offset(0.01));
// Not checking the variance because it can actually be distorted by the improper
// convolution
}
private NormalDistribution calculateDuration(RelativeMarkovChain chain) {
for (String state : chain.getRequestStates()) {
chain.removeState(state, NormalDistribution.ZERO);
}
return chain.getTransition(RelativeMarkovChain.INITIAL_STATE, RelativeMarkovChain.FINAL_STATE).getThinkTime();
}
}
| apache-2.0 |
thunderace/mpd-control | src/org/thunder/mpdcontrol/cover/provider/MusicBrainzCover.java | 4247 | package org.thunder.mpdcontrol.cover.provider;
import org.json.JSONArray;
import org.json.JSONObject;
import org.thunder.mpdcontrol.mpd.AlbumInfo;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Fetch cover from MusicBrainz
*/
public class MusicBrainzCover extends AbstractWebCover {
private static final String COVER_ART_ARCHIVE_URL = "http://coverartarchive.org/release-group/";
private List<String> extractImageUrls(String covertArchiveResponse)
{
JSONObject jsonRootObject;
JSONArray jsonArray;
String coverUrl;
JSONObject jsonObject;
List<String> coverUrls = new ArrayList<String>();
if (covertArchiveResponse == null || covertArchiveResponse.isEmpty())
{
return Collections.emptyList();
}
try
{
jsonRootObject = new JSONObject(covertArchiveResponse);
if (jsonRootObject.has("images"))
{
jsonArray = jsonRootObject.getJSONArray("images");
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.has("image")) {
coverUrl = jsonObject.getString("image");
if (coverUrl != null) {
coverUrls.add(coverUrl);
}
}
}
}
}
catch (Exception e)
{
d(MusicBrainzCover.class.getName(), "No cover in CovertArchive : " + e);
}
return coverUrls;
}
private List<String> extractReleaseIds(String response) {
List<String> releaseList = new ArrayList<String>();
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(response));
int eventType;
eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equals("release-group")) {
String id = xpp.getAttributeValue(null, "id");
if (id != null) {
releaseList.add(id);
}
}
}
eventType = xpp.next();
}
} catch (Exception e) {
e(MusicBrainzCover.class.getName(), "Musicbrainz release search failure : " + e);
}
return releaseList;
}
private String getCoverArtArchiveResponse(String mbid) {
String request = (COVER_ART_ARCHIVE_URL + mbid + "/");
return executeGetRequestWithConnection(request);
}
@Override
public String[] getCoverUrl(AlbumInfo albumInfo) throws Exception
{
List<String> releases;
List<String> coverUrls = new ArrayList<String>();
String covertArtResponse;
releases = searchForRelease(albumInfo);
if (releases == null) return null;
for (String release : releases)
{
covertArtResponse = getCoverArtArchiveResponse(release);
if (covertArtResponse != null && !covertArtResponse.isEmpty())
{
coverUrls.addAll(extractImageUrls(covertArtResponse));
}
if (!coverUrls.isEmpty()) break;
}
return coverUrls.toArray(new String[coverUrls.size()]);
}
@Override
public String getName() {
return "MUSICBRAINZ";
}
private List<String> searchForRelease(AlbumInfo albumInfo) {
String response;
String url = "http://musicbrainz.org/ws/2/release-group/?query=" + albumInfo.getArtist()
+ " " + albumInfo.getAlbum() + "&type=release-group&limit=5";
response = executeGetRequestWithConnection(url);
return extractReleaseIds(response);
}
}
| apache-2.0 |
jaredrummler/TrueTypeParser | lib-truetypeparser/src/main/java/com/jaredrummler/fontreader/complexscripts/fonts/Positionable.java | 2243 | /*
* Copyright (C) 2016 Jared Rummler <jared.rummler@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.jaredrummler.fontreader.complexscripts.fonts;
/**
* <p>Optional interface which indicates that glyph positioning is supported and, if supported,
* can perform positioning.</p>
*
* <p>This work was originally authored by Glenn Adams (gadams@apache.org).</p>
*/
public interface Positionable {
/**
* Determines if font performs glyph positioning.
*
* @return true if performs positioning
*/
boolean performsPositioning();
/**
* Perform glyph positioning.
*
* @param cs
* character sequence to map to position offsets (advancement adjustments)
* @param script
* a script identifier
* @param language
* a language identifier
* @param fontSize
* font size
* @return array (sequence) of 4-tuples of placement [PX,PY] and advance [AX,AY] adjustments, in that order,
* with one 4-tuple for each element of glyph sequence, or null if no non-zero adjustment applies
*/
int[][] performPositioning(CharSequence cs, String script, String language, int fontSize);
/**
* Perform glyph positioning using an implied font size.
*
* @param cs
* character sequence to map to position offsets (advancement adjustments)
* @param script
* a script identifier
* @param language
* a language identifier
* @return array (sequence) of 4-tuples of placement [PX,PY] and advance [AX,AY] adjustments, in that order,
* with one 4-tuple for each element of glyph sequence, or null if no non-zero adjustment applies
*/
int[][] performPositioning(CharSequence cs, String script, String language);
}
| apache-2.0 |
immopoly/android | src/org/immopoly/android/widget/ImmoPlaceOverlayItem.java | 1191 | /*
* This is the Android component of Immopoly
* http://immopoly.appspot.com
* Copyright (C) 2011 Tobias Sasse
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package org.immopoly.android.widget;
import java.util.ArrayList;
import org.immopoly.android.model.Flat;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;
public class ImmoPlaceOverlayItem extends OverlayItem {
ArrayList<Flat> flats;
public ImmoPlaceOverlayItem( GeoPoint point, ArrayList<Flat> flats ) {
super( point, "", "" );
this.flats = flats;
}
}
| apache-2.0 |
nicolashernandez/dev-star | uima-star/uima-mapper/src/main/java/fr/univnantes/lina/uima/mapper/view/ViewMapperAE.java | 24360 | /*
* 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 fr.univnantes.lina.uima.mapper.view;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.uima.UIMARuntimeException;
import org.apache.uima.UimaContext;
import org.apache.uima.analysis_component.JCasMultiplier_ImplBase;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.AbstractCas;
import org.apache.uima.cas.ArrayFS;
import org.apache.uima.cas.BooleanArrayFS;
import org.apache.uima.cas.ByteArrayFS;
import org.apache.uima.cas.CAS;
import org.apache.uima.cas.CASException;
import org.apache.uima.cas.CASRuntimeException;
import org.apache.uima.cas.DoubleArrayFS;
import org.apache.uima.cas.FSIndex;
import org.apache.uima.cas.FSIterator;
import org.apache.uima.cas.Feature;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.cas.FloatArrayFS;
import org.apache.uima.cas.IntArrayFS;
import org.apache.uima.cas.LongArrayFS;
import org.apache.uima.cas.ShortArrayFS;
import org.apache.uima.cas.SofaFS;
import org.apache.uima.cas.StringArrayFS;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.impl.CASImpl;
import org.apache.uima.cas.impl.LowLevelCAS;
import org.apache.uima.cas.text.AnnotationFS;
import org.apache.uima.examples.SourceDocumentInformation;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.util.CasCopier;
import fr.univnantes.lina.javautil.DateUtilities;
import fr.univnantes.lina.uima.common.cas.JCasUtils;
/**
* Rename the named view to another. The actual process copies the content (sofa
* and feature structure) of named views to a new one which is set with a target
* name. A list of from/to views couples is given in parameter.
*/
public class ViewMapperAE extends JCasMultiplier_ImplBase {
/*
* PARAMETERS NAMES
*/
/**
* Name of the FromViewToView Parameter
*/
public static final String PARAM_FROM_VIEW_TO_VIEW = "FromViewToView";
/**
* Name of the CopyFeatureStructuresExcept Parameter
*/
public static final String PARAM_COPY_FS_EXCEPT = "CopyFeatureStructuresExcept";
/*
* PARAMETERS DEFAULT VALUES
*/
/**
* Name of the default separator between the FromView and the ToView
* associated
*/
private static String DEFAULT_FROMVIEW_AND_TOVIEW_SEPARATOR = "->";
/*
* LOCAL VARIABLES
*/
private Map<String, String> fromViewToViewHashMap;
private JCas sourceJCas;
private CAS mDestCas;
private LowLevelCAS mLowLevelDestCas;
private Boolean renameDone = false;
private Map mFsMap = new HashMap();
private String mDoc;
private String mDocUri;
private static Boolean debug = false;
private Map<String, Integer> copyFSExceptMap;
/*
* ACCESSORS
*/
/**
* @return the renameDone
*/
private Boolean getRenameDone() {
return renameDone;
}
/**
* @param renameDone
* the renameDone to set
*/
private void setRenameDone(Boolean renameDone) {
this.renameDone = renameDone;
}
/**
* @return the initialJCas
*/
private JCas getSourceJCas() {
return sourceJCas;
}
/**
* @param initialJCas
* the initialJCas to set
*/
private void setSourceJCas(JCas initialJCas) {
this.sourceJCas = initialJCas;
}
/*
* METHODS
*/
/**
* Parameter settings and checking
*
*/
public void initialize(UimaContext context)
throws ResourceInitializationException {
// SUPER PARAMETER SETTINGS
super.initialize(context);
// CURRENT AE PARAMETER SETTINGS
// Get the from to view values
String[] fromViewToViewStringArray = (String[]) context
.getConfigParameterValue(PARAM_FROM_VIEW_TO_VIEW);
// check if at least one rename request is defined
if (fromViewToViewStringArray == null) {
String errmsg = "At least one FromViewToView parameter must be set and the refered views exist !";
throw new ResourceInitializationException(errmsg, new Object[] {});
}
// get the couple to rename and check if the syntax was correct
fromViewToViewHashMap = new HashMap<String, String>();
for (int i = 0; i < fromViewToViewStringArray.length; i++) {
String[] aFromViewToViewCouple = fromViewToViewStringArray[i]
.split(DEFAULT_FROMVIEW_AND_TOVIEW_SEPARATOR);
if (aFromViewToViewCouple.length == 2)
fromViewToViewHashMap.put(aFromViewToViewCouple[1].trim(),
aFromViewToViewCouple[0].trim());
else {
String errmsg = "Wrong syntax to the "
+ PARAM_FROM_VIEW_TO_VIEW
+ " paramater with the following line "
+ aFromViewToViewCouple.toString();
throw new ResourceInitializationException(errmsg,
new Object[] {});
}
}
copyFSExceptMap = new HashMap<String, Integer>();
// Get the list of FS not to copy and turn it into an hash map
String[] copyFSExceptArray = null;
copyFSExceptArray = (String[]) context
.getConfigParameterValue(PARAM_COPY_FS_EXCEPT);
copyFSExceptMap = new HashMap<String, Integer>();
if (copyFSExceptArray != null) {
for (int i = 0; i < copyFSExceptArray.length; i++) {
copyFSExceptMap.put(copyFSExceptArray[i], 1);
}
}
}
/**
* Main method for CAS Multiplier, the actual renaming is processed in the
* next method
*
* @see org.apache.uima.analysis_component.AnalysisComponent#process()
*/
public void process(JCas aJCas) throws AnalysisEngineProcessException {
System.err.println("INFO: " + this.getClass().getName() + " starts at "
+ DateUtilities.now());
// if (debug)
// System.out.println("Debug: ViewViewRenamerper process -------------");
// only one source cas will be processed
setRenameDone(false);
// make the source cas available for the other methods
setSourceJCas(aJCas);
mDoc = aJCas.getDocumentText();
// retrieve the filename of the input file from the CAS so that it can
// be added
// to each segment
FSIterator it = aJCas
.getAnnotationIndex(SourceDocumentInformation.type).iterator();
if (it.hasNext()) {
SourceDocumentInformation fileLoc = (SourceDocumentInformation) it
.next();
mDocUri = fileLoc.getUri();
} else {
mDocUri = null;
}
}
/**
* Actually only one CAS is assumed to be created
*
* @see org.apache.uima.analysis_component.AnalysisComponent#hasNext()
*/
public boolean hasNext() throws AnalysisEngineProcessException {
// if (debug)
// System.out.println("Debug: ViewRenamer hasNext -------------");
return !getRenameDone();
}
/**
* The actual renaming process the code is largely reused from the CasCopier
* class with some adaptations
*
* @see org.apache.uima.util.CasCopier {@link http
* ://uima.apache.org/downloads
* /releaseDocs/2.1.0-incubating/docs/html/tutorials_and_users_guides
* /tutorials_and_users_guides
* .html#ugr.tug.cm.developing_multiplier_code} {@link http
* ://uima.apache
* .org/d/uimaj-2.3.1/api/org/apache/uima/util/CasCopier.html}
* {@link http
* ://svn.apache.org/repos/asf/uima/uimaj/branches/uimaj-2.1.0
* /uimaj-core/src/main/java/org/apache/uima/util/CasCopier.java}
*
* @see org.apache.uima.analysis_component.AnalysisComponent#next()
*/
public AbstractCas next() throws AnalysisEngineProcessException {
// if (debug)
// System.out.println("Debug: ViewRenamer next --------------");
// set there is no more source CAS to process
setRenameDone(true);
// create the future CAS (automatically the _InitialView will be
// created)
JCas futureJCas = getEmptyJCas();
// if (debug) {
// Iterator viewIter = null;
// try {
// viewIter = getSourceJCas().getViewIterator();
// } catch (CASException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
// while (viewIter.hasNext()) {
// JCas aView = ((JCas)viewIter.next());
// System.out.println("Debug: ViewRenamer next view from getSourceJCas "+
// aView.getViewName());
// }
// }
//
//
// if (debug) {
// Iterator viewIter = null;
// try {
// viewIter = futureJCas.getViewIterator();
// } catch (CASException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
// while (viewIter.hasNext()) {
// JCas aView = ((JCas)viewIter.next());
// System.out.println("Debug: ViewRenamer next view from getEmptyJCas "+
// aView.getViewName());
// }}
// Settings the SourceDocumentInformation
if (mDocUri != null) {
SourceDocumentInformation sdi = new SourceDocumentInformation(
futureJCas);
sdi.setUri(mDocUri);
sdi.setOffsetInSource(0);
sdi.setDocumentSize(mDoc.length());
sdi.addToIndexes();
}
// Copy fromView toView
try {
mDestCas = futureJCas.getCas();
mLowLevelDestCas = futureJCas.getCas().getLowLevelCAS();
// full copy of the cas (copy the content and the name)
// works fine
// CasCopier.copyCas(sourceJCas.getView(getToViewName()).getCas(),mDestCas,true)
// ;
// for each fromTo view couples to process
Iterator<String> toViewStringIterator = fromViewToViewHashMap
.keySet().iterator();
while (toViewStringIterator.hasNext()) {
// get the names
String toViewName = toViewStringIterator.next();
String fromViewName = (String) fromViewToViewHashMap
.get(toViewName);
// get (in case the ToView is _InitialView) or create a target
// view
CAS targetView = getOrCreateView(futureJCas.getCas(),
toViewName);
// if (debug) {
// System.out.println("Debug: ViewRenamer next fromViewName "+fromViewName+" -> toViewName "+
// toViewName +" which should be targetViewName " +
// targetView.getViewName()); }
// copy sofaData, mimeType and language
copySofaData(targetView, fromViewName);
// now copy indexed FS, but keep track so we don't index
// anything more than once
Set indexedFs = new HashSet();
Iterator indexes = sourceJCas.getView(fromViewName).getCas()
.getIndexRepository().getIndexes();
while (indexes.hasNext()) {
FSIndex index = (FSIndex) indexes.next();
Iterator iter = index.iterator();
while (iter.hasNext()) {
FeatureStructure fs = (FeatureStructure) iter.next();
if (!indexedFs.contains(fs)) {
// nh
// FeatureStructure copyOfFs = copier.copyFs(fs);
FeatureStructure copyOfFs = copyFs(fs, fromViewName);
// also don't index the DocumentAnnotation (it's
// indexed by default)
if (!isDocumentAnnotation(copyOfFs)
&& !copyOfFs
.getType()
.getName()
.equalsIgnoreCase(
"org.apache.uima.examples.SourceDocumentInformation")) {
// if (debug)
// System.out.println("Debug: ViewMapperAE next copyOfFs.getType().getName() "+copyOfFs.getType().getName()+"; copyOfFs.toString() (not a DocumentAnnotation) "+
// copyOfFs.toString());
if (!copyFSExceptMap.containsKey(copyOfFs
.getType().getName())) {
targetView.addFsToIndexes(copyOfFs);
}
// else {
// if (debug)
// System.out.println("Debug: ViewMapperAE next not copying copyOfFs.getType().getName() "+copyOfFs.getType().getName()+"; copyOfFs.toString() (not a DocumentAnnotation) "+
// copyOfFs.toString());
// }
}
indexedFs.add(fs);
}
}
}
}
return futureJCas;
} catch (Exception e) {
futureJCas.release();
throw new AnalysisEngineProcessException(e);
}
}
/**
* Determines whether the given FS is the DocumentAnnotation for its view.
* This is more than just a type check; we actually check if it is the one
* "special" DocumentAnnotation that CAS.getDocumentAnnotation() would
* return.
*/
private static boolean isDocumentAnnotation(FeatureStructure aFS) {
// if (debug) {
// System.out.println("Debug: ViewMapperAE isDocumentAnnotation -------------- aFS.toString() "+
// aFS.toString());
// }
return (aFS instanceof AnnotationFS)
&& aFS.equals(((AnnotationFS) aFS).getView()
.getDocumentAnnotation());
}
/**
* Copies an FS from the source CAS to the destination CAS. Also copies any
* referenced FS, except that previously copied FS will not be copied again.
*
* @param aFS
* the FS to copy. Must be contained within the source CAS.
* @param aFromViewName
* TODO
* @return the copy of <code>aFS</code> in the target CAS.
*/
public FeatureStructure copyFs(FeatureStructure aFS, String aFromViewName) {
// if (debug) {
// System.out.println("Debug: ViewMapperAE copyFs ----------------------");}
// FS must be in the source CAS
// assert ((CASImpl)aFS.getCAS()).getBaseCAS() ==
// ((CASImpl)getSourceJCas().getCas()).getBaseCAS();
try {
assert ((CASImpl) aFS.getCAS()).getBaseCAS() == ((CASImpl) getSourceJCas()
.getView(aFromViewName).getCas()).getBaseCAS();
} catch (CASException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// check if we already copied this FS
FeatureStructure copy = (FeatureStructure) mFsMap.get(aFS);
if (copy != null)
return copy;
// get the type of the FS
Type srcType = aFS.getType();
// Certain types need to be handled specially
// Sofa - cannot be created by normal methods. Instead, we return the
// Sofa with the
// same Sofa ID in the target CAS. If it does not exist it will be
// created.
if (aFS instanceof SofaFS) {
String sofaId = ((SofaFS) aFS).getSofaID();
// return getOrCreateView(mDestCas, sofaId).getSofa();
try {
return getOrCreateView(
getSourceJCas().getView(aFromViewName).getCas(), sofaId)
.getSofa();
} catch (CASException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// DocumentAnnotation - instead of creating a new instance, reuse the
// automatically created
// instance in the destination view.
if (isDocumentAnnotation(aFS)) {
String viewName = ((AnnotationFS) aFS).getView().getViewName();
// nh
// is not yet recreated so cannot be used
// CAS destView = mDestCas.getView(viewName);
CAS destView = null;
try {
destView = getSourceJCas().getView(viewName).getCas();
} catch (CASException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FeatureStructure destDocAnnot = destView.getDocumentAnnotation();
//
if (destDocAnnot != null) {
copyFeatures(aFS, destDocAnnot, aFromViewName);
}
return destDocAnnot;
}
// Arrays - need to be created a populated differently than "normal" FS
if (aFS.getType().isArray()) {
copy = copyArray(aFS, aFromViewName);
mFsMap.put(aFS, copy);
return copy;
}
// create a new FS of the same type in the target CAS
// TODO: could optimize type lookup if type systems are identical
Type destType = mDestCas.getTypeSystem().getType(srcType.getName());
if (destType == null) {
throw new UIMARuntimeException(
UIMARuntimeException.TYPE_NOT_FOUND_DURING_CAS_COPY,
new Object[] { srcType.getName() });
}
// We need to use the LowLevel CAS interface to create the FS, because
// the usual
// CAS.createFS() call doesn't allow us to create subtypes of
// AnnotationBase from
// a base CAS. In any case we don't need the Sofa reference to be
// automatically
// set because we'll set it manually when in the copyFeatures method.
int typeCode = mLowLevelDestCas.ll_getTypeSystem().ll_getCodeForType(
destType);
int destFsAddr = mLowLevelDestCas.ll_createFS(typeCode);
FeatureStructure destFs = mDestCas.getLowLevelCAS().ll_getFSForRef(
destFsAddr);
// add to map so we don't try to copy this more than once
mFsMap.put(aFS, destFs);
copyFeatures(aFS, destFs, aFromViewName);
return destFs;
}
/**
* Copy feature values from one FS to another. For reference-valued
* features, this does a deep copy.
*
* @param aSrcFS
* FeatureStructure to copy from
* @param aDestFS
* FeatureStructure to copy to
* @param aFromViewName
* TODO
*/
private void copyFeatures(FeatureStructure aSrcFS,
FeatureStructure aDestFS, String aFromViewName) {
// if (debug)
// System.out.println("Debug: ViewMapperAE copyFeatures -------");
// set feature values
Type srcType = aSrcFS.getType();
Type destType = aDestFS.getType();
Iterator srcFeatIter = srcType.getFeatures().iterator();
while (srcFeatIter.hasNext()) {
Feature srcFeat = (Feature) srcFeatIter.next();
// TODO: could optimize type lookup if type systems are identical
Feature destFeat;
if (destType == aSrcFS.getType()) {
// sharing same type system, so destFeat == srcFeat
destFeat = srcFeat;
} else {
// not sharing same type system, so do a name loop up in
// destination type system
destFeat = destType
.getFeatureByBaseName(srcFeat.getShortName());
if (destFeat == null) {
throw new UIMARuntimeException(
UIMARuntimeException.TYPE_NOT_FOUND_DURING_CAS_COPY,
new Object[] { srcFeat.getName() });
}
}
// copy primitive values using their string representation
// TODO: could be optimized but this code would be very messy if we
// have to
// enumerate all possible primitive types. Maybe LowLevel CAS API
// could help?
if (srcFeat.getRange().isPrimitive()) {
aDestFS.setFeatureValueFromString(destFeat,
aSrcFS.getFeatureValueAsString(srcFeat));
} else {
// recursive copy
// if (debug)
// System.out.println("Debug: ViewMapperAE copyFeatures srcFeat.getName() "+
// srcFeat.getName() );
// nh
if (!srcFeat.getName().equalsIgnoreCase(
"uima.cas.AnnotationBase:sofa")) {
FeatureStructure refFS = aSrcFS.getFeatureValue(srcFeat);
// if (debug)
// System.out.println("Debug: ViewMapperAE copyFeatures refFS.toString() "+
// refFS.toString());
if (refFS != null) {
FeatureStructure copyRefFs = copyFs(refFS,
aFromViewName);
// if (debug)
// System.out.println("Debug: ViewMapperAE copyFeatures refFS.toString() "+
// refFS.toString());
aDestFS.setFeatureValue(destFeat, copyRefFs);
}
}
}
}
}
/**
* @param aFromViewName
* TODO
* @param arrayFS
* @return
*/
private FeatureStructure copyArray(FeatureStructure aSrcFs,
String aFromViewName) {
// TODO: there should be a way to do this without enumerating all the
// array types!
if (aSrcFs instanceof StringArrayFS) {
StringArrayFS arrayFs = (StringArrayFS) aSrcFs;
int len = arrayFs.size();
StringArrayFS destFS = mDestCas.createStringArrayFS(len);
for (int i = 0; i < len; i++) {
destFS.set(i, arrayFs.get(i));
}
return destFS;
}
if (aSrcFs instanceof IntArrayFS) {
IntArrayFS arrayFs = (IntArrayFS) aSrcFs;
int len = arrayFs.size();
IntArrayFS destFS = mDestCas.createIntArrayFS(len);
for (int i = 0; i < len; i++) {
destFS.set(i, arrayFs.get(i));
}
return destFS;
}
if (aSrcFs instanceof ByteArrayFS) {
ByteArrayFS arrayFs = (ByteArrayFS) aSrcFs;
int len = arrayFs.size();
ByteArrayFS destFS = mDestCas.createByteArrayFS(len);
for (int i = 0; i < len; i++) {
destFS.set(i, arrayFs.get(i));
}
return destFS;
}
if (aSrcFs instanceof ShortArrayFS) {
ShortArrayFS arrayFs = (ShortArrayFS) aSrcFs;
int len = arrayFs.size();
ShortArrayFS destFS = mDestCas.createShortArrayFS(len);
for (int i = 0; i < len; i++) {
destFS.set(i, arrayFs.get(i));
}
return destFS;
}
if (aSrcFs instanceof LongArrayFS) {
LongArrayFS arrayFs = (LongArrayFS) aSrcFs;
int len = arrayFs.size();
LongArrayFS destFS = mDestCas.createLongArrayFS(len);
for (int i = 0; i < len; i++) {
destFS.set(i, arrayFs.get(i));
}
return destFS;
}
if (aSrcFs instanceof FloatArrayFS) {
FloatArrayFS arrayFs = (FloatArrayFS) aSrcFs;
int len = arrayFs.size();
FloatArrayFS destFS = mDestCas.createFloatArrayFS(len);
for (int i = 0; i < len; i++) {
destFS.set(i, arrayFs.get(i));
}
return destFS;
}
if (aSrcFs instanceof DoubleArrayFS) {
DoubleArrayFS arrayFs = (DoubleArrayFS) aSrcFs;
int len = arrayFs.size();
DoubleArrayFS destFS = mDestCas.createDoubleArrayFS(len);
for (int i = 0; i < len; i++) {
destFS.set(i, arrayFs.get(i));
}
return destFS;
}
if (aSrcFs instanceof BooleanArrayFS) {
BooleanArrayFS arrayFs = (BooleanArrayFS) aSrcFs;
int len = arrayFs.size();
BooleanArrayFS destFS = mDestCas.createBooleanArrayFS(len);
for (int i = 0; i < len; i++) {
destFS.set(i, arrayFs.get(i));
}
return destFS;
}
if (aSrcFs instanceof ArrayFS) {
ArrayFS arrayFs = (ArrayFS) aSrcFs;
int len = arrayFs.size();
ArrayFS destFS = mDestCas.createArrayFS(len);
for (int i = 0; i < len; i++) {
FeatureStructure srcElem = arrayFs.get(i);
if (srcElem != null) {
FeatureStructure copyElem = copyFs(arrayFs.get(i),
aFromViewName);
destFS.set(i, copyElem);
}
}
return destFS;
}
assert false; // the set of array types should be exhaustive, so we
// should never get here
return null;
}
/**
* Gets the named view; if the view doesn't exist it will be created.
*/
private static CAS getOrCreateView(CAS aCas, String aViewName) {
// TODO: there should be some way to do this without the try...catch
try {
return aCas.getView(aViewName);
} catch (CASRuntimeException e) {
// create the view
return aCas.createView(aViewName);
}
}
/**
* Copy the sofa data, the mimeType and the DocumentLanguage
*
* @param targetView
* @param aFromViewName
*/
public void copySofaData(CAS targetView, String aFromViewName) {
try {
String sofaMime = sourceJCas.getView(aFromViewName).getCas()
.getSofa().getSofaMime();
if (sourceJCas.getView(aFromViewName).getCas().getDocumentText() != null) {
targetView.setSofaDataString(sourceJCas.getView(aFromViewName)
.getCas().getDocumentText(), sofaMime);
// if (debug)
// System.out.println("Debug: ViewRenamer next targetView.setSofaDataString(sourceJCas.getView(getFromViewName()).getCas().getDocumentText(), sofaMime);");
} else if (sourceJCas.getView(aFromViewName).getCas()
.getSofaDataURI() != null) {
targetView.setSofaDataURI(sourceJCas.getView(aFromViewName)
.getCas().getSofaDataURI(), sofaMime);
// if (debug)
// System.out.println("Debug: ViewRenamer next targetView.setSofaDataURI(sourceJCas.getView(getFromViewName()).getCas().getSofaDataURI(), sofaMime);");
} else if (sourceJCas.getView(aFromViewName).getCas()
.getSofaDataArray() != null) {
// targetView.setSofaDataArray(copier.copyFs(sourceJCas.getView(getFromViewName()).getCas().getSofaDataArray()),
// sofaMime);
targetView.setSofaDataArray(
copyFs(sourceJCas.getView(aFromViewName).getCas()
.getSofaDataArray(), aFromViewName), sofaMime);
// if (debug)
// System.out.println("Debug: ViewRenamer next targetView.setSofaDataArray(copyFs(sourceJCas.getView(getFromViewName()).getCas().getSofaDataArray()), sofaMime);");
}
// nh
// je suppose q le Sofa (et ses traits mimeType, sofaString... ) et
// le DocumentAnnotation (et son trait sofa et langage) sont définis
// à ce moment là et que l'on a pas besoin de le faire
targetView.setDocumentLanguage(sourceJCas.getView(aFromViewName)
.getCas().getDocumentLanguage());
} catch (CASException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| apache-2.0 |
iliat/utils-java-OBSOLETE | src/main/java/com/google/genomics/v1/GetVariantRequest.java | 14727 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/genomics/v1/variants.proto
package com.google.genomics.v1;
/**
* Protobuf type {@code google.genomics.v1.GetVariantRequest}
*/
public final class GetVariantRequest extends
com.google.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:google.genomics.v1.GetVariantRequest)
GetVariantRequestOrBuilder {
// Use GetVariantRequest.newBuilder() to construct.
private GetVariantRequest(com.google.protobuf.GeneratedMessage.Builder builder) {
super(builder);
}
private GetVariantRequest() {
variantId_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private GetVariantRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 10: {
com.google.protobuf.ByteString bs = input.readBytes();
variantId_ = bs;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.genomics.v1.VariantsProto.internal_static_google_genomics_v1_GetVariantRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.genomics.v1.VariantsProto.internal_static_google_genomics_v1_GetVariantRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.genomics.v1.GetVariantRequest.class, com.google.genomics.v1.GetVariantRequest.Builder.class);
}
public static final com.google.protobuf.Parser<GetVariantRequest> PARSER =
new com.google.protobuf.AbstractParser<GetVariantRequest>() {
public GetVariantRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new GetVariantRequest(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<GetVariantRequest> getParserForType() {
return PARSER;
}
public static final int VARIANT_ID_FIELD_NUMBER = 1;
private java.lang.Object variantId_;
/**
* <code>optional string variant_id = 1;</code>
*
* <pre>
* The ID of the variant.
* </pre>
*/
public java.lang.String getVariantId() {
java.lang.Object ref = variantId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
variantId_ = s;
}
return s;
}
}
/**
* <code>optional string variant_id = 1;</code>
*
* <pre>
* The ID of the variant.
* </pre>
*/
public com.google.protobuf.ByteString
getVariantIdBytes() {
java.lang.Object ref = variantId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
variantId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (!getVariantIdBytes().isEmpty()) {
output.writeBytes(1, getVariantIdBytes());
}
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (!getVariantIdBytes().isEmpty()) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(1, getVariantIdBytes());
}
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
public static com.google.genomics.v1.GetVariantRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.genomics.v1.GetVariantRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.genomics.v1.GetVariantRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.genomics.v1.GetVariantRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.genomics.v1.GetVariantRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.google.genomics.v1.GetVariantRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static com.google.genomics.v1.GetVariantRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static com.google.genomics.v1.GetVariantRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static com.google.genomics.v1.GetVariantRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.google.genomics.v1.GetVariantRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return new Builder(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(com.google.genomics.v1.GetVariantRequest prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code google.genomics.v1.GetVariantRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.genomics.v1.GetVariantRequest)
com.google.genomics.v1.GetVariantRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.genomics.v1.VariantsProto.internal_static_google_genomics_v1_GetVariantRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.genomics.v1.VariantsProto.internal_static_google_genomics_v1_GetVariantRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.genomics.v1.GetVariantRequest.class, com.google.genomics.v1.GetVariantRequest.Builder.class);
}
// Construct using com.google.genomics.v1.GetVariantRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
variantId_ = "";
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.genomics.v1.VariantsProto.internal_static_google_genomics_v1_GetVariantRequest_descriptor;
}
public com.google.genomics.v1.GetVariantRequest getDefaultInstanceForType() {
return com.google.genomics.v1.GetVariantRequest.getDefaultInstance();
}
public com.google.genomics.v1.GetVariantRequest build() {
com.google.genomics.v1.GetVariantRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.google.genomics.v1.GetVariantRequest buildPartial() {
com.google.genomics.v1.GetVariantRequest result = new com.google.genomics.v1.GetVariantRequest(this);
result.variantId_ = variantId_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.genomics.v1.GetVariantRequest) {
return mergeFrom((com.google.genomics.v1.GetVariantRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.genomics.v1.GetVariantRequest other) {
if (other == com.google.genomics.v1.GetVariantRequest.getDefaultInstance()) return this;
if (!other.getVariantId().isEmpty()) {
variantId_ = other.variantId_;
onChanged();
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.genomics.v1.GetVariantRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.genomics.v1.GetVariantRequest) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object variantId_ = "";
/**
* <code>optional string variant_id = 1;</code>
*
* <pre>
* The ID of the variant.
* </pre>
*/
public java.lang.String getVariantId() {
java.lang.Object ref = variantId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
variantId_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string variant_id = 1;</code>
*
* <pre>
* The ID of the variant.
* </pre>
*/
public com.google.protobuf.ByteString
getVariantIdBytes() {
java.lang.Object ref = variantId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
variantId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string variant_id = 1;</code>
*
* <pre>
* The ID of the variant.
* </pre>
*/
public Builder setVariantId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
variantId_ = value;
onChanged();
return this;
}
/**
* <code>optional string variant_id = 1;</code>
*
* <pre>
* The ID of the variant.
* </pre>
*/
public Builder clearVariantId() {
variantId_ = getDefaultInstance().getVariantId();
onChanged();
return this;
}
/**
* <code>optional string variant_id = 1;</code>
*
* <pre>
* The ID of the variant.
* </pre>
*/
public Builder setVariantIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
variantId_ = value;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:google.genomics.v1.GetVariantRequest)
}
// @@protoc_insertion_point(class_scope:google.genomics.v1.GetVariantRequest)
private static final com.google.genomics.v1.GetVariantRequest defaultInstance;static {
defaultInstance = new com.google.genomics.v1.GetVariantRequest();
}
public static com.google.genomics.v1.GetVariantRequest getDefaultInstance() {
return defaultInstance;
}
public com.google.genomics.v1.GetVariantRequest getDefaultInstanceForType() {
return defaultInstance;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-wafv2/src/main/java/com/amazonaws/services/wafv2/model/WAFLogDestinationPermissionIssueException.java | 1493 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.wafv2.model;
import javax.annotation.Generated;
/**
* <p>
* The operation failed because you don't have the permissions that your logging configuration requires. For
* information, see <a href="https://docs.aws.amazon.com/waf/latest/developerguide/logging.html">Logging web ACL traffic
* information</a> in the <i>WAF Developer Guide</i>.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class WAFLogDestinationPermissionIssueException extends com.amazonaws.services.wafv2.model.AWSWAFV2Exception {
private static final long serialVersionUID = 1L;
/**
* Constructs a new WAFLogDestinationPermissionIssueException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public WAFLogDestinationPermissionIssueException(String message) {
super(message);
}
}
| apache-2.0 |
jitsi/libjitsi | src/main/java/org/jitsi/impl/neomedia/rtp/remotebitrateestimator/InterArrival.java | 12895 | /*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.jitsi.impl.neomedia.rtp.remotebitrateestimator;
import org.jitsi.utils.TimestampUtils;
import org.jetbrains.annotations.*;
import org.jitsi.utils.logging.*;
/**
* Helper class to compute the inter-arrival time delta and the size delta
* between two timestamp groups. A timestamp is a 32 bit unsigned number with a
* client defined rate.
*
* webrtc/modules/remote_bitrate_estimator/inter_arrival.cc
* webrtc/modules/remote_bitrate_estimator/inter_arrival.h
*
* @author Lyubomir Marinov
* @author Julian Chukwu
* @author George Politis
*/
class InterArrival
{
private static final int kBurstDeltaThresholdMs = 5;
private static final Logger logger = Logger.getLogger(InterArrival.class);
/**
* webrtc/modules/include/module_common_types.h
*
* @param timestamp1
* @param timestamp2
* @return
*/
private static long latestTimestamp(long timestamp1, long timestamp2)
{
return TimestampUtils.latestTimestamp(timestamp1, timestamp2);
}
private boolean burstGrouping;
private TimestampGroup currentTimestampGroup = new TimestampGroup();
private final long kTimestampGroupLengthTicks;
private final DiagnosticContext diagnosticContext;
private TimestampGroup prevTimestampGroup = new TimestampGroup();
private double timestampToMsCoeff;
private int numConsecutiveReorderedPackets;
// After this many packet groups received out of order InterArrival will
// reset, assuming that clocks have made a jump.
private static final int kReorderedResetThreshold = 3;
private static final int kArrivalTimeOffsetThresholdMs = 3000;
/**
* A timestamp group is defined as all packets with a timestamp which are at
* most {@code timestampGroupLengthTicks} older than the first timestamp in
* that group.
*
* @param timestampGroupLengthTicks
* @param timestampToMsCoeff
* @param enableBurstGrouping
*/
public InterArrival(
long timestampGroupLengthTicks,
double timestampToMsCoeff,
boolean enableBurstGrouping,
@NotNull DiagnosticContext diagnosticContext)
{
kTimestampGroupLengthTicks = timestampGroupLengthTicks;
this.timestampToMsCoeff = timestampToMsCoeff;
burstGrouping = enableBurstGrouping;
numConsecutiveReorderedPackets = 0;
this.diagnosticContext = diagnosticContext;
}
private boolean belongsToBurst(long arrivalTimeMs, long timestamp)
{
if (!burstGrouping)
return false;
if (currentTimestampGroup.completeTimeMs < 0)
{
throw new IllegalStateException(
"currentTimestampGroup.completeTimeMs");
}
long arrivalTimeDeltaMs
= arrivalTimeMs - currentTimestampGroup.completeTimeMs;
long timestampDiff = TimestampUtils
.subtractAsUnsignedInt32(timestamp, currentTimestampGroup.timestamp);
long tsDeltaMs = (long) (timestampToMsCoeff * timestampDiff + 0.5);
if (tsDeltaMs == 0)
return true;
long propagationDeltaMs = arrivalTimeDeltaMs - tsDeltaMs;
return
propagationDeltaMs < 0
&& arrivalTimeDeltaMs <= kBurstDeltaThresholdMs;
}
/**
* Returns {@code true} if a delta was computed, or {@code false} if the
* current group is still incomplete or if only one group has been
* completed.
*
* @param timestamp is the timestamp.
* @param arrivalTimeMs is the local time at which the packet arrived.
* @param packetSize is the size of the packet.
* @param deltas {@code timestampDelta} is the computed timestamp delta,
* {@code arrivalTimeDeltaMs} is the computed arrival-time delta,
* {@code packetSizeDelta} is the computed size delta.
* @return
*
* @Note: We have two {@code computeDeltas}.
* One with a valid {@code systemTimeMs} according to webrtc
* implementation as of June 12,2017 and a previous one
* with a default systemTimeMs (-1L). the later may be removed or
* deprecated.
*/
public boolean computeDeltas(
long timestamp,
long arrivalTimeMs,
int packetSize,
long[] deltas){
return computeDeltas(timestamp,arrivalTimeMs,
packetSize,deltas,-1L);
}
public boolean computeDeltas(
long timestamp,
long arrivalTimeMs,
int packetSize,
long[] deltas,
long systemTimeMs)
{
if (deltas == null)
throw new NullPointerException("deltas");
if (deltas.length != 3)
throw new IllegalArgumentException("deltas.length");
boolean calculatedDeltas = false;
if (currentTimestampGroup.isFirstPacket())
{
// We don't have enough data to update the filter, so we store it
// until we have two frames of data to process.
currentTimestampGroup.timestamp = timestamp;
currentTimestampGroup.firstTimestamp = timestamp;
}
else if (!isPacketInOrder(timestamp))
{
return false;
}
else if (isNewTimestampGroup(arrivalTimeMs, timestamp))
{
// First packet of a later frame, the previous frame sample is
// ready.
if (prevTimestampGroup.completeTimeMs >= 0)
{
/* long timestampDelta */ deltas[0]
= TimestampUtils.subtractAsUnsignedInt32(
currentTimestampGroup.timestamp,
prevTimestampGroup.timestamp);
long arrivalTimeDeltaMs
= deltas[1]
= currentTimestampGroup.completeTimeMs
- prevTimestampGroup.completeTimeMs;
// Check system time differences to see if we have an unproportional jump
// in arrival time. In that case reset the inter-arrival computations.
long systemTimeDeltaMs =
currentTimestampGroup.lastSystemTimeMs -
prevTimestampGroup.lastSystemTimeMs;
if (prevTimestampGroup.lastSystemTimeMs != -1L &&
currentTimestampGroup.lastSystemTimeMs != -1L &&
arrivalTimeDeltaMs - systemTimeDeltaMs >=
kArrivalTimeOffsetThresholdMs) {
logger.warn( "The arrival time clock offset has changed (diff = "
+ String.valueOf(arrivalTimeDeltaMs - systemTimeDeltaMs)
+ " ms), resetting.");
Reset();
return false;
}
if (arrivalTimeDeltaMs < 0)
{
++numConsecutiveReorderedPackets;
if (numConsecutiveReorderedPackets >= kReorderedResetThreshold) {
// The group of packets has been reordered since receiving
// its local arrival timestamp.
logger.warn(
"Packets are being reordered on the path from the "
+ "socket to the bandwidth estimator. Ignoring "
+ "this packet for bandwidth estimation.");
Reset();
}
return false;
}
else
{
numConsecutiveReorderedPackets = 0;
}
/* int packetSizeDelta */ deltas[2]
= (int)
(currentTimestampGroup.size - prevTimestampGroup.size);
if (logger.isTraceEnabled())
{
logger.trace(diagnosticContext
.makeTimeSeriesPoint("computed_deltas")
.addField("inter_arrival", hashCode())
.addField("arrival_time_ms", arrivalTimeMs)
.addField("timestamp_delta", deltas[0])
.addField("arrival_time_ms_delta", deltas[1])
.addField("payload_size_delta", deltas[2]));
}
calculatedDeltas = true;
}
prevTimestampGroup.copy(currentTimestampGroup);
// The new timestamp is now the current frame.
currentTimestampGroup.firstTimestamp = timestamp;
currentTimestampGroup.timestamp = timestamp;
currentTimestampGroup.size = 0;
}
else
{
currentTimestampGroup.timestamp = latestTimestamp(
currentTimestampGroup.timestamp, timestamp);
}
// Accumulate the frame size.
currentTimestampGroup.size += packetSize;
currentTimestampGroup.completeTimeMs = arrivalTimeMs;
currentTimestampGroup.lastSystemTimeMs = systemTimeMs;
return calculatedDeltas;
}
/**
* Returns {@code true} if the last packet was the end of the current batch
* and the packet with {@code timestamp} is the first of a new batch.
*
* @param arrivalTimeMs
* @param timestamp
* @return
*/
private boolean isNewTimestampGroup(long arrivalTimeMs, long timestamp)
{
if (currentTimestampGroup.isFirstPacket())
{
return false;
}
else if (belongsToBurst(arrivalTimeMs, timestamp))
{
return false;
}
else
{
long timestampDiff
= TimestampUtils.subtractAsUnsignedInt32(
timestamp, currentTimestampGroup.firstTimestamp);
return timestampDiff > kTimestampGroupLengthTicks;
}
}
/**
* Returns {@code true} if the packet with timestamp {@code timestamp}
* arrived in order.
*
* @param timestamp
* @return
*/
private boolean isPacketInOrder(long timestamp)
{
if (currentTimestampGroup.isFirstPacket())
{
return true;
}
else
{
// Assume that a diff which is bigger than half the timestamp
// interval (32 bits) must be due to reordering. This code is almost
// identical to that in isNewerTimestamp() in module_common_types.h.
long timestampDiff
= TimestampUtils.subtractAsUnsignedInt32(
timestamp, currentTimestampGroup.firstTimestamp);
long tsDeltaMs = (long) (timestampToMsCoeff * timestampDiff + 0.5);
boolean inOrder = timestampDiff < 0x80000000L;
if (!inOrder && logger.isTraceEnabled())
{
logger.trace(diagnosticContext
.makeTimeSeriesPoint("reordered_packet")
.addField("inter_arrival", hashCode())
.addField("ts_delta_ms", tsDeltaMs));
}
return inOrder;
}
}
private static class TimestampGroup
{
public long completeTimeMs = -1L;
public long size = 0L;
public long firstTimestamp = 0L;
public long timestamp = 0L;
public long lastSystemTimeMs = -1L;
/**
* Assigns the values of the fields of <tt>source</tt> to the respective
* fields of this {@code TimestampGroup}.
*
* @param source the {@code TimestampGroup} the values of the fields of
* which are to be assigned to the respective fields of this
* {@code TimestampGroup}
*/
public void copy(TimestampGroup source)
{
completeTimeMs = source.completeTimeMs;
firstTimestamp = source.firstTimestamp;
size = source.size;
timestamp = source.timestamp;
}
public boolean isFirstPacket()
{
return completeTimeMs == -1L;
}
}
public void Reset() {
numConsecutiveReorderedPackets = 0;
currentTimestampGroup = new TimestampGroup();
prevTimestampGroup = new TimestampGroup();
}
}
| apache-2.0 |
wanliyang1990/AdViewPager | AdViewpager/app/src/main/java/adapter/ImageViewPagerAdapter.java | 1077 | package adapter;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageViewPagerAdapter extends PagerAdapter {
private ImageView[] imageViews;
private int size;
private Context context;
public ImageViewPagerAdapter(Context context, ImageView[] imageViews) {
this.context = context;
this.imageViews = imageViews;
size = imageViews.length;
}
@Override
public int getCount() {
return imageViews.length;
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// ((ViewPager) container).removeView((View) object);// 完全溢出view,避免数据多时出现重复现象
container.removeView(imageViews[position]);//删除页卡
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(imageViews[position], 0);
return imageViews[position];
}
}
| apache-2.0 |
ontop/ontop | core/model/src/main/java/it/unibz/inf/ontop/dbschema/AttributeNotFoundException.java | 698 | package it.unibz.inf.ontop.dbschema;
public class AttributeNotFoundException extends Exception {
private final RelationDefinition relation;
private final QuotedID attributeId;
public AttributeNotFoundException(RelationDefinition relation, QuotedID attributeId) {
this.relation = relation;
this.attributeId = attributeId;
}
public QuotedID getAttributeID() { return attributeId; }
public RelationDefinition getRelation() { return relation; }
@Override
public String toString() {
return "AttributeNotFoundException{" +
"relation=" + relation +
", attributeId=" + attributeId +
'}';
}
}
| apache-2.0 |
tommyettinger/sarong | src/main/java/sarong/discouraged/Rule90RNG.java | 8294 | package sarong.discouraged;
import sarong.StatefulRandomness;
import sarong.util.StringKit;
import java.io.Serializable;
/**
* Experimental StatefulRandomness relating to the elementary cellular automaton called "Rule 90."
* <br>
* Created by Tommy Ettinger on 10/1/2017.
*/
public class Rule90RNG implements StatefulRandomness, Serializable {
private static final long serialVersionUID = 1L;
/**
* Can be any long value.
*/
public long state;
/**
* Creates a new generator seeded using Math.random.
*/
public Rule90RNG() {
this((long) ((Math.random() - 0.5) * 0x10000000000000L)
^ (long) (((Math.random() - 0.5) * 2.0) * 0x8000000000000000L));
}
public Rule90RNG(final long seed) {
state = seed;
}
/**
* Get the current internal state of the StatefulRandomness as a long.
*
* @return the current internal state of this object.
*/
@Override
public long getState() {
return state;
}
/**
* Set the current internal state of this StatefulRandomness with a long.
*
* @param state a 64-bit long. You may want to avoid passing 0 for compatibility, though this implementation can handle that.
*/
@Override
public void setState(long state) {
this.state = state;
}
/**
* Using this method, any algorithm that might use the built-in Java Random
* can interface with this randomness source.
*
* @param bits the number of bits to be returned
* @return the integer containing the appropriate number of bits
*/
@Override
public final int next(int bits) {
return (int)((state ^ ((state = (state >>> 1 ^ state << 1) + 0x27BB2EE687B0B0FDL) >>> 24) * 0x5851F42D4C957F2DL) >>> (64 - bits));
//return (int)(((state = state * 0x5851F42D4C957F2DL + 0x14057B7EF767814FL) + (state >> 28)) >>> (64 - bits));
//(state = state * 0x5851F42D4C957F2DL + 0x14057B7EF767814FL) + (state >> 28)
//(state *= 0x2545F4914F6CDD1DL) + (state >> 28)
//((state += 0x2545F4914F6CDD1DL) ^ (state >>> 30 & state >> 27) * 0xBF58476D1CE4E5B9L)
//(state ^ (state += 0x2545F4914F6CDD1DL)) * 0x5851F42D4C957F2DL + 0x14057B7EF767814FL
}
/**
* Using this method, any algorithm that needs to efficiently generate more
* than 32 bits of random data can interface with this randomness source.
* <p>
* Get a random long between Long.MIN_VALUE and Long.MAX_VALUE (both inclusive).
*
* @return a random long between Long.MIN_VALUE and Long.MAX_VALUE (both inclusive)
*/
@Override
public final long nextLong() {
//final long z = (state += 36277L);
//return (z ^ ((z >>> 1 ^ z << 1) + 0x14057B7EF767814FL >>> 24) * 0x5851F42D4C957F2DL);
//return state += determine(state * (1000000L | 277L));
//use this next one as a known good version:
return (state ^ ((state = (state >>> 1 ^ state << 1) + 0x27BB2EE687B0B0FDL) >>> 24) * 0x5851F42D4C957F2DL);
//final long z = (state + 0x9E3779B97F4A7C15L);
//return (state ^= (0x27BB2EE687B0B0FDL ^ z >>> 14) + (z ^ z >>> 24) * 0x5851F42D4C957F2DL);
// 0x27BB2EE687B0B0FDL L'Ecuyer
//return ((state = state * 0x5851F42D4C957F2DL + 0x14057B7EF767814FL) + (state >> 28));
//return (state = state * 0x59A2B8F555F5828FL % 0x7FFFFFFFFFFFFFE7L) ^ state << 2;
//return (state = state * 0x5851F42D4C957F2DL + 0x14057B7EF767814FL);
//return (state ^ (state += 0x2545F4914F6CDD1DL)) * 0x5851F42D4C957F2DL + 0x14057B7EF767814FL;
//return (state * 0x5851F42D4C957F2DL) + ((state += 0x14057B7EF767814FL) >> 28);
//return (((state += 0x14057B7EF767814FL) >>> 24) * 0x5851F42D4C957F2DL + (state >>> 1));
}
/**
* Produces a copy of this RandomnessSource that, if next() and/or nextLong() are called on this object and the
* copy, both will generate the same sequence of random numbers from the point copy() was called. This just need to
* copy the state so it isn't shared, usually, and produce a new value with the same exact state.
*
* @return a copy of this RandomnessSource
*/
@Override
public Rule90RNG copy() {
return new Rule90RNG(state);
}
@Override
public String toString() {
return "Rule90RNG with state 0x" + StringKit.hex(state) + 'L';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Rule90RNG rule90RNG = (Rule90RNG) o;
return state == rule90RNG.state;
}
@Override
public int hashCode() {
return (int) (state ^ (state >>> 32));
}
/**
* Returns a random permutation of state; if state is the same on two calls to this, this will return the same
* number. This is expected to be called with some changing variable, but since this type of randomness isn't as
* statistically strong as ThrustRNG or especially LightRNG, this needs a fairly specific kind of update that isn't
* as fast as calling {@link #nextLong()} on a Rule90RNG: {@code (state += determine(state * 36277L))}, where state
* is a long that changes with each call and 36277L can be any large-enough odd number (typically, you can choose
* any number and bitwise-OR it with 277, such as {@code 1000000L | 277L}, and you will get a good multiplier).
* If you use the result of that call, which is the same as the value of state after calling, then it will be a
* rather-high-quality random number for most multipliers.
* @param state a variable that should be different every time you want a different random result;
* using the result of {@code (state += determine(state * 36277L))} as the random number is recommended
* and allows many large odd numbers in place of 36277L
* @return a pseudo-random permutation of state
*/
public static long determine(long state) { return (state ^ ((state >>> 1 ^ state << 1) + 0x14057B7EF767814FL >>> 24) * 0x5851F42D4C957F2DL); } // call with (state += determine(state * 36277L))
/**
* Given a state that should usually change each time this is called, and a bound that limits the result to some
* (typically fairly small) int, produces a pseudo-random int between 0 and bound (exclusive). The bound can be
* negative, which will cause this to produce 0 or a negative int; otherwise this produces 0 or a positive int.
* This is expected to be called with some changing variable, but since this type of randomness isn't as
* statistically strong as ThrustRNG or especially LightRNG, this needs a fairly specific kind of update that isn't
* as fast as calling {@link #nextLong()} on a Rule90RNG:
* {@code result = determineBounded(state * 36277L, bound)); state += result;}, where result stores the int between
* 0 and bound, state is a long that changes with each call, bound is the outer limit on the returned int and 36277L
* can be any large-enough odd number (typically, you can choose any number and bitwise-OR it with 277, such as
* {@code 1000000L | 277L}, and you will get a good multiplier). You may need to change {@code state += result;} to
* {@code state += result + 0x27BB2EE687B0B0FDL} or some other large increment to make the state change enough if
* bound is small.
* @param state a variable that should be different every time you want a different random result; using
* {@code result = determineBounded(state * 36277L, bound)); state += result + 0x27BB2EE687B0B0FDL;} is
* recommended if you use result as the desired int (36277 can be changed to other odd numbers).
* @param bound the outer exclusive bound for the int this produces; can be negative or positive
* @return a pseudo-random int between 0 (inclusive) and bound (exclusive)
*/
public static int determineBounded(long state, final int bound)
{
return (int)((bound * (
(state ^ ((state >>> 1 ^ state << 1) + 0x14057B7EF767814FL >>> 24) * 0x5851F42D4C957F2DL)
& 0x7FFFFFFFL)) >> 31);
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-kms/src/main/java/com/amazonaws/services/kms/model/InvalidGrantIdException.java | 1234 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.kms.model;
import javax.annotation.Generated;
/**
* <p>
* The request was rejected because the specified <code>GrantId</code> is not valid.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InvalidGrantIdException extends com.amazonaws.services.kms.model.AWSKMSException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new InvalidGrantIdException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public InvalidGrantIdException(String message) {
super(message);
}
}
| apache-2.0 |
pellcorp/fop | src/java/org/apache/fop/pdf/ASCII85Filter.java | 1881 | /*
* 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.
*/
/* $Id: ASCII85Filter.java 1296526 2012-03-03 00:18:45Z gadams $ */
package org.apache.fop.pdf;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.xmlgraphics.util.io.ASCII85OutputStream;
/**
* PDF Filter for ASCII85.
* This applies a filter to a pdf stream that converts
* the data to ASCII.
*/
public class ASCII85Filter extends PDFFilter {
/**
* Get the PDF name of this filter.
*
* @return the name of the filter to be inserted into the PDF
*/
public String getName() {
return "/ASCII85Decode";
}
/**
* {@inheritDoc}
*/
public boolean isASCIIFilter() {
return true;
}
/**
* Get the decode parameters.
*
* @return always null
*/
public PDFObject getDecodeParms() {
return null;
}
/**
* {@inheritDoc}
*/
public OutputStream applyFilter(OutputStream out) throws IOException {
if (isApplied()) {
return out;
} else {
return new ASCII85OutputStream(out);
}
}
}
| apache-2.0 |
android/tv-samples | LeanbackShowcase/app/src/main/java/androidx/leanback/leanbackshowcase/app/room/network/DownloadCompleteBroadcastReceiver.java | 3238 | /*
* Copyright (C) 2017 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 androidx.leanback.leanbackshowcase.app.room.network;
import android.app.DownloadManager;
import androidx.lifecycle.LifecycleObserver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import java.util.ArrayList;
import java.util.List;
public class DownloadCompleteBroadcastReceiver extends BroadcastReceiver
implements LifecycleObserver{
// singleton design pattern
private static DownloadCompleteBroadcastReceiver sReceiver;
private List<DownloadCompleteListener> downloadingCompletionListener;
public interface DownloadCompleteListener {
void onDownloadingCompleted(DownloadingTaskDescription desc);
}
public void registerListener(DownloadCompleteListener listener) {
downloadingCompletionListener.add(listener);
}
@Override
public void onReceive(Context context, Intent intent) {
final DownloadManager dm = (DownloadManager) context.getSystemService(
Context.DOWNLOAD_SERVICE);
Long downloadingTaskId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
if (NetworkManagerUtil.downloadingTaskQueue.containsKey(downloadingTaskId)) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadingTaskId);
Cursor cursor = dm.query(query);
// retrieve downloaded content's information through download manager.
if (!cursor.moveToFirst()) {
return;
}
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
!= DownloadManager.STATUS_SUCCESSFUL) {
return;
}
String path = cursor.getString(
cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
final DownloadingTaskDescription desc =
NetworkManagerUtil.downloadingTaskQueue.get(downloadingTaskId);
// update local storage path
desc.setStoragePath(path);
for (final DownloadCompleteListener listener: downloadingCompletionListener) {
listener.onDownloadingCompleted(desc);
}
}
}
public static DownloadCompleteBroadcastReceiver getInstance() {
if (sReceiver == null) {
sReceiver = new DownloadCompleteBroadcastReceiver();
}
return sReceiver;
}
private DownloadCompleteBroadcastReceiver() {
downloadingCompletionListener = new ArrayList<>();
}
}
| apache-2.0 |
mvniekerk/titanium4j | src/com/emitrom/ti4j/desktop/client/json/JSON.java | 1659 | /************************************************************************
* JSON.java is part of Ti4j 3.1.0 Copyright 2013 Emitrom 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 com.emitrom.ti4j.desktop.client.json;
import com.google.gwt.core.client.JavaScriptObject;
/**
* A module for serializing and deserializing JSON.
*
*/
public class JSON {
private JSON() {
}
/**
* Deserialize a JSON string into a JavaScript value.
*
* @param jSonString
* , JSON string to deserialize into a JavaScript object.
* @return
*/
public static native <T extends JavaScriptObject> T parse(String jSonString)/*-{
return Ti.JSON.parse(jSonString);
}-*/;
/**
* Serialize a JavaScript value into a JSON string.
*
* @param value
* ,The JavaScript value to serialize into a JSON string.
* @return
*/
public static native String stringify(Object value)/*-{
return Ti.JSON.stringify(value);
}-*/;
}
| apache-2.0 |
kingargyle/turmeric-bot | camel-core/src/test/java/org/apache/camel/component/bean/BeanComponentCustomCreateEndpointTest.java | 2388 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.bean;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Producer;
import org.apache.camel.impl.ProcessorEndpoint;
/**
* @version $Revision$
*/
public class BeanComponentCustomCreateEndpointTest extends ContextTestSupport {
public void testCreateEndpoint() throws Exception {
BeanComponent bc = context.getComponent("bean", BeanComponent.class);
ProcessorEndpoint pe = bc.createEndpoint(new MyFooBean());
assertNotNull(pe);
String uri = pe.getEndpointUri();
assertEquals("bean:generated:MyFooBean", uri);
Producer producer = pe.createProducer();
Exchange exchange = producer.createExchange();
exchange.getIn().setBody("World");
producer.start();
producer.process(exchange);
producer.stop();
assertEquals("Hello World", exchange.getOut().getBody());
}
public void testCreateEndpointUri() throws Exception {
BeanComponent bc = context.getComponent("bean", BeanComponent.class);
ProcessorEndpoint pe = bc.createEndpoint(new MyFooBean(), "cheese");
assertNotNull(pe);
String uri = pe.getEndpointUri();
assertEquals("cheese", uri);
Producer producer = pe.createProducer();
Exchange exchange = producer.createExchange();
exchange.getIn().setBody("World");
producer.start();
producer.process(exchange);
producer.stop();
assertEquals("Hello World", exchange.getOut().getBody());
}
}
| apache-2.0 |
lmenezes/elasticsearch | src/test/java/org/elasticsearch/indices/warmer/LocalGatewayIndicesWarmerTests.java | 8252 | /*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch 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.elasticsearch.indices.warmer;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.warmer.IndexWarmersMetaData;
import org.elasticsearch.test.AbstractIntegrationTest;
import org.elasticsearch.test.AbstractIntegrationTest.ClusterScope;
import org.elasticsearch.test.AbstractIntegrationTest.Scope;
import org.elasticsearch.test.TestCluster.RestartCallback;
import org.hamcrest.Matchers;
import org.junit.Test;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.hamcrest.Matchers.equalTo;
/**
*/
@ClusterScope(numNodes=0, scope=Scope.TEST)
public class LocalGatewayIndicesWarmerTests extends AbstractIntegrationTest {
private final ESLogger logger = Loggers.getLogger(LocalGatewayIndicesWarmerTests.class);
@Test
public void testStatePersistence() throws Exception {
logger.info("--> starting 1 nodes");
cluster().startNode(settingsBuilder().put("gateway.type", "local"));
logger.info("--> putting two templates");
client().admin().indices().prepareCreate("test")
.setSettings(ImmutableSettings.settingsBuilder().put("index.number_of_shards", 1))
.execute().actionGet();
client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet();
client().admin().indices().preparePutWarmer("warmer_1")
.setSearchRequest(client().prepareSearch("test").setQuery(QueryBuilders.termQuery("field", "value1")))
.execute().actionGet();
client().admin().indices().preparePutWarmer("warmer_2")
.setSearchRequest(client().prepareSearch("test").setQuery(QueryBuilders.termQuery("field", "value2")))
.execute().actionGet();
logger.info("--> put template with warmer");
client().admin().indices().preparePutTemplate("template_1")
.setSource("{\n" +
" \"template\" : \"xxx\",\n" +
" \"warmers\" : {\n" +
" \"warmer_1\" : {\n" +
" \"types\" : [],\n" +
" \"source\" : {\n" +
" \"query\" : {\n" +
" \"match_all\" : {}\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}")
.execute().actionGet();
logger.info("--> verify warmers are registered in cluster state");
ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
IndexWarmersMetaData warmersMetaData = clusterState.metaData().index("test").custom(IndexWarmersMetaData.TYPE);
assertThat(warmersMetaData, Matchers.notNullValue());
assertThat(warmersMetaData.entries().size(), equalTo(2));
IndexWarmersMetaData templateWarmers = clusterState.metaData().templates().get("template_1").custom(IndexWarmersMetaData.TYPE);
assertThat(templateWarmers, Matchers.notNullValue());
assertThat(templateWarmers.entries().size(), equalTo(1));
logger.info("--> restarting the node");
cluster().fullRestart(new RestartCallback() {
@Override
public Settings onNodeStopped(String nodeName) throws Exception {
return settingsBuilder().put("gateway.type", "local").build();
}
});
ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
logger.info("--> verify warmers are recovered");
clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
IndexWarmersMetaData recoveredWarmersMetaData = clusterState.metaData().index("test").custom(IndexWarmersMetaData.TYPE);
assertThat(recoveredWarmersMetaData.entries().size(), equalTo(warmersMetaData.entries().size()));
for (int i = 0; i < warmersMetaData.entries().size(); i++) {
assertThat(recoveredWarmersMetaData.entries().get(i).name(), equalTo(warmersMetaData.entries().get(i).name()));
assertThat(recoveredWarmersMetaData.entries().get(i).source(), equalTo(warmersMetaData.entries().get(i).source()));
}
logger.info("--> verify warmers in template are recovered");
IndexWarmersMetaData recoveredTemplateWarmers = clusterState.metaData().templates().get("template_1").custom(IndexWarmersMetaData.TYPE);
assertThat(recoveredTemplateWarmers.entries().size(), equalTo(templateWarmers.entries().size()));
for (int i = 0; i < templateWarmers.entries().size(); i++) {
assertThat(recoveredTemplateWarmers.entries().get(i).name(), equalTo(templateWarmers.entries().get(i).name()));
assertThat(recoveredTemplateWarmers.entries().get(i).source(), equalTo(templateWarmers.entries().get(i).source()));
}
logger.info("--> delete warmer warmer_1");
client().admin().indices().prepareDeleteWarmer().setIndices("test").setName("warmer_1").execute().actionGet();
logger.info("--> verify warmers (delete) are registered in cluster state");
clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
warmersMetaData = clusterState.metaData().index("test").custom(IndexWarmersMetaData.TYPE);
assertThat(warmersMetaData, Matchers.notNullValue());
assertThat(warmersMetaData.entries().size(), equalTo(1));
logger.info("--> restarting the node");
cluster().fullRestart(new RestartCallback() {
@Override
public Settings onNodeStopped(String nodeName) throws Exception {
return settingsBuilder().put("gateway.type", "local").build();
}
});
healthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
logger.info("--> verify warmers are recovered");
clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
recoveredWarmersMetaData = clusterState.metaData().index("test").custom(IndexWarmersMetaData.TYPE);
assertThat(recoveredWarmersMetaData.entries().size(), equalTo(warmersMetaData.entries().size()));
for (int i = 0; i < warmersMetaData.entries().size(); i++) {
assertThat(recoveredWarmersMetaData.entries().get(i).name(), equalTo(warmersMetaData.entries().get(i).name()));
assertThat(recoveredWarmersMetaData.entries().get(i).source(), equalTo(warmersMetaData.entries().get(i).source()));
}
}
}
| apache-2.0 |
AlecStrong/sqlbrite | sqlbrite/src/androidTest/java/com/squareup/sqlbrite/QueryObservableTest.java | 2503 | package com.squareup.sqlbrite;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.support.test.runner.AndroidJUnit4;
import com.squareup.sqlbrite.SqlBrite.Query;
import org.junit.Test;
import org.junit.runner.RunWith;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.functions.Func1;
import rx.observers.TestSubscriber;
import static com.google.common.truth.Truth.assertThat;
@RunWith(AndroidJUnit4.class)
public final class QueryObservableTest {
@Test public void mapToListThrowsFromQueryRun() {
TestSubscriber<Object> testSubscriber = new TestSubscriber<>();
Observable.<Query>just(new Query() {
@Override public Cursor run() {
throw new IllegalStateException("test exception");
}
}).extend(new Func1<OnSubscribe<Query>, QueryObservable>() {
@Override public QueryObservable call(OnSubscribe<Query> func) {
return new QueryObservable(func);
}
}).mapToList(new Func1<Cursor, Object>() {
@Override public Object call(Cursor cursor) {
throw new AssertionError("Must not be called");
}
}).subscribe(testSubscriber);
testSubscriber.awaitTerminalEvent();
testSubscriber.assertNoValues();
assertThat(testSubscriber.getOnErrorEvents()).hasSize(1);
IllegalStateException expected = (IllegalStateException) testSubscriber.getOnErrorEvents().get(0);
assertThat(expected).hasMessage("test exception");
}
@Test public void mapToListThrowsFromMapFunction() {
TestSubscriber<Object> testSubscriber = new TestSubscriber<>();
Observable.<Query>just(new Query() {
@Override public Cursor run() {
MatrixCursor cursor = new MatrixCursor(new String[]{"col1"});
cursor.addRow(new Object[]{"value1"});
return cursor;
}
}).extend(new Func1<OnSubscribe<Query>, QueryObservable>() {
@Override public QueryObservable call(OnSubscribe<Query> func) {
return new QueryObservable(func);
}
}).mapToList(new Func1<Cursor, Object>() {
@Override public Object call(Cursor cursor) {
throw new IllegalStateException("test exception");
}
}).subscribe(testSubscriber);
testSubscriber.awaitTerminalEvent();
testSubscriber.assertNoValues();
assertThat(testSubscriber.getOnErrorEvents()).hasSize(1);
IllegalStateException expected = (IllegalStateException) testSubscriber.getOnErrorEvents().get(0);
assertThat(expected).hasMessage("test exception");
}
}
| apache-2.0 |
x-meta/xworker | xworker_uiflow/src/main/java/xworker/lang/flow/uiflow/ActionFlow.java | 4227 | package xworker.lang.flow.uiflow;
import java.util.Map;
import org.eclipse.swt.widgets.Composite;
import org.xmeta.ActionContext;
import org.xmeta.ActionException;
import org.xmeta.Thing;
import org.xmeta.util.UtilThing;
import xworker.lang.executor.Executor;
/**
* 动作流,简单化的UiFlow,它执行动作并根据返回值执行下一个动作。
*
* @author zyx
*
*/
public class ActionFlow extends AbstractUiFlow{
private static final String TAG = ActionFlow.class.getName();
ActionFlow parent;
public ActionFlow(Thing thing, ActionContext actionContext){
super(thing, actionContext);
}
public ActionFlow(ActionFlow parent, Thing thing){
super(thing, null);
this.parent = parent;
this.actionContext = new ActionContext();
this.actionContext.put("uiFlow", this);
thing.doAction("intiParams", actionContext);
}
public void nodeFinished(Thing node, String nextConnectionName){
//首先查找是否有对应的子节点
Thing nextNode = null;
for(Thing conn : node.getChilds("Connection")){
if(nextConnectionName != null && !"".equals(nextConnectionName)){
if(conn.getMetadata().getName().equals(nextConnectionName)){
nextNode = UtilThing.getQuoteThing(conn, "nodeRef");
break;
}
}else{
//使用默认
if(conn.getMetadata().getName().equals("default")){
nextNode = UtilThing.getQuoteThing(conn, "nodeRef");
break;
}
}
}
if(nextNode == null){
nextNode = UtilThing.getQuoteThing(node, "nextNode");
}
nodeFinishedWithNextNode(node, nextNode);
}
private void nodeFinishedWithNextNode(Thing node, Thing nextNode){
log("节点完成:" + node.getMetadata().getLabel() + ", path=" + node.getMetadata().getPath());
if(nextNode == null){
nextNode = UtilThing.getQuoteThing(node, "nextNode");
}
if(nextNode == null){
log("流程结束:" + thing.getMetadata().getPath());
}else{
start(nextNode);
}
}
@Override
public void log(String message) {
Executor.info(TAG, message);
}
@Override
public void log(Throwable e) {
Executor.error(TAG, "Error flow=" + thing.getMetadata().getPath(), e);
}
@Override
public Object get(String key) {
return actionContext.g().get(key);
}
@Override
public void set(String key, Object value) {
actionContext.g().put(key, value);
}
@Override
public ActionContext runComposite(Thing flowNode, Thing composite) {
throw new ActionException("ActionFlow not suuport SWT");
}
@Override
public ActionContext runComposite(Thing flowNode, Thing composite,
Map<String, Object> params) {
throw new ActionException("ActionFlow not suuport SWT");
}
@Override
public Object runAction(Thing action) {
return action.doAction(UiFlow.ACTION_ACTION, actionContext, "uiFlow", this, "flowNode", action);
}
@Override
public void start(Thing nextNode) {
if(nextNode == null){
Executor.warn(TAG, "start node is null, flow=" + thing.getMetadata().getPath());
}else{
nextNode.doAction(UiFlow.NODE_ACTION, actionContext, "uiFlow", this, "flowNode", nextNode);
}
}
@Override
public void start() {
start(getStartNode());
}
@Override
public void end() {
if(parent != null){
//初始化到父节点的参数
thing.doAction("setReturnValues", actionContext);
//返回值
String returnString = (String) thing.doAction("getRetunString", actionContext);
//调用父节点的节点结束
parent.nodeFinished(thing, returnString);
}else{
return;
}
}
@Override
public Composite getMainComposite() {
return null;
}
public Thing getStartNode(){
for(Thing node : thing.getChilds()){
if("Start".equals(node.getThingName())){
return node;
}
}
if(thing.getChilds().size() > 0){
return thing.getChilds().get(0);
}
return null;
}
@Override
public void startChildFlow(Thing childFlow) {
ActionFlow child = new ActionFlow(this, childFlow);
child.start();
}
@Override
public IFlow getParent() {
return parent;
}
@Override
public Thing getThing() {
return thing;
}
}
| apache-2.0 |
komamj/FileManager | app/src/main/java/com/koma/filemanager/widget/FastScroller.java | 13290 | package com.koma.filemanager.widget;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.koma.filemanager.R;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class FastScroller extends FrameLayout {
private static final int BUBBLE_ANIMATION_DURATION = 300;
private static final int TRACK_SNAP_RANGE = 5;
private TextView bubble;
private ImageView handle;
private int height;
private boolean isInitialized = false;
private ObjectAnimator currentAnimator;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private BubbleTextCreator bubbleTextCreator;
private List<OnScrollStateChangeListener> scrollStateChangeListeners = new ArrayList<OnScrollStateChangeListener>();
private final RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (bubble == null || handle.isSelected())
return;
int verticalScrollOffset = recyclerView.computeVerticalScrollOffset();
int verticalScrollRange = recyclerView.computeVerticalScrollRange();
float proportion = (float) verticalScrollOffset / ((float) verticalScrollRange - height);
setBubbleAndHandlePosition(height * proportion);
}
};
public FastScroller(Context context) {
super(context);
init();
}
public FastScroller(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FastScroller(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
protected void init() {
if (isInitialized) return;
isInitialized = true;
setClipChildren(false);
}
public void setRecyclerView(final RecyclerView recyclerView) {
this.recyclerView = recyclerView;
this.recyclerView.addOnScrollListener(onScrollListener);
this.recyclerView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
layoutManager = FastScroller.this.recyclerView.getLayoutManager();
}
});
if (recyclerView.getAdapter() instanceof BubbleTextCreator)
this.bubbleTextCreator = (BubbleTextCreator) recyclerView.getAdapter();
if (recyclerView.getAdapter() instanceof OnScrollStateChangeListener)
addOnScrollStateChangeListener((OnScrollStateChangeListener) recyclerView.getAdapter());
this.recyclerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
FastScroller.this.recyclerView.getViewTreeObserver().removeOnPreDrawListener(this);
if (bubble == null || handle.isSelected()) return true;
int verticalScrollOffset = FastScroller.this.recyclerView.computeVerticalScrollOffset();
int verticalScrollRange = FastScroller.this.computeVerticalScrollRange();
float proportion = (float) verticalScrollOffset / ((float) verticalScrollRange - height);
setBubbleAndHandlePosition(height * proportion);
return true;
}
});
}
public void addOnScrollStateChangeListener(OnScrollStateChangeListener stateChangeListener) {
if (stateChangeListener != null && !scrollStateChangeListeners.contains(stateChangeListener))
scrollStateChangeListeners.add(stateChangeListener);
}
public void removeOnScrollStateChangeListener(OnScrollStateChangeListener stateChangeListener) {
scrollStateChangeListeners.remove(stateChangeListener);
}
private void notifyScrollStateChange(boolean scrolling) {
for (OnScrollStateChangeListener stateChangeListener : scrollStateChangeListeners) {
stateChangeListener.onFastScrollerStateChange(scrolling);
}
}
/**
* Layout customization.<br/>
* Color for Selected State is the color defined inside the Drawables.
*
* @param layoutResId Main layout of Fast Scroller
* @param bubbleResId Drawable resource for Bubble containing the Text
* @param handleResId Drawable resource for the Handle
*/
public void setViewsToUse(@LayoutRes int layoutResId, @IdRes int bubbleResId, @IdRes int handleResId) {
if (bubble != null) return;//Already inflated
LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(layoutResId, this, true);
bubble = (TextView) findViewById(bubbleResId);
if (bubble != null) bubble.setVisibility(INVISIBLE);
handle = (ImageView) findViewById(handleResId);
}
/**
* Layout customization<br/>
* Color for Selected State is also customized by the user.
*
* @param layoutResId Main layout of Fast Scroller
* @param bubbleResId Drawable resource for Bubble containing the Text
* @param handleResId Drawable resource for the Handle
* @param accentColor Color for Selected state during touch and scrolling (usually accent color)
*/
public void setViewsToUse(@LayoutRes int layoutResId, @IdRes int bubbleResId, @IdRes int handleResId, int accentColor) {
setViewsToUse(layoutResId, bubbleResId, handleResId);
setBubbleAndHandleColor(accentColor);
}
private void setBubbleAndHandleColor(int accentColor) {
//TODO: Programmatically generate the Drawables instead of using resources
//BubbleDrawable accentColor
GradientDrawable bubbleDrawable;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
bubbleDrawable = (GradientDrawable) getResources().getDrawable(R.drawable.fast_scroller_bubble, null);
} else {
//noinspection deprecation
bubbleDrawable = (GradientDrawable) getResources().getDrawable(R.drawable.fast_scroller_bubble);
}
assert bubbleDrawable != null;
bubbleDrawable.setColor(accentColor);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
bubble.setBackground(bubbleDrawable);
} else {
//noinspection deprecation
bubble.setBackgroundDrawable(bubbleDrawable);
}
//HandleDrawable accentColor
try {
StateListDrawable stateListDrawable;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
stateListDrawable = (StateListDrawable) getResources().getDrawable(R.drawable.fast_scroller_handle, null);
} else {
//noinspection deprecation
stateListDrawable = (StateListDrawable) getResources().getDrawable(R.drawable.fast_scroller_handle);
}
//Method is still hidden, invoke Java reflection
Method getStateDrawable = StateListDrawable.class.getMethod("getStateDrawable", int.class);
GradientDrawable handleDrawable = (GradientDrawable) getStateDrawable.invoke(stateListDrawable, 0);
handleDrawable.setColor(accentColor);
handle.setImageDrawable(stateListDrawable);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
height = h;
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
if (event.getX() < handle.getX() - ViewCompat.getPaddingStart(handle)) return false;
if (currentAnimator != null) currentAnimator.cancel();
handle.setSelected(true);
notifyScrollStateChange(true);
showBubble();
case MotionEvent.ACTION_MOVE:
float y = event.getY();
setBubbleAndHandlePosition(y);
setRecyclerViewPosition(y);
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
handle.setSelected(false);
notifyScrollStateChange(false);
hideBubble();
return true;
}
return super.onTouchEvent(event);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (recyclerView != null)
recyclerView.removeOnScrollListener(onScrollListener);
}
private void setRecyclerViewPosition(float y) {
if (recyclerView != null) {
int itemCount = recyclerView.getAdapter().getItemCount();
//Calculate proportion
float proportion;
if (handle.getY() == 0) {
proportion = 0f;
} else if (handle.getY() + handle.getHeight() >= height - TRACK_SNAP_RANGE) {
proportion = 1f;
} else {
proportion = y / (float) height;
}
int targetPos = getValueInRange(0, itemCount - 1, (int) (proportion * (float) itemCount));
//Scroll To Position based on LayoutManager
if (layoutManager instanceof StaggeredGridLayoutManager) {
((StaggeredGridLayoutManager) layoutManager).scrollToPositionWithOffset(targetPos, 0);
} else {
((LinearLayoutManager) layoutManager).scrollToPositionWithOffset(targetPos, 0);
}
//Update bubbleText
if (bubble != null) {
String bubbleText = bubbleTextCreator.onCreateBubbleText(targetPos);
if (bubbleText != null) {
bubble.setVisibility(View.VISIBLE);
bubble.setText(bubbleText);
} else {
bubble.setVisibility(View.GONE);
}
}
}
}
private static int getValueInRange(int min, int max, int value) {
int minimum = Math.max(min, value);
return Math.min(minimum, max);
}
private void setBubbleAndHandlePosition(float y) {
int handleHeight = handle.getHeight();
handle.setY(getValueInRange(0, height - handleHeight, (int) (y - handleHeight / 2)));
if (bubble != null) {
int bubbleHeight = bubble.getHeight();
bubble.setY(getValueInRange(0, height - bubbleHeight - handleHeight / 2, (int) (y - bubbleHeight)));
}
}
private void showBubble() {
if (bubble != null && bubble.getVisibility() != VISIBLE) {
bubble.setVisibility(VISIBLE);
if (currentAnimator != null)
currentAnimator.cancel();
currentAnimator = ObjectAnimator.ofFloat(bubble, "alpha", 0f, 1f).setDuration(BUBBLE_ANIMATION_DURATION);
currentAnimator.start();
}
}
private void hideBubble() {
if (bubble == null)
return;
if (currentAnimator != null)
currentAnimator.cancel();
currentAnimator = ObjectAnimator.ofFloat(bubble, "alpha", 1f, 0f).setDuration(BUBBLE_ANIMATION_DURATION);
currentAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
bubble.setVisibility(INVISIBLE);
currentAnimator = null;
}
@Override
public void onAnimationCancel(Animator animation) {
super.onAnimationCancel(animation);
bubble.setVisibility(INVISIBLE);
currentAnimator = null;
}
});
currentAnimator.start();
}
public interface BubbleTextCreator {
String onCreateBubbleText(int pos);
}
public interface OnScrollStateChangeListener {
/**
* Called when scrolling state changes.
*
* @param scrolling true if the user is actively scrolling, false when idle
*/
void onFastScrollerStateChange(boolean scrolling);
}
} | apache-2.0 |
Ile2/struts2-showcase-demo | src/apps/showcase/src/main/java/org/apache/struts2/showcase/action/EmployeeAction.java | 3437 | /*
* $Id$
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.showcase.action;
import com.opensymphony.xwork2.Preparable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.showcase.application.TestDataProvider;
import org.apache.struts2.showcase.dao.Dao;
import org.apache.struts2.showcase.dao.EmployeeDao;
import org.apache.struts2.showcase.model.Employee;
import org.apache.struts2.showcase.model.Skill;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* JsfEmployeeAction.
*/
public class EmployeeAction extends AbstractCRUDAction implements Preparable {
private static final long serialVersionUID = 7047317819789938957L;
private static final Logger log = LogManager.getLogger(EmployeeAction.class);
@Autowired
private EmployeeDao employeeDao;
private Long empId;
private Employee currentEmployee;
private List<String> selectedSkills;
public String execute() throws Exception {
if (getCurrentEmployee() != null && getCurrentEmployee().getOtherSkills() != null) {
setSelectedSkills(new ArrayList<String>());
Iterator it = getCurrentEmployee().getOtherSkills().iterator();
while (it.hasNext()) {
getSelectedSkills().add(((Skill) it.next()).getName());
}
}
return super.execute();
}
public String save() throws Exception {
if (getCurrentEmployee() != null) {
setEmpId((Long) employeeDao.merge(getCurrentEmployee()));
employeeDao.setSkills(getEmpId(), getSelectedSkills());
}
return SUCCESS;
}
public Long getEmpId() {
return empId;
}
public void setEmpId(Long empId) {
this.empId = empId;
}
public Employee getCurrentEmployee() {
return currentEmployee;
}
public void setCurrentEmployee(Employee currentEmployee) {
this.currentEmployee = currentEmployee;
}
public String[] getAvailablePositions() {
return TestDataProvider.POSITIONS;
}
public List getAvailableLevels() {
return Arrays.asList(TestDataProvider.LEVELS);
}
public List<String> getSelectedSkills() {
return selectedSkills;
}
public void setSelectedSkills(List<String> selectedSkills) {
this.selectedSkills = selectedSkills;
}
protected Dao getDao() {
return employeeDao;
}
/**
* This method is called to allow the action to prepare itself.
*
* @throws Exception thrown if a system level exception occurs.
*/
public void prepare() throws Exception {
Employee preFetched = (Employee) fetch(getEmpId(), getCurrentEmployee());
if (preFetched != null) {
setCurrentEmployee(preFetched);
}
}
}
| apache-2.0 |
agileowl/tapestry-5 | tapestry-ioc/src/main/java/org/apache/tapestry5/ioc/internal/util/LoggingInvokableWrapper.java | 1221 | // Copyright 2011 The Apache Software Foundation
//
// 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.apache.tapestry5.ioc.internal.util;
import org.apache.tapestry5.ioc.Invokable;
import org.slf4j.Logger;
/**
* @since 5.3
*/
public class LoggingInvokableWrapper<T> implements Invokable<T>
{
private final Logger logger;
private final String message;
private final Invokable<T> delegate;
public LoggingInvokableWrapper(Logger logger, String message, Invokable<T> delegate)
{
this.logger = logger;
this.message = message;
this.delegate = delegate;
}
public T invoke()
{
logger.debug(message);
return delegate.invoke();
}
}
| apache-2.0 |
Overruler/gerrit | gerrit-gwtui/src/main/java/com/google/gerrit/client/change/ReplyBox.java | 16023 | // 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.google.gerrit.client.change;
import static com.google.gwt.event.dom.client.KeyCodes.KEY_ENTER;
import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.changes.ChangeApi;
import com.google.gerrit.client.changes.ChangeInfo.ApprovalInfo;
import com.google.gerrit.client.changes.ChangeInfo.LabelInfo;
import com.google.gerrit.client.changes.ChangeInfo.MessageInfo;
import com.google.gerrit.client.changes.CommentApi;
import com.google.gerrit.client.changes.CommentInfo;
import com.google.gerrit.client.changes.ReviewInput;
import com.google.gerrit.client.changes.Util;
import com.google.gerrit.client.rpc.GerritCallback;
import com.google.gerrit.client.rpc.NativeMap;
import com.google.gerrit.client.rpc.Natives;
import com.google.gerrit.client.ui.CommentLinkProcessor;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.common.data.LabelValue;
import com.google.gerrit.reviewdb.client.Patch;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
class ReplyBox extends Composite {
private static final String CODE_REVIEW = "Code-Review";
interface Binder extends UiBinder<HTMLPanel, ReplyBox> {}
private static final Binder uiBinder = GWT.create(Binder.class);
interface Styles extends CssResource {
String label_name();
String label_value();
String label_help();
}
private final CommentLinkProcessor clp;
private final PatchSet.Id psId;
private final String revision;
private ReviewInput in = ReviewInput.create();
private int labelHelpColumn;
private Runnable lgtm;
@UiField Styles style;
@UiField TextArea message;
@UiField Element labelsParent;
@UiField Grid labelsTable;
@UiField Button post;
@UiField Button cancel;
@UiField ScrollPanel commentsPanel;
@UiField FlowPanel comments;
ReplyBox(
CommentLinkProcessor clp,
PatchSet.Id psId,
String revision,
NativeMap<LabelInfo> all,
NativeMap<JsArrayString> permitted) {
this.clp = clp;
this.psId = psId;
this.revision = revision;
initWidget(uiBinder.createAndBindUi(this));
List<String> names = new ArrayList<>(permitted.keySet());
if (names.isEmpty()) {
UIObject.setVisible(labelsParent, false);
} else {
Collections.sort(names);
renderLabels(names, all, permitted);
}
addDomHandler(
new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent e) {
e.stopPropagation();
if ((e.getCharCode() == '\n' || e.getCharCode() == KEY_ENTER)
&& e.isControlKeyDown()) {
e.preventDefault();
if (post.isEnabled()) {
onPost(null);
}
}
}
},
KeyPressEvent.getType());
}
@Override
protected void onLoad() {
commentsPanel.setVisible(false);
post.setEnabled(false);
CommentApi.drafts(psId, new AsyncCallback<NativeMap<JsArray<CommentInfo>>>() {
@Override
public void onSuccess(NativeMap<JsArray<CommentInfo>> result) {
attachComments(result);
displayComments(result);
post.setEnabled(true);
}
@Override
public void onFailure(Throwable caught) {
post.setEnabled(true);
}
});
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
message.setFocus(true);
}});
Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
@Override
public boolean execute() {
String t = message.getText();
if (t != null) {
message.setCursorPos(t.length());
}
return false;
}}, 0);
}
@UiHandler("message")
void onMessageKey(KeyPressEvent event) {
if (lgtm != null
&& event.getCharCode() == 'M'
&& message.getValue().equals("LGT")) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
lgtm.run();
}
});
}
}
@UiHandler("post")
void onPost(@SuppressWarnings("unused") ClickEvent e) {
postReview();
}
void quickApprove(ReviewInput quickApproveInput) {
in.mergeLabels(quickApproveInput);
postReview();
}
private void postReview() {
in.message(message.getText().trim());
in.prePost();
ChangeApi.revision(psId.getParentKey().get(), revision)
.view("review")
.post(in, new GerritCallback<ReviewInput>() {
@Override
public void onSuccess(ReviewInput result) {
Gerrit.display(PageLinks.toChange(
psId.getParentKey(),
String.valueOf(psId.get())));
}
});
hide();
}
@UiHandler("cancel")
void onCancel(@SuppressWarnings("unused") ClickEvent e) {
message.setText("");
hide();
}
void replyTo(MessageInfo msg) {
if (msg.message() != null) {
String t = message.getText();
String m = quote(msg);
if (t == null || t.isEmpty()) {
t = m;
} else if (t.endsWith("\n\n")) {
t += m;
} else if (t.endsWith("\n")) {
t += "\n" + m;
} else {
t += "\n\n" + m;
}
message.setText(t + "\n\n");
}
}
private static String quote(MessageInfo msg) {
String m = msg.message().trim();
if (m.startsWith("Patch Set ")) {
int i = m.indexOf('\n');
if (i > 0) {
m = m.substring(i + 1).trim();
}
}
StringBuilder quotedMsg = new StringBuilder();
for (String line : m.split("\\n")) {
line = line.trim();
while (line.length() > 67) {
int i = line.lastIndexOf(' ', 67);
if (i < 50) {
i = line.indexOf(' ', 67);
}
if (i > 0) {
quotedMsg.append(" > ").append(line.substring(0, i)).append("\n");
line = line.substring(i + 1);
} else {
break;
}
}
quotedMsg.append(" > ").append(line).append("\n");
}
return quotedMsg.toString().substring(0, quotedMsg.length() - 1); // remove last '\n'
}
private void hide() {
for (Widget w = getParent(); w != null; w = w.getParent()) {
if (w instanceof PopupPanel) {
((PopupPanel) w).hide();
break;
}
}
}
private void renderLabels(
List<String> names,
NativeMap<LabelInfo> all,
NativeMap<JsArrayString> permitted) {
TreeSet<Short> values = new TreeSet<>();
List<LabelAndValues> labels = new ArrayList<>(permitted.size());
for (String id : names) {
JsArrayString p = permitted.get(id);
if (p != null) {
Set<Short> a = new TreeSet<>();
for (int i = 0; i < p.length(); i++) {
a.add(LabelInfo.parseValue(p.get(i)));
}
labels.add(new LabelAndValues(all.get(id), a));
values.addAll(a);
}
}
List<Short> columns = new ArrayList<>(values);
labelsTable.resize(1 + labels.size(), 2 + values.size());
for (int c = 0; c < columns.size(); c++) {
labelsTable.setText(0, 1 + c, LabelValue.formatValue(columns.get(c)));
labelsTable.getCellFormatter().setStyleName(0, 1 + c, style.label_value());
}
List<LabelAndValues> checkboxes = new ArrayList<>(labels.size());
int row = 1;
for (LabelAndValues lv : labels) {
if (isCheckBox(lv.info.value_set())) {
checkboxes.add(lv);
} else {
renderRadio(row++, columns, lv);
}
}
for (LabelAndValues lv : checkboxes) {
renderCheckBox(row++, lv);
}
}
private Short normalizeDefaultValue(Short defaultValue, Set<Short> permittedValues) {
Short pmin = Collections.min(permittedValues);
Short pmax = Collections.max(permittedValues);
Short dv = defaultValue;
if (dv > pmax) {
dv = pmax;
} else if (dv < pmin) {
dv = pmin;
}
return dv;
}
private void renderRadio(int row,
List<Short> columns,
LabelAndValues lv) {
String id = lv.info.name();
Short dv = normalizeDefaultValue(lv.info.defaultValue(), lv.permitted);
labelHelpColumn = 1 + columns.size();
labelsTable.setText(row, 0, id);
CellFormatter fmt = labelsTable.getCellFormatter();
fmt.setStyleName(row, 0, style.label_name());
fmt.setStyleName(row, labelHelpColumn, style.label_help());
ApprovalInfo self = Gerrit.isSignedIn()
? lv.info.for_user(Gerrit.getUserAccount().getId().get())
: null;
final LabelRadioGroup group =
new LabelRadioGroup(row, id, lv.permitted.size());
for (int i = 0; i < columns.size(); i++) {
Short v = columns.get(i);
if (lv.permitted.contains(v)) {
String text = lv.info.value_text(LabelValue.formatValue(v));
LabelRadioButton b = new LabelRadioButton(group, text, v);
if ((self != null && v == self.value()) || (self == null && v.equals(dv))) {
b.setValue(true);
group.select(b);
in.label(group.label, v);
labelsTable.setText(row, labelHelpColumn, b.text);
}
group.buttons.add(b);
labelsTable.setWidget(row, 1 + i, b);
}
}
if (CODE_REVIEW.equalsIgnoreCase(id) && !group.buttons.isEmpty()) {
lgtm = new Runnable() {
@Override
public void run() {
group.selectMax();
}
};
}
}
private void renderCheckBox(int row, LabelAndValues lv) {
ApprovalInfo self = Gerrit.isSignedIn()
? lv.info.for_user(Gerrit.getUserAccount().getId().get())
: null;
final String id = lv.info.name();
final CheckBox b = new CheckBox();
b.setText(id);
b.setTitle(lv.info.value_text("+1"));
b.setEnabled(lv.permitted.contains((short) 1));
if (self != null && self.value() == 1) {
b.setValue(true);
}
b.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
in.label(id, event.getValue() ? (short) 1 : (short) 0);
}
});
b.setStyleName(style.label_name());
labelsTable.setWidget(row, 0, b);
if (CODE_REVIEW.equalsIgnoreCase(id)) {
lgtm = new Runnable() {
@Override
public void run() {
b.setValue(true, true);
}
};
}
}
private static boolean isCheckBox(Set<Short> values) {
return values.size() == 2
&& values.contains((short) 0)
&& values.contains((short) 1);
}
private void attachComments(NativeMap<JsArray<CommentInfo>> result) {
in.drafts(ReviewInput.DraftHandling.KEEP);
in.comments(result);
}
private void displayComments(NativeMap<JsArray<CommentInfo>> m) {
comments.clear();
JsArray<CommentInfo> l = m.get(Patch.COMMIT_MSG);
if (l != null) {
comments.add(new FileComments(clp, psId,
Util.C.commitMessage(), copyPath(Patch.COMMIT_MSG, l)));
}
List<String> paths = new ArrayList<>(m.keySet());
Collections.sort(paths);
for (String path : paths) {
if (!path.equals(Patch.COMMIT_MSG)) {
comments.add(new FileComments(clp, psId,
path, copyPath(path, m.get(path))));
}
}
commentsPanel.setVisible(comments.getWidgetCount() > 0);
}
private static List<CommentInfo> copyPath(String path, JsArray<CommentInfo> l) {
for (int i = 0; i < l.length(); i++) {
l.get(i).path(path);
}
return Natives.asList(l);
}
private static class LabelAndValues {
final LabelInfo info;
final Set<Short> permitted;
LabelAndValues(LabelInfo info, Set<Short> permitted) {
this.info = info;
this.permitted = permitted;
}
}
private class LabelRadioGroup {
final int row;
final String label;
final List<LabelRadioButton> buttons;
LabelRadioButton selected;
LabelRadioGroup(int row, String label, int cnt) {
this.row = row;
this.label = label;
this.buttons = new ArrayList<>(cnt);
}
void select(LabelRadioButton b) {
selected = b;
labelsTable.setText(row, labelHelpColumn, b.text);
}
void selectMax() {
for (int i = 0; i < buttons.size() - 1; i++) {
buttons.get(i).setValue(false, false);
}
LabelRadioButton max = buttons.get(buttons.size() - 1);
max.setValue(true, true);
max.select();
}
}
private class LabelRadioButton extends RadioButton implements
ValueChangeHandler<Boolean>, ClickHandler, MouseOverHandler,
MouseOutHandler {
private final LabelRadioGroup group;
private final String text;
private final short value;
LabelRadioButton(LabelRadioGroup group, String text, short value) {
super(group.label);
this.group = group;
this.text = text;
this.value = value;
addValueChangeHandler(this);
addClickHandler(this);
addMouseOverHandler(this);
addMouseOutHandler(this);
}
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
if (event.getValue()) {
select();
}
}
@Override
public void onClick(ClickEvent event) {
select();
}
void select() {
group.select(this);
in.label(group.label, value);
}
@Override
public void onMouseOver(MouseOverEvent event) {
labelsTable.setText(group.row, labelHelpColumn, text);
}
@Override
public void onMouseOut(MouseOutEvent event) {
LabelRadioButton b = group.selected;
String s = b != null ? b.text : "";
labelsTable.setText(group.row, labelHelpColumn, s);
}
}
}
| apache-2.0 |
rlon008/testamation | testamation-hibernate-support/src/main/java/nz/co/testamation/hibernate/step/AbstractHibernateEntityStep.java | 1552 | /*
* Copyright 2016 Ratha Long
*
* 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 nz.co.testamation.hibernate.step;
import nz.co.testamation.hibernate.HibernateEntityTemplate;
import nz.co.testamation.core.step.AbstractStep;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class AbstractHibernateEntityStep<T> extends AbstractStep<T> {
@Autowired
HibernateEntityTemplate hibernateEntityTemplate;
public void doWithNewEntity( HibernateEntityTemplate.EntityWork work ) {
hibernateEntityTemplate.doWithNewEntity( work );
}
public <T> T doInHibernate( HibernateEntityTemplate.Work<T> work ) {
return hibernateEntityTemplate.doInHibernate( work );
}
public void doInHibernateNoResult( HibernateEntityTemplate.WorkNoResult work ) {
hibernateEntityTemplate.doInHibernateNoResult( work );
}
public <T> T reload( Session session, T obj ) {
return hibernateEntityTemplate.reload( session, obj );
}
}
| apache-2.0 |
samskivert/robovm-samples | PhotoScroller/src/main/java/org/robovm/samples/photoscroller/ui/ImageScrollView.java | 12434 | /*
* Copyright (C) 2013-2015 RoboVM AB
*
* 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.
*
* Portions of this code is based on Apple Inc's PhotoScroller sample (v1.3)
* which is copyright (C) 2010-2012 Apple Inc.
*/
package org.robovm.samples.photoscroller.ui;
import java.io.File;
import org.robovm.apple.coregraphics.CGPoint;
import org.robovm.apple.coregraphics.CGRect;
import org.robovm.apple.coregraphics.CGSize;
import org.robovm.apple.foundation.NSArray;
import org.robovm.apple.foundation.NSBundle;
import org.robovm.apple.foundation.NSData;
import org.robovm.apple.foundation.NSDictionary;
import org.robovm.apple.foundation.NSErrorException;
import org.robovm.apple.foundation.NSObject;
import org.robovm.apple.foundation.NSPropertyListMutabilityOptions;
import org.robovm.apple.foundation.NSPropertyListSerialization;
import org.robovm.apple.foundation.NSString;
import org.robovm.apple.uikit.UIImage;
import org.robovm.apple.uikit.UIImageView;
import org.robovm.apple.uikit.UIScreen;
import org.robovm.apple.uikit.UIScrollView;
import org.robovm.apple.uikit.UIScrollViewDelegateAdapter;
import org.robovm.apple.uikit.UIView;
public class ImageScrollView extends UIScrollView {
private static final boolean TILE_IMAGES = true; // turn on to use tiled
// images, if off, we use
// whole images
private static NSArray<?> imageData;
private UIImageView zoomView; // if tiling, this contains a very low-res
// placeholder image,
// otherwise it contains the full image.
private CGSize imageSize;
private TilingView tilingView;
private int index;
private CGPoint pointToCenterAfterResize;
private double scaleToRestoreAfterResize;
public ImageScrollView() {
setShowsHorizontalScrollIndicator(false);
setShowsHorizontalScrollIndicator(false);
setBouncesZoom(true);
setDecelerationRate(UIScrollView.getFastDecelerationRate());
setDelegate(new UIScrollViewDelegateAdapter() {
@Override
public UIView getViewForZooming(UIScrollView scrollView) {
return zoomView;
}
});
}
public void setIndex(int index) {
this.index = index;
if (TILE_IMAGES) {
displayTiledImage(getImageName(index), getImageSize(index));
} else {
displayImage(getImage(index));
}
}
@Override
public void layoutSubviews() {
super.layoutSubviews();
// center the zoom view as it becomes smaller than the size of the
// screen
CGSize boundsSize = getBounds().getSize();
CGRect frameToCenter = zoomView.getFrame();
// center horizontally
if (frameToCenter.getSize().getWidth() < boundsSize.getWidth())
frameToCenter.getOrigin().setX((boundsSize.getWidth() - frameToCenter.getSize().getWidth()) / 2);
else
frameToCenter.getOrigin().setX(0);
// center vertically
if (frameToCenter.getSize().getHeight() < boundsSize.getHeight())
frameToCenter.getOrigin().setY((boundsSize.getHeight() - frameToCenter.getSize().getHeight()) / 2);
else
frameToCenter.getOrigin().setY(0);
zoomView.setFrame(frameToCenter);
}
@Override
public void setFrame(CGRect frame) {
boolean sizeChanging = !frame.getSize().equalsTo(getFrame().getSize());
if (sizeChanging) {
prepareToResize();
}
super.setFrame(frame);
if (sizeChanging) {
recoverFromResizing();
}
}
private void displayTiledImage(String imageName, CGSize imageSize) {
// clear views for the previous image
if (zoomView != null) {
zoomView.removeFromSuperview();
zoomView = null;
}
tilingView = null;
// reset our zoomScale to 1.0 before doing any further calculations
setZoomScale(1);
// make views to display the new image
zoomView = new UIImageView(new CGRect(CGPoint.Zero(), imageSize));
zoomView.setImage(getPlaceholderImage(imageName));
addSubview(zoomView);
tilingView = new TilingView(imageName, imageSize);
tilingView.setFrame(zoomView.getBounds());
zoomView.addSubview(tilingView);
configureForImageSize(imageSize);
}
private void displayImage(UIImage image) {
// clear the previous image
if (zoomView != null) {
zoomView.removeFromSuperview();
zoomView = null;
}
// reset our zoomScale to 1.0 before doing any further calculations
setZoomScale(1);
// make a new UIImageView for the new image
zoomView = new UIImageView(image);
addSubview(zoomView);
configureForImageSize(image.getSize());
}
private void configureForImageSize(CGSize imageSize) {
this.imageSize = imageSize;
setContentSize(imageSize);
setMaxMinZoomScalesForCurrentBounds();
setZoomScale(getMinimumZoomScale());
}
private void setMaxMinZoomScalesForCurrentBounds() {
CGSize boundsSize = getBounds().getSize();
// calculate min/max zoomscale
double xScale = boundsSize.getWidth() / imageSize.getWidth(); // the
// scale
// needed
// to
// perfectly
// fit the
// image
// width-wise
double yScale = boundsSize.getHeight() / imageSize.getHeight(); // the
// scale
// needed
// to
// perfectly
// fit
// the
// image
// height-wise
// fill width if the image and phone are both portrait or both
// landscape; otherwise take smaller scale
boolean imagePortrait = imageSize.getHeight() > imageSize.getWidth();
boolean phonePortrait = boundsSize.getHeight() > boundsSize.getWidth();
double minScale = imagePortrait == phonePortrait ? xScale : Math.min(xScale, yScale);
// on high resolution screens we have double the pixel density, so we
// will be seeing every pixel if we limit the
// maximum zoom scale to 0.5.
double maxScale = 1.0 / UIScreen.getMainScreen().getScale();
// don't let minScale exceed maxScale. (If the image is smaller than the
// screen, we don't want to force it to be zoomed.)
if (minScale > maxScale) {
minScale = maxScale;
}
setMaximumZoomScale(maxScale);
setMinimumZoomScale(minScale);
}
private void prepareToResize() {
CGPoint boundsCenter = new CGPoint(getBounds().getMidX(), getBounds().getMidY());
pointToCenterAfterResize = convertPointToView(boundsCenter, zoomView);
scaleToRestoreAfterResize = getZoomScale();
// If we're at the minimum zoom scale, preserve that by returning 0,
// which will be converted to the minimum
// allowable scale when the scale is restored.
if (scaleToRestoreAfterResize <= getMinimumZoomScale() + 1.19209290E-07F) {
scaleToRestoreAfterResize = 0;
}
}
private void recoverFromResizing() {
setMaxMinZoomScalesForCurrentBounds();
// Step 1: restore zoom scale, first making sure it is within the
// allowable range.
double maxZoomScale = Math.max(getMinimumZoomScale(), scaleToRestoreAfterResize);
setZoomScale(Math.min(getMaximumZoomScale(), maxZoomScale));
// Step 2: restore center point, first making sure it is within the
// allowable range.
// 2a: convert our desired center point back to our own coordinate space
CGPoint boundsCenter = convertPointFromView(pointToCenterAfterResize, zoomView);
// 2b: calculate the content offset that would yield that center point
CGPoint offset = new CGPoint(boundsCenter.getX() - getBounds().getSize().getWidth() / 2.0, boundsCenter.getY()
- getBounds().getSize().getHeight() / 2.0);
// 2c: restore offset, adjusted to be within the allowable range
CGPoint maxOffset = getMaximumContentOffset();
CGPoint minOffset = getMinimumContentOffset();
double realMaxOffset = Math.min(maxOffset.getX(), offset.getX());
offset.setX(Math.max(minOffset.getX(), realMaxOffset));
realMaxOffset = Math.min(maxOffset.getY(), offset.getY());
offset.setY(Math.max(minOffset.getY(), realMaxOffset));
setContentOffset(offset);
}
private CGPoint getMaximumContentOffset() {
CGSize contentSize = getContentSize();
CGSize boundsSize = getBounds().getSize();
return new CGPoint(contentSize.getWidth() - boundsSize.getWidth(), contentSize.getHeight()
- boundsSize.getHeight());
}
private CGPoint getMinimumContentOffset() {
return CGPoint.Zero();
}
private static NSArray<?> getImageData() {
if (imageData == null) {
String path = NSBundle.getMainBundle().findResourcePath("ImageData", "plist");
NSData plistData = NSData.read(new File(path));
try {
imageData = (NSArray<?>) NSPropertyListSerialization.getPropertyListFromData(plistData,
NSPropertyListMutabilityOptions.None);
} catch (NSErrorException e) {
System.err.println("Unable to read image data: " + e.getError());
}
}
return imageData;
}
public static int getImageCount() {
NSArray<?> imageData = getImageData();
if (imageData == null)
return 0;
return imageData.size();
}
@SuppressWarnings("unchecked")
private static String getImageName(int index) {
NSDictionary<NSString, NSObject> info = (NSDictionary<NSString, NSObject>) getImageData().get(index);
return info.get(new NSString("name")).toString();
}
private static UIImage getImage(int index) {
String imageName = getImageName(index);
String path = NSBundle.getMainBundle().findResourcePath(String.format("Full Images/%s", imageName), "jpg");
return UIImage.create(new File(path));
}
@SuppressWarnings("unchecked")
private static CGSize getImageSize(int index) {
NSDictionary<NSString, NSObject> info = (NSDictionary<NSString, NSObject>) getImageData().get(index);
float width = Float.valueOf(info.get(new NSString("width")).toString());
float height = Float.valueOf(info.get(new NSString("height")).toString());
return new CGSize(width, height);
}
private static UIImage getPlaceholderImage(String name) {
return UIImage.create(String.format("Placeholder Images/%s_Placeholder", name));
}
public int getPageIndex() {
return index;
}
}
| apache-2.0 |
kwmt/GitHubSearch | app/src/main/java/net/kwmt27/codesearch/entity/payloads/DownloadEventEntity.java | 458 | package net.kwmt27.codesearch.entity.payloads;
import com.google.gson.annotations.SerializedName;
/**
* @deprecated Downloads API is Deprecated https://developer.github.com/v3/repos/downloads/
*/
@Deprecated
public class DownloadEventEntity {
@SerializedName("download")
private DownloadEntity mDownload;
public DownloadEntity getDownload() {
if(mDownload == null) { return new DownloadEntity(); }
return mDownload;
}
}
| apache-2.0 |
PRImA-Research-Lab/prima-page-viewer | src/org/primaresearch/page/viewer/PageViewer.java | 8428 | /*
* Copyright 2019 PRImA Research Lab, University of Salford, United Kingdom
*
* 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.primaresearch.page.viewer;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.primaresearch.page.viewer.dla.XmlDocumentLayoutLoader;
import org.primaresearch.page.viewer.extra.Task;
import org.primaresearch.page.viewer.ui.MainWindow;
import org.primaresearch.page.viewer.ui.views.DocumentView;
/**
* Entry point class for the Page Viewer tool
*
* @author Christian Clausner
*
*/
public class PageViewer {
private MainWindow mainWindow;
private EventListener mainEventListener;
private Task currentTask = null;
private List<Task> taskQueue = new ArrayList<Task>();
private XmlDocumentLayoutLoader xmlLoader;
private String imageFilePath;
private String resolveDir;
private Document document;
private Set<DocumentView> documentViews = new HashSet<DocumentView>();
/**
* Main function
* @param args Argument 0 (optional): Page XML file; Argument 1 (optional): Image file; Options: --resolve-dir </path/to/img>
*/
public static void main(String[] args) {
String pageFilePath = null;
String imageFilePath = null;
String resolveDir = null;
for (int i=0; i<args.length; i++) {
if ("--resolve-dir".equals(args[i])) {
i++;
resolveDir = args[i];
}
else if (pageFilePath == null)
pageFilePath = args[i];
else
imageFilePath = args[i];
}
//Resolve
if (imageFilePath != null && resolveDir != null)
imageFilePath = resolveDir + (resolveDir.endsWith(File.separator) ? "" : File.separator) + imageFilePath;
Display display = new Display();
new PageViewer(display, pageFilePath, imageFilePath, resolveDir);
display.dispose();
}
/**
* Constructor
* @param display Responsible for managing the connection between SWT and the underlying operating system
* @param pageFilePath Path to page content XML file (optional, use <code>null</code> if not used)
* @param imageFilePath Path to page image file (optional, use <code>null</code> if not used)
* @param resolveDir Root path for loading images (using relative image path)
*/
public PageViewer(Display display, String pageFilePath, String imageFilePath, String resolveDir) {
this.imageFilePath = imageFilePath;
this.resolveDir = resolveDir;
Shell shell = new Shell();
//Icon
try {
Image smallIcon = new Image(display, getClass().getResourceAsStream("/org/primaresearch/page/viewer/ui/res/shell_icon_16.png"));
Image largeIcon = new Image(display, getClass().getResourceAsStream("/org/primaresearch/page/viewer/ui/res/shell_icon_32.png"));
shell.setImages(new Image[] { smallIcon, largeIcon });
} catch (Exception exc) {
exc.printStackTrace();
}
try {
mainEventListener = new EventListener(this);
shell.addKeyListener(mainEventListener);
mainWindow = new MainWindow(shell, this);
mainWindow.init();
//Load page content now?
if (pageFilePath != null)
openDocument(pageFilePath, imageFilePath);
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
catch (Exception exc) {
exc.printStackTrace(); //TODO
}
}
/**
* A central event listener (toolbar, load events, keyboard)
* @return Listener object
*/
public EventListener getMainEventListener() {
return mainEventListener;
}
/**
* Returns the main window of the Page Viewer
*/
public MainWindow getMainWindow() {
return mainWindow;
}
/**
* Exits the tool and cleans up
*/
public void exit() {
try {
mainWindow.dispose();
cleanUp();
}
catch (Exception exc) {
exc.printStackTrace(); //TODO
}
System.exit(0);
}
/**
* Releases resources
*/
private void cleanUp() {
if (document != null)
document.dispose();
}
/**
* Queues a task to be run asynchronously
* @param task Task object
*/
public synchronized void runTaskAsync(Task task) {
taskQueue.add(task);
processNextTask();
}
/**
* Starts the next task from the task queue (if not empty).
*/
public void processNextTask() {
if (!taskQueue.isEmpty()) {
currentTask = taskQueue.get(0);
taskQueue.remove(0);
try {
currentTask.addListener(mainEventListener);
currentTask.runAsync();
} catch (Exception exc) {
exc.printStackTrace(); //TODO
}
}
}
/**
* Loads the specified PAGE file.
* Resets image file path.
*/
public void openDocument(String filePath) {
openDocument(filePath, null);
}
/**
* Loads the specified PAGE file
*/
public void openDocument(String xmlFilePath, String imageFilePath) {
setImageFilePath(imageFilePath);
Document doc = new Document();
setDocument(doc);
xmlLoader = new XmlDocumentLayoutLoader(xmlFilePath, resolveDir);
runTaskAsync(xmlLoader);
updateTitle(xmlFilePath);
}
private void updateTitle(String xmlFilePath) {
String title = "Page Viewer";
if (xmlFilePath != null) {
title += " (" + xmlFilePath;
if (imageFilePath != null) {
title += ", " + imageFilePath;
}
title += ")";
}
mainWindow.setTitle(title);
}
/**
* Sets the current document
* @param document Document object
*/
public void setDocument(Document document) {
if (this.document != null)
this.document.removeListeners();
this.document = document;
for (Iterator<DocumentView> it = documentViews.iterator(); it.hasNext(); )
it.next().setDocument(document);
}
/**
* Returns the current document
*/
public Document getDocument() {
return document;
}
/**
* Adds the given document view
*/
public void registerDocumentView(DocumentView view) {
documentViews.add(view);
}
/**
* Returns a set of all registered document views
*/
public Set<DocumentView> getDocumentViews() {
return documentViews;
}
/**
* Enables/disables a specific action
* @param actionId ID of the action
* @param enable <code>true</code> to enable; <code>false</code> to disable
*/
public void enableAction(String actionId, boolean enable) {
mainWindow.getToolbar().setEnabled(actionId, enable);
}
/**
* Checks the toolbar button that corresponds to the given action (checked usually means lowered)
* @param actionId ID of the button action
* @param check <code>true</code> to check (lower); <code>false</code> for normal state (raised)
*/
public void checkButtonForAction(String actionId, boolean check) {
mainWindow.getToolbar().setChecked(actionId, check);
}
/**
* Sets the display mode of all document views.
* @param mode New display mode (see DocumentView.DISPLAYMODE_... constants)
*/
public void setDisplayMode(int mode) {
for (Iterator<DocumentView> it = documentViews.iterator(); it.hasNext(); ) {
it.next().setDisplayMode(mode);
}
}
/**
* Refreshes document views.
* @param mode New display mode (see DocumentView.DISPLAYMODE_... constants)
*/
public void refreshViews() {
for (Iterator<DocumentView> it = documentViews.iterator(); it.hasNext(); ) {
it.next().refresh();
}
}
/**
* Returns the XML loader that is used for page XML files
* @return
*/
public XmlDocumentLayoutLoader getXmlLoader() {
return xmlLoader;
}
/**
* Returns the current image file path
* @return File path or <code>null</code>
*/
public String getImageFilePath() {
if (imageFilePath != null)
return imageFilePath;
return xmlLoader.getImageFilePath();
}
/**
* Sets the current image file path
* @param imageFilePath File path or <code>null</code>
*/
public void setImageFilePath(String imageFilePath) {
this.imageFilePath = imageFilePath;
}
}
| apache-2.0 |
UniversityOfWuerzburg-ChairCompSciVI/ueps | src/main/java/de/uniwue/info6/database/map/UserResult.java | 4063 | package de.uniwue.info6.database.map;
/*
* #%L
* ************************************************************************
* ORGANIZATION : Institute of Computer Science, University of Wuerzburg
* PROJECT : UEPS - Uebungs-Programm fuer SQL
* FILENAME : UserResult.java
* ************************************************************************
* %%
* Copyright (C) 2014 - 2015 Institute of Computer Science, University of Wuerzburg
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
// Generated Oct 30, 2013 2:01:27 PM by Hibernate Tools 4.0.0
import java.util.Date;
import de.uniwue.info6.database.map.daos.UserResultDao;
/**
* UserResult generated by hbm2java
*/
public class UserResult implements java.io.Serializable {
// ******************************************************************
// custom (not generated methods)
// ******************************************************************
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof UserResult)) {
return false;
}
UserResult other = (UserResult) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
// ******************************************************************
// generated methods of hibernate
// ******************************************************************
private Integer id;
private UserEntry userEntry;
private User user;
private SolutionQuery solutionQuery;
private byte credits;
private Date lastModified;
private String comment;
public UserResult() {
}
public UserResult(UserEntry userEntry, byte credits, Date lastModified) {
this.userEntry = userEntry;
this.credits = credits;
this.lastModified = lastModified;
}
public UserResult(UserEntry userEntry, User user, SolutionQuery solutionQuery, byte credits, Date lastModified,
String comment) {
this.userEntry = userEntry;
this.user = user;
this.solutionQuery = solutionQuery;
this.credits = credits;
this.lastModified = lastModified;
this.comment = comment;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public UserEntry getUserEntry() {
return this.userEntry;
}
public void setUserEntry(UserEntry userEntry) {
this.userEntry = userEntry;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public SolutionQuery getSolutionQuery() {
return this.solutionQuery;
}
public void setSolutionQuery(SolutionQuery solutionQuery) {
this.solutionQuery = solutionQuery;
}
public byte getCredits() {
return this.credits;
}
public void setCredits(byte credits) {
this.credits = credits;
}
public Date getLastModified() {
return this.lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public String getComment() {
return this.comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public UserResult pull() {
return new UserResultDao().getById(getId());
}
}
| apache-2.0 |
fdondorf/SpontaneousRunningServer | src/main/java/org/spontaneous/server/usermanagement/dao/UserRepository.java | 373 | package org.spontaneous.server.usermanagement.dao;
import java.util.List;
import org.spontaneous.server.usermanagement.entity.UserEntity;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<UserEntity, Long>{
UserEntity findByEmail(String email);
List<UserEntity> findByLastName(String lastname);
}
| apache-2.0 |
mylovemaliang/newBmAndroid | app/src/main/java/cn/fuyoushuo/fqbb/view/Layout/MyLinearLayout.java | 2041 | package cn.fuyoushuo.fqbb.view.Layout;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.widget.LinearLayout;
public class MyLinearLayout extends LinearLayout {
private static String TAG = "MyLinearLayout";
private int DRAG_X_THROD = 0;
private int SCROLL_X = 0;
public MyLinearLayout(Context context) {
super(context);
//判断横划的阈值,为了兼容不同尺寸的设备,以dp为单位
DRAG_X_THROD = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, context.getResources().getDisplayMetrics());
SCROLL_X = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, context.getResources().getDisplayMetrics());
}
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
//判断横划的阈值,为了兼容不同尺寸的设备,以dp为单位
DRAG_X_THROD = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, context.getResources().getDisplayMetrics());
SCROLL_X = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, context.getResources().getDisplayMetrics());
}
public MyLinearLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
//判断横划的阈值,为了兼容不同尺寸的设备,以dp为单位
DRAG_X_THROD = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, context.getResources().getDisplayMetrics());
SCROLL_X = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, context.getResources().getDisplayMetrics());
}
int downX, downY;
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = (int) event.getX();
downY = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
return true;
case MotionEvent.ACTION_UP:
break;
default:
break;
}
return super.dispatchTouchEvent(event);
}
}
| apache-2.0 |
kpavlov/fixio | core/src/test/java/fixio/fixprotocol/fields/UTCTimestampFieldTest.java | 6496 | /*
* Copyright 2014 The FIX.io Project
*
* The FIX.io Project 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 fixio.fixprotocol.fields;
import fixio.netty.pipeline.FixClock;
import org.junit.Test;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoField;
import java.util.Random;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class UTCTimestampFieldTest {
public static final int MILLIS = 537;
public static final int MICROS = 537123;
public static final int NANOS = 537123456;
public static final long PICOS = 537123456987L; // java time does not support picos
//
private static final String TIMESTAMP_NO_MILLIS = "19980604-08:03:31";
private static final String TIMESTAMP_WITH_MILLIS = TIMESTAMP_NO_MILLIS+"."+MILLIS;
private static final String TIMESTAMP_WITH_MICROS = TIMESTAMP_NO_MILLIS+"."+MICROS;
private static final String TIMESTAMP_WITH_NANOS = TIMESTAMP_NO_MILLIS+"."+NANOS;
private static final String TIMESTAMP_WITH_PICOS = TIMESTAMP_NO_MILLIS+"."+PICOS;
//
private final ZonedDateTime testDate = ZonedDateTime.of(LocalDate.of(1998, 6, 4), LocalTime.of(8, 3, 31), FixClock.systemUTC().getZone());
private final ZonedDateTime testDateWithMillis = testDate.plus(MILLIS, ChronoField.MILLI_OF_DAY.getBaseUnit());
private final ZonedDateTime testDateWithMicros = testDate.plus(MICROS, ChronoField.MICRO_OF_DAY.getBaseUnit());
private final ZonedDateTime testDateWithNanos = testDate.plusNanos(NANOS);
@Test
public void testParseNoMillis() throws Exception {
assertEquals(testDate, UTCTimestampField.parse(TIMESTAMP_NO_MILLIS.getBytes()));
}
@Test
public void testParseWithMillis() throws Exception {
assertEquals(testDateWithMillis, UTCTimestampField.parse((TIMESTAMP_WITH_MILLIS.getBytes())));
}
@Test
public void testParseWithMicros() throws Exception {
assertEquals(testDateWithMicros, UTCTimestampField.parse((TIMESTAMP_WITH_MICROS.getBytes())));
}
@Test
public void testParseWithNanos() throws Exception {
assertEquals(testDateWithNanos, UTCTimestampField.parse((TIMESTAMP_WITH_NANOS.getBytes())));
}
@Test
public void testParseWithPicos() throws Exception {
// pico are not supported, expect last 3 digits to be truncated
assertEquals(testDateWithNanos, UTCTimestampField.parse((TIMESTAMP_WITH_PICOS.getBytes())));
}
/// testCreate ////////////////
@Test
public void testCreateNoMillis() throws Exception {
int tag = new Random().nextInt();
byte[] bytes = TIMESTAMP_NO_MILLIS.getBytes();
UTCTimestampField field = new UTCTimestampField(tag, bytes, 0, bytes.length);
assertEquals(testDate, field.getValue());
}
@Test
public void testCreateWithMillis() throws Exception {
int tag = new Random().nextInt();
byte[] bytes = TIMESTAMP_WITH_MILLIS.getBytes();
UTCTimestampField field = new UTCTimestampField(tag, bytes, 0, bytes.length);
assertEquals(testDateWithMillis, field.getValue());
}
@Test
public void testCreateWithMicros() throws Exception {
int tag = new Random().nextInt();
byte[] bytes = TIMESTAMP_WITH_MICROS.getBytes();
UTCTimestampField field = new UTCTimestampField(tag, bytes, 0, bytes.length);
assertEquals(testDateWithMicros, field.getValue());
}
@Test
public void testCreateWithNanos() throws Exception {
int tag = new Random().nextInt();
byte[] bytes = TIMESTAMP_WITH_NANOS.getBytes();
UTCTimestampField field = new UTCTimestampField(tag, bytes, 0, bytes.length);
assertEquals(testDateWithNanos, field.getValue());
}
@Test
public void testCreateWithPicos() throws Exception {
int tag = new Random().nextInt();
byte[] bytes = TIMESTAMP_WITH_PICOS.getBytes();
UTCTimestampField field = new UTCTimestampField(tag, bytes, 0, bytes.length);
// pico are not supported, expect last 3 digits to be truncated
assertEquals(testDateWithNanos, field.getValue());
}
/// testGetBytes ////////////////
@Test
public void testGetBytesNoMillis() throws Exception {
int tag = new Random().nextInt();
byte[] bytes = TIMESTAMP_NO_MILLIS.getBytes();
UTCTimestampField field = new UTCTimestampField(tag, bytes, 0, bytes.length);
assertArrayEquals(bytes, field.getBytes());
}
@Test
public void testGetBytesWithMillis() throws Exception {
int tag = new Random().nextInt();
byte[] bytes = TIMESTAMP_WITH_MILLIS.getBytes();
UTCTimestampField field = new UTCTimestampField(tag, bytes, 0, bytes.length);
assertArrayEquals(bytes, field.getBytes());
}
@Test
public void testGetBytesMicros() throws Exception {
int tag = new Random().nextInt();
byte[] bytes = TIMESTAMP_WITH_MICROS.getBytes();
UTCTimestampField field = new UTCTimestampField(tag, bytes, 0, bytes.length);
assertArrayEquals(bytes, field.getBytes());
}
@Test
public void testGetBytesNanos() throws Exception {
int tag = new Random().nextInt();
byte[] bytes = TIMESTAMP_WITH_NANOS.getBytes();
UTCTimestampField field = new UTCTimestampField(tag, bytes, 0, bytes.length);
assertArrayEquals(bytes, field.getBytes());
}
@Test
public void testGetBytesPicos() throws Exception {
int tag = new Random().nextInt();
byte[] bytes = TIMESTAMP_WITH_PICOS.getBytes();
UTCTimestampField field = new UTCTimestampField(tag, bytes, 0, bytes.length);
// pico are not supported, expect last 3 digits to be truncated
byte[] nanosBytes = (TIMESTAMP_WITH_NANOS+"000").getBytes();
assertArrayEquals(nanosBytes, field.getBytes());
}
}
| apache-2.0 |
anupcshan/bazel | src/main/java/com/google/devtools/build/lib/rules/cpp/CppCompilationContext.java | 42129 | // Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.cpp;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.ActionOwner;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.MiddlemanFactory;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.TransitiveInfoProvider;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.util.Pair;
import com.google.devtools.build.lib.util.Preconditions;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* Immutable store of information needed for C++ compilation that is aggregated
* across dependencies.
*/
@Immutable
public final class CppCompilationContext implements TransitiveInfoProvider {
/** An empty compilation context. */
public static final CppCompilationContext EMPTY = new Builder(null).build();
private final CommandLineContext commandLineContext;
private final ImmutableList<DepsContext> depsContexts;
private final CppModuleMap cppModuleMap;
private final Artifact headerModule;
private final Artifact picHeaderModule;
// True if this context is for a compilation that needs transitive module maps.
private final boolean provideTransitiveModuleMaps;
// True if this context is for a compilation that should use header modules from dependencies.
private final boolean useHeaderModules;
// Derived from depsContexts; no need to consider it for equals/hashCode.
private final ImmutableSet<Artifact> compilationPrerequisites;
private CppCompilationContext(
CommandLineContext commandLineContext,
List<DepsContext> depsContexts,
CppModuleMap cppModuleMap,
Artifact headerModule,
Artifact picHeaderModule,
boolean provideTransitiveModuleMaps,
boolean useHeaderModules) {
Preconditions.checkNotNull(commandLineContext);
Preconditions.checkArgument(!depsContexts.isEmpty());
this.commandLineContext = commandLineContext;
this.depsContexts = ImmutableList.copyOf(depsContexts);
this.cppModuleMap = cppModuleMap;
this.headerModule = headerModule;
this.picHeaderModule = picHeaderModule;
this.provideTransitiveModuleMaps = provideTransitiveModuleMaps;
this.useHeaderModules = useHeaderModules;
if (depsContexts.size() == 1) {
// Only LIPO targets have more than one DepsContexts. This codepath avoids creating
// an ImmutableSet.Builder for the vast majority of the cases.
compilationPrerequisites = (depsContexts.get(0).compilationPrerequisiteStampFile != null)
? ImmutableSet.<Artifact>of(depsContexts.get(0).compilationPrerequisiteStampFile)
: ImmutableSet.<Artifact>of();
} else {
ImmutableSet.Builder<Artifact> prerequisites = ImmutableSet.builder();
for (DepsContext depsContext : depsContexts) {
if (depsContext.compilationPrerequisiteStampFile != null) {
prerequisites.add(depsContext.compilationPrerequisiteStampFile);
}
}
compilationPrerequisites = prerequisites.build();
}
}
/**
* Returns the transitive compilation prerequisites consolidated into middlemen
* prerequisites, or an empty set if there are no prerequisites.
*
* <p>Transitive compilation prerequisites are the prerequisites that will be needed by all
* reverse dependencies; note that these do specifically not include any compilation prerequisites
* that are only needed by the rule itself (for example, compiled source files from the
* {@code srcs} attribute).
*
* <p>To reduce the number of edges in the action graph, we express the dependency on compilation
* prerequisites as a transitive dependency via a middleman.
* After they have been accumulated (using
* {@link Builder#addCompilationPrerequisites(Iterable)},
* {@link Builder#mergeDependentContext(CppCompilationContext)}, and
* {@link Builder#mergeDependentContexts(Iterable)}, they are consolidated
* into a single middleman Artifact when {@link Builder#build()} is called.
*
* <p>The returned set can be empty if there are no prerequisites. Usually it
* contains a single middleman, but if LIPO is used there can be two.
*/
public ImmutableSet<Artifact> getTransitiveCompilationPrerequisites() {
return compilationPrerequisites;
}
/**
* Returns the immutable list of include directories to be added with "-I"
* (possibly empty but never null). This includes the include dirs from the
* transitive deps closure of the target. This list does not contain
* duplicates. All fragments are either absolute or relative to the exec root
* (see {@link com.google.devtools.build.lib.analysis.BlazeDirectories#getExecRoot}).
*/
public ImmutableList<PathFragment> getIncludeDirs() {
return commandLineContext.includeDirs;
}
/**
* Returns the immutable list of include directories to be added with
* "-iquote" (possibly empty but never null). This includes the include dirs
* from the transitive deps closure of the target. This list does not contain
* duplicates. All fragments are either absolute or relative to the exec root
* (see {@link com.google.devtools.build.lib.analysis.BlazeDirectories#getExecRoot}).
*/
public ImmutableList<PathFragment> getQuoteIncludeDirs() {
return commandLineContext.quoteIncludeDirs;
}
/**
* Returns the immutable list of include directories to be added with
* "-isystem" (possibly empty but never null). This includes the include dirs
* from the transitive deps closure of the target. This list does not contain
* duplicates. All fragments are either absolute or relative to the exec root
* (see {@link com.google.devtools.build.lib.analysis.BlazeDirectories#getExecRoot}).
*/
public ImmutableList<PathFragment> getSystemIncludeDirs() {
return commandLineContext.systemIncludeDirs;
}
/**
* Returns the immutable set of declared include directories, relative to a
* "-I" or "-iquote" directory" (possibly empty but never null). The returned
* collection may contain duplicate elements.
*
* <p>Note: The iteration order of this list is preserved as ide_build_info
* writes these directories and sources out and the ordering will help when
* used by consumers.
*/
public NestedSet<PathFragment> getDeclaredIncludeDirs() {
if (depsContexts.isEmpty()) {
return NestedSetBuilder.emptySet(Order.STABLE_ORDER);
}
if (depsContexts.size() == 1) {
return depsContexts.get(0).declaredIncludeDirs;
}
NestedSetBuilder<PathFragment> builder = NestedSetBuilder.stableOrder();
for (DepsContext depsContext : depsContexts) {
builder.addTransitive(depsContext.declaredIncludeDirs);
}
return builder.build();
}
/**
* Returns the immutable set of include directories, relative to a "-I" or
* "-iquote" directory", from which inclusion will produce a warning (possibly
* empty but never null). The returned collection may contain duplicate
* elements.
*
* <p>Note: The iteration order of this list is preserved as ide_build_info
* writes these directories and sources out and the ordering will help when
* used by consumers.
*/
public NestedSet<PathFragment> getDeclaredIncludeWarnDirs() {
if (depsContexts.isEmpty()) {
return NestedSetBuilder.emptySet(Order.STABLE_ORDER);
}
if (depsContexts.size() == 1) {
return depsContexts.get(0).declaredIncludeWarnDirs;
}
NestedSetBuilder<PathFragment> builder = NestedSetBuilder.stableOrder();
for (DepsContext depsContext : depsContexts) {
builder.addTransitive(depsContext.declaredIncludeWarnDirs);
}
return builder.build();
}
/**
* Returns the immutable set of headers that have been declared in the
* {@code src} or {@code headers attribute} (possibly empty but never null).
* The returned collection may contain duplicate elements.
*
* <p>Note: The iteration order of this list is preserved as ide_build_info
* writes these directories and sources out and the ordering will help when
* used by consumers.
*/
public NestedSet<Artifact> getDeclaredIncludeSrcs() {
if (depsContexts.isEmpty()) {
return NestedSetBuilder.emptySet(Order.STABLE_ORDER);
}
if (depsContexts.size() == 1) {
return depsContexts.get(0).declaredIncludeSrcs;
}
NestedSetBuilder<Artifact> builder = NestedSetBuilder.stableOrder();
for (DepsContext depsContext : depsContexts) {
builder.addTransitive(depsContext.declaredIncludeSrcs);
}
return builder.build();
}
/**
* Returns the immutable pairs of (header file, pregrepped header file). The value artifacts
* (pregrepped header file) are generated by {@link ExtractInclusionAction}.
*/
NestedSet<Pair<Artifact, Artifact>> getPregreppedHeaders() {
if (depsContexts.isEmpty()) {
return NestedSetBuilder.emptySet(Order.STABLE_ORDER);
}
if (depsContexts.size() == 1) {
return depsContexts.get(0).pregreppedHdrs;
}
NestedSetBuilder<Pair<Artifact, Artifact>> builder = NestedSetBuilder.stableOrder();
for (DepsContext depsContext : depsContexts) {
builder.addTransitive(depsContext.pregreppedHdrs);
}
return builder.build();
}
/**
* Returns the immutable set of additional transitive inputs needed for
* compilation, like C++ module map artifacts.
*/
public NestedSet<Artifact> getAdditionalInputs(boolean usePic) {
if (depsContexts.isEmpty()) {
return NestedSetBuilder.emptySet(Order.STABLE_ORDER);
}
NestedSetBuilder<Artifact> builder = NestedSetBuilder.stableOrder();
for (DepsContext depsContext : depsContexts) {
if (useHeaderModules) {
if (usePic) {
builder.addTransitive(depsContext.picTopLevelHeaderModules);
builder.addTransitive(depsContext.picImpliedHeaderModules);
} else {
builder.addTransitive(depsContext.topLevelHeaderModules);
builder.addTransitive(depsContext.impliedHeaderModules);
}
}
builder.addTransitive(depsContext.directModuleMaps);
if (provideTransitiveModuleMaps) {
builder.addTransitive(depsContext.transitiveModuleMaps);
}
}
if (cppModuleMap != null) {
builder.add(cppModuleMap.getArtifact());
}
return builder.build();
}
/**
* @return modules maps from direct dependencies.
*/
public NestedSet<Artifact> getDirectModuleMaps() {
NestedSetBuilder<Artifact> builder = NestedSetBuilder.stableOrder();
for (DepsContext depsContext : depsContexts) {
builder.addTransitive(depsContext.directModuleMaps);
}
return builder.build();
}
/**
* @return modules maps in the transitive closure that are not from direct dependencies.
*/
private NestedSet<Artifact> getTransitiveModuleMaps() {
NestedSetBuilder<Artifact> builder = NestedSetBuilder.stableOrder();
for (DepsContext depsContext : depsContexts) {
builder.addTransitive(depsContext.transitiveModuleMaps);
}
return builder.build();
}
/**
* @return all declared headers of the current module if the current target
* is compiled as a module.
*/
protected NestedSet<Artifact> getHeaderModuleSrcs() {
NestedSetBuilder<Artifact> builder = NestedSetBuilder.stableOrder();
for (DepsContext depsContext : depsContexts) {
builder.addTransitive(depsContext.headerModuleSrcs);
}
return builder.build();
}
/**
* @return all header modules in our transitive closure that are not in the transitive closure
* of another header module in our transitive closure.
*/
protected NestedSet<Artifact> getTopLevelHeaderModules(boolean usePic) {
NestedSetBuilder<Artifact> builder = NestedSetBuilder.stableOrder();
for (DepsContext depsContext : depsContexts) {
builder.addTransitive(
usePic ? depsContext.picTopLevelHeaderModules : depsContext.topLevelHeaderModules);
}
return builder.build();
}
/**
* @return all header modules in the transitive closure of {@code getTopLevelHeaderModules()}.
*/
protected NestedSet<Artifact> getImpliedHeaderModules(boolean usePic) {
NestedSetBuilder<Artifact> builder = NestedSetBuilder.stableOrder();
for (DepsContext depsContext : depsContexts) {
builder.addTransitive(
usePic ? depsContext.picImpliedHeaderModules : depsContext.impliedHeaderModules);
}
return builder.build();
}
/**
* Returns the set of defines needed to compile this target (possibly empty
* but never null). This includes definitions from the transitive deps closure
* for the target. The order of the returned collection is deterministic.
*/
public ImmutableList<String> getDefines() {
return commandLineContext.defines;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CppCompilationContext)) {
return false;
}
CppCompilationContext other = (CppCompilationContext) obj;
return Objects.equals(headerModule, other.headerModule)
&& Objects.equals(cppModuleMap, other.cppModuleMap)
&& Objects.equals(picHeaderModule, other.picHeaderModule)
&& commandLineContext.equals(other.commandLineContext)
&& depsContexts.equals(other.depsContexts)
&& (provideTransitiveModuleMaps == other.provideTransitiveModuleMaps)
&& (useHeaderModules == other.useHeaderModules);
}
@Override
public int hashCode() {
return Objects.hash(
headerModule,
picHeaderModule,
commandLineContext,
depsContexts,
cppModuleMap,
provideTransitiveModuleMaps,
useHeaderModules);
}
/**
* Returns a context that is based on a given context but returns empty sets
* for {@link #getDeclaredIncludeDirs()} and {@link #getDeclaredIncludeWarnDirs()}.
*/
public static CppCompilationContext disallowUndeclaredHeaders(CppCompilationContext context) {
ImmutableList.Builder<DepsContext> builder = ImmutableList.builder();
for (DepsContext depsContext : context.depsContexts) {
builder.add(
new DepsContext(
depsContext.compilationPrerequisiteStampFile,
NestedSetBuilder.<PathFragment>emptySet(Order.STABLE_ORDER),
NestedSetBuilder.<PathFragment>emptySet(Order.STABLE_ORDER),
depsContext.declaredIncludeSrcs,
depsContext.pregreppedHdrs,
depsContext.headerModuleSrcs,
depsContext.topLevelHeaderModules,
depsContext.picTopLevelHeaderModules,
depsContext.impliedHeaderModules,
depsContext.picImpliedHeaderModules,
depsContext.transitiveModuleMaps,
depsContext.directModuleMaps));
}
return new CppCompilationContext(
context.commandLineContext,
builder.build(),
context.cppModuleMap,
context.headerModule,
context.picHeaderModule,
context.provideTransitiveModuleMaps,
context.useHeaderModules);
}
/**
* Returns the context for a LIPO compile action. This uses the include dirs
* and defines of the library, but the declared inclusion dirs/srcs from both
* the library and the owner binary.
*
* <p>TODO(bazel-team): this might make every LIPO target have an unnecessary large set of
* inclusion dirs/srcs. The correct behavior would be to merge only the contexts
* of actual referred targets (as listed in .imports file).
*
* <p>Undeclared inclusion checking ({@link #getDeclaredIncludeDirs()},
* {@link #getDeclaredIncludeWarnDirs()}, and
* {@link #getDeclaredIncludeSrcs()}) needs to use the union of the contexts
* of the involved source files.
*
* <p>For include and define command line flags ({@link #getIncludeDirs()}
* {@link #getQuoteIncludeDirs()}, {@link #getSystemIncludeDirs()}, and
* {@link #getDefines()}) LIPO compilations use the same values as non-LIPO
* compilation.
*
* <p>Include scanning is not handled by this method. See
* {@code IncludeScannable#getAuxiliaryScannables()} instead.
*
* @param ownerContext the compilation context of the owner binary
* @param libContext the compilation context of the library
*/
public static CppCompilationContext mergeForLipo(CppCompilationContext ownerContext,
CppCompilationContext libContext) {
return new CppCompilationContext(
libContext.commandLineContext,
ImmutableList.copyOf(Iterables.concat(ownerContext.depsContexts, libContext.depsContexts)),
libContext.cppModuleMap,
libContext.headerModule,
libContext.picHeaderModule,
/*providesTransitiveModuleMaps=*/ false,
/*useHeaderModules=*/ false);
}
/**
* @return the C++ module map of the owner.
*/
public CppModuleMap getCppModuleMap() {
return cppModuleMap;
}
/**
* @return the non-pic C++ header module of the owner.
*/
private Artifact getHeaderModule() {
return headerModule;
}
/**
* @return the pic C++ header module of the owner.
*/
private Artifact getPicHeaderModule() {
return picHeaderModule;
}
/**
* The parts of the compilation context that influence the command line of
* compilation actions.
*/
@Immutable
private static class CommandLineContext {
private final ImmutableList<PathFragment> includeDirs;
private final ImmutableList<PathFragment> quoteIncludeDirs;
private final ImmutableList<PathFragment> systemIncludeDirs;
private final ImmutableList<String> defines;
CommandLineContext(ImmutableList<PathFragment> includeDirs,
ImmutableList<PathFragment> quoteIncludeDirs,
ImmutableList<PathFragment> systemIncludeDirs,
ImmutableList<String> defines) {
this.includeDirs = includeDirs;
this.quoteIncludeDirs = quoteIncludeDirs;
this.systemIncludeDirs = systemIncludeDirs;
this.defines = defines;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CommandLineContext)) {
return false;
}
CommandLineContext other = (CommandLineContext) obj;
return Objects.equals(includeDirs, other.includeDirs)
&& Objects.equals(quoteIncludeDirs, other.quoteIncludeDirs)
&& Objects.equals(systemIncludeDirs, other.systemIncludeDirs)
&& Objects.equals(defines, other.defines);
}
@Override
public int hashCode() {
return Objects.hash(includeDirs, quoteIncludeDirs, systemIncludeDirs, defines);
}
}
/**
* The parts of the compilation context that defined the dependencies of
* actions of scheduling and inclusion validity checking.
*/
@Immutable
private static class DepsContext {
private final Artifact compilationPrerequisiteStampFile;
private final NestedSet<PathFragment> declaredIncludeDirs;
private final NestedSet<PathFragment> declaredIncludeWarnDirs;
private final NestedSet<Artifact> declaredIncludeSrcs;
/**
* Module maps from direct dependencies.
*/
private final NestedSet<Artifact> directModuleMaps;
/**
* All declared headers of the current module, if compiled as a header module.
*/
private final NestedSet<Artifact> headerModuleSrcs;
/**
* All header modules in the transitive closure of {@code topLevelHeaderModules}.
*/
private final NestedSet<Artifact> impliedHeaderModules;
private final NestedSet<Artifact> picImpliedHeaderModules;
private final NestedSet<Pair<Artifact, Artifact>> pregreppedHdrs;
/**
* All header modules in our transitive closure that are not in the transitive closure of
* another header module in our transitive closure.
*/
private final NestedSet<Artifact> topLevelHeaderModules;
private final NestedSet<Artifact> picTopLevelHeaderModules;
/**
* The module maps from all targets the current target depends on transitively.
*/
private final NestedSet<Artifact> transitiveModuleMaps;
DepsContext(
Artifact compilationPrerequisiteStampFile,
NestedSet<PathFragment> declaredIncludeDirs,
NestedSet<PathFragment> declaredIncludeWarnDirs,
NestedSet<Artifact> declaredIncludeSrcs,
NestedSet<Pair<Artifact, Artifact>> pregreppedHdrs,
NestedSet<Artifact> headerModuleSrcs,
NestedSet<Artifact> topLevelHeaderModules,
NestedSet<Artifact> picTopLevelHeaderModules,
NestedSet<Artifact> impliedHeaderModules,
NestedSet<Artifact> picImpliedHeaderModules,
NestedSet<Artifact> transitiveModuleMaps,
NestedSet<Artifact> directModuleMaps) {
this.compilationPrerequisiteStampFile = compilationPrerequisiteStampFile;
this.declaredIncludeDirs = declaredIncludeDirs;
this.declaredIncludeWarnDirs = declaredIncludeWarnDirs;
this.declaredIncludeSrcs = declaredIncludeSrcs;
this.directModuleMaps = directModuleMaps;
this.headerModuleSrcs = headerModuleSrcs;
this.impliedHeaderModules = impliedHeaderModules;
this.picImpliedHeaderModules = picImpliedHeaderModules;
this.pregreppedHdrs = pregreppedHdrs;
this.topLevelHeaderModules = topLevelHeaderModules;
this.picTopLevelHeaderModules = picTopLevelHeaderModules;
this.transitiveModuleMaps = transitiveModuleMaps;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof DepsContext)) {
return false;
}
DepsContext other = (DepsContext) obj;
return Objects.equals(
compilationPrerequisiteStampFile, other.compilationPrerequisiteStampFile)
&& Objects.equals(declaredIncludeDirs, other.declaredIncludeDirs)
&& Objects.equals(declaredIncludeWarnDirs, other.declaredIncludeWarnDirs)
&& Objects.equals(declaredIncludeSrcs, other.declaredIncludeSrcs)
&& Objects.equals(directModuleMaps, other.directModuleMaps)
&& Objects.equals(headerModuleSrcs, other.headerModuleSrcs)
&& Objects.equals(impliedHeaderModules, other.impliedHeaderModules)
&& Objects.equals(picImpliedHeaderModules, other.picImpliedHeaderModules)
// TODO(bazel-team): add pregreppedHdrs?
&& Objects.equals(topLevelHeaderModules, other.topLevelHeaderModules)
&& Objects.equals(picTopLevelHeaderModules, other.picTopLevelHeaderModules)
&& Objects.equals(transitiveModuleMaps, other.transitiveModuleMaps);
}
@Override
public int hashCode() {
return Objects.hash(
compilationPrerequisiteStampFile,
declaredIncludeDirs,
declaredIncludeWarnDirs,
declaredIncludeSrcs,
directModuleMaps,
headerModuleSrcs,
impliedHeaderModules,
picImpliedHeaderModules,
// pregreppedHdrs ?
transitiveModuleMaps,
topLevelHeaderModules,
picTopLevelHeaderModules);
}
}
/**
* Builder class for {@link CppCompilationContext}.
*/
public static class Builder {
private String purpose;
private final Set<Artifact> compilationPrerequisites = new LinkedHashSet<>();
private final Set<PathFragment> includeDirs = new LinkedHashSet<>();
private final Set<PathFragment> quoteIncludeDirs = new LinkedHashSet<>();
private final Set<PathFragment> systemIncludeDirs = new LinkedHashSet<>();
private final NestedSetBuilder<PathFragment> declaredIncludeDirs =
NestedSetBuilder.stableOrder();
private final NestedSetBuilder<PathFragment> declaredIncludeWarnDirs =
NestedSetBuilder.stableOrder();
private final NestedSetBuilder<Artifact> declaredIncludeSrcs =
NestedSetBuilder.stableOrder();
private final NestedSetBuilder<Pair<Artifact, Artifact>> pregreppedHdrs =
NestedSetBuilder.stableOrder();
private final NestedSetBuilder<Artifact> headerModuleSrcs =
NestedSetBuilder.stableOrder();
private final NestedSetBuilder<Artifact> topLevelHeaderModules =
NestedSetBuilder.stableOrder();
private final NestedSetBuilder<Artifact> picTopLevelHeaderModules =
NestedSetBuilder.stableOrder();
private final NestedSetBuilder<Artifact> impliedHeaderModules =
NestedSetBuilder.stableOrder();
private final NestedSetBuilder<Artifact> picImpliedHeaderModules =
NestedSetBuilder.stableOrder();
private final NestedSetBuilder<Artifact> transitiveModuleMaps =
NestedSetBuilder.stableOrder();
private final NestedSetBuilder<Artifact> directModuleMaps =
NestedSetBuilder.stableOrder();
private final Set<String> defines = new LinkedHashSet<>();
private CppModuleMap cppModuleMap;
private Artifact headerModule;
private Artifact picHeaderModule;
private boolean provideTransitiveModuleMaps = false;
private boolean useHeaderModules = false;
/** The rule that owns the context */
private final RuleContext ruleContext;
/**
* Creates a new builder for a {@link CppCompilationContext} instance.
*/
public Builder(RuleContext ruleContext) {
this(ruleContext, /*forInterface=*/ false);
}
/**
* Creates a new builder for a {@link CppCompilationContext} instance.
*
* @param forInterface if true, this context is designated for the compilation of an interface.
*/
public Builder(RuleContext ruleContext, boolean forInterface) {
this.ruleContext = ruleContext;
this.purpose = forInterface ? "cpp_interface_prerequisites" : "cpp_compilation_prerequisites";
}
/**
* Overrides the purpose of this context. This is useful if a Target
* needs more than one CppCompilationContext. (The purpose is used to
* construct the name of the prerequisites middleman for the context, and
* all artifacts for a given Target must have distinct names.)
*
* @param purpose must be a string which is suitable for use as a filename.
* A single rule may have many middlemen with distinct purposes.
*
* @see MiddlemanFactory#createErrorPropagatingMiddleman
*/
public Builder setPurpose(String purpose) {
this.purpose = purpose;
return this;
}
public String getPurpose() {
return purpose;
}
/**
* Merges the context of a dependency into this one by adding the contents
* of all of its attributes.
*/
public Builder mergeDependentContext(CppCompilationContext otherContext) {
Preconditions.checkNotNull(otherContext);
compilationPrerequisites.addAll(otherContext.getTransitiveCompilationPrerequisites());
includeDirs.addAll(otherContext.getIncludeDirs());
quoteIncludeDirs.addAll(otherContext.getQuoteIncludeDirs());
systemIncludeDirs.addAll(otherContext.getSystemIncludeDirs());
declaredIncludeDirs.addTransitive(otherContext.getDeclaredIncludeDirs());
declaredIncludeWarnDirs.addTransitive(otherContext.getDeclaredIncludeWarnDirs());
declaredIncludeSrcs.addTransitive(otherContext.getDeclaredIncludeSrcs());
pregreppedHdrs.addTransitive(otherContext.getPregreppedHeaders());
NestedSet<Artifact> othersTransitiveModuleMaps = otherContext.getTransitiveModuleMaps();
NestedSet<Artifact> othersDirectModuleMaps = otherContext.getDirectModuleMaps();
NestedSet<Artifact> othersTopLevelHeaderModules =
otherContext.getTopLevelHeaderModules(/*usePic=*/ false);
NestedSet<Artifact> othersPicTopLevelHeaderModules =
otherContext.getTopLevelHeaderModules(/*usePic=*/ true);
// Forward transitive information.
// The other target's transitive module maps do not include its direct module maps, so we
// add both.
transitiveModuleMaps.addTransitive(othersTransitiveModuleMaps);
transitiveModuleMaps.addTransitive(othersDirectModuleMaps);
impliedHeaderModules.addTransitive(otherContext.getImpliedHeaderModules(/*usePic=*/ false));
picImpliedHeaderModules.addTransitive(otherContext.getImpliedHeaderModules(/*usePic=*/ true));
topLevelHeaderModules.addTransitive(othersTopLevelHeaderModules);
picTopLevelHeaderModules.addTransitive(othersPicTopLevelHeaderModules);
// All module maps of direct dependencies are inputs to the current compile independently of
// the build type.
if (otherContext.getCppModuleMap() != null) {
directModuleMaps.add(otherContext.getCppModuleMap().getArtifact());
}
if (otherContext.getHeaderModule() != null || otherContext.getPicHeaderModule() != null) {
// If the other context is for a target that compiles a header module, that context's
// header module becomes our top-level header module, and its top-level header modules
// become our implied header modules.
impliedHeaderModules.addTransitive(othersTopLevelHeaderModules);
picImpliedHeaderModules.addTransitive(othersPicTopLevelHeaderModules);
if (otherContext.getHeaderModule() != null) {
topLevelHeaderModules.add(otherContext.getHeaderModule());
}
if (otherContext.getPicHeaderModule() != null) {
picTopLevelHeaderModules.add(otherContext.getPicHeaderModule());
}
}
defines.addAll(otherContext.getDefines());
return this;
}
/**
* Merges the context of some targets into this one by adding the contents
* of all of their attributes. Targets that do not implement
* {@link CppCompilationContext} are ignored.
*/
public Builder mergeDependentContexts(Iterable<CppCompilationContext> targets) {
for (CppCompilationContext target : targets) {
mergeDependentContext(target);
}
return this;
}
/**
* Adds multiple compilation prerequisites.
*/
public Builder addCompilationPrerequisites(Iterable<Artifact> prerequisites) {
// LIPO collector must not add compilation prerequisites in order to avoid
// the creation of a middleman action.
Iterables.addAll(compilationPrerequisites, prerequisites);
return this;
}
/**
* Add a single include directory to be added with "-I". It can be either
* relative to the exec root (see {@link BuildConfiguration#getExecRoot}) or
* absolute. Before it is stored, the include directory is normalized.
*/
public Builder addIncludeDir(PathFragment includeDir) {
includeDirs.add(includeDir.normalize());
return this;
}
/**
* Add multiple include directories to be added with "-I". These can be
* either relative to the exec root (see {@link
* BuildConfiguration#getExecRoot}) or absolute. The entries are normalized
* before they are stored.
*/
public Builder addIncludeDirs(Iterable<PathFragment> includeDirs) {
for (PathFragment includeDir : includeDirs) {
addIncludeDir(includeDir);
}
return this;
}
/**
* Add a single include directory to be added with "-iquote". It can be
* either relative to the exec root (see {@link
* BuildConfiguration#getExecRoot}) or absolute. Before it is stored, the
* include directory is normalized.
*/
public Builder addQuoteIncludeDir(PathFragment quoteIncludeDir) {
quoteIncludeDirs.add(quoteIncludeDir.normalize());
return this;
}
/**
* Add a single include directory to be added with "-isystem". It can be
* either relative to the exec root (see {@link
* BuildConfiguration#getExecRoot}) or absolute. Before it is stored, the
* include directory is normalized.
*/
public Builder addSystemIncludeDir(PathFragment systemIncludeDir) {
systemIncludeDirs.add(systemIncludeDir.normalize());
return this;
}
/**
* Add a single declared include dir, relative to a "-I" or "-iquote"
* directory".
*/
public Builder addDeclaredIncludeDir(PathFragment dir) {
declaredIncludeDirs.add(dir);
return this;
}
/**
* Add a single declared include directory, relative to a "-I" or "-iquote"
* directory", from which inclusion will produce a warning.
*/
public Builder addDeclaredIncludeWarnDir(PathFragment dir) {
declaredIncludeWarnDirs.add(dir);
return this;
}
/**
* Adds a header that has been declared in the {@code src} or {@code headers attribute}. The
* header will also be added to the compilation prerequisites.
*/
public Builder addDeclaredIncludeSrc(Artifact header) {
declaredIncludeSrcs.add(header);
compilationPrerequisites.add(header);
headerModuleSrcs.add(header);
return this;
}
/**
* Adds multiple headers that have been declared in the {@code src} or {@code headers
* attribute}. The headers will also be added to the compilation prerequisites.
*/
public Builder addDeclaredIncludeSrcs(Iterable<Artifact> declaredIncludeSrcs) {
this.declaredIncludeSrcs.addAll(declaredIncludeSrcs);
this.headerModuleSrcs.addAll(declaredIncludeSrcs);
return addCompilationPrerequisites(declaredIncludeSrcs);
}
/**
* Add a map of generated source or header Artifact to an output Artifact after grepping
* the file for include statements.
*/
public Builder addPregreppedHeaderMap(Map<Artifact, Artifact> pregrepped) {
addCompilationPrerequisites(pregrepped.values());
for (Map.Entry<Artifact, Artifact> entry : pregrepped.entrySet()) {
this.pregreppedHdrs.add(Pair.of(entry.getKey(), entry.getValue()));
}
return this;
}
/**
* Adds a single define.
*/
public Builder addDefine(String define) {
defines.add(define);
return this;
}
/**
* Adds multiple defines.
*/
public Builder addDefines(Iterable<String> defines) {
Iterables.addAll(this.defines, defines);
return this;
}
/**
* Sets the C++ module map.
*/
public Builder setCppModuleMap(CppModuleMap cppModuleMap) {
this.cppModuleMap = cppModuleMap;
return this;
}
/**
* Sets the C++ header module in non-pic mode.
*/
public Builder setHeaderModule(Artifact headerModule) {
this.headerModule = headerModule;
return this;
}
/**
* Sets the C++ header module in pic mode.
*/
public Builder setPicHeaderModule(Artifact picHeaderModule) {
this.picHeaderModule = picHeaderModule;
return this;
}
/**
* Sets that the context will be used by a compilation that needs transitive module maps.
*/
public Builder setProvideTransitiveModuleMaps(boolean provideTransitiveModuleMaps) {
this.provideTransitiveModuleMaps = provideTransitiveModuleMaps;
return this;
}
/**
* Sets that the context will be used by a compilation that uses header modules provided by
* its dependencies.
*/
public Builder setUseHeaderModules(boolean useHeaderModules) {
this.useHeaderModules = useHeaderModules;
return this;
}
/**
* Builds the {@link CppCompilationContext}.
*/
public CppCompilationContext build() {
return build(
ruleContext == null ? null : ruleContext.getActionOwner(),
ruleContext == null ? null : ruleContext.getAnalysisEnvironment().getMiddlemanFactory());
}
@VisibleForTesting // productionVisibility = Visibility.PRIVATE
public CppCompilationContext build(ActionOwner owner, MiddlemanFactory middlemanFactory) {
// During merging we might have put header modules into topLevelHeaderModules that were
// also in the transitive closure of a different header module; we need to filter those out.
NestedSet<Artifact> impliedHeaderModules = this.impliedHeaderModules.build();
NestedSet<Artifact> topLevelHeaderModules =
filterTopLevelHeaderModules(this.topLevelHeaderModules.build(), impliedHeaderModules);
NestedSet<Artifact> picImpliedHeaderModules = this.picImpliedHeaderModules.build();
NestedSet<Artifact> picTopLevelHeaderModules =
filterTopLevelHeaderModules(
this.picTopLevelHeaderModules.build(), picImpliedHeaderModules);
// We don't create middlemen in LIPO collector subtree, because some target CT
// will do that instead.
Artifact prerequisiteStampFile = (ruleContext != null
&& ruleContext.getFragment(CppConfiguration.class).isLipoContextCollector())
? getMiddlemanArtifact(middlemanFactory)
: createMiddleman(owner, middlemanFactory);
return new CppCompilationContext(
new CommandLineContext(
ImmutableList.copyOf(includeDirs),
ImmutableList.copyOf(quoteIncludeDirs),
ImmutableList.copyOf(systemIncludeDirs),
ImmutableList.copyOf(defines)),
ImmutableList.of(
new DepsContext(
prerequisiteStampFile,
declaredIncludeDirs.build(),
declaredIncludeWarnDirs.build(),
declaredIncludeSrcs.build(),
pregreppedHdrs.build(),
headerModuleSrcs.build(),
topLevelHeaderModules,
picTopLevelHeaderModules,
impliedHeaderModules,
picImpliedHeaderModules,
transitiveModuleMaps.build(),
directModuleMaps.build())),
cppModuleMap,
headerModule,
picHeaderModule,
provideTransitiveModuleMaps,
useHeaderModules);
}
/**
* Filter out artifacts from {@code topLevelHeaderModuels} that are also in
* {@code impliedHeaderModules}.
*/
private static NestedSet<Artifact> filterTopLevelHeaderModules(
NestedSet<Artifact> topLevelHeaderModules, NestedSet<Artifact> impliedHeaderModules) {
NestedSetBuilder<Artifact> filtered = NestedSetBuilder.stableOrder();
Set<Artifact> impliedHeaderModulesSet = impliedHeaderModules.toSet();
for (Artifact artifact : topLevelHeaderModules) {
if (!impliedHeaderModulesSet.contains(artifact)) {
filtered.add(artifact);
}
}
return filtered.build();
}
/**
* Creates a middleman for the compilation prerequisites.
*
* @return the middleman or null if there are no prerequisites
*/
private Artifact createMiddleman(ActionOwner owner,
MiddlemanFactory middlemanFactory) {
if (compilationPrerequisites.isEmpty()) {
return null;
}
// Compilation prerequisites gathered in the compilationPrerequisites
// must be generated prior to executing C++ compilation step that depends
// on them (since these prerequisites include all potential header files, etc
// that could be referenced during compilation). So there is a definite need
// to ensure scheduling edge dependency. However, those prerequisites should
// have no effect on the decision whether C++ compilation should happen in
// the first place - only CppCompileAction outputs (*.o and *.d files) and
// all files referenced by the *.d file should be used to make that decision.
// If this action was never executed, then *.d file would be missing, forcing
// compilation to occur. If *.d file is present and has not changed then the
// only reason that would force us to re-compile would be change in one of
// the files referenced by the *.d file, since no other files participated
// in the compilation. We also need to propagate errors through this
// dependency link. So we use an error propagating middleman.
// Such middleman will be ignored by the dependency checker yet will still
// represent an edge in the action dependency graph - forcing proper execution
// order and error propagation.
return middlemanFactory.createErrorPropagatingMiddleman(
owner, ruleContext.getLabel().toString(), purpose,
ImmutableList.copyOf(compilationPrerequisites),
ruleContext.getConfiguration().getMiddlemanDirectory());
}
/**
* Returns the same set of artifacts as createMiddleman() would, but without
* actually creating middlemen.
*/
private Artifact getMiddlemanArtifact(MiddlemanFactory middlemanFactory) {
if (compilationPrerequisites.isEmpty()) {
return null;
}
return middlemanFactory.getErrorPropagatingMiddlemanArtifact(ruleContext.getLabel()
.toString(), purpose, ruleContext.getConfiguration().getMiddlemanDirectory());
}
}
}
| apache-2.0 |
templatetools/trace | trace-service-provider/src/test/java/org/food/safety/trace/repository/ListViewDaoTest.java | 1087 | package org.food.safety.trace.repository;
import lombok.extern.slf4j.Slf4j;
import org.food.safety.trace.TestSmartApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.Map;
/**
* 用户信息
* Created by tom on 2017-03-07 13:25:01.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = TestSmartApplication.class)
@ComponentScan("org.food.safety.trace")
@EnableAutoConfiguration
@Slf4j
public class ListViewDaoTest {
@Autowired
ListViewDao listViewDao;
@Test
public void findByEntityNameLike() {
List list = listViewDao.findByEntityNameLike("%UserEntity");
log.debug("findByEntityNameLike:{}", list);
}
}
| apache-2.0 |
synyx/urlaubsverwaltung | src/main/java/org/synyx/urlaubsverwaltung/overtime/web/OvertimeDetailRecordDto.java | 2115 | package org.synyx.urlaubsverwaltung.overtime.web;
import java.time.Duration;
import java.time.LocalDate;
import java.util.Objects;
public class OvertimeDetailRecordDto {
private final Integer id;
private final OvertimeDetailPersonDto person;
private final LocalDate startDate;
private final LocalDate endDate;
private final Duration duration;
private final LocalDate lastModificationDate;
OvertimeDetailRecordDto(Integer id, OvertimeDetailPersonDto person, LocalDate startDate, LocalDate endDate, Duration duration, LocalDate lastModificationDate) {
this.id = id;
this.person = person;
this.startDate = startDate;
this.endDate = endDate;
this.duration = duration;
this.lastModificationDate = lastModificationDate;
}
public Integer getId() {
return id;
}
public OvertimeDetailPersonDto getPerson() {
return person;
}
public LocalDate getStartDate() {
return startDate;
}
public LocalDate getEndDate() {
return endDate;
}
public Duration getDuration() {
return duration;
}
public LocalDate getLastModificationDate() {
return lastModificationDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OvertimeDetailRecordDto that = (OvertimeDetailRecordDto) o;
return Objects.equals(person, that.person) && Objects.equals(startDate, that.startDate) && Objects.equals(endDate, that.endDate) && Objects.equals(duration, that.duration);
}
@Override
public int hashCode() {
return Objects.hash(person, startDate, endDate, duration);
}
@Override
public String toString() {
return "OvertimeDetailRecordDto{" +
"id=" + id +
", person=" + person +
", startDate=" + startDate +
", endDate=" + endDate +
", duration=" + duration +
", lastModificationDate=" + lastModificationDate +
'}';
}
}
| apache-2.0 |
dream-x/ignite | modules/ml/src/main/java/org/apache/ignite/ml/util/MnistUtils.java | 4510 | /*
* 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.ignite.ml.util;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.Stream;
import org.apache.ignite.ml.math.impls.vector.DenseLocalOnHeapVector;
/**
* Utility class for reading MNIST dataset.
*/
public class MnistUtils {
/**
* Read random {@code count} samples from MNIST dataset from two files (images and labels) into a stream of labeled vectors.
* @param imagesPath Path to the file with images.
* @param labelsPath Path to the file with labels.
* @param rnd Random numbers generatror.
* @param count Count of samples to read.
* @return Stream of MNIST samples.
* @throws IOException
*/
public static Stream<DenseLocalOnHeapVector> mnist(String imagesPath, String labelsPath, Random rnd, int count) throws IOException {
FileInputStream isImages = new FileInputStream(imagesPath);
FileInputStream isLabels = new FileInputStream(labelsPath);
int magic = read4Bytes(isImages); // Skip magic number.
int numOfImages = read4Bytes(isImages);
int imgHeight = read4Bytes(isImages);
int imgWidth = read4Bytes(isImages);
read4Bytes(isLabels); // Skip magic number.
read4Bytes(isLabels); // Skip number of labels.
int numOfPixels = imgHeight * imgWidth;
System.out.println("Magic: " + magic);
System.out.println("Num of images: " + numOfImages);
System.out.println("Num of pixels: " + numOfPixels);
double[][] vecs = new double[numOfImages][numOfPixels + 1];
for (int imgNum = 0; imgNum < numOfImages; imgNum++) {
vecs[imgNum][numOfPixels] = isLabels.read();
for (int p = 0; p < numOfPixels; p++) {
int c = 128 - isImages.read();
vecs[imgNum][p] = (double)c / 128;
}
}
List<double[]> lst = Arrays.asList(vecs);
Collections.shuffle(lst, rnd);
isImages.close();
isLabels.close();
return lst.subList(0, count).stream().map(DenseLocalOnHeapVector::new);
}
/**
* Convert random {@code count} samples from MNIST dataset from two files (images and labels) into libsvm format.
* @param imagesPath Path to the file with images.
* @param labelsPath Path to the file with labels.
* @param outPath Path to output path.
* @param rnd Random numbers generator.
* @param count Count of samples to read.
* @throws IOException
*/
public static void asLIBSVM(String imagesPath, String labelsPath, String outPath, Random rnd, int count) throws IOException {
try (FileWriter fos = new FileWriter(outPath)) {
mnist(imagesPath, labelsPath, rnd, count).forEach(vec -> {
try {
fos.write((int)vec.get(vec.size() - 1) + " ");
for (int i = 0; i < vec.size() - 1; i++) {
double val = vec.get(i);
if (val != 0)
fos.write((i + 1) + ":" + val + " ");
}
fos.write("\n");
}
catch (IOException e) {
e.printStackTrace();
}
});
}
}
/**
* Utility method for reading 4 bytes from input stream.
* @param is Input stream.
* @throws IOException
*/
private static int read4Bytes(FileInputStream is) throws IOException {
return (is.read() << 24) | (is.read() << 16) | (is.read() << 8) | (is.read());
}
}
| apache-2.0 |
x-meta/xworker | xworker_swt/src/main/java/xworker/lang/executor/UIHandler.java | 396 | package xworker.lang.executor;
import java.util.List;
/**
* UI请求的处理器。
*
* @author zyx
*
*/
public interface UIHandler {
public void handleUIRequest(Request request);
public List<Request> getRequests();
public void removeRequest(Request request) ;
public Thread getThread();
public void setExecutorService(ExecutorService executorService);
}
| apache-2.0 |
pointphoton/AndroidMVPTemplate | app/src/main/java/com/photon/templatemvp/data/model/gallery/Person.java | 789 |
package com.photon.templatemvp.data.model.gallery;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.SerializedName;
@Generated("net.hexar.json2pojo")
@SuppressWarnings("unused")
public class Person {
@SerializedName("age")
private Long mAge;
@SerializedName("cars")
private List<Car> mCars;
@SerializedName("name")
private String mName;
public Long getAge() {
return mAge;
}
public void setAge(Long age) {
mAge = age;
}
public List<Car> getCars() {
return mCars;
}
public void setCars(List<Car> cars) {
mCars = cars;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
}
| apache-2.0 |
joewalnes/idea-community | platform/platform-api/src/com/intellij/ui/SearchTextField.java | 11112 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @author max
*/
package com.intellij.ui;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.CommonShortcuts;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.ui.components.JBList;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class SearchTextField extends JPanel {
private int myHistorySize = 5;
private final MyModel myModel;
private final TextFieldWithProcessing myTextField;
private JBPopup myPopup;
private JLabel myClearFieldLabel;
private JLabel myToggleHistoryLabel;
private JPopupMenu myNativeSearchPopup;
private KeyListener myListener = null;
private JMenuItem myNoItems;
public SearchTextField() {
this(true);
}
public SearchTextField(boolean historyEnabled) {
super(new BorderLayout());
myModel = new MyModel();
myTextField = new TextFieldWithProcessing() {
@Override
public void processKeyEvent(final KeyEvent e) {
if (preprocessEventForTextField(e)) return;
super.processKeyEvent(e);
}
@Override
public void setBackground(final Color bg) {
super.setBackground(bg);
if (myClearFieldLabel != null) {
myClearFieldLabel.setBackground(bg);
}
if (myToggleHistoryLabel != null) {
myToggleHistoryLabel.setBackground(bg);
}
}
};
myTextField.setColumns(15);
myTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
onFocusLost();
super.focusLost(e);
}
});
add(myTextField, BorderLayout.CENTER);
if (hasNativeLeopardSearchControl()) {
myTextField.putClientProperty("JTextField.variant", "search");
myNativeSearchPopup = new JPopupMenu();
myNoItems = new JMenuItem("No recent searches");
myNoItems.setEnabled(false);
updateMenu();
if (historyEnabled) {
myTextField.putClientProperty("JTextField.Search.FindPopup", myNativeSearchPopup);
}
}
else {
myToggleHistoryLabel = new JLabel(IconLoader.getIcon("/actions/search.png"));
myToggleHistoryLabel.setOpaque(true);
myToggleHistoryLabel.setBackground(myTextField.getBackground());
myToggleHistoryLabel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
togglePopup();
}
});
if (historyEnabled) {
add(myToggleHistoryLabel, BorderLayout.WEST);
}
myClearFieldLabel = new JLabel(IconLoader.getIcon("/actions/cleanLight.png"));
myClearFieldLabel.setOpaque(true);
myClearFieldLabel.setBackground(myTextField.getBackground());
add(myClearFieldLabel, BorderLayout.EAST);
myClearFieldLabel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
myTextField.setText("");
onFieldCleared();
}
});
final Border originalBorder;
if (SystemInfo.isMac) {
originalBorder = BorderFactory.createLoweredBevelBorder();
}
else {
originalBorder = myTextField.getBorder();
}
setBorder(new CompoundBorder(IdeBorderFactory.createEmptyBorder(4, 0, 4, 0), originalBorder));
myTextField.setOpaque(true);
myTextField.setBorder(IdeBorderFactory.createEmptyBorder(0, 5, 0, 5));
}
final ActionManager actionManager = ActionManager.getInstance();
if (actionManager != null) {
final AnAction clearTextAction = actionManager.getAction(IdeActions.ACTION_CLEAR_TEXT);
if (clearTextAction.getShortcutSet().getShortcuts().length == 0) {
clearTextAction.registerCustomShortcutSet(CommonShortcuts.ESCAPE, this);
}
}
}
protected void onFieldCleared() {
}
protected void onFocusLost() {
}
private void updateMenu() {
if (myNativeSearchPopup != null) {
myNativeSearchPopup.removeAll();
final int itemsCount = myModel.getSize();
if (itemsCount == 0) {
myNativeSearchPopup.add(myNoItems);
}
else {
for (int i = 0; i < itemsCount; i++) {
String item = (String)myModel.getElementAt(i);
addMenuItem(item);
}
}
}
}
private static boolean hasNativeLeopardSearchControl() {
return SystemInfo.isMacOSLeopard && UIUtil.isUnderAquaLookAndFeel();
}
public void addDocumentListener(DocumentListener listener) {
getTextEditor().getDocument().addDocumentListener(listener);
}
public void removeDocumentListener(DocumentListener listener) {
getTextEditor().getDocument().removeDocumentListener(listener);
}
public void addKeyboardListener(final KeyListener listener) {
getTextEditor().addKeyListener(listener);
}
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (myToggleHistoryLabel != null) {
final Color bg = enabled ? UIUtil.getTextFieldBackground() : UIUtil.getPanelBackground();
myToggleHistoryLabel.setBackground(bg);
myClearFieldLabel.setBackground(bg);
}
}
public void setHistorySize(int aHistorySize) {
myHistorySize = aHistorySize;
}
public void setHistory(java.util.List<String> aHistory) {
myModel.setItems(aHistory);
}
public java.util.List<String> getHistory() {
final int itemsCount = myModel.getSize();
java.util.List<String> history = new ArrayList<String>(itemsCount);
for (int i = 0; i < itemsCount; i++) {
history.add((String)myModel.getElementAt(i));
}
return history;
}
public void setText(String aText) {
getTextEditor().setText(aText);
}
public String getText() {
return getTextEditor().getText();
}
public void removeNotify() {
super.removeNotify();
hidePopup();
}
public void addCurrentTextToHistory() {
final String item = getText();
myModel.addElement(item);
}
private void addMenuItem(final String item) {
if (myNativeSearchPopup != null) {
myNativeSearchPopup.remove(myNoItems);
final JMenuItem menuItem = new JMenuItem(item);
myNativeSearchPopup.add(menuItem);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
myTextField.setText(item);
}
});
}
}
public void selectText() {
getTextEditor().selectAll();
}
public JTextField getTextEditor() {
return myTextField;
}
public boolean requestFocusInWindow() {
return myTextField.requestFocusInWindow();
}
public void requestFocus() {
getTextEditor().requestFocus();
}
public class MyModel extends AbstractListModel {
private java.util.List<String> myFullList = new ArrayList<String>();
private Object mySelectedItem;
public Object getElementAt(int index) {
return myFullList.get(index);
}
public int getSize() {
return Math.min(myHistorySize, myFullList.size());
}
public void addElement(Object obj) {
String newItem = ((String)obj).trim();
if (0 == newItem.length()) {
return;
}
if (!contains(newItem)) {
insertElementAt(newItem, 0);
}
}
public void insertElementAt(Object obj, int index) {
myFullList.add(index, (String)obj);
fireContentsChanged();
}
public Object getSelectedItem() {
return mySelectedItem;
}
public void setSelectedItem(Object anItem) {
mySelectedItem = anItem;
}
public void fireContentsChanged() {
fireContentsChanged(this, -1, -1);
updateMenu();
}
public boolean contains(String aNewValue) {
return myFullList.contains(aNewValue);
}
public void setItems(java.util.List<String> aList) {
myFullList = new ArrayList<String>(aList);
fireContentsChanged();
}
}
private void hidePopup() {
if (myPopup != null) {
myPopup.cancel();
myPopup = null;
}
}
protected void showPopup() {
if (myPopup == null) {
final JList list = new JBList(myModel);
if (myListener != null) {
removeKeyListener(myListener);
}
final Runnable chooseRunnable = new Runnable() {
public void run() {
final String value = (String)list.getSelectedValue();
getTextEditor().setText(value != null ? value : "");
if (myPopup != null) {
myPopup.cancel();
myPopup = null;
}
}
};
myListener = new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
if (list.getSelectedIndex() < list.getModel().getSize() - 1) {
list.setSelectedIndex(list.getSelectedIndex() + 1);
}
}
else if (e.getKeyCode() == KeyEvent.VK_UP) {
if (list.getSelectedIndex() > 0) {
list.setSelectedIndex(list.getSelectedIndex() - 1);
}
}
else if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if (list.getSelectedIndex() > -1) {
chooseRunnable.run();
}
}
}
};
addKeyboardListener(myListener);
myPopup = JBPopupFactory.getInstance().createListPopupBuilder(list)
.setMovable(false)
.setRequestFocus(false)
.setItemChoosenCallback(chooseRunnable).createPopup();
if (isShowing()) myPopup.showUnderneathOf(this);
}
}
private void togglePopup() {
if (myPopup == null) {
showPopup();
}
else {
hidePopup();
}
}
public void setSelectedItem(final String s) {
getTextEditor().setText(s);
}
public int getSelectedIndex() {
return myModel.myFullList.indexOf(getText());
}
protected static class TextFieldWithProcessing extends JTextField {
public void processKeyEvent(KeyEvent e) {
super.processKeyEvent(e);
}
}
public final void keyEventToTextField(KeyEvent e) {
myTextField.processKeyEvent(e);
}
protected boolean preprocessEventForTextField(KeyEvent e) {
return false;
}
}
| apache-2.0 |
mattxia/spring-2.5-analysis | src/org/springframework/orm/hibernate3/AbstractSessionFactoryBean.java | 14580 | /*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.orm.hibernate3;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.JDBCException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.jdbc.support.SQLExceptionTranslator;
/**
* Abstract {@link org.springframework.beans.factory.FactoryBean} that creates
* a Hibernate {@link org.hibernate.SessionFactory} within a Spring application
* context, providing general infrastructure not related to Hibernate's
* specific configuration API.
*
* <p>This class implements the
* {@link org.springframework.dao.support.PersistenceExceptionTranslator}
* interface, as autodetected by Spring's
* {@link org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor},
* for AOP-based translation of native exceptions to Spring DataAccessExceptions.
* Hence, the presence of e.g. LocalSessionFactoryBean automatically enables
* a PersistenceExceptionTranslationPostProcessor to translate Hibernate exceptions.
*
* <p>This class mainly serves as common base class for {@link LocalSessionFactoryBean}.
* For details on typical SessionFactory setup, see the LocalSessionFactoryBean javadoc.
*
* @author Juergen Hoeller
* @since 2.0
* @see #setExposeTransactionAwareSessionFactory
* @see org.hibernate.SessionFactory#getCurrentSession()
* @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor
*/
public abstract class AbstractSessionFactoryBean
implements FactoryBean, InitializingBean, DisposableBean, PersistenceExceptionTranslator {
/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());
private DataSource dataSource;
private boolean useTransactionAwareDataSource = false;
private boolean exposeTransactionAwareSessionFactory = true;
private SQLExceptionTranslator jdbcExceptionTranslator;
private SessionFactory sessionFactory;
/**
* Set the DataSource to be used by the SessionFactory.
* If set, this will override corresponding settings in Hibernate properties.
* <p>If this is set, the Hibernate settings should not define
* a connection provider to avoid meaningless double configuration.
* <p>If using HibernateTransactionManager as transaction strategy, consider
* proxying your target DataSource with a LazyConnectionDataSourceProxy.
* This defers fetching of an actual JDBC Connection until the first JDBC
* Statement gets executed, even within JDBC transactions (as performed by
* HibernateTransactionManager). Such lazy fetching is particularly beneficial
* for read-only operations, in particular if the chances of resolving the
* result in the second-level cache are high.
* <p>As JTA and transactional JNDI DataSources already provide lazy enlistment
* of JDBC Connections, LazyConnectionDataSourceProxy does not add value with
* JTA (i.e. Spring's JtaTransactionManager) as transaction strategy.
* @see #setUseTransactionAwareDataSource
* @see HibernateTransactionManager
* @see org.springframework.transaction.jta.JtaTransactionManager
* @see org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* Return the DataSource to be used by the SessionFactory.
*/
public DataSource getDataSource() {
return this.dataSource;
}
/**
* Set whether to use a transaction-aware DataSource for the SessionFactory,
* i.e. whether to automatically wrap the passed-in DataSource with Spring's
* TransactionAwareDataSourceProxy.
* <p>Default is "false": LocalSessionFactoryBean is usually used with Spring's
* HibernateTransactionManager or JtaTransactionManager, both of which work nicely
* on a plain JDBC DataSource. Hibernate Sessions and their JDBC Connections are
* fully managed by the Hibernate/JTA transaction infrastructure in such a scenario.
* <p>If you switch this flag to "true", Spring's Hibernate access will be able to
* <i>participate in JDBC-based transactions managed outside of Hibernate</i>
* (for example, by Spring's DataSourceTransactionManager). This can be convenient
* if you need a different local transaction strategy for another O/R mapping tool,
* for example, but still want Hibernate access to join into those transactions.
* <p>A further benefit of this option is that <i>plain Sessions opened directly
* via the SessionFactory</i>, outside of Spring's Hibernate support, will still
* participate in active Spring-managed transactions. However, consider using
* Hibernate's <code>getCurrentSession()</code> method instead (see javadoc of
* "exposeTransactionAwareSessionFactory" property).
* <p><b>WARNING:</b> When using a transaction-aware JDBC DataSource in combination
* with OpenSessionInViewFilter/Interceptor, whether participating in JTA or
* external JDBC-based transactions, it is strongly recommended to set Hibernate's
* Connection release mode to "after_transaction" or "after_statement", which
* guarantees proper Connection handling in such a scenario. In contrast to that,
* HibernateTransactionManager generally requires release mode "on_close".
* <p>Note: If you want to use Hibernate's Connection release mode "after_statement"
* with a DataSource specified on this LocalSessionFactoryBean (for example, a
* JTA-aware DataSource fetched from JNDI), switch this setting to "true".
* Else, the ConnectionProvider used underneath will vote against aggressive
* release and thus silently switch to release mode "after_transaction".
* @see #setDataSource
* @see #setExposeTransactionAwareSessionFactory
* @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
* @see org.springframework.jdbc.datasource.DataSourceTransactionManager
* @see org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
* @see org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor
* @see HibernateTransactionManager
* @see org.springframework.transaction.jta.JtaTransactionManager
*/
public void setUseTransactionAwareDataSource(boolean useTransactionAwareDataSource) {
this.useTransactionAwareDataSource = useTransactionAwareDataSource;
}
/**
* Return whether to use a transaction-aware DataSource for the SessionFactory.
*/
protected boolean isUseTransactionAwareDataSource() {
return this.useTransactionAwareDataSource;
}
/**
* Set whether to expose a transaction-aware current Session from the
* SessionFactory's <code>getCurrentSession()</code> method, returning the
* Session that's associated with the current Spring-managed transaction, if any.
* <p>Default is "true", letting data access code work with the plain
* Hibernate SessionFactory and its <code>getCurrentSession()</code> method,
* while still being able to participate in current Spring-managed transactions:
* with any transaction management strategy, either local or JTA / EJB CMT,
* and any transaction synchronization mechanism, either Spring or JTA.
* Furthermore, <code>getCurrentSession()</code> will also seamlessly work with
* a request-scoped Session managed by OpenSessionInViewFilter/Interceptor.
* <p>Turn this flag off to expose the plain Hibernate SessionFactory with
* Hibernate's default <code>getCurrentSession()</code> behavior, supporting
* plain JTA synchronization only. Alternatively, simply override the
* corresponding Hibernate property "hibernate.current_session_context_class".
* @see SpringSessionContext
* @see org.hibernate.SessionFactory#getCurrentSession()
* @see org.springframework.transaction.jta.JtaTransactionManager
* @see HibernateTransactionManager
* @see org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
* @see org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor
*/
public void setExposeTransactionAwareSessionFactory(boolean exposeTransactionAwareSessionFactory) {
this.exposeTransactionAwareSessionFactory = exposeTransactionAwareSessionFactory;
}
/**
* Return whether to expose a transaction-aware proxy for the SessionFactory.
*/
protected boolean isExposeTransactionAwareSessionFactory() {
return this.exposeTransactionAwareSessionFactory;
}
/**
* Set the JDBC exception translator for the SessionFactory,
* exposed via the PersistenceExceptionTranslator interface.
* <p>Applied to any SQLException root cause of a Hibernate JDBCException,
* overriding Hibernate's default SQLException translation (which is
* based on Hibernate's Dialect for a specific target database).
* @param jdbcExceptionTranslator the exception translator
* @see java.sql.SQLException
* @see org.hibernate.JDBCException
* @see org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator
* @see org.springframework.jdbc.support.SQLStateSQLExceptionTranslator
* @see org.springframework.dao.support.PersistenceExceptionTranslator
*/
public void setJdbcExceptionTranslator(SQLExceptionTranslator jdbcExceptionTranslator) {
this.jdbcExceptionTranslator = jdbcExceptionTranslator;
}
/**
* Build and expose the SessionFactory.
* @see #buildSessionFactory()
* @see #wrapSessionFactoryIfNecessary
*/
public void afterPropertiesSet() throws Exception {
SessionFactory rawSf = buildSessionFactory();
this.sessionFactory = wrapSessionFactoryIfNecessary(rawSf);
afterSessionFactoryCreation();
}
/**
* Wrap the given SessionFactory with a proxy, if demanded.
* <p>The default implementation simply returns the given SessionFactory as-is.
* Subclasses may override this to implement transaction awareness through
* a SessionFactory proxy, for example.
* @param rawSf the raw SessionFactory as built by {@link #buildSessionFactory()}
* @return the SessionFactory reference to expose
* @see #buildSessionFactory()
*/
protected SessionFactory wrapSessionFactoryIfNecessary(SessionFactory rawSf) {
return rawSf;
}
/**
* Return the exposed SessionFactory.
* Will throw an exception if not initialized yet.
* @return the SessionFactory (never <code>null</code>)
* @throws IllegalStateException if the SessionFactory has not been initialized yet
*/
protected final SessionFactory getSessionFactory() {
if (this.sessionFactory == null) {
throw new IllegalStateException("SessionFactory not initialized yet");
}
return this.sessionFactory;
}
/**
* Close the SessionFactory on bean factory shutdown.
*/
public void destroy() throws HibernateException {
logger.info("Closing Hibernate SessionFactory");
try {
beforeSessionFactoryDestruction();
}
finally {
this.sessionFactory.close();
}
}
/**
* Return the singleton SessionFactory.
*/
public Object getObject() {
return this.sessionFactory;
}
public Class getObjectType() {
return (this.sessionFactory != null) ? this.sessionFactory.getClass() : SessionFactory.class;
}
public boolean isSingleton() {
return true;
}
/**
* Implementation of the PersistenceExceptionTranslator interface,
* as autodetected by Spring's PersistenceExceptionTranslationPostProcessor.
* <p>Converts the exception if it is a HibernateException;
* else returns <code>null</code> to indicate an unknown exception.
* @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor
* @see #convertHibernateAccessException
*/
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
if (ex instanceof HibernateException) {
return convertHibernateAccessException((HibernateException) ex);
}
return null;
}
/**
* Convert the given HibernateException to an appropriate exception from the
* <code>org.springframework.dao</code> hierarchy.
* <p>Will automatically apply a specified SQLExceptionTranslator to a
* Hibernate JDBCException, else rely on Hibernate's default translation.
* @param ex HibernateException that occured
* @return a corresponding DataAccessException
* @see SessionFactoryUtils#convertHibernateAccessException
* @see #setJdbcExceptionTranslator
*/
protected DataAccessException convertHibernateAccessException(HibernateException ex) {
if (this.jdbcExceptionTranslator != null && ex instanceof JDBCException) {
JDBCException jdbcEx = (JDBCException) ex;
return this.jdbcExceptionTranslator.translate(
"Hibernate operation: " + jdbcEx.getMessage(), jdbcEx.getSQL(), jdbcEx.getSQLException());
}
return SessionFactoryUtils.convertHibernateAccessException(ex);
}
/**
* Build the underlying Hibernate SessionFactory.
* @return the raw SessionFactory (potentially to be wrapped with a
* transaction-aware proxy before it is exposed to the application)
* @throws Exception in case of initialization failure
*/
protected abstract SessionFactory buildSessionFactory() throws Exception;
/**
* Hook that allows post-processing after the SessionFactory has been
* successfully created. The SessionFactory is already available through
* <code>getSessionFactory()</code> at this point.
* <p>This implementation is empty.
* @throws Exception in case of initialization failure
* @see #getSessionFactory()
*/
protected void afterSessionFactoryCreation() throws Exception {
}
/**
* Hook that allows shutdown processing before the SessionFactory
* will be closed. The SessionFactory is still available through
* <code>getSessionFactory()</code> at this point.
* <p>This implementation is empty.
* @see #getSessionFactory()
*/
protected void beforeSessionFactoryDestruction() {
}
}
| apache-2.0 |
sekiguchi-nagisa/Aquarius | aquarius-core/src/main/java/aquarius/expression/Sequence.java | 2056 | /*
* Copyright (C) 2014-2015 Nagisa Sekiguchi
*
* 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 aquarius.expression;
import aquarius.ExpressionVisitor;
import aquarius.ParserContext;
/**
* try to match the sequence of expressions and return matched results as array.
* -> expr1 expr2 ... exprN
*
* @author skgchxngsxyz-opensuse
*/
public class Sequence implements ParsingExpression<Void> {
private final ParsingExpression<?>[] exprs;
@SafeVarargs
public Sequence(ParsingExpression<?>... exprs) {
this.exprs = exprs;
}
public ParsingExpression<?>[] getExprs() {
return this.exprs;
}
@Override
public String toString() {
StringBuilder sBuilder = new StringBuilder();
final int size = this.exprs.length;
for(int i = 0; i < size; i++) {
if(i > 0) {
sBuilder.append(' ');
}
sBuilder.append(this.exprs[i]);
}
return sBuilder.toString();
}
@Override
public boolean parse(ParserContext context) {
int pos = context.getInputStream().getPosition();
for(ParsingExpression<?> e : this.exprs) {
if(!e.parse(context)) {
context.getInputStream().setPosition(pos);
return false;
}
}
return true;
}
@Override
public <T> T accept(ExpressionVisitor<T> visitor) {
return visitor.visitSequence(this);
}
@Override
public boolean isReturnable() {
return false;
}
} | apache-2.0 |
google/nomulus | core/src/main/java/google/registry/tools/DeleteReservedListCommand.java | 2189 | // Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.tools;
import static com.google.common.base.Preconditions.checkArgument;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import google.registry.model.tld.label.ReservedList;
import google.registry.model.tld.label.ReservedListDao;
/**
* Command to delete a {@link ReservedList} from the database. This command will fail if the
* reserved list is currently in use on a tld.
*/
@Parameters(separators = " =", commandDescription = "Deletes a ReservedList from the database.")
final class DeleteReservedListCommand extends ConfirmingCommand implements CommandWithRemoteApi {
@Parameter(
names = {"-n", "--name"},
description = "The name of the reserved list to delete.",
required = true)
private String name;
@Override
protected void init() {
checkArgument(
ReservedList.get(name).isPresent(),
"Cannot delete the reserved list %s because it doesn't exist.",
name);
ReservedList existing = ReservedList.get(name).get();
ImmutableSet<String> tldsUsedOn = existing.getReferencingTlds();
checkArgument(
tldsUsedOn.isEmpty(),
"Cannot delete reserved list because it is used on these tld(s): %s",
Joiner.on(", ").join(tldsUsedOn));
}
@Override
protected String execute() {
ReservedList existing = ReservedList.get(name).get();
ReservedListDao.delete(existing);
return String.format("Deleted reserved list: %s", name);
}
}
| apache-2.0 |
Vincit/multi-user-test-runner | examples/src/test/java/fi/vincit/mutrproject/feature/todo/TodoService_FocusedWithClassIT.java | 5394 | package fi.vincit.mutrproject.feature.todo;
import fi.vincit.multiusertest.annotation.IgnoreForUsers;
import fi.vincit.multiusertest.annotation.RunWithUsers;
import fi.vincit.multiusertest.util.UserIdentifiers;
import fi.vincit.mutrproject.feature.todo.command.ListVisibility;
import fi.vincit.mutrproject.testconfig.AbstractConfiguredMultiRoleIT;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import static fi.vincit.multiusertest.rule.expectation.TestExpectations.*;
import static fi.vincit.multiusertest.util.UserIdentifiers.roles;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* A more advanced example on focusing to certain users can be combined with UserDefinitionClass.
*/
@RunWithUsers(
producerClass = TodoProducers.class, // Defines all producers
producers = {"$role:ROLE_SYSTEM_ADMIN"}, // Defines the producers we focus for debugging
consumerClass = TodoConsumers.class, // Defines all consumers
consumers = {"$role:ROLE_USER"}, // Defines the consumers we focus for debugging
focusEnabled = true // Enable the focus mode
)
public class TodoService_FocusedWithClassIT extends AbstractConfiguredMultiRoleIT {
// Service under test
@Autowired
private TodoService todoService;
@Before
public void init() {
todoService.setSecureSystemAdminTodos(false);
}
@Test
public void getPrivateTodoList() throws Throwable {
// At this point the producer has been logged in automatically
long id = todoService.createTodoList("Test list", ListVisibility.PRIVATE);
authorization().given(() -> todoService.getTodoList(id))
.whenCalledWithAnyOf(roles("ROLE_USER"), UserIdentifiers.anonymous())
.then(expectExceptionInsteadOfValue(AccessDeniedException.class))
.otherwise(assertValue(todoList -> {
assertThat(todoList, notNullValue());
assertThat(todoList.getId(), is(id));
assertThat(todoList.getName(), is("Test list"));
assertThat(todoList.isPublicList(), is(false));
}))
.test();
}
@Test
public void getPublicTodoList() throws Throwable {
long id = todoService.createTodoList("Test list", ListVisibility.PUBLIC);
authorization().given(() -> todoService.getTodoList(id))
.otherwise(assertValue(todoList -> {
assertThat(todoList, notNullValue());
assertThat(todoList.getId(), is(id));
assertThat(todoList.getName(), is("Test list"));
assertThat(todoList.isPublicList(), is(true));
}))
.test();
}
/**
* Example on how to only check that the method do test
* that a method call doesn't fail. This version explicitly
* shows the test writer/reader that it is not expected to fail
* ever.
* @throws Throwable
*/
@Test
public void getPublicTodoListNotFailsExplicit() throws Throwable {
long id = todoService.createTodoList("Test list", ListVisibility.PUBLIC);
authorization().given(() -> todoService.getTodoList(id))
.byDefault(expectNotToFailIgnoringValue())
.test();
}
/**
* Example on how to only check that the method do test
* that a method call doesn't fail. This version uses the default
* expectation and omits the <pre>.byDefault(expectNotToFailIgnoringValue())</pre>
* call.
* @throws Throwable
*/
@Test
public void getPublicTodoListNotFailsSimple() throws Throwable {
long id = todoService.createTodoList("Test list", ListVisibility.PUBLIC);
authorization().given(() -> todoService.getTodoList(id))
.test();
}
/**
* This test is run for all producers but ignored for the anonymous consumer
* @throws Throwable
*/
@Test
@IgnoreForUsers(consumers = RunWithUsers.ANONYMOUS)
public void addTodoItem() throws Throwable {
long listId = todoService.createTodoList("Test list", ListVisibility.PRIVATE);
authorization().given(() -> todoService.addItemToList(listId, "Write tests"))
.whenCalledWithAnyOf(roles("ROLE_ADMIN", "ROLE_SYSTEM_ADMIN"), UserIdentifiers.producer())
.then(expectNotToFailIgnoringValue())
.otherwise(expectExceptionInsteadOfValue(AccessDeniedException.class))
.test();
}
/**
* This test is run for all producers but only when the consumer is ANONYMOUS
* @throws Throwable
*/
@Test
@RunWithUsers(consumers = RunWithUsers.ANONYMOUS)
public void addTodoItemAnonymous() throws Throwable {
long listId = todoService.createTodoList("Test list", ListVisibility.PRIVATE);
authorization().given(() -> todoService.addItemToList(listId, "Write tests"))
.byDefault(expectExceptionInsteadOfValue(AuthenticationCredentialsNotFoundException.class))
.test();
}
}
| apache-2.0 |
terrancesnyder/solr-analytics | solr/core/src/java/org/apache/solr/highlight/GapFragmenter.java | 3735 | /*
* 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.solr.highlight;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.NullFragmenter;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.solr.common.params.HighlightParams;
import org.apache.solr.common.params.SolrParams;
public class GapFragmenter extends HighlightingPluginBase implements SolrFragmenter
{
public Fragmenter getFragmenter(String fieldName, SolrParams params )
{
numRequests++;
params = SolrParams.wrapDefaults(params, defaults);
int fragsize = params.getFieldInt( fieldName, HighlightParams.FRAGSIZE, 100 );
return (fragsize <= 0) ? new NullFragmenter() : new LuceneGapFragmenter(fragsize);
}
///////////////////////////////////////////////////////////////////////
//////////////////////// SolrInfoMBeans methods ///////////////////////
///////////////////////////////////////////////////////////////////////
@Override
public String getDescription() {
return "GapFragmenter";
}
@Override
public String getSource() {
return "$URL: https://svn.apache.org/repos/asf/lucene/dev/branches/lucene_solr_4_0/solr/core/src/java/org/apache/solr/highlight/GapFragmenter.java $";
}
}
/**
* A simple modification of SimpleFragmenter which additionally creates new
* fragments when an unusually-large position increment is encountered
* (this behaves much better in the presence of multi-valued fields).
*/
class LuceneGapFragmenter extends SimpleFragmenter {
/**
* When a gap in term positions is observed that is at least this big, treat
* the gap as a fragment delimiter.
*/
public static final int INCREMENT_THRESHOLD = 50;
protected int fragOffset = 0;
private OffsetAttribute offsetAtt;
private PositionIncrementAttribute posIncAtt;
public LuceneGapFragmenter() {
}
public LuceneGapFragmenter(int fragsize) {
super(fragsize);
}
/* (non-Javadoc)
* @see org.apache.lucene.search.highlight.TextFragmenter#start(java.lang.String)
*/
@Override
public void start(String originalText, TokenStream tokenStream) {
offsetAtt = tokenStream.getAttribute(OffsetAttribute.class);
posIncAtt = tokenStream.getAttribute(PositionIncrementAttribute.class);
fragOffset = 0;
}
/* (non-Javadoc)
* @see org.apache.lucene.search.highlight.TextFragmenter#isNewFragment(org.apache.lucene.analysis.Token)
*/
@Override
public boolean isNewFragment() {
int endOffset = offsetAtt.endOffset();
boolean isNewFrag =
endOffset >= fragOffset + getFragmentSize() ||
posIncAtt.getPositionIncrement() > INCREMENT_THRESHOLD;
if(isNewFrag) {
fragOffset = endOffset;
}
return isNewFrag;
}
}
| apache-2.0 |
SwapnilChaudhari/CustomAlarmManager | src/com/example/setalarm/ActivityReceiveAlarm.java | 2803 | package com.example.setalarm;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
public class ActivityReceiveAlarm extends Activity
{
private MediaPlayer mMediaPlayer;
private Vibrator vibrator;
private long[] pattern = { 0, 2000, 1000 };//start from, vibrate till , pause duration
private Animation shake;
private SimpleDateFormat sdfTime = new SimpleDateFormat("hh:mm:ss a", Locale.getDefault());
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receive_alarm);
initData();
initUI();
}
private void initUI()
{
playAlarm();
findViewById(R.id.ibCancelAlarm).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mMediaPlayer.stop();
vibrator.cancel();
finish();
}
});
long time=getIntent().getLongExtra("TIME", 0);
((TextView)findViewById(R.id.tvTimeRecAct)).setText(sdfTime.format(new Date(time))+"");
((TextView)findViewById(R.id.tvTimeRecAct)).setTypeface(Typeface.createFromAsset(getAssets(), "fonts/Raleway-Regular.ttf"));
shake=AnimationUtils.loadAnimation(getApplicationContext(), R.anim.vibrate_anim);
findViewById(R.id.ibCancelAlarm).setAnimation(shake);
}
private void playAlarm()
{
try {
/*timerVibrate=new Timer();
timerVibrate.sc*/
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(pattern,0);
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(getApplicationContext(), alert);
getSystemService(AUDIO_SERVICE);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
//}
}
catch(Exception e)
{
}
}
private void initData()
{
Window wind;
wind = this.getWindow();
wind.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
wind.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
wind.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
}
| apache-2.0 |
guynir/storageio | src/main/java/io/storage/core/StorageServiceProvider.java | 11669 | package io.storage.core;
import io.storage.core.entities.FileEntity;
import io.storage.core.entities.FolderEntity;
import java.io.InputStream;
import java.io.OutputStream;
/**
* //@formatter:off
* Definition of Storage Service Provider Interface (SPI). <p>
* Each of the operations implemented by a storage
* service provider may generate one of the following exceptions:
* <ul>
* <li>IllegalArgumentException - If one of the required arguments is {@code null} or contains invalid value.</li>
* <li>EntryNotFoundException - If resource (file or directory) specified via <i>path</i> argument does not exist.</li>
* <li>InvalidEntityPathException - If path of a
* resource does not exist.</li> <li>CredentialsException - If provided credentials are not supported by the underlying
* service provider or are no longer valid.</li> <li>StorageException - General exception indicating there was a
* failure.</li> </ul> <p> The resource path reference follows Unix-style path, following these conventions: <ul>
* <li>All paths start with forward slash -- /</li> <li>All path elements are separated by forward slash.</li> <li>In
* cases where distinction is required, a path ending with forward slash -- / -- is considered to be a folder.</li>
* </ul>
* <p>
* //@formatter:on
*
* @author Guy Raz Nir
* @since 25/06/2017
*/
public interface StorageServiceProvider<C extends Credentials> {
/**
* Read folder meta data (without including children).
*
* @param credentials Credentials to access storage service.
* @param path Path of folder.
* @return Folder meta data.
* @throws IllegalArgumentException If either arguments are {@code null}.
* @throws EntityNotFoundException If <i>path</i> does not exist.
* @throws InvalidEntityPathException If <i>path</i> reference a non-folder entity.
* @throws CredentialsException If provided credentials are not supported by the underlying implementation or it has
* expired.
* @throws InvalidPathFormatException If <i>path</i> has invalid format.
*/
FolderEntity listFolderContents(C credentials, String path) throws
IllegalArgumentException,
EntityNotFoundException,
InvalidEntityPathException,
CredentialsException,
InvalidPathFormatException;
/**
* Check if file or folder exists.
*
* @param credentials Credentials to access storage service.
* @param path Path to file.
* @return {@code true} if entity exists at the given path (either file or folder), {@code false} if not.
* @throws IllegalArgumentException If either arguments are {@code null}.
* @throws EntityNotFoundException If entity does not exist.
* @throws CredentialsException If provided credentials are not supported by the underlying implementation or it has
* expired.
* @throws InvalidPathFormatException If <i>path</i> has invalid format.
*/
boolean exists(C credentials, String path) throws
IllegalArgumentException,
CredentialsException,
InvalidPathFormatException;
/**
* Read a file meta data.
*
* @param credentials Credentials to access storage service.
* @param path Path to file.
* @return File entity metadata.
* @throws IllegalArgumentException If either arguments are {@code null}.
* @throws EntityNotFoundException If entity does not exist.
* @throws CredentialsException If provided credentials are not supported by the underlying implementation or it has
* expired.
* @throws InvalidPathFormatException If <i>path</i> has invalid format.
*/
FileEntity readFileMeta(C credentials, String path) throws
IllegalArgumentException,
EntityNotFoundException,
CredentialsException,
InvalidPathFormatException;
/**
* Read a file.
*
* @param credentials Credentials to access storage service.
* @param path Path to file.
* @param out Output stream to write file content.
* @throws IllegalArgumentException If either arguments are {@code null}.
* @throws EntityNotFoundException If entity does not exist.
* @throws CredentialsException If provided credentials are not supported by the underlying implementation or it has
* expired.
* @throws InvalidPathFormatException If <i>path</i> has invalid format.
*/
void readFile(C credentials, String path, OutputStream out) throws
IllegalArgumentException,
EntityNotFoundException,
CredentialsException,
InvalidRevisionException,
InvalidPathFormatException;
/**
* Create new or overwrite existing file.
*
* @param credentials Credentials to access storage service.
* @param path Path to file.
* @param in Input stream to read file data.
* @return File entry representing the file.
* @throws IllegalArgumentException If either arguments are {@code null}.
* @throws InvalidEntityPathException If path to entity is invalid.
* @throws CredentialsException If provided credentials are not supported by the underlying implementation or it has
* expired.
* @throws InvalidRevisionException If <i>revision</i> is not {@code null} and it does not the latest file revision
* managed by the underlying storage service.
* @throws InvalidPathFormatException If <i>path</i> has invalid format.
*/
FileEntity writeFile(C credentials, String path, InputStream in) throws
IllegalArgumentException,
InvalidEntityPathException,
CredentialsException,
InvalidRevisionException,
InvalidPathFormatException;
/**
* Create new or overwrite existing file. This method supports writing file with revision verification, i.e. - if
* <i>revision</i> is specified, the process first validates that the last file revision is the same as specified
* revision.<br> If revisions match, a file is written normally, otherwise (if no match), an exception is
* generated.<p> This facility provide a collusion prevention mechanism in an environment when multiple writers
* address the same file. In such a way, a caller can make sure he/she is overwriting the latest file version.
*
* @param credentials Credentials to access storage service.
* @param path Path to file.
* @param in Input stream to read file data.
* @param revision Optional file revision (may be {@code null}).
* @return File entry representing the file.
* @throws IllegalArgumentException If either arguments are {@code null}.
* @throws InvalidEntityPathException If path to entity is invalid.
* @throws CredentialsException If provided credentials are not supported by the underlying implementation or it has
* expired.
* @throws InvalidRevisionException If <i>revision</i> is not {@code null} and it does not the latest file revision
* managed by the underlying storage service.
* @throws InvalidPathFormatException If <i>path</i> has invalid format.
*/
FileEntity writeFile(C credentials, String path, InputStream in, String revision) throws
IllegalArgumentException,
InvalidEntityPathException,
CredentialsException,
InvalidRevisionException,
InvalidPathFormatException;
/**
* Create new or overwrite existing file.
*
* @param credentials Credentials to access storage service.
* @param path Path to file.
* @param data Data to write.
* @return File entry representing the file.
* @throws IllegalArgumentException If either arguments are {@code null}.
* @throws InvalidEntityPathException If path to entity is invalid.
* @throws CredentialsException If provided credentials are not supported by the underlying implementation or it has
* expired.
* @throws InvalidRevisionException If <i>revision</i> is not {@code null} and it does not the latest file revision
* managed by the underlying storage service.
* @throws InvalidPathFormatException If <i>path</i> has invalid format.
*/
FileEntity writeFile(C credentials, String path, byte[] data) throws
IllegalArgumentException,
InvalidEntityPathException,
CredentialsException,
InvalidRevisionException,
InvalidPathFormatException;
/**
* Create new or overwrite existing file. This method supports writing file with revision verification, i.e. - if
* <i>revision</i> is specified, the process first validates that the last file revision is the same as specified
* revision.<br> If revisions match, a file is written normally, otherwise (if no match), an exception is
* generated.<p> This facility provide a collusion prevention mechanism in an environment when multiple writers
* address the same file. In such a way, a caller can make sure he/she is overwriting the latest file version.
*
* @param credentials Credentials to access storage service.
* @param path Path to file.
* @param data Data to write.
* @param revision Optional file revision (may be {@code null}).
* @return File entry representing the file.
* @throws IllegalArgumentException If either arguments are {@code null}.
* @throws InvalidEntityPathException If path to entity is invalid.
* @throws CredentialsException If provided credentials are not supported by the underlying implementation or it has
* expired.
* @throws InvalidRevisionException If <i>revision</i> is not {@code null} and it does not the latest file revision
* managed by the underlying storage service.
* @throws InvalidPathFormatException If <i>path</i> has invalid format.
*/
FileEntity writeFile(C credentials, String path, byte[] data, String revision) throws
IllegalArgumentException,
InvalidEntityPathException,
CredentialsException,
InvalidRevisionException,
InvalidPathFormatException;
/**
* Delete a file or directory.
*
* @param credentials Credentials to access storage service.
* @param path Path to file or directory.
* @throws IllegalArgumentException If either arguments are {@code null}.
* @throws EntityNotFoundException If path to file or folder does not exist.
* @throws CredentialsException If provided credentials are not supported by the underlying implementation or it has
* expired.
* @throws InvalidPathFormatException If <i>path</i> has invalid format.
*/
void delete(C credentials, String path) throws
IllegalArgumentException,
EntityNotFoundException,
CredentialsException,
InvalidPathFormatException;
/**
* @return The type credentials this provider requires.
*/
Class<C> credentialsTypes();
}
| apache-2.0 |
venusdrogon/feilong-core | src/test/java/com/feilong/core/util/predicate/beanpredicateutil/ContainsPredicateTest.java | 2859 | /*
* Copyright (C) 2008 feilong
*
* 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.feilong.core.util.predicate.beanpredicateutil;
import static org.junit.Assert.assertEquals;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.PredicateUtils;
import org.junit.Test;
import com.feilong.core.util.predicate.BeanPredicateUtil;
import com.feilong.store.member.User;
public class ContainsPredicateTest{
@Test
public void testContainsPredicate12(){
User guanyu30 = new User("关羽", 30);
Predicate<User> predicate = PredicateUtils.andPredicate(
BeanPredicateUtil.containsPredicate("name", "关羽", "刘备"),
BeanPredicateUtil.containsPredicate("age", 30));
assertEquals(true, predicate.evaluate(guanyu30));
}
//---------------------------------------------------------------
/**
* Test equal predicate.
*/
@Test
public void testContainsPredicate(){
User user = new User(2L);
Predicate<User> containsPredicate = BeanPredicateUtil.containsPredicate("id", 2L);
assertEquals(true, containsPredicate.evaluate(user));
}
/**
* Test equal predicate 1.
*/
@Test
public void testContainsPredicate1(){
User user = new User(2L);
Predicate<User> containsPredicate = BeanPredicateUtil.containsPredicate("id", (String) null);
assertEquals(false, containsPredicate.evaluate(user));
}
//---------------------------------------------------------------------------
/**
* Test equal predicate null property name.
*/
@Test(expected = NullPointerException.class)
public void testContainsPredicateNullPropertyName(){
BeanPredicateUtil.containsPredicate((String) null, (String) null);
}
/**
* Test equal predicate empty property name.
*/
@Test(expected = IllegalArgumentException.class)
public void testContainsPredicateEmptyPropertyName(){
BeanPredicateUtil.containsPredicate("", (String) null);
}
/**
* Test equal predicate blank property name.
*/
@Test(expected = IllegalArgumentException.class)
public void testContainsPredicateBlankPropertyName(){
BeanPredicateUtil.containsPredicate("", (String) null);
}
}
| apache-2.0 |
darzul/FlexItemDecoration | example/src/main/java/com/example/flexitemdecoration/common/PokemonViewHolder.java | 629 | package com.example.flexitemdecoration.common;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.example.flexitemdecoration.R;
/**
* Created by Guillaume 'DarzuL' Bourderye on 3/25/17.
* <p>
* Pokemon ViewHolder
*/
public class PokemonViewHolder extends RecyclerView.ViewHolder {
private final TextView mPokemonTv;
public PokemonViewHolder(View itemView) {
super(itemView);
mPokemonTv = (TextView) itemView.findViewById(R.id.tv);
}
public void bindPokemon(String pokemon) {
mPokemonTv.setText(pokemon);
}
}
| apache-2.0 |
nimble-platform/identity-service | identity-service/src/main/java/eu/nimble/core/infrastructure/identity/uaa/KeycloakConfig.java | 1640 | package eu.nimble.core.infrastructure.identity.uaa;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@SuppressWarnings("unused")
@ConfigurationProperties(prefix = "nimble.keycloak")
public class KeycloakConfig {
private String serverUrl;
private String realm;
private final Admin admin = new Admin();
public String getServerUrl() {
return serverUrl;
}
public void setServerUrl(String serverUrl) {
this.serverUrl = serverUrl;
}
public String getRealm() {
return realm;
}
public void setRealm(String realm) {
this.realm = realm;
}
public Admin getAdmin() {
return admin;
}
public static class Admin {
String username;
String password;
String cliendId;
String cliendSecret;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCliendId() {
return cliendId;
}
public void setCliendId(String cliendId) {
this.cliendId = cliendId;
}
public String getCliendSecret() {
return cliendSecret;
}
public void setCliendSecret(String cliendSecret) {
this.cliendSecret = cliendSecret;
}
}
}
| apache-2.0 |