hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
a92fee48afbed6c633e4cf71f2796b8805e09a8b | 2,305 | /*
* #%L
* Gravia :: Integration Tests :: Common
* %%
* Copyright (C) 2010 - 2014 JBoss by Red Hat
* %%
* 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%
*/
package org.jboss.test.gravia.itests.sub.b;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import org.jboss.gravia.resource.ResourceIdentity;
import org.jboss.gravia.runtime.Module;
import org.jboss.gravia.runtime.ModuleActivator;
import org.jboss.gravia.runtime.ModuleContext;
import org.jboss.gravia.runtime.ServiceLocator;
import org.jboss.test.gravia.itests.sub.b1.ModuleStateB;
public class ModuleActivatorB implements ModuleActivator {
@Override
public void start(final ModuleContext context) throws Exception {
MBeanServer server = ServiceLocator.getRequiredService(context, MBeanServer.class);
ModuleStateB moduleState = new ModuleStateB() {
@Override
public String getModuleState() {
return context.getModule().getState().toString();
}
};
StandardMBean mbean = new StandardMBean(moduleState, ModuleStateB.class);
server.registerMBean(mbean, getObjectName(context.getModule()));
}
@Override
public void stop(ModuleContext context) throws Exception {
MBeanServer server = ServiceLocator.getRequiredService(context, MBeanServer.class);
server.unregisterMBean(getObjectName(context.getModule()));
}
private ObjectName getObjectName(Module module) throws MalformedObjectNameException {
ResourceIdentity identity = module.getIdentity();
return new ObjectName("test:name=" + identity.getSymbolicName() + ",version=" + identity.getVersion());
}
}
| 38.416667 | 111 | 0.732321 |
881c12de536ab866d1f55cdfd53d09e881cd8669 | 2,863 | package com.github.nacoscustomerservice;
import com.github.nacoscustomerservice.model.Coffee;
import com.github.nacoscustomerservice.model.CoffeeOrder;
import com.github.nacoscustomerservice.model.NewOrderRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.Arrays;
import java.util.List;
@Component
@Slf4j
public class CustomerRunner implements ApplicationRunner {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@Override
public void run(ApplicationArguments args) throws Exception {
showServiceInstances();
readMenu();
Long id = orderCoffee();
queryOrder(id);
}
private void showServiceInstances() {
log.info("DiscoveryClient: {}", discoveryClient.getClass().getName());
discoveryClient.getInstances("waiter-service").forEach(s -> {
log.info("Host: {}, Port: {}", s.getHost(), s.getPort());
});
}
private void readMenu() {
ParameterizedTypeReference<List<Coffee>> ptr =
new ParameterizedTypeReference<List<Coffee>>() {
};
ResponseEntity<List<Coffee>> list = restTemplate
.exchange("http://waiter-service/coffee/", HttpMethod.GET, null, ptr);
list.getBody().forEach(c -> log.info("Coffee: {}", c));
}
private Long orderCoffee() {
NewOrderRequest orderRequest = NewOrderRequest.builder()
.customer("Li Lei")
.items(Arrays.asList("capuccino"))
.build();
RequestEntity<NewOrderRequest> request = RequestEntity
.post(UriComponentsBuilder.fromUriString("http://waiter-service/order/").build().toUri())
.body(orderRequest);
ResponseEntity<CoffeeOrder> response = restTemplate.exchange(request, CoffeeOrder.class);
log.info("Order Request Status Code: {}", response.getStatusCode());
Long id = response.getBody().getId();
log.info("Order ID: {}", id);
return id;
}
private void queryOrder(Long id) {
CoffeeOrder order = restTemplate
.getForObject("http://waiter-service/order/{id}", CoffeeOrder.class, id);
log.info("Order: {}", order);
}
}
| 37.671053 | 105 | 0.690534 |
5e6296573581377a630d12afa271baf192b83b9d | 2,620 |
package com.cab.libmgmt.dao;
import com.cab.libmgmt.db.DBConnection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Jack Sparrow
*/
public class LoginDao {
public boolean checkUser(String username, String password){
boolean isValidUser = false;
//writing this 3 line codes to skip the authentication process with the database, because database is not created yet.
if(username.equals("admin")){
isValidUser = true;
return isValidUser;
}
// String query = "select username,password from users where username=? and "
// + "password = ?";
// //statement by me String query = "select username,password from users where username=? and password = ?";
// PreparedStatement stmt = DBConnection.conn.prepareStatement(query);
//
// stmt.setString(1, username);
// stmt.setString(2, password);
try {
Statement stmt = DBConnection.conn.createStatement();
String query = "select username,password from user_credential where username='"+username+"' and password='"+password+"'";
ResultSet rs = stmt.executeQuery(query);
if(rs.next()){
isValidUser = true;
}
} catch (SQLException ex) {
Logger.getLogger(LoginDao.class.getName()).log(Level.SEVERE, null, ex);
}
return isValidUser;
}
public String userType(String username)
{
String usertype = null;
//writing this 3 line codes to skip the authentication process with the database, because database is not created yet.
if(username.equals("admin")){
usertype = "admin";
return usertype;
}
try {
Statement stmt = DBConnection.conn.createStatement();
String query = "select type from user_credential where username='"+username+"'";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
usertype = rs.getString(1);
}
} catch (SQLException ex) {
Logger.getLogger(LoginDao.class.getName()).log(Level.SEVERE, null, ex);
}
return usertype;
}
}
| 33.164557 | 168 | 0.55458 |
fa6527396ef1698b0a8ca844e6c81955b237e869 | 962 | package com.symulakr.service.user.service.db.test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = LiquibaseMigrationTest.TestConfiguration.class)
public class LiquibaseMigrationTest {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
void shouldSuccessfullyQueryTableCreatedByLiquibase() throws Exception {
jdbcTemplate.execute("select count(*) from user");
}
@Configuration
@EnableAutoConfiguration
public static class TestConfiguration {
}
}
| 33.172414 | 75 | 0.821206 |
74bc81f4733bc70be210b5b03f3b3ac20ded8a70 | 767 | package de.jpaw8.batch.producers.impl;
import java.util.function.Function;
import java.util.function.ObjIntConsumer;
import de.jpaw8.batch.api.BatchReader;
import de.jpaw8.batch.factories.BatchLinked;
public class BatchReaderMap<E, R> extends BatchLinked implements BatchReader<R> {
private final BatchReader<? extends E> producer;
private final Function<E, R> function;
public BatchReaderMap(BatchReader<? extends E> producer, Function<E, R> function) {
super(producer);
this.producer = producer;
this.function = function;
}
@Override
public void produceTo(final ObjIntConsumer<? super R> whereToPut) throws Exception {
producer.produceTo((data, i) -> whereToPut.accept(function.apply(data), i));
}
}
| 31.958333 | 88 | 0.723598 |
44931ee3adc05438006c685de7023c14ef73e342 | 6,234 | /*******************************************************************************
* Copyright (c) 2010-2011 VIVO Harvester Team. For full list of contributors, please see the AUTHORS file provided.
* All rights reserved.
* This program and the accompanying materials are made available under the terms of the new BSD license which accompanies this distribution, and is available at http://www.opensource.org/licenses/bsd-license.html
******************************************************************************/
package org.vivoweb.harvester.util;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Adapts Enumerations and Iterators to be Iterable
* @param <T> type
*/
public class IterableAdaptor<T> {
/**
* sometimes you have an Enumeration and you want an Iterable but want to cast the elements to a subtype
* @param <T> return subtype
* @param <E> original type
* @param enin enumeration to adapt
* @param returnClass the subtype to cast each element
* @return an iterable adapter for the enumeration with each element casted
*/
public static <E, T extends E> Iterable<T> adapt(final Enumeration<E> enin, @SuppressWarnings("unused") Class<T> returnClass) {
return enin==null?Collections.<T>emptyList():new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
@Override
public boolean hasNext() {
return enin.hasMoreElements();
}
@SuppressWarnings("unchecked")
@Override
public T next() {
return (T)enin.nextElement();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
/**
* sometimes you have an Enumeration and you want an Iterable
* @param <T> type
* @param enin enumeration to adapt
* @return an iterable adapter for the enumeration
*/
public static <T> Iterable<T> adapt(final Enumeration<T> enin) {
return enin==null?Collections.<T>emptyList():new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
@Override
public boolean hasNext() {
return enin.hasMoreElements();
}
@Override
public T next() {
return enin.nextElement();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
/**
* sometimes you have an Iterator but you want to use a for
* @param <T> type
* @param itin iterator to adapt
* @return an iterable adapter for the iterator
*/
public static <T> Iterable<T> adapt(final Iterator<T> itin) {
return itin==null?Collections.<T>emptyList():new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return itin;
}
};
}
/**
* sometimes you have an Iterator and you want an Iterable but want to cast the elements to a subtype
* @param <T> return subtype
* @param <E> original type
* @param itin iterator to adapt
* @param returnClass the subtype to cast each element
* @return an iterable adapter for the iterator with each element casted
*/
public static <E, T extends E> Iterable<T> adapt(final Iterator<E> itin, @SuppressWarnings("unused") Class<T> returnClass) {
return itin==null?Collections.<T>emptyList():new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
@Override
public boolean hasNext() {
return itin.hasNext();
}
@SuppressWarnings("unchecked")
@Override
public T next() {
return (T)itin.next();
}
@Override
public void remove() {
itin.remove();
}
};
}
};
}
/**
* sometimes you have a NodeList but you want to use a for
* @param nlin NodeList to adapt
* @param returnClass cast each Node to this class
* @return an iterable adapter for the NodeList
*/
public static <T extends Node> Iterable<T> adapt(final NodeList nlin, @SuppressWarnings("unused") Class<T> returnClass) {
return nlin==null?Collections.<T>emptyList():new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
int index = 0;
@Override
public boolean hasNext() {
return this.index < nlin.getLength();
}
@SuppressWarnings("unchecked")
@Override
public T next() {
if(hasNext()) {
return (T)nlin.item(this.index++);
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
/**
* sometimes you have a NodeList but you want to use a for
* @param nlin NodeList to adapt
* @return an iterable adapter for the NodeList
*/
public static Iterable<Node> adapt(final NodeList nlin) {
return adapt(nlin, Node.class);
}
/**
* sometimes you have a NamedNodeMap but you want to use a for
* @param nnmin NamedNodeMap to adapt
* @param returnClass cast each Node to this class
* @return an iterable adapter for the NodeList
*/
public static <T extends Node> Iterable<T> adapt(final NamedNodeMap nnmin, @SuppressWarnings("unused") Class<T> returnClass) {
return nnmin==null?Collections.<T>emptyList():new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
int index = 0;
@Override
public boolean hasNext() {
return this.index < nnmin.getLength();
}
@SuppressWarnings("unchecked")
@Override
public T next() {
if(hasNext()) {
return (T)nnmin.item(this.index++);
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
/**
* sometimes you have a NamedNodeMap but you want to use a for
* @param nnmin NamedNodeMap to adapt
* @return an iterable adapter for the NodeList
*/
public static Iterable<Node> adapt(final NamedNodeMap nnmin) {
return adapt(nnmin, Node.class);
}
}
| 28.081081 | 213 | 0.633622 |
5e7efb9a128536bcdfe1a5cceb7ab6a4f8f9f887 | 872 | package com.xuxl.redis.admin.mapper;
import com.xuxl.redis.admin.entity.Cluster;
import com.xuxl.redis.admin.entity.ClusterCriteria;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ClusterMapper {
long countByExample(ClusterCriteria example);
int deleteByExample(ClusterCriteria example);
int deleteByPrimaryKey(Integer id);
int insert(Cluster record);
int insertSelective(Cluster record);
List<Cluster> selectByExample(ClusterCriteria example);
Cluster selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") Cluster record, @Param("example") ClusterCriteria example);
int updateByExample(@Param("record") Cluster record, @Param("example") ClusterCriteria example);
int updateByPrimaryKeySelective(Cluster record);
int updateByPrimaryKey(Cluster record);
} | 28.129032 | 109 | 0.775229 |
c5a82665d5e7d62c4f33b676349103f2e6a42849 | 167 | package com.room.ui.viewmodel;
import android.arch.lifecycle.ViewModel;
/**
* author by Anuj Sharma on 12/7/2017.
*/
public class BaseModel extends ViewModel{
}
| 13.916667 | 41 | 0.736527 |
b8da2c7dbb439bf08c00ab2f48dec7044cb68660 | 717 | package lt.insoft.webdriver.testCase;
import org.junit.After;
import lt.insoft.webdriver.testCase.webTester.WebTester;
import lt.insoft.webdriver.testCase.webTester.WebTesterBase;
public class WebDriverTestCase implements AutoCloseable {
protected WebTester t = null;
protected int threadId;
@After
public void after() throws Exception {
}
public WebDriverTestCase() {
setTester(new WebTester());
}
public WebTesterBase getTester() {
return t;
}
public void setTester(WebTester t) {
this.t = t;
}
@Override
public void close() throws Exception {
t.destroy();
}
public void setThreadId(int threadId) {
this.threadId = threadId;
}
public int getThreadId() {
return threadId;
}
} | 17.487805 | 60 | 0.736402 |
2e6c947f399e77c79d52481e190d579b2de8c1b4 | 13,199 | package org.azbuilder.api;
import com.yahoo.elide.core.exceptions.HttpStatus;
import org.junit.jupiter.api.Test;
import org.springframework.test.context.jdbc.Sql;
import static com.yahoo.elide.test.jsonapi.JsonApiDSL.*;
import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.equalTo;
class WorkspaceTests extends ServerApplicationTests{
@Test
@Sql(statements = {
"DELETE SCHEDULE; DELETE step; DELETE history; DELETE job; DELETE variable; DELETE workspace; DELETE implementation; DELETE version; DELETE module; DELETE vcs; DELETE FROM provider; DELETE FROM team; DELETE FROM organization;",
"INSERT INTO organization (id, name, description) VALUES\n" +
"\t\t('a42f538b-8c75-4311-8e73-ea2c0f2fb577','Organization','Description');",
"INSERT INTO team (id, name, manage_workspace, manage_module, manage_provider, organization_id) VALUES\n" +
"\t\t('a42f538b-8c75-4311-8e73-ea2c0f2fb579','sample_team', true, true, true, 'a42f538b-8c75-4311-8e73-ea2c0f2fb577');",
"INSERT INTO vcs (id, name, description, vcs_type, organization_id) VALUES\n" +
"\t\t('0f21ba16-16d4-4ac7-bce0-3484024ee6bf','publicConnection', 'publicConnection', 'PUBLIC', 'a42f538b-8c75-4311-8e73-ea2c0f2fb577');",
"INSERT INTO workspace (id, name, source, branch, terraform_version, organization_id, vcs_id) VALUES\n" +
"\t\t('c05da917-81a3-4da3-9619-20b240cbd7f7','Workspace','https://github.com/AzBuilder/terraform-sample-repository.git', 'main', '0.15.2', 'a42f538b-8c75-4311-8e73-ea2c0f2fb577', '0f21ba16-16d4-4ac7-bce0-3484024ee6bf');"
})
void workspaceApiGetTest() {
when()
.get("/api/v1/organization/a42f538b-8c75-4311-8e73-ea2c0f2fb577/workspace")
.then()
.log().all()
.body(equalTo(
data(
resource(
type( "workspace"),
id("c05da917-81a3-4da3-9619-20b240cbd7f7"),
attributes(
attr("branch", "main"),
attr("name", "Workspace"),
attr("source", "https://github.com/AzBuilder/terraform-sample-repository.git"),
attr("terraformVersion", "0.15.2")
),
relationships(
relation("history"),
relation("job"),
relation("organization",true,
resource(
type("organization"),
id("a42f538b-8c75-4311-8e73-ea2c0f2fb577")
)
),
relation("schedule"),
relation("variable"),
relation("vcs",true,
resource(
type("vcs"),
id("0f21ba16-16d4-4ac7-bce0-3484024ee6bf")
)
)
)
)
).toJSON())
)
.log().all()
.statusCode(HttpStatus.SC_OK);
}
@Test
@Sql(statements = {
"DELETE SCHEDULE; DELETE step; DELETE history; DELETE job; DELETE variable; DELETE workspace; DELETE implementation; DELETE version; DELETE module; DELETE vcs; DELETE FROM provider; DELETE FROM team; DELETE FROM organization;",
"INSERT INTO organization (id, name, description) VALUES\n" +
"\t\t('a42f538b-8c75-4311-8e73-ea2c0f2fb577','Organization','Description');",
"INSERT INTO team (id, name, manage_workspace, manage_module, manage_provider, organization_id) VALUES\n" +
"\t\t('a42f538b-8c75-4311-8e73-ea2c0f2fb579','sample_team', true, true, true, 'a42f538b-8c75-4311-8e73-ea2c0f2fb577');",
"INSERT INTO workspace (id, name, source, branch, terraform_version, organization_id) VALUES\n" +
"\t\t('c05da917-81a3-4da3-9619-20b240cbd7f7','Workspace','https://github.com/AzBuilder/terraform-sample-repository.git', 'main', '0.15.2', 'a42f538b-8c75-4311-8e73-ea2c0f2fb577');",
"INSERT INTO variable (id, variable_key, variable_value, variable_category, sensitive, workspace_id, variable_description, hcl) VALUES\n" +
"\t\t('4ea7855d-ab07-4080-934c-3aab429da889','variableKey','variableValue', 'TERRAFORM', false, 'c05da917-81a3-4da3-9619-20b240cbd7f7', 'someDescription', true);"
})
void variableApiGetTest() {
when()
.get("/api/v1/organization/a42f538b-8c75-4311-8e73-ea2c0f2fb577/workspace/c05da917-81a3-4da3-9619-20b240cbd7f7/variable")
.then()
.log().all()
.body(equalTo(
data(
resource(
type( "variable"),
id("4ea7855d-ab07-4080-934c-3aab429da889"),
attributes(
attr("category", "TERRAFORM"),
attr("description", "someDescription"),
attr("hcl", true),
attr("key", "variableKey"),
attr("sensitive", false),
attr("value", "variableValue")
),
relationships(
relation("workspace",true,
resource(
type("workspace"),
id("c05da917-81a3-4da3-9619-20b240cbd7f7")
)
)
)
)
).toJSON())
)
.log().all()
.statusCode(HttpStatus.SC_OK);
}
@Test
@Sql(statements = {
"DELETE SCHEDULE; DELETE step; DELETE history; DELETE job; DELETE variable; DELETE workspace; DELETE implementation; DELETE version; DELETE module; DELETE vcs; DELETE FROM provider; DELETE FROM team; DELETE FROM organization;",
"INSERT INTO organization (id, name, description) VALUES\n" +
"\t\t('a42f538b-8c75-4311-8e73-ea2c0f2fb577','Organization','Description');",
"INSERT INTO team (id, name, manage_workspace, manage_module, manage_provider, organization_id) VALUES\n" +
"\t\t('a42f538b-8c75-4311-8e73-ea2c0f2fb579','sample_team', true, true, true, 'a42f538b-8c75-4311-8e73-ea2c0f2fb577');",
"INSERT INTO workspace (id, name, source, branch, terraform_version, organization_id) VALUES\n" +
"\t\t('c05da917-81a3-4da3-9619-20b240cbd7f7','Workspace','https://github.com/AzBuilder/terraform-sample-repository.git', 'main', '0.15.2', 'a42f538b-8c75-4311-8e73-ea2c0f2fb577');",
"INSERT INTO history (id, output, workspace_id) VALUES\n" +
"\t\t('4ea7855d-ab07-4080-934c-3aab429da889','sampleOutput', 'c05da917-81a3-4da3-9619-20b240cbd7f7');"
})
void stateApiGetTest() {
when()
.get("/api/v1/organization/a42f538b-8c75-4311-8e73-ea2c0f2fb577/workspace/c05da917-81a3-4da3-9619-20b240cbd7f7/history")
.then()
.log().all()
.body(equalTo(
data(
resource(
type( "history"),
id("4ea7855d-ab07-4080-934c-3aab429da889"),
attributes(
attr("createdBy", null),
attr("createdDate", null),
attr("output", "sampleOutput"),
attr("updatedBy", null),
attr("updatedDate", null)
),
relationships(
relation("workspace",true,
resource(
type("workspace"),
id("c05da917-81a3-4da3-9619-20b240cbd7f7")
)
)
)
)
).toJSON())
)
.log().all()
.statusCode(HttpStatus.SC_OK);
}
@Test
@Sql(statements = {
"DELETE SCHEDULE; DELETE step; DELETE history; DELETE job; DELETE variable; DELETE workspace; DELETE implementation; DELETE version; DELETE module; DELETE vcs; DELETE FROM provider; DELETE FROM team; DELETE FROM organization;",
"INSERT INTO organization (id, name, description) VALUES\n" +
"\t\t('a42f538b-8c75-4311-8e73-ea2c0f2fb577','Organization','Description');",
"INSERT INTO team (id, name, manage_workspace, manage_module, manage_provider, organization_id) VALUES\n" +
"\t\t('a42f538b-8c75-4311-8e73-ea2c0f2fb579','sample_team', true, true, true, 'a42f538b-8c75-4311-8e73-ea2c0f2fb577');",
"INSERT INTO workspace (id, name, source, branch, terraform_version, organization_id) VALUES\n" +
"\t\t('c05da917-81a3-4da3-9619-20b240cbd7f7','Workspace','https://github.com/AzBuilder/terraform-sample-repository.git', 'main', '0.15.2', 'a42f538b-8c75-4311-8e73-ea2c0f2fb577');",
"INSERT INTO schedule (id, cron, tcl, enabled, description, workspace_id) VALUES\n" +
"\t\t('4ea7855d-ab07-4080-934c-3aab429da889','0/30 0/1 * 1/1 * ? *', 'sampleSchedule', true, 'sampleDescription', 'c05da917-81a3-4da3-9619-20b240cbd7f7');"
})
void scheduleApiGetTest() {
when()
.get("/api/v1/organization/a42f538b-8c75-4311-8e73-ea2c0f2fb577/workspace/c05da917-81a3-4da3-9619-20b240cbd7f7/schedule")
.then()
.log().all()
.body(equalTo(
data(
resource(
type( "schedule"),
id("4ea7855d-ab07-4080-934c-3aab429da889"),
attributes(
attr("createdBy", null),
attr("createdDate", null),
attr("cron", "0/30 0/1 * 1/1 * ? *"),
attr("description", "sampleDescription"),
attr("enabled", true),
attr("tcl", "sampleSchedule"),
attr("updatedBy", null),
attr("updatedDate", null)
),
relationships(
relation("workspace",true,
resource(
type("workspace"),
id("c05da917-81a3-4da3-9619-20b240cbd7f7")
)
)
)
)
).toJSON())
)
.log().all()
.statusCode(HttpStatus.SC_OK);
}
}
| 65.341584 | 240 | 0.434124 |
e2b09f77233aa62035b14ba203bfa670c1324885 | 7,587 | /**
* Copyright (c) 2009, A.Q.Yang.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* RandomReader.java
* @since 2009-04-29
*
* $Id$
*/
package com.aqy.openexr4j.header.io;
import static com.aqy.openexr4j.header.io.BasicDataTypeConstant.BIT_NUMBER_OF_BYTE;
import static com.aqy.openexr4j.header.io.BasicDataTypeConstant.BYTE_NUMBER_OF_INTEGER;
import static com.aqy.openexr4j.header.io.BasicDataTypeConstant.BYTE_NUMBER_OF_LONG;
import org.apache.log4j.Logger;
/**
* RandomReader.java
*
* @author [email protected]
* @since 2009-04-29
* @version $Id$
*
*/
public class ByteArrayReader {
// log4j logger
private final static Logger log = Logger.getLogger(ByteArrayReader.class);
/**
* ReaderUtils.byteArrayReader should be used as public access.
*
* @see {@link com.aqy.openexr4j.header.io.ReaderUtils}
*
*/
ByteArrayReader() {
// default constructor
}
/**
* Reads an integer at the offset of a byte array.
*
* @param byteAttay the byte array
* @param offset the offset
* @return an integer
*
* */
public int readInteger(byte[] byteArray, int offset) {
int result = 0;
// read integer byte by byte
for(int i=0; i<BYTE_NUMBER_OF_INTEGER; ++i) {
// uses short since the data is an unsigned byte
short s = (short)(byteArray[offset + i] & 0xff);
// compute the bits to shift to the left
int bitsToShift = (i * BIT_NUMBER_OF_BYTE);
// aggregate the result
result |= s << bitsToShift;
log.trace(String.format("%d. [0x%x] read, %d bits to shift, resulting [0x%x].",
i, s, bitsToShift, result));
}
log.debug(String.format("%d bits [0x%x] read.",
BYTE_NUMBER_OF_INTEGER * BIT_NUMBER_OF_BYTE, result));
return result;
}
/**
* Reads a float at the offset of a byte array.
*
* @param byteArray the byte array
* @param offset the offset
* @return a float number
*
* */
public float readFloat(byte[] byteArray, int offset) {
// reads the raw bits of the float
int bits = readInteger(byteArray, offset);
// gets the float by raw bits
return Float.intBitsToFloat(bits);
}
/**
* Reads a long at the offset of a byte array.
*
* @param byteArray the byte array
* @param offset the offset
* @return a long number
*
* */
public long readLong(byte[] byteArray, int offset) {
long result = 0;
// read integer byte by byte
for(int i=0; i<BYTE_NUMBER_OF_LONG; ++i) {
// uses short since the data is an unsigned byte
short s = (short)(byteArray[offset + i] & 0xff);
// compute the bits to shift to the left
int bitsToShift = (i * BIT_NUMBER_OF_BYTE);
// aggregate the result
result |= s << bitsToShift;
log.trace(String.format("%d. [0x%x] read, %d bits to shift, resulting [0x%x].",
i, s, bitsToShift, result));
}
log.debug(String.format("%d bits [0x%x] read.",
BYTE_NUMBER_OF_LONG * BIT_NUMBER_OF_BYTE, result));
return result;
}
/**
* Reads a double number at the offset of a byte array.
*
* @param byteArray the byte array
* @param offset the offset
* @return a double number
*
* */
public double readDouble(byte[] byteArray, int offset) {
// read raw bits of a double number
long bits = readLong(byteArray, offset);
// get the double number by the raw bits
return Double.longBitsToDouble(bits);
}
/**
* Reads a byte at the offset of a byte array.
*
* @param byteArray the byte array
* @param offset the offset
* @return a byte
*
* */
public byte readByte(byte[] byteArray, int offset) {
return byteArray[offset];
}
/**
* Reads a char at the offset of a byte array.
*
* @param byteArray the byte array
* @param offset the offset
* @return a char
*
* */
public char readChar(byte[] byteArray, int offset) {
return (char)byteArray[offset];
}
/**
* Reads a char array of provided length at the offset of a byte array.
*
* @param byteArray the byte array
* @param offset the offset
* @param length the length of the result char array
* @return the char array
*
* */
public char[] readCharArray(byte[] byteArray, int offset, int length) {
char[] array = new char[length];
for(int i=0; i<length; ++i) {
array[i] = (char)byteArray[offset + i];
}
return array;
}
/**
* Reads a null-terminated string at the offset of a byte array. It also provides
* a length requirement for minimum length and maximum length.
*
* @param byteArray the byte array
* @param offset the offset
* @param minimum the minimum length
* @param maximum the maximum length
* @return a string meets the length requirement
*
* @throws EndOfInputException unexpected end of input
* @throws StringTooLongException string exceeds the maximum length
* @throws StringTooShortException string length is under minimum length requirement
*
* */
public String readString(byte[] byteArray, int offset, int minimum, int maximum)
throws EndOfInputException, StringTooLongException, StringTooShortException {
StringBuilder builder = new StringBuilder();
boolean nullRead = false;
// maximum reads could be maximum + 1, the one is the terminator, '\0'
for(int i=0; i <= maximum; ++i) {
if(i < byteArray.length) {
byte b = byteArray[offset + i];
if(b == 0) {
// the end of string
nullRead = true;
break;
} else {
builder.append((char)b);
}
} else {
// array too short
throwEndOfInputeException(builder);
}
}
if(!nullRead) {
// too long
throw new StringTooLongException(builder.toString(), maximum);
} else if(builder.length() < minimum) {
// too short
throw new StringTooShortException(builder.toString(), minimum);
}
return builder.toString();
}
// no null-ternimator of string read but reaches the end of input
private void throwEndOfInputeException(StringBuilder builder) throws EndOfInputException {
throw new EndOfInputException(String.format(
"Reaches the end of input without null-terminator. [%s]", builder));
}
}
| 31.222222 | 92 | 0.663899 |
8543d54c6fcad1f6f02aedc1cb8e3b9fae3bf58b | 2,007 | package io.reflectoring.coderadar.game.service.get;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import io.reflectoring.coderadar.domain.Quest;
import io.reflectoring.coderadar.game.port.driven.ListQuestsPort;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class ListQuestsServiceTest {
@Mock private ListQuestsPort listQuestsPort;
@InjectMocks private ListQuestsService listQuestsService;
@Test
void listQuests() {
List<Quest> quests =
List.of(
new Quest(1L, "Quest 1", "Description", 100, 100, List.of(""), List.of(0), 100, 0, 1L, false),
new Quest(2L, "Quest 2", "Description", 100, 100, List.of(""), List.of(0), 100, 0, 1L, false),
new Quest(3L, "Quest 3", "Description", 100, 100, List.of(""), List.of(0), 100, 0, 1L, false),
new Quest(4L, "Quest 4", "Description", 100, 100, List.of(""), List.of(0), 100, 0, 1L, false));
when(listQuestsPort.listQuests()).thenReturn(quests);
List<Quest> result = listQuestsService.listQuests();
assertThat(result).isEqualTo(quests);
assertThat(result).hasSize(4);
}
@Test
void listQuestsByIds() {
List<Quest> quests =
List.of(
new Quest(1L, "Quest 1", "Description", 100, 100, List.of(""), List.of(0), 100, 0, 1L, false),
new Quest(2L, "Quest 2", "Description", 100, 100, List.of(""), List.of(0), 100, 0, 1L, false),
new Quest(3L, "Quest 3", "Description", 100, 100, List.of(""), List.of(0), 100, 0, 1L, false));
when(listQuestsPort.listQuestsByIds(List.of(1L, 2L, 3L))).thenReturn(quests);
List<Quest> result = listQuestsService.listQuestsByIds(List.of(1L, 2L, 3L));
assertThat(result).isEqualTo(quests);
assertThat(result).hasSize(3);
}
}
| 37.166667 | 107 | 0.672147 |
b574774fad90a5afc18adb8c3bf600a59b821c35 | 2,856 | package quests;
import l2f.commons.util.Rnd;
import l2f.gameserver.model.instances.NpcInstance;
import l2f.gameserver.model.quest.Quest;
import l2f.gameserver.model.quest.QuestState;
import l2f.gameserver.scripts.ScriptFile;
/**
* @author pchayka
*/
public class _288_HandleWithCare extends Quest implements ScriptFile
{
private static final int Ankumi = 32741;
private static final int MiddleGradeLizardScale = 15498;
private static final int HighestGradeLizardScale = 15497;
public _288_HandleWithCare()
{
super(true);
addStartNpc(Ankumi);
addQuestItem(MiddleGradeLizardScale, HighestGradeLizardScale);
}
@Override
public String onEvent(String event, QuestState st, NpcInstance npc)
{
String htmltext = event;
if (event.equalsIgnoreCase("ankumi_q288_03.htm"))
{
st.setState(STARTED);
st.setCond(1);
st.playSound(SOUND_ACCEPT);
}
else if (event.equalsIgnoreCase("request_reward"))
{
if (st.getCond() == 2 && st.getQuestItemsCount(MiddleGradeLizardScale) >= 1)
{
st.takeAllItems(MiddleGradeLizardScale);
switch (Rnd.get(1, 6))
{
case 1:
st.giveItems(959, 1);
break;
case 2:
st.giveItems(960, 1);
break;
case 3:
st.giveItems(960, 2);
break;
case 4:
st.giveItems(960, 3);
break;
case 5:
st.giveItems(9557, 1);
break;
case 6:
st.giveItems(9557, 2);
break;
}
htmltext = "ankumi_q288_06.htm";
st.exitCurrentQuest(true);
}
else if (st.getCond() == 3 && st.getQuestItemsCount(HighestGradeLizardScale) >= 1)
{
st.takeAllItems(HighestGradeLizardScale);
switch (Rnd.get(1, 4))
{
case 1:
st.giveItems(959, 1);
st.giveItems(9557, 1);
break;
case 2:
st.giveItems(960, 1);
st.giveItems(9557, 1);
break;
case 3:
st.giveItems(960, 2);
st.giveItems(9557, 1);
break;
case 4:
st.giveItems(960, 3);
st.giveItems(9557, 1);
break;
}
htmltext = "ankumi_q288_06.htm";
st.exitCurrentQuest(true);
}
else
{
htmltext = "ankumi_q288_07.htm";
st.exitCurrentQuest(true);
}
}
return htmltext;
}
@Override
public String onTalk(NpcInstance npc, QuestState st)
{
String htmltext = "noquest";
int npcId = npc.getNpcId();
int cond = st.getCond();
if (npcId == Ankumi)
{
if (cond == 0)
{
if (st.getPlayer().getLevel() >= 82)
htmltext = "ankumi_q288_01.htm";
else
{
htmltext = "ankumi_q288_00.htm";
st.exitCurrentQuest(true);
}
}
else if (cond == 1)
htmltext = "ankumi_q288_04.htm";
else if (cond == 2 || cond == 3)
htmltext = "ankumi_q288_05.htm";
}
return htmltext;
}
@Override
public void onLoad()
{
}
@Override
public void onReload()
{
}
@Override
public void onShutdown()
{
}
} | 20.546763 | 85 | 0.630952 |
af0c7fc0bb5c39ab3d75c3fe739b75f4da119616 | 6,252 | package com.oss.project;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.joda.time.DateTime;
import com.eova.aop.AopContext;
import com.eova.aop.MetaObjectIntercept;
import com.eova.common.utils.io.FileUtil;
import com.eova.common.utils.time.FormatUtil;
import com.eova.config.EovaConfig;
import com.eova.model.MetaObject;
import com.eova.service.sm;
import com.eova.template.common.util.TemplateUtil;
import com.eova.widget.WidgetManager;
import com.jfinal.core.Controller;
import com.oss.model.Project;
import com.oss.model.ProjectFj;
public class ProjectController extends Controller {
final Controller ctrl = this;
static final int BUFFER_SIZE = 100 * 1024;
/** 自定义拦截器 **/
protected MetaObjectIntercept intercept = null;
public void add() throws Exception {
String objectCode = this.getPara(0);
MetaObject object = sm.meta.getMeta(objectCode);
// 构建关联参数值
WidgetManager.buildRef(this, object);
intercept = TemplateUtil.initIntercept(object.getBizIntercept());
if (intercept != null) {
AopContext ac = new AopContext(ctrl, object);
intercept.addInit(ac);
setAttr("author_name", ac.user.get("nickname"));
setAttr("create_time", FormatUtil.format(new Date(), FormatUtil.YYYY_MM_DD_HH_MM_SS));
}
setAttr("object", object);
setAttr("fields", object.getFields());
render("/oss/project/add.html");
}
public void update() throws Exception {
int id = getParaToInt(0);
Project project = Project.dao.findById(id);
setAttr("project", project);
render("/oss/project/update.html");
}
public void detail() throws Exception {
int id = getParaToInt(0);
Project project = Project.dao.findById(id);
setAttr("project", project);
render("/oss/project/detail.html");
}
public void upload() throws Exception {
int id = getParaToInt(0);
Project project = Project.dao.findById(id);
setAttr("project", project);
render("/oss/project/upload.html");
}
public void plupload() throws Exception {
HttpServletRequest request = this.getRequest();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
int id = getParaToInt(0);
if (isMultipart) {
String fileName = "";
Integer chunk = 0, chunks = 0;
String fileDir = EovaConfig.props.get("static_root");
String canonical_path = File.separator + "project" + File.separator
+ String.valueOf(id);
// 检查文件目录,不存在则创建
File folder = new File(fileDir + canonical_path);
if (!folder.exists()) {
folder.mkdirs();
}
DiskFileItemFactory diskFactory = new DiskFileItemFactory();
// threshold 极限、临界值,即硬盘缓存 1M
diskFactory.setSizeThreshold(4 * 1024);
ServletFileUpload upload = new ServletFileUpload(diskFactory);
// 设置允许上传的最大文件大小(单位MB)
upload.setSizeMax(1024 * 1048576);
upload.setHeaderEncoding("UTF-8");
try {
List<FileItem> fileList = upload.parseRequest(request);
Iterator<FileItem> it = fileList.iterator();
boolean flag = true;
while (it.hasNext()) {
FileItem item = it.next();
String name = item.getFieldName();
InputStream input = item.getInputStream();
if ("name".equals(name)) {
fileName = Streams.asString(input);
continue;
}
if ("chunk".equals(name)) {
chunk = Integer.valueOf(Streams.asString(input));
continue;
}
if ("chunks".equals(name)) {
chunks = Integer.valueOf(Streams.asString(input));
continue;
}
// 处理上传文件内容
if (!item.isFormField()) {
// 目标文件
File destFile = new File(folder, fileName);
// 文件已存在修改旧文件名(上传了同名的文件)
if (chunk == 0 && destFile.exists()) {
renameFile(destFile);
destFile = new File(folder, fileName);
}
// 合成文件
flag = appendFile(input, destFile);
if (!flag) {
break;
}
}
}
if (flag) {
ProjectFj.dao.attach(this, id, fileName, canonical_path,
fileName.substring(fileName.lastIndexOf(".") + 1));
}
} catch (FileUploadException ex) {
System.out.println("上传文件失败:" + ex.getMessage());
return;
}
}
render("/oss/project/upload.html");
}
public void download() {
String id = getPara(0);
ProjectFj fj = ProjectFj.dao.loadById(this, id);
renderFile(FileUtil.formatPath(fj.get("canonical_path").toString())
+ File.separator + fj.get("filename").toString());
}
private boolean appendFile(InputStream in, File destFile) {
OutputStream out = null;
try {
// plupload 配置了chunk的时候新上传的文件append到文件末尾
if (destFile.exists()) {
out = new BufferedOutputStream(new FileOutputStream(destFile,
true), BUFFER_SIZE);
} else {
out = new BufferedOutputStream(new FileOutputStream(destFile),
BUFFER_SIZE);
}
in = new BufferedInputStream(in, BUFFER_SIZE);
int len = 0;
byte[] buffer = new byte[BUFFER_SIZE];
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
} finally {
try {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
/**
* 文件重命名
*
* @throws Exception
*/
private void renameFile(File file) throws Exception {
if (null != file) {
String fName = file.getCanonicalPath();
String path = fName.substring(0, fName.lastIndexOf("\\"));
String fileName = file.getName();
String newFileName = fileName.substring(0,
fileName.lastIndexOf("."));
String prefix = fileName.substring(fileName.lastIndexOf("."));
file.renameTo(new File(path, newFileName + "-"
+ DateTime.now().toString("yyMMddHHmmss") + prefix));
}
}
}
| 28.162162 | 89 | 0.684421 |
82daa63de5a2c11d5726015e785028aae58e17c2 | 2,427 | package kernbeisser.Windows.Trasaction;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import kernbeisser.DBConnection.DBConnection;
import kernbeisser.DBEntities.Transaction;
import kernbeisser.DBEntities.User;
import kernbeisser.Enums.TransactionType;
import kernbeisser.Exeptions.InvalidTransactionException;
import kernbeisser.Windows.MVC.IModel;
import lombok.Cleanup;
import lombok.Getter;
public class TransactionModel implements IModel<TransactionController> {
private final User owner;
@Getter private final TransactionType transactionType;
TransactionModel(User owner, TransactionType transactionType) {
this.transactionType = transactionType;
this.owner = owner;
}
private final Collection<Transaction> transactions = new ArrayList<>();
void addTransaction(Transaction t) {
transactions.add(t);
}
User findUser(String username) throws NoResultException {
if (username.matches("Benutzer[\\[]\\d+[]]")) {
return User.getById(Integer.parseInt(username.replace("Benutzer[", "").replace("]", "")));
}
return User.getByUsername(username);
}
Collection<Transaction> getTransactions() {
return transactions;
}
void transfer() throws InvalidTransactionException {
@Cleanup EntityManager em = DBConnection.getEntityManager();
EntityTransaction et = em.getTransaction();
et.begin();
for (Transaction transaction : transactions) {
String info = transaction.getInfo();
if (transactionType == TransactionType.PAYIN && (info == null || info.isEmpty())) {
info = "Guthabeneinzahlung";
}
try {
Transaction.doTransaction(
em,
transaction.getFromUser(),
transaction.getToUser(),
transaction.getValue(),
transactionType,
info);
} catch (InvalidTransactionException e) {
et.rollback();
em.close();
throw e;
}
}
em.flush();
et.commit();
}
double getSum() {
return transactions.stream().mapToDouble(Transaction::getValue).sum();
}
int getCount() {
return transactions.size();
}
public void remove(Transaction selectedTransaction) {
transactions.remove(selectedTransaction);
}
public User getOwner() {
return owner;
}
}
| 27.579545 | 96 | 0.700453 |
ad5961279d88de6d8a9821470270e2b2e332c51b | 673 | package com.dopoiv.clinic.project.order.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dopoiv.clinic.project.order.entity.Order;
/**
* @author dov
* @since 2021-03-03
*/
public interface OrderMapper extends BaseMapper<Order> {
/**
* 分页查询订单
*
* @param page 分页
* @param params 参数个数
* @param startDate 开始日期
* @param endDate 结束日期
* @return {@link IPage<Order>}
*/
IPage<Order> selectPageForQuery(Page<Order> page, Order params, String startDate, String endDate);
}
| 26.92 | 102 | 0.699851 |
7efad2bd62783638d9b0bc1c5cc7de03e8c4427a | 2,901 | /*
* Copyright (c) 2019. Chris Wohlbrecht
*
* MIT License
* 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 de.smarthome.assistant.menu.dto.mapper;
import de.smarthome.assistant.menu.dto.IngredientsRequestDto;
import de.smarthome.assistant.menu.dto.IngredientsResponseDto;
import de.smarthome.assistant.menu.dto.MenuRequestDto;
import de.smarthome.assistant.menu.dto.MenuResponseDto;
import de.smarthome.assistant.menu.persistance.model.Menu;
import java.util.List;
import java.util.stream.Collectors;
import de.smarthome.assistant.menu.persistance.model.MenuIngredient;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.Named;
import org.mapstruct.factory.Mappers;
@Mapper(componentModel = "spring")
public interface MenuMapper {
MenuMapper INSTANCE = Mappers.getMapper(MenuMapper.class);
@Mappings({ @Mapping(source = "ingredients", target = "ingredients", qualifiedByName = "ingredientRequestMap") })
Menu menuRequestDto2Menu(MenuRequestDto menuRequestDto);
@Mappings({ @Mapping(source = "ingredients", target = "ingredients", qualifiedByName = "ingredientsMap") })
MenuResponseDto menu2MenuResponseDto(Menu menu);
MenuRequestDto menuResponseDto2MenuRequestDto(MenuResponseDto menuResponseDto);
@Named("ingredientsMap")
default List<IngredientsResponseDto> ingredientsMap(List<MenuIngredient> ingredients) {
return ingredients.stream().map(IngredientsMapper.INSTANCE::ingredient2IngredientsResponseDto).collect(Collectors.toList());
}
@Named("ingredientRequestMap")
default List<MenuIngredient> ingredientRequestMap(List<IngredientsRequestDto> ingredientsRequestDtos) {
return ingredientsRequestDtos.stream().map(IngredientsMapper.INSTANCE::ingredientsRequestDto2Ingredient)
.collect(Collectors.toList());
}
}
| 44.630769 | 132 | 0.780076 |
d3b4be0d214e89aa27b7d1928ddbc2945214fd73 | 2,868 | package uk.co.optimisticpanda.configuration.healthcheck.annotations;
import static org.fest.assertions.Assertions.assertThat;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import uk.co.optimisticpanda.configuration.healthcheck.ConfigurationErrorReporter;
import uk.co.optimisticpanda.configuration.healthcheck.Violation;
import uk.co.optimisticpanda.configuration.healthcheck.annotations.EnableInProduction;
import uk.co.optimisticpanda.configuration.healthcheck.annotations.TestInstances.EnabledInProductionObject;
public class EnableInProductionTest {
private ConfigurationErrorReporter reporter;
@Before
public void createReporter() {
reporter = new ConfigurationErrorReporter();
}
@Test
public void enabledInProductionEnabledPrimitiveHasNoError() {
EnabledInProductionObject annotatedInstance = new EnabledInProductionObject(true);
List<Violation> violations = reporter.getErrors(annotatedInstance);
assertThat(violations).isEmpty();
}
@Test
public void enabledInProductionEnabledWrapperHasNoError() {
EnabledInProductionObject annotatedInstance = new EnabledInProductionObject(Boolean.TRUE);
List<Violation> violations = reporter.getErrors(annotatedInstance);
assertThat(violations).isEmpty();
}
@Test
public void enabledInProductionNullHasError() {
EnabledInProductionObject annotatedInstance = new EnabledInProductionObject(null);
List<Violation> violations = reporter.getErrors(annotatedInstance);
assertThat(violations).hasSize(1);
assertThat(violations.get(0).getType()).isEqualTo(EnableInProduction.class);
}
@Test
public void enabledInProductionDisabledPrimitiveHasError() {
EnabledInProductionObject annotatedInstance = new EnabledInProductionObject(false);
List<Violation> violations = reporter.getErrors(annotatedInstance);
assertThat(violations).hasSize(1);
assertThat(violations.get(0).getType()).isEqualTo(EnableInProduction.class);
}
@Test
public void enabledInProductionDisabledWrapperHasError() {
EnabledInProductionObject annotatedInstance = new EnabledInProductionObject(Boolean.FALSE);
List<Violation> violations = reporter.getErrors(annotatedInstance);
assertThat(violations).hasSize(1);
assertThat(violations.get(0).getType()).isEqualTo(EnableInProduction.class);
}
@Test
public void enabledInProductionNotBooleanHasError() {
EnabledInProductionObject annotatedInstance = new EnabledInProductionObject("sampleString");
List<Violation> violations = reporter.getErrors(annotatedInstance);
assertThat(violations).hasSize(1);
assertThat(violations.get(0).getType()).isEqualTo(EnableInProduction.class);
}
}
| 40.394366 | 107 | 0.756625 |
fedff066aa540bdbce721387784f05f11d62cae0 | 779 | package com.icepoint.framework.web.system.expression.node;
/**
* 字面值
*
* @author Jiawei Zhao
*/
public abstract class Literal extends AbstractExpressionNode {
private final TypedValue value;
private final Object originalValue;
protected Literal(Object originalValue, int startPos, int endPos) {
super(startPos, endPos);
this.value = newTypedValue(originalValue);
this.originalValue = originalValue;
}
public TypedValue getLiteralValue() {
return this.value;
}
public Object getOriginalValue() {
return this.originalValue;
}
@Override
public final ExpressionNode[] getChildren() {
return NO_CHILDREN;
}
protected abstract TypedValue newTypedValue(Object originalValue);
}
| 22.257143 | 71 | 0.690629 |
b78abf0dfc89f231e706a596a1774db43c1a14d9 | 1,009 | package net.brian.italker.common.app;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import net.brian.italker.common.R;
/**
* Created by with_you on 2017/8/19.
*/
public abstract class ToolbarActivity extends Activity {
protected Toolbar mToolbar;
@Override
protected void initWidget() {
super.initWidget();
initToolbar((Toolbar) findViewById(R.id.toolbar));
}
/**
* 初始化toolbar
* @param toolbar Toolbar
*/
public void initToolbar(Toolbar toolbar){
mToolbar = toolbar;
if(toolbar!=null){
setSupportActionBar(toolbar);
}
initTitleNeedBack();
}
protected void initTitleNeedBack(){
//设置左上角的返回按钮为实际的返回效果
ActionBar actionBar = getSupportActionBar();
if(actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
}
}
| 22.931818 | 59 | 0.613479 |
4c23e04244727741b11a59a23f209d6ba26c5e8f | 9,669 | package cz.abclinuxu.datoveschranky.impl;
import cz.abclinuxu.datoveschranky.common.entities.DataBox;
import cz.abclinuxu.datoveschranky.common.entities.DeliveryEvent;
import cz.abclinuxu.datoveschranky.common.entities.Hash;
import cz.abclinuxu.datoveschranky.common.entities.MessageEnvelope;
import cz.abclinuxu.datoveschranky.common.entities.MessageType;
import cz.abclinuxu.datoveschranky.common.entities.DeliveryInfo;
import cz.abclinuxu.datoveschranky.common.entities.DocumentIdent;
import cz.abclinuxu.datoveschranky.common.entities.MessageState;
import cz.abclinuxu.datoveschranky.common.entities.MessageStateChange;
import cz.abclinuxu.datoveschranky.common.impl.DataBoxException;
import cz.abclinuxu.datoveschranky.common.interfaces.DataBoxMessagesService;
import cz.abclinuxu.datoveschranky.ws.XMLUtils;
import cz.abclinuxu.datoveschranky.ws.dm.DmInfoPortType;
import cz.abclinuxu.datoveschranky.ws.dm.TDelivery;
import cz.abclinuxu.datoveschranky.ws.dm.TEvent;
import cz.abclinuxu.datoveschranky.ws.dm.THash;
import cz.abclinuxu.datoveschranky.ws.dm.TRecord;
import cz.abclinuxu.datoveschranky.ws.dm.TRecordsArray;
import cz.abclinuxu.datoveschranky.ws.dm.TStateChangesArray;
import cz.abclinuxu.datoveschranky.ws.dm.TStateChangesRecord;
import cz.abclinuxu.datoveschranky.ws.dm.TStatus;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.Holder;
import org.apache.log4j.Logger;
/**
*
* @author xrosecky
*/
public class DataBoxMessagesServiceImpl implements DataBoxMessagesService {
protected DmInfoPortType dataMessageInfo;
static Logger logger = Logger.getLogger(DataBoxMessagesServiceImpl.class);
public DataBoxMessagesServiceImpl(DmInfoPortType dmInfo) {
this.dataMessageInfo = dmInfo;
}
public List<MessageEnvelope> getListOfReceivedMessages(Date from,
Date to, EnumSet<MessageState> filter, int offset, int limit) {
logger.info(String.format("getListOfReceivedMessages: offset:%s limit:%s", offset, limit));
Holder<TRecordsArray> records = new Holder<TRecordsArray>();
Holder<TStatus> status = new Holder<TStatus>();
XMLGregorianCalendar xmlFrom = XMLUtils.toXmlDate(from);
XMLGregorianCalendar xmlTo = XMLUtils.toXmlDate(to);
BigInteger bOffset = BigInteger.valueOf(offset);
BigInteger bLimit = BigInteger.valueOf(limit);
String value = String.valueOf(MessageState.toInt(filter));
dataMessageInfo.getListOfReceivedMessages(xmlFrom, xmlTo, null, value, bOffset, bLimit, records, status);
ErrorHandling.throwIfError("Nemohu stahnout seznam prijatych zprav", status.value);
logger.info(String.format("getListOfReceivedMessages finished"));
return createMessages(records.value, MessageType.RECEIVED);
}
public List<MessageEnvelope> getListOfSentMessages(Date from,
Date to, EnumSet<MessageState> filter, int offset, int limit) {
logger.info(String.format("getListOfSentMessages: offset:%s limit:%s", offset, limit));
Holder<TRecordsArray> records = new Holder<TRecordsArray>();
Holder<TStatus> status = new Holder<TStatus>();
XMLGregorianCalendar xmlSince = XMLUtils.toXmlDate(from);
XMLGregorianCalendar xmlTo = XMLUtils.toXmlDate(to);
BigInteger bOffset = BigInteger.valueOf(offset);
BigInteger bLimit = BigInteger.valueOf(limit);
String value = String.valueOf(MessageState.toInt(filter));
dataMessageInfo.getListOfSentMessages(xmlSince, xmlTo, null, value, bOffset, bLimit, records, status);
ErrorHandling.throwIfError("Nemohu stahnout seznam odeslanych zprav", status.value);
logger.info(String.format("getListOfSentMessages finished"));
return createMessages(records.value, MessageType.SENT);
}
public List<MessageStateChange> GetMessageStateChanges(Date from, Date to) {
logger.info(String.format("GetMessageStateChanges: from:%s to:%s", from, to));
Holder<TStatus> status = new Holder<TStatus>();
Holder<TStateChangesArray> changes = new Holder<TStateChangesArray>();
XMLGregorianCalendar xmlSince = null;
if (from != null) {
xmlSince = XMLUtils.toXmlDate(from);
}
XMLGregorianCalendar xmlTo = null;
if (to != null) {
xmlTo = XMLUtils.toXmlDate(to);
}
dataMessageInfo.getMessageStateChanges(xmlSince, xmlTo, changes, status);
ErrorHandling.throwIfError("GetMessageStateChanges failed", status.value);
List<MessageStateChange> result = new ArrayList<MessageStateChange>();
for (TStateChangesRecord record : changes.value.getDmRecord()) {
MessageStateChange stateChange = new MessageStateChange();
stateChange.setEventTime(record.getDmEventTime().toGregorianCalendar());
stateChange.setMessageId(record.getDmID());
stateChange.setState(MessageState.valueOf(record.getDmMessageStatus()));
result.add(stateChange);
}
logger.info(String.format("GetMessageStateChanges finished, result size is %s.", changes.value.getDmRecord().size()));
return result;
}
public Hash verifyMessage(MessageEnvelope envelope) {
Holder<TStatus> status = new Holder<TStatus>();
Holder<THash> hash = new Holder<THash>();
dataMessageInfo.verifyMessage(envelope.getMessageID(), hash, status);
ErrorHandling.throwIfError("Nemohu overit hash zpravy.", status.value);
return new Hash(hash.value.getAlgorithm(), hash.value.getValue());
}
public void markMessageAsDownloaded(MessageEnvelope env) {
TStatus status = dataMessageInfo.markMessageAsDownloaded(env.getMessageID());
ErrorHandling.throwIfError("Nemohu oznacit zpravu jako prectenou.", status);
}
public DeliveryInfo getDeliveryInfo(MessageEnvelope env) {
Holder<TStatus> status = new Holder<TStatus>();
Holder<TDelivery> delivery = new Holder<TDelivery>();
dataMessageInfo.getDeliveryInfo(env.getMessageID(), delivery, status);
ErrorHandling.throwIfError("Nemohu stahnout informace o doruceni.", status.value);
return MessageValidator.buildDeliveryInfo(env, delivery.value);
}
public void getSignedDeliveryInfo(MessageEnvelope envelope, OutputStream os) {
Holder<TStatus> status = new Holder<TStatus>();
Holder<byte[]> signedDeliveryInfo = new Holder<byte[]>();
dataMessageInfo.getSignedDeliveryInfo(envelope.getMessageID(), signedDeliveryInfo, status);
ErrorHandling.throwIfError(String.format("Nemohu stahnout podepsanou dorucenku pro zpravu s id=%s.",
envelope.getMessageID()), status.value);
try {
os.write(signedDeliveryInfo.value);
os.flush();
logger.info(String.format("getSignedDeliveryInfo successfull"));
} catch (IOException ioe) {
throw new DataBoxException("Chyba pri zapisu do vystupniho proudu.", ioe);
}
}
protected List<MessageEnvelope> createMessages(TRecordsArray records, MessageType type) {
List<MessageEnvelope> result = new ArrayList<MessageEnvelope>();
for (TRecord record : records.getDmRecord()) {
// odesílatel
String senderID = record.getDbIDSender().getValue();
String senderIdentity = record.getDmSender().getValue();
String senderAddress = record.getDmSenderAddress().getValue();
DataBox sender = new DataBox(senderID, senderIdentity, senderAddress);
// příjemce
String recipientID = record.getDbIDRecipient().getValue();
String recipientIdentity = record.getDmRecipient().getValue();
String recipientAddress = record.getDmRecipientAddress().getValue();
DataBox recipient = new DataBox(recipientID, recipientIdentity, recipientAddress);
// anotace
String annotation = record.getDmAnnotation().getValue();
if (annotation == null) { // může se stát, že anotace je null...
annotation = "";
}
String messageID = record.getDmID();
MessageEnvelope env = new MessageEnvelope(type, sender, recipient, messageID, annotation);
if (record.getDmAcceptanceTime().getValue() != null) {
env.setAcceptanceTime(record.getDmAcceptanceTime().getValue().toGregorianCalendar());
}
if (record.getDmDeliveryTime().getValue() != null) {
env.setDeliveryTime(record.getDmDeliveryTime().getValue().toGregorianCalendar());
}
env.setState(MessageState.valueOf(record.getDmMessageStatus().intValue()));
// identifikace zprávy odesílatelem
String senderIdent = record.getDmSenderIdent().getValue();
String senderRefNumber = record.getDmSenderRefNumber().getValue();
env.setSenderIdent(new DocumentIdent(senderRefNumber, senderIdent));
// identifikace zprávy příjemcem
String recipientIdent = record.getDmRecipientIdent().getValue();
String recipientRefNumber = record.getDmRecipientRefNumber().getValue();
env.setRecipientIdent(new DocumentIdent(recipientRefNumber, recipientIdent));
env.setToHands(record.getDmToHands().getValue());
env.setAllowSubstDelivery(record.getDmAllowSubstDelivery().getValue());
env.setPersonalDelivery(record.getDmPersonalDelivery().getValue());
// a máme hotovo :-)
result.add(env);
}
return result;
}
}
| 51.983871 | 119 | 0.71993 |
7e744700708df09a01bf9a01b319edf7bdcf36ad | 4,491 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016-2018:
* Una Thompson (unascribed),
* Isaac Ellingson (Falkreon),
* Jamie Mansfield (jamierocks),
* Alex Ponebshek (capitalthree),
* and contributors
*
* 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.elytradev.concrete.inventory;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
import java.util.function.Predicate;
import com.google.common.collect.Lists;
/**
* A base class for managing fluid storage.
*
* <h2>Validation</h2>
*
* Just like {@link ConcreteItemStorage}, ConcreteFluidTank <em>does not</em> perform its own validation. Rather, this
* is offloaded to its own wrapper for such functionality, {@link ValidatedFluidTankWrapper}.
*
* <h2>Serialization and Deserialization</h2>
*
* <p>If you're using this object to manage the fluid tank of a TileEntity, it takes three small tweaks to get no-fuss
* serialization. In your constructor, add
*
* <code><pre>fluidTank.listen(this::markDirty);</pre></code>
*
* <p>This will mark your tile dirty any time the inventory changes, so that Minecraft won't skip serialization. Then in
* writeToNBT:
*
* <code><pre>tagOut.setTag("fluid_tank", CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.writeNBT(fluidTank, null));</pre></code>
*
* <p>and in readFromNBT:
*
* <code><pre>CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.readNBT(fluidTank, null, tag.getTag("fluid_tank"));</pre></code>
*
* <p>Where <code>fluidTank</code> is your ConcreteFluidTank object. At that point the Forge Capability system will
* do all the work for you on this, and you can focus on the interesting part of making your tile do what it's supposed to.
*
* <h2>Exposing as a capability</h2>
*
* <p>This was mentioned above in the Validation section, but although this object supplies the IFluidHandler interface,
* generally you want to create a ValidatedFluidTankWrapper instead. These wrappers are okay to cache or memoize,
* and merely provide a succinct delegation based on the access rules this object provides.
*
* <p>Simplifying hasCapability and getCapability are outside the scope of this object... but remember that "null" is a
* valid side, and often represents the side a probe observer accesses, so plan your views accordingly.
*
*/
public class ConcreteFluidTank extends FluidTank implements IObservableFluidTank {
private final List<Runnable> listeners = Lists.newArrayList();
private Predicate<FluidStack> fillValidator = Validators.ANY_FLUID;
public ConcreteFluidTank(int capacity) {
this(null, capacity);
}
public ConcreteFluidTank(Fluid fluid, int amount, int capacity) {
this(new FluidStack(fluid, amount), capacity);
}
public ConcreteFluidTank(@Nullable FluidStack fluidStack, int capacity) {
super(fluidStack, capacity);
}
public final ConcreteFluidTank withFillValidator(Predicate<FluidStack> fillValidator) {
this.fillValidator = fillValidator;
return this;
}
public void markDirty() {
listeners.forEach(Runnable::run);
}
@Override
public void listen(@Nonnull Runnable r) {
listeners.add(r);
}
@Override
protected void onContentsChanged() {
this.markDirty();
super.onContentsChanged();
}
@Nonnull
public Predicate<FluidStack> getFillValidator() {
return this.fillValidator;
}
}
| 35.928 | 130 | 0.758183 |
2d1bd7c507fe1c6b7d5960b64cecbf48ede7c3f3 | 1,170 | package com.internousdev.leisurepass.dto;
import java.util.Date;
public class MCategoryDTO {
private int id;
private int categoryId;
private String categoryName;
private String categoryDescription;
private Date insertDate;
private Date updateDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryDescription() {
return categoryDescription;
}
public void setCategoryDescription(String categoryDescription) {
this.categoryDescription = categoryDescription;
}
public Date getInsertDate() {
return insertDate;
}
public void setInsertDate(Date insertDate) {
this.insertDate = insertDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
}
| 18.870968 | 66 | 0.709402 |
a2485024aa5edc76d364cfe49c453a89a8951b85 | 4,645 | package me.gavincook.test.io;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
/**
* @author GavinCook
* @date 2017-04-08
* @since 1.0.0
*/
public class RenameTest {
/**
* 在同目录重命名文件
* @throws IOException
*/
@Test
public void testIORenameFileInSameDir() throws IOException {
File src = new File("/test/file/src");
src.delete();
if (!src.exists()) {
src.createNewFile();
}
boolean ret = src.renameTo(new File("/test/file/dest"));
assert ret;
}
/**
* 在不同目录重命名文件
* @throws IOException
*/
@Test
public void testIORenameFileInDiffDirs() throws IOException {
File src = new File("/test/file/src");
src.delete();
if (!src.exists()) {
src.createNewFile();
}
File targetFile = new File("/test/file-another/dest");
if(!targetFile.getParentFile().exists()){
targetFile.getParentFile().mkdirs();
}
boolean ret = src.renameTo(targetFile);
assert ret;
}
/**
* 重命名非空目录
* @throws IOException
*/
@Test
public void testIORenameDirectory() throws IOException {
File src = new File("/test/file/src");
deleteUnEmptyDir(src);
src.mkdirs();
File subFile = new File(src, "subFile");
if(!subFile.exists()){
subFile.createNewFile();
}
boolean ret = src.renameTo(new File("/test/file/dest"));
assert ret;
}
/**
* NIO方式重命名文件
* @throws IOException
*/
@Test
public void testNIORenameInSameDir() throws IOException {
File src = new File("/test/file/src");
if (!src.exists()) {
src.createNewFile();
}
Path path = Files.move(src.toPath(), Paths.get("/test/file/dest"), StandardCopyOption.REPLACE_EXISTING);
assert path.equals(Paths.get("/test/file/dest"));
}
/**
* NIO方式重命名文件(不同目录)
* @throws IOException
*/
@Test
public void testNIORenameInDiffDirs() throws IOException {
File src = new File("/test/file/src");
if (!src.exists()) {
src.createNewFile();
}
Path path = Files.move(src.toPath(), Paths.get("/test/file-another/dest"), StandardCopyOption.REPLACE_EXISTING);
assert path.equals(Paths.get("/test/file-another/dest"));
}
/**
* NIO方式重命名目录
* @throws IOException
*/
@Test
public void testNIORenameDirectory() throws IOException {
File src = new File("/test/file/src");
deleteUnEmptyDir(src);
src.mkdirs();
File subFile = new File(src, "subFile");
if(!subFile.exists()){
subFile.createNewFile();
}
Path path = Files.move(src.toPath(), Paths.get("/test/file/dest"), StandardCopyOption.REPLACE_EXISTING);
assert path.equals(Paths.get("/test/file/dest"));
}
/**
* 使用guava重命名文件
* @throws IOException
*/
@Test
public void testGuavaRenameFileInSameDir() throws IOException {
File src = new File("/test/file/src");
if (!src.exists()) {
src.createNewFile();
}
com.google.common.io.Files.move(src, new File("/test/file/dest"));
}
/**
* guava方式重命名文件(不同目录)
* @throws IOException
*/
@Test
public void testGuavaRenameInDiffDirs() throws IOException {
File src = new File("/test/file/src");
if (!src.exists()) {
src.createNewFile();
}
com.google.common.io.Files.move(src, new File("/test/file-another/dest"));
}
/**
* NIO方式重命名目录
* @throws IOException
*/
@Test
public void testGuavaRenameDirectory() throws IOException {
File src = new File("/test/file/src");
deleteUnEmptyDir(src);
src.mkdirs();
File subFile = new File(src, "subFile");
if(!subFile.exists()){
subFile.createNewFile();
}
com.google.common.io.Files.move(src, new File("/test/file/dest"));
}
/**
* 删除目录(包括子文件(夹))
* @param dir
*/
private void deleteUnEmptyDir(File dir){
File[] subFiles = dir.listFiles();
if(subFiles == null){
dir.delete();
return;
}
for(File subFile : dir.listFiles()){
if(subFile.isDirectory()){
deleteUnEmptyDir(subFile);
}
subFile.delete();
}
}
}
| 25.949721 | 120 | 0.559526 |
1795917c088b217f8cf8795165f6f000dc3b597c | 2,432 | package com.mikescamell.sharedelementtransitions.flash_fix.programmatic_activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.transition.Fade;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.mikescamell.sharedelementtransitions.R;
public class FlashFixProgrammaticActivityA extends AppCompatActivity {
public static final String STARFISH_IMAGE_URL = "https://upload.wikimedia.org/wikipedia/commons/f/f2/Starfish_09_(paulshaffner).jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flash_fix_a);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Fade fade = new Fade();
fade.excludeTarget(R.id.appBar, true);
fade.excludeTarget(android.R.id.statusBarBackground, true);
fade.excludeTarget(android.R.id.navigationBarBackground, true);
getWindow().setEnterTransition(fade);
getWindow().setExitTransition(fade);
}
final ImageView imageView = (ImageView) findViewById(R.id.flash_fix_xml_activity_a_imageView);
Glide.with(this)
.load(STARFISH_IMAGE_URL)
.centerCrop()
.into(imageView);
Button button = (Button) findViewById(R.id.flash_fix_xml_activity_a_btn);
button.setText(R.string.starfish);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FlashFixProgrammaticActivityA.this, FlashFixProgrammaticActivityB.class);
ActivityOptionsCompat options = ActivityOptionsCompat.
makeSceneTransitionAnimation(FlashFixProgrammaticActivityA.this,
imageView,
ViewCompat.getTransitionName(imageView));
startActivity(intent, options.toBundle());
}
});
}
}
| 40.533333 | 137 | 0.690789 |
ee1de181df408c55d95abb651d3867fc6571b39d | 3,897 | package ch.hsr.ogv.model;
import javafx.geometry.Point3D;
import javafx.scene.paint.Color;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
@XmlType(propOrder = {"uniqueID", "attributeValues"})
public class ModelObject extends ModelBox {
// for un/marshaling only
private String uniqueID = UUID.randomUUID().toString();
private Map<Attribute, String> attributeValues = new LinkedHashMap<Attribute, String>();
private ModelClass modelClass;
public static volatile AtomicInteger modelObjectCounter = new AtomicInteger(0);
public String getUniqueID() {
return uniqueID;
}
public void setUniqueID(String uniqueID) {
this.uniqueID = uniqueID;
}
public Map<Attribute, String> getAttributeValues() {
return attributeValues;
}
public void setAttributeValues(Map<Attribute, String> attributeValues) {
this.attributeValues = attributeValues;
}
public String getAttributeValue(String attributeName) {
for (Attribute attribute : attributeValues.keySet()) {
if (attribute.getName().equals(attributeName)) {
return attributeValues.get(attribute);
}
}
return null;
}
@XmlTransient
public ModelClass getModelClass() {
return modelClass;
}
public void setModelClass(ModelClass modelClass) {
this.modelClass = modelClass;
}
@XmlTransient
public List<ModelObject> getSuperObjects() {
if (this.modelClass == null)
return new ArrayList<ModelObject>();
return this.modelClass.getSuperObjects(this);
}
public void addSuperObject(ModelObject superObject) {
if (this.modelClass == null)
return;
this.modelClass.addSuperObject(this, superObject);
}
public boolean isSuperObject() {
if (this.modelClass == null)
return false;
return !this.modelClass.getModelObjects().contains(this);
}
// for un/marshaling only
public ModelObject() {
}
public ModelObject(String name, ModelClass modelClass, Point3D coordinates, double width, double heigth, Color color) {
super(name, coordinates, width, heigth, color);
this.modelClass = modelClass;
}
public void changeAttributeName(Attribute attribute, String name) {
attribute.setName(name);
setChanged();
notifyObservers(attribute);
}
public void changeAttributeValue(Attribute attribute, String value) {
String oldValue = this.attributeValues.put(attribute, value);
if (oldValue != null) {
setChanged();
notifyObservers(attribute);
}
}
public void changeAttributeValue(String attributeName, String value) {
for (Attribute attribute : attributeValues.keySet()) {
if (attribute.getName().equals(attributeName)) {
changeAttributeValue(attribute, value);
}
}
}
public boolean addAttributeValue(Attribute attribute, String attributeValue) {
if (attributeValues.containsKey(attribute)) {
return false;
}
attributeValues.put(attribute, attributeValue);
setChanged();
notifyObservers(attribute);
return true;
}
public String deleteAttributeValue(Attribute attribute) {
String deleted = attributeValues.remove(attribute);
if (deleted != null) {
setChanged();
notifyObservers(attribute);
}
return deleted;
}
public void updateAttribute(Attribute attribute, String value) {
attributeValues.replace(attribute, value);
}
@Override
public String toString() {
return super.toString() + " - " + name;
}
} | 29.08209 | 123 | 0.651527 |
43570208fcc70e3a53756950e01dae53f78adead | 760 | package claseinner;
interface Engine {
int getFuelCapacity();
}
class Car {
private int plateNumber = 10;
private class OttoEngine implements Engine {
private int fuelCapacity;
private int plateNumber;
public OttoEngine(int fuelCapacity) {
this.fuelCapacity = fuelCapacity;
}
public int getFuelCapacity() {
return fuelCapacity;
}
public void printPlateNumber() {
System.out.println(plateNumber);
System.out.println(Car.this.plateNumber);
}
}
public Engine getEngine() {
OttoEngine engine = new OttoEngine(11);
return engine;
}
}
public class Test {
public static void main(String[] args) {
Car car = new Car();
Engine firstEngine = car.getEngine();
System.out.println(firstEngine.getFuelCapacity());
}
}
| 17.674419 | 52 | 0.713158 |
27a12e6fe74a141a1c6969f565f476b2d003bc2a | 78,946 | package it.polimi.ingsw.view.GUI.controller;
import it.polimi.ingsw.message.connection.CClientDisconnectedMsg;
import it.polimi.ingsw.message.connection.VServerUnableMsg;
import it.polimi.ingsw.message.controllerMsg.*;
import it.polimi.ingsw.message.viewMsg.VActionTokenActivateMsg;
import it.polimi.ingsw.message.viewMsg.VActivateProductionPowerRequestMsg;
import it.polimi.ingsw.message.viewMsg.VChooseActionTurnRequestMsg;
import it.polimi.ingsw.message.viewMsg.VChooseLeaderCardRequestMsg;
import it.polimi.ingsw.model.Resource;
import it.polimi.ingsw.model.TurnAction;
import it.polimi.ingsw.model.TypeResource;
import it.polimi.ingsw.model.board.*;
import it.polimi.ingsw.model.board.resourceManagement.Depot;
import it.polimi.ingsw.model.board.resourceManagement.ResourceManager;
import it.polimi.ingsw.model.board.resourceManagement.StrongBox;
import it.polimi.ingsw.model.board.resourceManagement.Warehouse;
import it.polimi.ingsw.model.card.LeaderCard;
import it.polimi.ingsw.model.card.LeaderCardDeck;
import it.polimi.ingsw.model.card.SpecialCard;
import it.polimi.ingsw.view.GUI.GUI;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TitledPane;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.effect.Glow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import java.util.ArrayList;
import java.util.HashMap;
/**
* After initialization, the scene changes to the PersonalBoardScene which is the main scene where the game
* is concentrated.
*/
public class PersonalBoardSceneController {
private GUI gui;
@FXML
private Button buyCardButton, buyFromMarketButton, moveResourceButton, endTurnButton, activePPButton, visitOtherBoardButton, activeLeaderCardButton, discardLeaderCardButton,okButton;
@FXML
private Label chooseActionMessage;
@FXML
private Pane backgroundBox0;
@FXML
private ImageView blackFaith0,blackFaith1,blackFaith2,blackFaith3,blackFaith4,blackFaith5,blackFaith6,blackFaith7,blackFaith8,blackFaith9,blackFaith10,blackFaith11,blackFaith12,blackFaith13,blackFaith14,blackFaith15,blackFaith16,blackFaith17,blackFaith18,blackFaith19,blackFaith20,blackFaith21,blackFaith22,blackFaith23,blackFaith24;
@FXML
private ImageView faithMarker0,faithMarker1,faithMarker2,faithMarker3,faithMarker4,faithMarker5,faithMarker6,faithMarker7,faithMarker8,faithMarker9,faithMarker10,faithMarker11,faithMarker12,faithMarker13,faithMarker14,faithMarker15,faithMarker16,faithMarker17,faithMarker18,faithMarker19,faithMarker20,faithMarker21,faithMarker22,faithMarker23,faithMarker24;
@FXML
private ImageView popesFavorTile1,popesFavorTile2,popesFavorTile3;
@FXML
private ImageView resource1_1,resource2_1,resource2_2,resource3_1,resource3_2,resource3_3,resource4_1,resource4_2,resource5_1,resource5_2;
@FXML
private Label servantLabel,coinLabel,shieldLabel,stoneLabel;
@FXML
private ImageView cardSpace1,cardSpace2,cardSpace3;
@FXML
private ImageView leaderCard1,leaderCard2;
@FXML
private ImageView specialDepot1,specialDepot2;
@FXML
private Pane depot1Pane,depot2Pane,depot3Pane,depot4Pane,depot5Pane;
@FXML
private Label victoryPoints;
@FXML
private TitledPane actionButtons,errorMessagePane;
@FXML
private Pane standardPPPane,strongBoxPane;
@FXML
private Label errorMessage;
@FXML
private Button stopPPPowerButton;
@FXML
private TitledPane chooseResourcePane;
@FXML
private Label chooseResourceLabel;
@FXML
private ImageView coin,servant,shield,stone;
@FXML
private TitledPane chooseOtherPlayerPane;
@FXML
private Button player1Button, player2Button, player3Button;
@FXML
private ImageView specialCard1,specialCard2;
@FXML
private TitledPane waitPane;
@FXML
private Pane lastActionTokenPane;
@FXML
private ImageView lastActionToken;
@FXML
private Label actionLabel;
private boolean returnToMarket;
private boolean actionButtonsVisible;
private TurnAction action;
private ArrayList<Integer> activatablePP;
private String where;
private Integer whichPP;
private CActivateProductionPowerResponseMsg response;
private ArrayList<TypeResource> resourcesToRemove=new ArrayList<>();
private ArrayList<Integer> chosenDepots=new ArrayList<>();
private ArrayList<String> otherPlayers=new ArrayList<>();
private HashMap<Integer,ImageView> leaderCardWithID;
/**
* When the PersonalBoardScene is set, this method prepares it, rendering every element,
* like pop-up, panes or selectable images, hidden and updating the view situation of the various components
* of the Personal Board
*/
public void start(){
setLabelText(actionLabel,"");
updateFaithTrackView(gui.getPlayer().getGameSpace().getFaithTrack());
if(gui.getSoloMode()){
updateBlackFaithMarkerView(gui.getPlayer().getGameSpace());
}
updateResourceManagerView(gui.getPlayer().getGameSpace().getResourceManager());
updateCardSpacesView(gui.getPlayer().getGameSpace().getCardSpaces());
updateVictoryPointsView(gui.getPlayer().getVictoryPoints());
updateAdditionalPPView(gui.getPlayer().getSpecialCard());
setAllLeaderDisable();
disableActionButtons();
disableDepotPanes();
notVisibleDepotPanes();
okButton.setDisable(true);
errorMessagePane.setVisible(false);
actionButtons.setVisible(false);
strongBoxPane.setVisible(false);
strongBoxPane.setDisable(true);
disablePP();
disableCardSpaces();
stopPPPowerButton.setVisible(false);
stopPPPowerButton.setDisable(true);
chooseResourcePane.setVisible(false);
chooseOtherPlayerPane.setVisible(false);
disableOtherPlayersButtons();
lastActionTokenPane.setVisible(false);
}
/**
* It's the player turn so the message of wait is hidden and
* a pop-up with all possible actions that the player can do is shown
* @param msg VChooseActionTurnRequestMsg
*/
public void chooseAction(VChooseActionTurnRequestMsg msg){
waitPane.setVisible(false);
chooseResourcePane.setVisible(false);
if(!returnToMarket) {
setLabelText(chooseActionMessage,"These are your available actions.\nChoose one action:");
actionButtons.setVisible(true);
showActionButtons(msg.getAvailableActions());
}else{
returnToMarket=false;
}
}
//BUY DEVELOPMENT CARD
/**
* The player has chosen the BUY_CARD action, send a message to Server/Message Handler.
* The execution of the action is managed in the DevCardTableScene and DevCardTableSceneController.
*/
public void clickBuyCard(){
CChooseActionTurnResponseMsg msg = new CChooseActionTurnResponseMsg("I choose the action",gui.getUsername(),TurnAction.BUY_CARD);
gui.sendMsg(msg);
disableActionButtons();
actionButtons.setVisible(false);
}
//BUY FROM MARKET
/**
* The player has chosen the BUY_FROM_MARKET action, send a message to Server/Message Handler.
* The execution of the action is managed in the MarketStructureScene and MarketStructureSceneController.
*/
public void clickBuyFromMarket(){
CChooseActionTurnResponseMsg msg = new CChooseActionTurnResponseMsg("I choose the action",gui.getUsername(),TurnAction.BUY_FROM_MARKET);
gui.sendMsg(msg);
disableActionButtons();
actionButtons.setVisible(false);
action=TurnAction.BUY_FROM_MARKET;
}
//PRODUCTION POWER
/**
* The player has chosen the ACTIVATE_PRODUCTION_POWER action, send a message to Server/Message Handler.
* Save the action in the controller
*/
public void clickActivatePP(){
CChooseActionTurnResponseMsg msg = new CChooseActionTurnResponseMsg("I choose the action",gui.getUsername(),TurnAction.ACTIVE_PRODUCTION_POWER);
gui.sendMsg(msg);
disableActionButtons();
actionButtons.setVisible(false);
action=TurnAction.ACTIVE_PRODUCTION_POWER;
}
/**
* When the player choose to activate some production powers, if there's activatable some Production Power,
* the controller highlight the warehouse and the strongbox to allow to choose where take resources to pay
* the power and the StopPP Button is shown in case the player has finished.
* If not the StopPP Button is hidden and a message to alert the player is shown.
* The activatable Production Powers are saved in the controller, because they are useful for others method.
* @param msg VActivateProductionPowerRequestMsg
*/
public void choosePP(VActivateProductionPowerRequestMsg msg){
activatablePP=msg.getActivatablePP();
if(activatablePP.size()>0) {
setLabelText(actionLabel,"Choose where to pay from");
actionLabel.setVisible(true);
chooseDepots();
strongBoxPane.setVisible(true);
strongBoxPane.setDisable(false);
stopPPPowerButton.setVisible(true);
stopPPPowerButton.setDisable(false);
}else{
stopPPPowerButton.setVisible(false);
okButton.setDisable(false);
errorMessagePane.setVisible(true);
setLabelText(errorMessage,"No available\n Production Power");
}
}
/**
* When the player has chosen where to take the resources, based on the Activatable Production Power
* memorized in the controller, this last one highlight the StandardPP, the card spaces and/or, if
* there are, the additional power of the leader cards.
*/
private void activatePP(){
ArrayList<ImageView> cardSpacesView = getCardSpacesView();
for(Integer i:activatablePP){
if(i==0) {
standardPPPane.setVisible(true);
standardPPPane.setDisable(false);
}else if(i>=1 && i<=3){
cardSpacesView.get(i-1).setDisable(false);
cardSpacesView.get(i-1).setEffect(null);
}else if(i>=4 && i<=5){
getSpecialCardsView().get(i-4).setDisable(false);
getSpecialCardsView().get(i-4).setEffect(null);
}
}
}
/**
* If the StopPP Button is clicked, the client send a message to the Server/Message Handler to end the choices
* and executes the chosen ones.
* All panes visible are disabled.
*/
public void clickStopPPPowerButton(){
gui.sendMsg(new CStopPPMsg("I don't want to activate any production power anymore",gui.getUsername()));
stopPPPowerButton.setDisable(true);
stopPPPowerButton.setVisible(false);
notVisibleDepotPanes();
disableDepotPanes();
strongBoxPane.setVisible(false);
strongBoxPane.setDisable(true);
setLabelText(actionLabel,"");
action=null;
}
/**
* When the mouse enters on the "StrongBox" Pane
*/
public void mouseEnteredStrongBoxPane(){
if(!strongBoxPane.isDisable()){
strongBoxPane.setEffect(new Glow());
}
}
/**
* When the mouse exits from the "StrongBox" Pane
*/
public void mouseExitedStrongBoxPane(){
if(!strongBoxPane.isDisable()){
strongBoxPane.setEffect(null);
}
}
/**
* When the player clicks on the strongbox pane, the controller memorize that he choose
* to take the resources to activate the production power from the strongbox, then disables and
* hides all panes
*/
public void clickStrongBoxPane(){
if(!strongBoxPane.isDisable()){
where="strongbox";
disableDepotPanes();
strongBoxPane.setVisible(false);
strongBoxPane.setDisable(true);
activatePP();
strongBoxPane.setDisable(true);
strongBoxPane.setVisible(false);
disableDepotPanes();
setLabelText(actionLabel,"Choose the Production Power you want to activate");
actionLabel.setVisible(true);
}
}
/**
* When the mouse enters in the "StandardPP" Pane
*/
public void mouseEnteredStandardPPPane(){
if(!standardPPPane.isDisable()){
standardPPPane.setEffect(new Glow());
}
}
/**
* When the mouse exits from the "StandardPP" Pane
*/
public void mouseExitedStandardPPPane(){
if(!standardPPPane.isDisable()){
standardPPPane.setEffect(null);
}
}
/**
* When the player clicks on the "StandardPP" Pane, the controller memorizes the choice disable all
* production power panes/images and prepares the pop-up to choose the resources to pay and to receive.
*/
public void clickStandardPPPane(){
if(!standardPPPane.isDisable()){
whichPP=0;
stopPPPowerButton.setVisible(false);
disablePP();
setLabelText(chooseResourceLabel,"Choose first resource to remove");
chooseResourcePane.setVisible(true);
setLabelText(actionLabel,"");
}
}
/**
* When the mouse enters on the "SpecialCard1" image, which is the first additional power
*/
public void mouseEnteredSpecialCard1(){
if(!specialCard1.isDisable()){
specialCard1.setEffect(new Glow());
}
}
/**
* When the mouse exits from the "SpecialCard1" image, which is the first additional power
*/
public void mouseExitedSpecialCard1(){
if(!specialCard1.isDisable()){
specialCard1.setEffect(null);
}
}
/**
* When the player clicks on the "SpecialCard1" image, which is the first additional power,
* the choice is memorized in the controller and prepares a pop-up to make the player choose
* the resource to received.
*/
public void clickSpecialCard1(){
if(!specialCard1.isDisable()) {
whichPP = 4;
stopPPPowerButton.setVisible(false);
disablePP();
setLabelText(chooseResourceLabel,"Choose the resource you want");
chooseResourcePane.setVisible(true);
setLabelText(actionLabel,"");
}
}
/**
* When the mouse enters on the "SpecialCard2" image, which is the second additional power
*/
public void mouseEnteredSpecialCard2(){
if(!specialCard2.isDisable()){
specialCard2.setEffect(new Glow());
}
}
/**
* When the mouse exits from the "SpecialCard2" image, which is the second additional power
*/
public void mouseExitedSpecialCard2(){
if(!specialCard2.isDisable()){
specialCard2.setEffect(null);
}
}
/**
* When the mouse enters on the "SpecialCard2" image, which is the second additional power,
* the choice is memorized in the controller and prepares a pop-up to make the player choose
* the resource to received.
*/
public void clickSpecialCard2(){
if(!specialCard2.isDisable()) {
whichPP = 5;
stopPPPowerButton.setVisible(false);
disablePP();
setLabelText(chooseResourceLabel,"Choose the resource you want");
chooseResourcePane.setVisible(true);
setLabelText(actionLabel,"");
}
}
/**
* When the mouse enters on the "COIN" image
*/
public void mouseEnteredCoin(){
if(!coin.isDisable()){
coin.setEffect(new Glow());
}
}
/**
* When the mouse enters on the "SHIELD" image
*/
public void mouseEnteredShield(){
if(!shield.isDisable()){
shield.setEffect(new Glow());
}
}
/**
* When the mouse enters on the "STONE" image
*/
public void mouseEnteredStone(){
if(!stone.isDisable()){
stone.setEffect(new Glow());
}
}
/**
* When the mouse enters on the "SERVANT" image
*/
public void mouseEnteredServant(){
if(!servant.isDisable()){
servant.setEffect(new Glow());
}
}
/**
* When the mouse exits from the "COIN" image
*/
public void mouseExitedCoin(){
if(!coin.isDisable()){
coin.setEffect(null);
}
}
/**
* When the mouse exits from the "SHIELD" image
*/
public void mouseExitedShield(){
if(!shield.isDisable()){
shield.setEffect(null);
}
}
/**
* When the mouse exits from the "STONE" image
*/
public void mouseExitedStone(){
if(!stone.isDisable()){
stone.setEffect(null);
}
}
/**
* When the mouse exits from the "SERVANT" image
*/
public void mouseExitedServant(){
if(!servant.isDisable()){
servant.setEffect(null);
}
}
/**
* When the player clicks on the "COIN" image, based on the choices made the resources chosen are
* memorized and the pop-up compares one or more time.
* When the player has made all resource choices the response message of the production power with all
* choices made is send to server/message handler.
*/
public void clickCoin(){
if(!coin.isDisable()){
if(whichPP==0 && resourcesToRemove.size()==0){
//STANDARD PP AND 0 RESOURCES ALREADY CHOSEN, SO CHOSEN THE FIRST RESOURCE
resourcesToRemove.add(TypeResource.COIN);
setLabelText(chooseResourceLabel,"Choose second resource to remove");
}else if(whichPP==0 && resourcesToRemove.size()==1){
//STANDARD PP AND 1 RESOURCES ALREADY CHOSEN, SO CHOSEN THE SECOND RESOURCE
resourcesToRemove.add(TypeResource.COIN);
setLabelText(chooseResourceLabel,"Choose the resource you want to receive");
}else if(whichPP==0 && resourcesToRemove.size()==2){
//STANDARD PP AND 2 RESOURCES ALREADY CHOSEN, SO CHOSEN THE THIRD RESOURCE AND SEND MESSAGE
CActivateProductionPowerResponseMsg responseMsg = new CActivateProductionPowerResponseMsg("I choose my production power",gui.getUsername(),where,whichPP);
stopPPPowerButton.setVisible(true);
responseMsg.setResourcesToPay(resourcesToRemove);
responseMsg.setResourceToGet(TypeResource.COIN);
disableCardSpaces();
standardPPPane.setVisible(false);
standardPPPane.setDisable(true);
resourcesToRemove=new ArrayList<>();
chooseResourcePane.setVisible(false);
gui.sendMsg(responseMsg);
}else if((whichPP>=4 && whichPP<=5)){
//ADDITIONAL POWER CHOSEN, SO CHOSEN THE UNIQUE RESOURCE TO RECEIVE AND SEND MSG
CActivateProductionPowerResponseMsg responseMsg = new CActivateProductionPowerResponseMsg("I choose my production power",gui.getUsername(),where,whichPP);
stopPPPowerButton.setVisible(true);
responseMsg.setResourceToGet(TypeResource.COIN);
disableCardSpaces();
standardPPPane.setVisible(false);
standardPPPane.setDisable(true);
chooseResourcePane.setVisible(false);
gui.sendMsg(responseMsg);
}
}
}
/**
* When the player clicks on the "SHIELD" image, based on the choices made the resources chosen are
* memorized and the pop-up compares one or more time.
* When the player has made all resource choices the response message of the production power with all
* choices made is send to server/message handler.
*/
public void clickShield(){
if(!shield.isDisable()){
if(whichPP==0 && resourcesToRemove.size()==0){
resourcesToRemove.add(TypeResource.SHIELD);
setLabelText(chooseResourceLabel,"Choose second resource to remove");
}else if(whichPP==0 && resourcesToRemove.size()==1){
resourcesToRemove.add(TypeResource.SHIELD);
setLabelText(chooseResourceLabel,"Choose the resource you want to receive");
}else if(whichPP==0 && resourcesToRemove.size()==2){
CActivateProductionPowerResponseMsg responseMsg = new CActivateProductionPowerResponseMsg("I choose my production power",gui.getUsername(),where,whichPP);
stopPPPowerButton.setVisible(true);
responseMsg.setResourcesToPay(resourcesToRemove);
responseMsg.setResourceToGet(TypeResource.SHIELD);
disableCardSpaces();
standardPPPane.setVisible(false);
standardPPPane.setDisable(true);
resourcesToRemove=new ArrayList<>();
chooseResourcePane.setVisible(false);
gui.sendMsg(responseMsg);
}else if((whichPP>=4 && whichPP<=5)){
CActivateProductionPowerResponseMsg responseMsg = new CActivateProductionPowerResponseMsg("I choose my production power",gui.getUsername(),where,whichPP);
stopPPPowerButton.setVisible(true);
responseMsg.setResourceToGet(TypeResource.SHIELD);
disableCardSpaces();
standardPPPane.setVisible(false);
standardPPPane.setDisable(true);
chooseResourcePane.setVisible(false);
gui.sendMsg(responseMsg);
}
}
}
/**
* When the player clicks on the "STONE" image, based on the choices made the resources chosen are
* memorized and the pop-up compares one or more time.
* When the player has made all resource choices the response message of the production power with all
* choices made is send to server/message handler.
*/
public void clickStone(){
if(!stone.isDisable()){
if(whichPP==0 && resourcesToRemove.size()==0){
resourcesToRemove.add(TypeResource.STONE);
setLabelText(chooseResourceLabel,"Choose second resource to remove");
}else if(whichPP==0 && resourcesToRemove.size()==1){
resourcesToRemove.add(TypeResource.STONE);
setLabelText(chooseResourceLabel,"Choose the resource you want to receive");
}else if(whichPP==0 && resourcesToRemove.size()==2){
CActivateProductionPowerResponseMsg responseMsg = new CActivateProductionPowerResponseMsg("I choose my production power",gui.getUsername(),where,whichPP);
stopPPPowerButton.setVisible(true);
responseMsg.setResourcesToPay(resourcesToRemove);
responseMsg.setResourceToGet(TypeResource.STONE);
disableCardSpaces();
standardPPPane.setVisible(false);
standardPPPane.setDisable(true);
resourcesToRemove=new ArrayList<>();
chooseResourcePane.setVisible(false);
gui.sendMsg(responseMsg);
}else if((whichPP>=4 && whichPP<=5)){
CActivateProductionPowerResponseMsg responseMsg = new CActivateProductionPowerResponseMsg("I choose my production power",gui.getUsername(),where,whichPP);
stopPPPowerButton.setVisible(true);
responseMsg.setResourceToGet(TypeResource.STONE);
disableCardSpaces();
standardPPPane.setVisible(false);
standardPPPane.setDisable(true);
chooseResourcePane.setVisible(false);
gui.sendMsg(responseMsg);
}
}
}
/**
* When the player clicks on the "SERVANT" image, based on the choices made the resources chosen are
* memorized and the pop-up compares one or more time.
* When the player has made all resource choices the response message of the production power with all
* choices made is send to server/message handler.
*/
public void clickServant(){
if(!servant.isDisable()){
if(whichPP==0 && resourcesToRemove.size()==0){
resourcesToRemove.add(TypeResource.SERVANT);
setLabelText(chooseResourceLabel,"Choose second resource to remove");
}else if(whichPP==0 && resourcesToRemove.size()==1){
resourcesToRemove.add(TypeResource.SERVANT);
setLabelText(chooseResourceLabel,"Choose the resource you want to receive");
}else if(whichPP==0 && resourcesToRemove.size()==2){
CActivateProductionPowerResponseMsg responseMsg = new CActivateProductionPowerResponseMsg("I choose my production power",gui.getUsername(),where,whichPP);
stopPPPowerButton.setVisible(true);
responseMsg.setResourcesToPay(resourcesToRemove);
responseMsg.setResourceToGet(TypeResource.SERVANT);
disableCardSpaces();
standardPPPane.setVisible(false);
standardPPPane.setDisable(true);
resourcesToRemove=new ArrayList<>();
chooseResourcePane.setVisible(false);
gui.sendMsg(responseMsg);
}else if((whichPP>=4 && whichPP<=5)){
CActivateProductionPowerResponseMsg responseMsg = new CActivateProductionPowerResponseMsg("I choose my production power",gui.getUsername(),where,whichPP);
stopPPPowerButton.setVisible(true);
responseMsg.setResourceToGet(TypeResource.SERVANT);
disableCardSpaces();
standardPPPane.setVisible(false);
standardPPPane.setDisable(true);
chooseResourcePane.setVisible(false);
gui.sendMsg(responseMsg);
}
}
}
/**
* When the mouse enters on the "Card Space 1" image
*/
public void mouseEnteredCardSpace1(){
if(!cardSpace1.isDisable()){
cardSpace1.setEffect(new Glow());
}
}
/**
* When the mouse enters on the "Card Space 2" image
*/
public void mouseEnteredCardSpace2(){
if(!cardSpace2.isDisable()){
cardSpace2.setEffect(new Glow());
}
}
/**
* When the mouse enters on the "Card Space 3" image
*/
public void mouseEnteredCardSpace3(){
if(!cardSpace3.isDisable()){
cardSpace3.setEffect(new Glow());
}
}
/**
* When the mouse exits from the "Card Space 1" image
*/
public void mouseExitedCardSpace1(){
if(!cardSpace1.isDisable()){
cardSpace1.setEffect(null);
}
}
/**
* When the mouse exits from the "Card Space 2" image
*/
public void mouseExitedCardSpace2(){
if(!cardSpace2.isDisable()){
cardSpace2.setEffect(null);
}
}
/**
* When the mouse exits from the "Card Space 3" image
*/
public void mouseExitedCardSpace3(){
if(!cardSpace3.isDisable()){
cardSpace3.setEffect(null);
}
}
/**
* When the player clicks on the "Card Space 1" image, send a response
* message of the production power with the card space chosen and disable all Production Power panes and images
*/
public void clickCardSpace1(){
if(!cardSpace1.isDisable()){
response=new CActivateProductionPowerResponseMsg("I choose my production power",gui.getUsername(),where,1);
disablePP();
gui.sendMsg(response);
setLabelText(actionLabel,"");
}
}
/**
* When the player clicks on the "Card Space 2" image, send a response
* message of the production power with the card space chosen and disable all Production Power panes and images
*/
public void clickCardSpace2(){
if(!cardSpace2.isDisable()){
response=new CActivateProductionPowerResponseMsg("I choose my production power",gui.getUsername(),where,2);
disablePP();
gui.sendMsg(response);
setLabelText(actionLabel,"");
}
}
/**
* When the player clicks on the "Card Space 3" image, send a response
* message of the production power with the card space chosen and disable all Production Power panes and images
*/
public void clickCardSpace3(){
if(!cardSpace3.isDisable()){
response=new CActivateProductionPowerResponseMsg("I choose my production power",gui.getUsername(),where,3);
disablePP();
gui.sendMsg(response);
setLabelText(actionLabel,"");
}
}
/**
* To disable and hide all production power panes and images
*/
private void disablePP(){
ColorAdjust colorAdjust=new ColorAdjust();
colorAdjust.setBrightness(-0.5);
standardPPPane.setVisible(false);
standardPPPane.setDisable(true);
for(ImageView cardSpaceView:getCardSpacesView()){
cardSpaceView.setDisable(true);
cardSpaceView.setEffect(colorAdjust);
}
for(ImageView specialCardView: getSpecialCardsView()){
specialCardView.setDisable(true);
specialCardView.setEffect(colorAdjust);
}
}
//MOVE RESOURCES
/**
* The player has chosen the MOVE_RESOURCES action, send a message to server/message handler.
* The action is saved in the controller.
*/
public void clickMoveResources(){
CChooseActionTurnResponseMsg msg = new CChooseActionTurnResponseMsg("I choose the action",gui.getUsername(),TurnAction.MOVE_RESOURCE);
gui.sendMsg(msg);
disableActionButtons();
actionButtons.setVisible(false);
action=TurnAction.MOVE_RESOURCE;
}
/**
* The depots panes became visible and active to allow the player to choose the "from" depot.
*/
public void chooseDepots(){
if(actionButtons.isVisible()){
actionButtons.setVisible(false);
actionButtonsVisible=true;
}
ArrayList<ImageView> specialDepotView = getSpecialDepotsView();
ArrayList<Pane> depotPanes=getDepotPanes();
for(int i=0;i<5;i++){
if((i+1==4||i+1==5) && specialDepotView.get(i-3).isVisible()){
depotPanes.get(i).setDisable(false);
}else{
depotPanes.get(i).setDisable(false);
depotPanes.get(i).setVisible(true);
}
}
setLabelText(actionLabel,"Choose the depot where to move the resource from");
actionLabel.setVisible(true);
}
/**
* When the mouse enters in the "Depot 1" Pane
*/
public void mouseEnteredDepot1Pane(){
if(!depot1Pane.isDisable()){
depot1Pane.setEffect(new Glow());
}
}
/**
* When the mouse enters in the "Depot 2" Pane
*/
public void mouseEnteredDepot2Pane(){
if(!depot2Pane.isDisable()){
depot2Pane.setEffect(new Glow());
}
}
/**
* When the mouse enters in the "Depot 3" Pane
*/
public void mouseEnteredDepot3Pane(){
if(!depot3Pane.isDisable()){
depot3Pane.setEffect(new Glow());
}
}
/**
* When the mouse enters in the "Depot 4" Pane
*/
public void mouseEnteredDepot4Pane(){
if(!depot4Pane.isDisable()){
depot4Pane.setEffect(new Glow());
}
}
/**
* When the mouse enters in the "Depot 5" Pane
*/
public void mouseEnteredDepot5Pane(){
if(!depot5Pane.isDisable()){
depot5Pane.setEffect(new Glow());
}
}
/**
* When the mouse exits from the "Depot 1" Pane
*/
public void mouseExitedDepot1Pane(){
if(!depot1Pane.isDisable()){
depot1Pane.setEffect(null);
}
}
/**
* When the mouse exits from the "Depot 2" Pane
*/
public void mouseExitedDepot2Pane(){
if(!depot2Pane.isDisable()){
depot2Pane.setEffect(null);
}
}
/**
* When the mouse exits from the "Depot 3" Pane
*/
public void mouseExitedDepot3Pane(){
if(!depot3Pane.isDisable()){
depot3Pane.setEffect(null);
}
}
/**
* When the mouse exits from the "Depot 4" Pane
*/
public void mouseExitedDepot4Pane(){
if(!depot4Pane.isDisable()){
depot4Pane.setEffect(null);
}
}
/**
* When the mouse exits from the "Depot 5" Pane
*/
public void mouseExitedDepot5Pane(){
if(!depot5Pane.isDisable()){
depot5Pane.setEffect(null);
}
}
/**
* When the player clicks on the "Depot 1" Pane:
* - if the action memorized is "MOVE_RESOURCE", saved the depot choice in the controller and if
* it is the second depot chosen send a message to server/message handler to make the move, if not
* allows the player to choose the second depot. In addition if the returnToMarket is true that means the
* move resource action was made in the MarketStructureScene so the scene is changed to the MarketStructureScene.
* - if the action memorized is "ACTIVATE_PRODUCTION_POWER", the controller memorize that the resources to
* take when the production power is execute must be from the warehouse, then disable the warehouse and strongbox
* panes.
*/
public void clickDepot1Pane(){
if(!depot1Pane.isDisable()){
if(this.action.equals(TurnAction.MOVE_RESOURCE)){
chosenDepots.add(1);
setLabelText(actionLabel,"Choose the depot where to move the resource to");
actionLabel.setVisible(true);
if(chosenDepots.size()==2){
setLabelText(actionLabel,"");
notVisibleDepotPanes();
disableDepotPanes();
gui.sendMsg(new CMoveResourceInfoMsg("I choose the depots",gui.getUsername(),chosenDepots.get(0),chosenDepots.get(1),true));
chosenDepots=new ArrayList<>();
action=null;
if(returnToMarket){
gui.seeMarketBoard();
gui.getMarketStructureSceneController().copyWarehouseFromPersonalBoard();
action=TurnAction.BUY_FROM_MARKET;
returnToMarket=!returnToMarket;
}
if(actionButtonsVisible){
actionButtonsVisible=false;
actionButtons.setVisible(true);
}
}
}else if(this.action.equals(TurnAction.ACTIVE_PRODUCTION_POWER)){
where="warehouse";
disableDepotPanes();
strongBoxPane.setVisible(false);
strongBoxPane.setDisable(true);
activatePP();
strongBoxPane.setDisable(true);
strongBoxPane.setVisible(false);
disableDepotPanes();
notVisibleDepotPanes();
setLabelText(actionLabel,"Choose the Production Power you want to activate");
actionLabel.setVisible(true);
}
}
}
/**
* When the player clicks on the "Depot 2" Pane:
* - if the action memorized is "MOVE_RESOURCE", saved the depot choice in the controller and if
* it is the second depot chosen send a message to server/message handler to make the move, if not
* allows the player to choose the second depot. In addition if the returnToMarket is true that means the
* move resource action was made in the MarketStructureScene so the scene is changed to the MarketStructureScene.
* - if the action memorized is "ACTIVATE_PRODUCTION_POWER", the controller memorize that the resources to
* take when the production power is execute must be from the warehouse, then disable the warehouse and strongbox
* panes.
*/
public void clickDepot2Pane(){
if(!depot2Pane.isDisable()){
if(this.action.equals(TurnAction.MOVE_RESOURCE)){
chosenDepots.add(2);
setLabelText(actionLabel,"Choose the depot where to move the resource to");
actionLabel.setVisible(true);
if(chosenDepots.size()==2){
setLabelText(actionLabel,"");
notVisibleDepotPanes();
disableDepotPanes();
gui.sendMsg(new CMoveResourceInfoMsg("I choose the depots",gui.getUsername(),chosenDepots.get(0),chosenDepots.get(1),true));
chosenDepots=new ArrayList<>();
action=null;
if(returnToMarket){
gui.seeMarketBoard();
gui.getMarketStructureSceneController().copyWarehouseFromPersonalBoard();
action=TurnAction.BUY_FROM_MARKET;
returnToMarket=!returnToMarket;
}
if(actionButtonsVisible){
actionButtonsVisible=false;
actionButtons.setVisible(true);
}
}
}else if(this.action.equals(TurnAction.ACTIVE_PRODUCTION_POWER)){
where="warehouse";
disableDepotPanes();
strongBoxPane.setVisible(false);
strongBoxPane.setDisable(true);
activatePP();
strongBoxPane.setDisable(true);
strongBoxPane.setVisible(false);
disableDepotPanes();
notVisibleDepotPanes();
setLabelText(actionLabel,"Choose the Production Power you want to activate");
actionLabel.setVisible(true);
}
}
}
/**
* When the player clicks on the "Depot 3" Pane:
* - if the action memorized is "MOVE_RESOURCE", saved the depot choice in the controller and if
* it is the second depot chosen send a message to server/message handler to make the move, if not
* allows the player to choose the second depot. In addition if the returnToMarket is true that means the
* move resource action was made in the MarketStructureScene so the scene is changed to the MarketStructureScene.
* - if the action memorized is "ACTIVATE_PRODUCTION_POWER", the controller memorize that the resources to
* take when the production power is execute must be from the warehouse, then disable the warehouse and strongbox
* panes.
*/
public void clickDepot3Pane(){
if(!depot3Pane.isDisable()){
if(this.action.equals(TurnAction.MOVE_RESOURCE)){
chosenDepots.add(3);
setLabelText(actionLabel,"Choose the depot where to move the resource to");
actionLabel.setVisible(true);
if(chosenDepots.size()==2){
setLabelText(actionLabel,"");
notVisibleDepotPanes();
disableDepotPanes();
gui.sendMsg(new CMoveResourceInfoMsg("I choose the depots",gui.getUsername(),chosenDepots.get(0),chosenDepots.get(1),true));
chosenDepots=new ArrayList<>();
action=null;
if(returnToMarket){
gui.seeMarketBoard();
gui.getMarketStructureSceneController().copyWarehouseFromPersonalBoard();
action=TurnAction.BUY_FROM_MARKET;
returnToMarket=!returnToMarket;
}
if(actionButtonsVisible){
actionButtonsVisible=false;
actionButtons.setVisible(true);
}
}
}else if(this.action.equals(TurnAction.ACTIVE_PRODUCTION_POWER)){
where="warehouse";
disableDepotPanes();
strongBoxPane.setVisible(false);
strongBoxPane.setDisable(true);
activatePP();
strongBoxPane.setDisable(true);
strongBoxPane.setVisible(false);
disableDepotPanes();
notVisibleDepotPanes();
setLabelText(actionLabel,"Choose the Production Power you want to activate");
actionLabel.setVisible(true);
}
}
}
/**
* When the player clicks on the "Depot 4" Pane:
* - if the action memorized is "MOVE_RESOURCE", saved the depot choice in the controller and if
* it is the second depot chosen send a message to server/message handler to make the move, if not
* allows the player to choose the second depot. In addition if the returnToMarket is true that means the
* move resource action was made in the MarketStructureScene so the scene is changed to the MarketStructureScene.
* - if the action memorized is "ACTIVATE_PRODUCTION_POWER", the controller memorize that the resources to
* take when the production power is execute must be from the warehouse, then disable the warehouse and strongbox
* panes.
*/
public void clickDepot4Pane(){
if(!depot4Pane.isDisable()){
if(this.action.equals(TurnAction.MOVE_RESOURCE)){
chosenDepots.add(4);
setLabelText(actionLabel,"Choose the depot where to move the resource to");
actionLabel.setVisible(true);
if(chosenDepots.size()==2){
setLabelText(actionLabel,"");
notVisibleDepotPanes();
disableDepotPanes();
gui.sendMsg(new CMoveResourceInfoMsg("I choose the depots",gui.getUsername(),chosenDepots.get(0),chosenDepots.get(1),true));
chosenDepots=new ArrayList<>();
action=null;
if(returnToMarket){
gui.seeMarketBoard();
gui.getMarketStructureSceneController().copyWarehouseFromPersonalBoard();
action=TurnAction.BUY_FROM_MARKET;
returnToMarket=!returnToMarket;
}
if(actionButtonsVisible){
actionButtonsVisible=false;
actionButtons.setVisible(true);
}
}
}else if(this.action.equals(TurnAction.ACTIVE_PRODUCTION_POWER)){
where="warehouse";
disableDepotPanes();
strongBoxPane.setVisible(false);
strongBoxPane.setDisable(true);
activatePP();
strongBoxPane.setDisable(true);
strongBoxPane.setVisible(false);
disableDepotPanes();
notVisibleDepotPanes();
setLabelText(actionLabel,"Choose the Production Power you want to activate");
actionLabel.setVisible(true);
}
}
}
/**
* When the player clicks on the "Depot 5" Pane:
* - if the action memorized is "MOVE_RESOURCE", saved the depot choice in the controller and if
* it is the second depot chosen send a message to server/message handler to make the move, if not
* allows the player to choose the second depot. In addition if the returnToMarket is true that means the
* move resource action was made in the MarketStructureScene so the scene is changed to the MarketStructureScene.
* - if the action memorized is "ACTIVATE_PRODUCTION_POWER", the controller memorize that the resources to
* take when the production power is execute must be from the warehouse, then disable the warehouse and strongbox
* panes.
*/
public void clickDepot5Pane(){
if(!depot5Pane.isDisable()){
if(this.action.equals(TurnAction.MOVE_RESOURCE)){
chosenDepots.add(5);
setLabelText(actionLabel,"Choose the depot where to move the resource to");
actionLabel.setVisible(true);
if(chosenDepots.size()==2){
setLabelText(actionLabel,"");
notVisibleDepotPanes();
disableDepotPanes();
gui.sendMsg(new CMoveResourceInfoMsg("I choose the depots",gui.getUsername(),chosenDepots.get(0),chosenDepots.get(1),true));
chosenDepots=new ArrayList<>();
action=null;
if(returnToMarket){
gui.seeMarketBoard();
gui.getMarketStructureSceneController().copyWarehouseFromPersonalBoard();
action=TurnAction.BUY_FROM_MARKET;
}
if(actionButtonsVisible){
actionButtonsVisible=false;
actionButtons.setVisible(true);
}
}
}else if(this.action.equals(TurnAction.ACTIVE_PRODUCTION_POWER)){
where="warehouse";
disableDepotPanes();
strongBoxPane.setVisible(false);
strongBoxPane.setDisable(true);
activatePP();
strongBoxPane.setDisable(true);
strongBoxPane.setVisible(false);
disableDepotPanes();
notVisibleDepotPanes();
setLabelText(actionLabel,"Choose the Production Power you want to activate");
actionLabel.setVisible(true);
}
}
}
//ACTIVE OR DISCARD LEADER CARD ACTION
/**
* The player has chosen the "ACTIVE_LEADER_CARD" action, so notify to server/message handler and save
* the action in the controller.
*/
public void clickActivateLeaderCard(){
CChooseActionTurnResponseMsg msg = new CChooseActionTurnResponseMsg("I choose the action",gui.getUsername(),TurnAction.ACTIVE_LEADER_CARD);
gui.sendMsg(msg);
disableActionButtons();
actionButtons.setVisible(false);
action=TurnAction.ACTIVE_LEADER_CARD;
}
/**
* The player has chosen the "REMOVE_LEADER_CARD" action, so notify to server/message handler and save
* the action in the controller.
*/
public void clickDiscardLeaderCard(){
CChooseActionTurnResponseMsg msg = new CChooseActionTurnResponseMsg("I choose the action",gui.getUsername(),TurnAction.REMOVE_LEADER_CARD);
gui.sendMsg(msg);
disableActionButtons();
actionButtons.setVisible(false);
action=TurnAction.REMOVE_LEADER_CARD;
}
/**
* When the player choose to activate or discard a leader card, he receive through a message which can be
* activate/removed, so the controller highlights with which ones he can interact.
* @param msg VChooseLeaderCardRequestMsg
*/
public void chooseLeaderCard(VChooseLeaderCardRequestMsg msg){
ArrayList<Integer> leaderCards=msg.getMiniDeckLeaderCardFour();
if(msg.getMiniDeckLeaderCardFour().size()>0) {
for(int i=0;i<leaderCards.size();i++){
getLeaderCardViewByID(leaderCards.get(i)).setDisable(false);
getLeaderCardViewByID(leaderCards.get(i)).setEffect(null);
setLabelText(actionLabel,"Choose leader card to "+msg.getWhatFor());
actionLabel.setVisible(true);
}
}else{
setLabelText(errorMessage,"No card to "+msg.getWhatFor());
okButton.setDisable(false);
errorMessagePane.setVisible(true);
}
}
/**
* When the player clicks on the OK button of the alert message, based on the action, notify the
* server/message handler, set the action to null and close the alert message.
* If the alert message notify a SERVER UNABLE error,
* the GUI is automatically closed.
*/
public void clickOKButton(){
if(action==TurnAction.ACTIVE_LEADER_CARD||action==TurnAction.REMOVE_LEADER_CARD) {
gui.sendMsg(new CChangeActionTurnMsg("Not possible to do action, I want to change action", gui.getUsername(), action));
}else if(action==TurnAction.ACTIVE_PRODUCTION_POWER){
gui.sendMsg(new CStopPPMsg("No Production Power Available",gui.getUsername()));
notVisibleDepotPanes();
disableDepotPanes();
}else if(!gui.isServerAvailable() && !gui.isOffline()){
gui.close();
}
action = null;
okButton.setDisable(true);
errorMessagePane.setVisible(false);
}
/**
* When the mouse enters on the "Leader Card 1" image
*/
public void mouseEnteredLeaderCard1(){
if(!leaderCard1.isDisable()){
leaderCard1.setEffect(new Glow());
}
}
/**
* When the mouse exits from the "Leader Card 1" image
*/
public void mouseExitedLeaderCard1(){
if(!leaderCard1.isDisable()){
leaderCard1.setEffect(null);
}
}
/**
* When the mouse enters on the "Leader Card 2" image
*/
public void mouseEnteredLeaderCard2(){
if(!leaderCard2.isDisable()){
leaderCard2.setEffect(new Glow());
}
}
/**
* When the mouse exits from the "Leader Card 2" image
*/
public void mouseExitedLeaderCard2(){
if(!leaderCard2.isDisable()){
leaderCard2.setEffect(null);
}
}
/**
* When the player clicks on the "Leader Card 1" image, send a message to activate/discard the chosen
* leader card and, if it is a remove action, cover the card.
*/
public void clickLeaderCard1(){
if(!leaderCard1.isDisable()){
if(this.action.equals(TurnAction.ACTIVE_LEADER_CARD)){
gui.sendMsg(new CChooseLeaderCardResponseMsg("I choose the leader card",gui.getLeaderCards().get(0).getCardID(),gui.getUsername(),"active"));
leaderCard1.setEffect(null);
leaderCard1.setDisable(true);
}else if(this.action.equals(TurnAction.REMOVE_LEADER_CARD)){
gui.sendMsg(new CChooseLeaderCardResponseMsg("I choose the leader card",gui.getLeaderCards().get(0).getCardID(),gui.getUsername(),"remove"));
leaderCard1.setEffect(null);
leaderCard1.setDisable(true);
leaderCard1.setImage(new Image("/images/backCards/LeaderCard (1).png"));
}
setLabelText(actionLabel,"");
action=null;
}
}
/**
* When the player clicks on the "Leader Card 2" image, send a message to activate/discard the chosen
* leader card and, if it is a remove action, cover the card.
*/
public void clickLeaderCard2(){
if(!leaderCard2.isDisable()){
if(this.action.equals(TurnAction.ACTIVE_LEADER_CARD)){
gui.sendMsg(new CChooseLeaderCardResponseMsg("I choose the leader card",gui.getLeaderCards().get(1).getCardID(),gui.getUsername(),"active"));
leaderCard2.setEffect(null);
leaderCard2.setDisable(true);
}else if(this.action.equals(TurnAction.REMOVE_LEADER_CARD)){
gui.sendMsg(new CChooseLeaderCardResponseMsg("I choose the leader card",gui.getLeaderCards().get(1).getCardID(),gui.getUsername(),"remove"));
leaderCard2.setEffect(null);
leaderCard2.setDisable(true);
leaderCard2.setImage(new Image("/images/backCards/LeaderCard (1).png"));
}
setLabelText(actionLabel,"");
action=null;
}
}
//VISIT OTHER PLAYER
/**
* The player has chosen the "SEE_OTHER_PERSONALBOARD" action, notify the server/message handler.
*/
public void clickVisitOtherPersonalBoard(){
CChooseActionTurnResponseMsg msg = new CChooseActionTurnResponseMsg("I choose the action",gui.getUsername(),TurnAction.SEE_OTHER_PLAYER);
gui.sendMsg(msg);
disableActionButtons();
actionButtons.setVisible(false);
}
/**
* After chosen to visit another player, the server replies with a list of player that he can see,
* so this method make a pop-up with the list of player to see.
* @param players the list of player.
*/
public void chooseOtherPlayer(ArrayList<String> players){
otherPlayers=players;
for(int i=0;i<players.size();i++){
setButtonText(getOtherPlayersButtons().get(i),"Player "+(i+1)+": "+players.get(i));
getOtherPlayersButtons().get(i).setDisable(false);
}
chooseOtherPlayerPane.setVisible(true);
}
/**
* When the client clicks on the "Player 1" button, notify the server which player wants to see and
* hide the pop-up
*/
public void clickPlayer1Button(){
if(!player1Button.isDisable()){
gui.sendMsg(new CAskSeeSomeoneElseMsg("I want to see player",gui.getUsername(),otherPlayers.get(0)));
otherPlayers=new ArrayList<>();
chooseOtherPlayerPane.setVisible(false);
disableOtherPlayersButtons();
}
}
/**
* When the client clicks on the "Player 2" button, notify the server which player wants to see and
* hide the pop-up
*/
public void clickPlayer2Button(){
if(!player2Button.isDisable()){
gui.sendMsg(new CAskSeeSomeoneElseMsg("I want to see player",gui.getUsername(),otherPlayers.get(1)));
otherPlayers=new ArrayList<>();
chooseOtherPlayerPane.setVisible(false);
disableOtherPlayersButtons();
}
}
/**
* When the client clicks on the "Player 3" button, notify the server which player wants to see and
* hide the pop-up
*/
public void clickPlayer3Button(){
if(!player3Button.isDisable()){
gui.sendMsg(new CAskSeeSomeoneElseMsg("I want to see player",gui.getUsername(),otherPlayers.get(2)));
otherPlayers=new ArrayList<>();
chooseOtherPlayerPane.setVisible(false);
disableOtherPlayersButtons();
}
}
//END TURN
/**
* The player has chosen to end his turn, so notify the server/message handler and hide the actions pop-up
*/
public void clickEndTurn(){
CChooseActionTurnResponseMsg msg = new CChooseActionTurnResponseMsg("I choose the action",gui.getUsername(),TurnAction.END_TURN);
gui.sendMsg(msg);
disableActionButtons();
actionButtons.setVisible(false);
}
/**
* The player can see the MarketStructureScene without interact with it.
*/
public void clickSeeMarketBoardButton(){
gui.getMarketStructureSceneController().update(gui.getMarketStructureData());
gui.seeMarketBoard();
}
/**
* The player can see the DevCardTableScene without interact with it.
*/
public void clickSeeDevCardTableButton(){
gui.getDevCardTableSceneController().setAllCardNormal();
gui.getDevCardTableSceneController().setJustSee(true);
gui.getDevCardTableSceneController().update(gui.getDevelopmentCardTable());
gui.getDevCardTableSceneController().update(gui.getDevelopmentCardTable());
gui.seeDevCardTable();
}
/**
* To set the GUI which refers to.
* @param gui the GUI of the player
*/
public void setGui(GUI gui) {
this.gui = gui;
}
/**
* To disable every action buttons.
*/
private void disableActionButtons(){
for(Button button:getActionButtons()){
button.setDisable(true);
}
}
//Update FXML Elements based on Model Elements
/**
* To update the leader cards view of the personal board based on the leader cards data of the player
* in the model
* @param leaderCards the leader cards in the model.
*/
public void updateLeaderCards(ArrayList<LeaderCard> leaderCards){
leaderCardWithID=new HashMap<>();
for(int i=0;i<2;i++){
if(i+1<=leaderCards.size()){
leaderCardWithID.put(leaderCards.get(i).getCardID(),getLeaderCardsView().get(i));
getLeaderCardsView().get(i).setImage(new Image("/images/frontCards/LeaderCard ("+leaderCards.get(i).getCardID()+").png"));
}else{
getLeaderCardsView().get(i).setImage(new Image("/images/backCards/LeaderCard (1).png"));
}
}
}
/**
* To update the faithtrack view of the personal board based on the faithtrack data of the player in the model
* @param faithTrack the faithtrack in the model
*/
public void updateFaithTrackView(FaithTrack faithTrack){
for (int i = 0; i < 25; i++) {
if (faithTrack.getPositionFaithMarker() == i) {
if (i == 0) {
backgroundBox0.setVisible(true);
}
getFaithMarkersView().get(i).setVisible(true);
} else {
if (i == 0) {
backgroundBox0.setVisible(false);
}
getFaithMarkersView().get(i).setVisible(false);
}
if(!gui.getSoloMode()) {
getBlackMarkersView().get(i).setVisible(false);
}
}
for (int i = 0; i < 3; i++) {
if (faithTrack.getPopesFavorTiles().get(i).getState() instanceof Active) {
getPopesFavorTilesView().get(i).setImage(new Image("/images/punchboard/pope's_tile" + (i + 1) + "Active.png"));
} else {
getPopesFavorTilesView().get(i).setImage(new Image("/images/punchboard/pope's_tile" + (i + 1) + "Inactive.png"));
}
}
}
/**
* To update the Black Faith Marker in the Personal Board based on the position of the Black Faith Marker in the model
* @param personalBoard the personal board to access at the position of Lorenzo
*/
public void updateBlackFaithMarkerView(PersonalBoard personalBoard){
SoloPersonalBoard soloPersonalBoard = (SoloPersonalBoard) personalBoard;
for(int i=0;i<25;i++){
if(soloPersonalBoard.getLorenzoIlMagnifico().getPosition()==i){
if(i==0){
backgroundBox0.setVisible(true);
}else{
backgroundBox0.setVisible(false);
}
getBlackMarkersView().get(i).setVisible(true);
}else{
if(i==0){
backgroundBox0.setVisible(false);
}else{
backgroundBox0.setVisible(true);
}
getBlackMarkersView().get(i).setVisible(false);
}
}
}
/**
* To update the resource manager view based on the resource manager in the model
* @param resourceManager the resource manager in the model
*/
public void updateResourceManagerView(ResourceManager resourceManager){
updateWarehouseView(resourceManager.getWarehouse());
updateStrongBoxView(resourceManager.getStrongBox());
}
/**
* To update the warehouse view based on the warehouse in the model
* @param warehouse the warehouse in the model
*/
public void updateWarehouseView(Warehouse warehouse){
for(int i=0;i<5;i++){
if (i+1<=warehouse.getDepots().size()) {
Depot depot = warehouse.getDepots().get(i);
ArrayList<ImageView> depotView = getWarehouseView().get(i);
if (i+1==4||i+1==5) {
switch (depot.getType()) {
case COIN:
getSpecialDepotsView().get(i-3).setImage(new Image("/images/personalboard/SpecialDepotCoin.png"));
break;
case SERVANT:
getSpecialDepotsView().get(i-3).setImage(new Image("/images/personalboard/SpecialDepotServant.png"));
break;
case STONE:
getSpecialDepotsView().get(i-3).setImage(new Image("/images/personalboard/SpecialDepotStone.png"));
break;
case SHIELD:
getSpecialDepotsView().get(i-3).setImage(new Image("/images/personalboard/SpecialDepotShield.png"));
break;
}
getDepotPanes().get(i).setVisible(true);
getSpecialDepotsView().get(i-3).setVisible(true);
}
for (int j = 0; j < depot.getSize(); j++) {
if (j + 1 <= depot.getNumberResources()) {
Resource resource = depot.getResources().get(j);
switch (resource.getType()) {
case COIN:
depotView.get(j).setImage(new Image("/images/punchboard/coin.png"));
break;
case SHIELD:
depotView.get(j).setImage(new Image("/images/punchboard/shield.png"));
break;
case SERVANT:
depotView.get(j).setImage(new Image("/images/punchboard/servant.png"));
break;
case STONE:
depotView.get(j).setImage(new Image("/images/punchboard/stone.png"));
break;
}
depotView.get(j).setVisible(true);
} else {
depotView.get(j).setImage(null);
depotView.get(j).setVisible(false);
}
}
}else{
if(i==3||i==4){
getSpecialDepotsView().get(i-3).setVisible(false);
ArrayList<ImageView> depotView = getWarehouseView().get(i);
for(int k=0;k<2;k++){
depotView.get(k).setVisible(false);
}
}
}
}
}
/**
* To update the strongbox view based on the strongbox in the model
* @param strongBox the strongbox in the model
*/
public void updateStrongBoxView(StrongBox strongBox){
HashMap<TypeResource,Integer> countResourcesInStrongBox=new HashMap<>();
int servant=0;
int shield=0;
int coin=0;
int stone=0;
for(Resource resource:strongBox.getContent()){
switch(resource.getType()){
case COIN:coin++;break;
case SHIELD:shield++;break;
case STONE:stone++;break;
case SERVANT:servant++;break;
}
}
setLabelText(getStrongboxLabelsView().get(TypeResource.COIN),""+coin);
setLabelText(getStrongboxLabelsView().get(TypeResource.SHIELD),""+shield);
setLabelText(getStrongboxLabelsView().get(TypeResource.SERVANT),""+servant);
setLabelText(getStrongboxLabelsView().get(TypeResource.STONE),""+stone);
}
/**
* To update the card spaces view based on the card spaces in the model
* @param cardSpaces the card spaces in the model
*/
public void updateCardSpacesView(ArrayList<CardSpace> cardSpaces){
for(int i=0;i<cardSpaces.size();i++){
if(cardSpaces.get(i).getNumberOfCards()!=0){
getCardSpacesView().get(i).setImage(new Image("/images/frontCards/DevelopmentCard ("+cardSpaces.get(i).getUpperCard().getId()+").png"));
getCardSpacesView().get(i).setVisible(true);
}else{
getCardSpacesView().get(i).setImage(null);
getCardSpacesView().get(i).setVisible(false);
}
}
}
/**
* Update the special cards/additional power view based on the special cards/additional power in the model
* @param specialCards the special cards/additional power in the model
*/
public void updateAdditionalPPView(ArrayList<SpecialCard> specialCards){
for(int i=0;i<2;i++){
if(specialCards!=null && i+1<=specialCards.size()){
String type="";
switch(specialCards.get(i).getCostProductionPower().get(0).getType()){
case COIN:type="Coin";break;
case SHIELD:type="Shield";break;
case STONE:type="Stone";break;
case SERVANT:type="Servant";break;
}
getSpecialCardsView().get(i).setImage(new Image("/images/personalboard/AdditionalPower_"+type+".png"));
getSpecialCardsView().get(i).setVisible(true);
}else{
getSpecialCardsView().get(i).setVisible(false);
}
}
}
/**
* Update the count of the victory points view based on the count of the victory points in the model
* @param victoryPoints the victory points in the model
*/
public void updateVictoryPointsView(int victoryPoints){
setLabelText(this.victoryPoints,""+victoryPoints);
}
/**
* Update the action token view based on the last action token drew.
* @param msg VActionTokenActivateMsg
*/
public void updateLastActionToken(VActionTokenActivateMsg msg){
lastActionToken.setImage(new Image("/images/punchboard/actiontoken ("+msg.getActionToken().getCardID()+").png"));
if(!lastActionTokenPane.isVisible()){
lastActionTokenPane.setVisible(true);
}
}
/**
* To activate the action buttons
* @param activatableActions the list of the activatable actions
*/
private void showActionButtons(ArrayList<TurnAction> activatableActions){
for(TurnAction action:activatableActions){
switch(action){
case BUY_CARD:buyCardButton.setDisable(false);break;
case BUY_FROM_MARKET:buyFromMarketButton.setDisable(false);break;
case ACTIVE_PRODUCTION_POWER:activePPButton.setDisable(false);break;
case ACTIVE_LEADER_CARD:activeLeaderCardButton.setDisable(false);break;
case REMOVE_LEADER_CARD:discardLeaderCardButton.setDisable(false);break;
case MOVE_RESOURCE:moveResourceButton.setDisable(false);break;
case SEE_OTHER_PLAYER:visitOtherBoardButton.setDisable(false);break;
case END_TURN:endTurnButton.setDisable(false);break;
}
}
}
//Getter Method for FXML Elements
/**
* @return a list of all action buttons
*/
private ArrayList<Button> getActionButtons(){
ArrayList<Button> actionButtons = new ArrayList<>();
actionButtons.add(buyCardButton);
actionButtons.add(buyFromMarketButton);
actionButtons.add(activePPButton);
actionButtons.add(activeLeaderCardButton);
actionButtons.add(discardLeaderCardButton);
actionButtons.add(moveResourceButton);
actionButtons.add(visitOtherBoardButton);
actionButtons.add(endTurnButton);
return actionButtons;
}
/**
* @return a list of black markers images
*/
private ArrayList<ImageView> getBlackMarkersView(){
ArrayList<ImageView> blackMarkersView=new ArrayList<>();
blackMarkersView.add(blackFaith0);
blackMarkersView.add(blackFaith1);
blackMarkersView.add(blackFaith2);
blackMarkersView.add(blackFaith3);
blackMarkersView.add(blackFaith4);
blackMarkersView.add(blackFaith5);
blackMarkersView.add(blackFaith6);
blackMarkersView.add(blackFaith7);
blackMarkersView.add(blackFaith8);
blackMarkersView.add(blackFaith9);
blackMarkersView.add(blackFaith10);
blackMarkersView.add(blackFaith11);
blackMarkersView.add(blackFaith12);
blackMarkersView.add(blackFaith13);
blackMarkersView.add(blackFaith14);
blackMarkersView.add(blackFaith15);
blackMarkersView.add(blackFaith16);
blackMarkersView.add(blackFaith17);
blackMarkersView.add(blackFaith18);
blackMarkersView.add(blackFaith19);
blackMarkersView.add(blackFaith20);
blackMarkersView.add(blackFaith21);
blackMarkersView.add(blackFaith22);
blackMarkersView.add(blackFaith23);
blackMarkersView.add(blackFaith24);
return blackMarkersView;
}
/**
* @return a list of faith markers images
*/
private ArrayList<ImageView> getFaithMarkersView(){
ArrayList<ImageView> faithMarkerPositionsView = new ArrayList<>();
faithMarkerPositionsView.add(faithMarker0);
faithMarkerPositionsView.add(faithMarker1);
faithMarkerPositionsView.add(faithMarker2);
faithMarkerPositionsView.add(faithMarker3);
faithMarkerPositionsView.add(faithMarker4);
faithMarkerPositionsView.add(faithMarker5);
faithMarkerPositionsView.add(faithMarker6);
faithMarkerPositionsView.add(faithMarker7);
faithMarkerPositionsView.add(faithMarker8);
faithMarkerPositionsView.add(faithMarker9);
faithMarkerPositionsView.add(faithMarker10);
faithMarkerPositionsView.add(faithMarker11);
faithMarkerPositionsView.add(faithMarker12);
faithMarkerPositionsView.add(faithMarker13);
faithMarkerPositionsView.add(faithMarker14);
faithMarkerPositionsView.add(faithMarker15);
faithMarkerPositionsView.add(faithMarker16);
faithMarkerPositionsView.add(faithMarker17);
faithMarkerPositionsView.add(faithMarker18);
faithMarkerPositionsView.add(faithMarker19);
faithMarkerPositionsView.add(faithMarker20);
faithMarkerPositionsView.add(faithMarker21);
faithMarkerPositionsView.add(faithMarker22);
faithMarkerPositionsView.add(faithMarker23);
faithMarkerPositionsView.add(faithMarker24);
return faithMarkerPositionsView;
}
/**
* @return a list of pope's favor tiles images
*/
private ArrayList<ImageView> getPopesFavorTilesView(){
ArrayList<ImageView> popesFavorTilesView = new ArrayList<>();
popesFavorTilesView.add(popesFavorTile1);
popesFavorTilesView.add(popesFavorTile2);
popesFavorTilesView.add(popesFavorTile3);
return popesFavorTilesView;
}
/**
* @return the structure of images of the warehouse view
*/
public ArrayList<ArrayList<ImageView>> getWarehouseView(){
ArrayList<ArrayList<ImageView>> warehouseView= new ArrayList<>();
ArrayList<ImageView> depot1View=new ArrayList<>();
depot1View.add(resource1_1);
ArrayList<ImageView> depot2View=new ArrayList<>();
depot2View.add(resource2_1);
depot2View.add(resource2_2);
ArrayList<ImageView> depot3View=new ArrayList<>();
depot3View.add(resource3_1);
depot3View.add(resource3_2);
depot3View.add(resource3_3);
ArrayList<ImageView> depot4View=new ArrayList<>();
depot4View.add(resource4_1);
depot4View.add(resource4_2);
ArrayList<ImageView> depot5View=new ArrayList<>();
depot5View.add(resource5_1);
depot5View.add(resource5_2);
warehouseView.add(depot1View);
warehouseView.add(depot2View);
warehouseView.add(depot3View);
warehouseView.add(depot4View);
warehouseView.add(depot5View);
return warehouseView;
}
/**
* @return a map with all label of the strongbox referring to the type
*/
private HashMap<TypeResource,Label> getStrongboxLabelsView(){
HashMap<TypeResource,Label> strongboxLabel = new HashMap<>();
strongboxLabel.put(TypeResource.SERVANT,servantLabel);
strongboxLabel.put(TypeResource.SHIELD,shieldLabel);
strongboxLabel.put(TypeResource.COIN,coinLabel);
strongboxLabel.put(TypeResource.STONE,stoneLabel);
return strongboxLabel;
}
/**
* @return a list of the card spaces images
*/
public ArrayList<ImageView> getCardSpacesView(){
ArrayList<ImageView> cardSpaceView = new ArrayList<>();
cardSpaceView.add(cardSpace1);
cardSpaceView.add(cardSpace2);
cardSpaceView.add(cardSpace3);
return cardSpaceView;
}
/**
* @return a list of the leader cards images
*/
private ArrayList<ImageView> getLeaderCardsView(){
ArrayList<ImageView> leaderCardsView = new ArrayList<>();
leaderCardsView.add(leaderCard1);
leaderCardsView.add(leaderCard2);
return leaderCardsView;
}
/**
* @return a list of the special depots images
*/
public ArrayList<ImageView> getSpecialDepotsView(){
ArrayList<ImageView> specialDepotsView = new ArrayList<>();
specialDepotsView.add(specialDepot1);
specialDepotsView.add(specialDepot2);
return specialDepotsView;
}
/**
* @return a list of the depot panes
*/
private ArrayList<Pane> getDepotPanes(){
ArrayList<Pane> depotPanes=new ArrayList<>();
depotPanes.add(depot1Pane);
depotPanes.add(depot2Pane);
depotPanes.add(depot3Pane);
depotPanes.add(depot4Pane);
depotPanes.add(depot5Pane);
return depotPanes;
}
/**
* To disable the depot panes
*/
private void disableDepotPanes(){
for(Pane pane:getDepotPanes()){
pane.setDisable(true);
}
}
/**
* To hide the first three depot panes
*/
private void notVisibleDepotPanes(){
for(int i=0;i<3;i++){
getDepotPanes().get(i).setVisible(false);
}
}
/**
* To set the turn action in the controller
* @param action which turn action
*/
public void setTurnAction(TurnAction action){this.action =action;}
/**
* To disable the leader cards images
*/
private void setAllLeaderDisable(){
for(ImageView image: getLeaderCardsView()){
image.setDisable(true);
}
}
/**
* To set the returnToMarket boolean
* @param returnToMarket if true the controller should return in the MarketStructureScene
*/
public void setReturnToMarket(boolean returnToMarket) {
this.returnToMarket = returnToMarket;
}
/**
* To disable the card spaces images
*/
private void disableCardSpaces(){
ColorAdjust colorAdjust = new ColorAdjust();
colorAdjust.setBrightness(-0.5);
for(ImageView imageView: getCardSpacesView()){
imageView.setDisable(true);
imageView.setEffect(colorAdjust);
}
}
/**
* To set a label text
* @param label the label to change
* @param content the text to set
*/
public void setLabelText(Label label,String content){
Platform.runLater(()->{
label.setText(content);
});
}
/**
* @return a list of the players buttons
*/
private ArrayList<Button> getOtherPlayersButtons(){
ArrayList<Button> otherPlayersButtons=new ArrayList<>();
otherPlayersButtons.add(player1Button);
otherPlayersButtons.add(player2Button);
otherPlayersButtons.add(player3Button);
return otherPlayersButtons;
}
/**
* To disable the players buttons
*/
private void disableOtherPlayersButtons(){
for(Button button:getOtherPlayersButtons()){
button.setDisable(true);
}
}
/**
* To set a button text
* @param button the button to change
* @param content the text to set
*/
private void setButtonText(Button button,String content){
Platform.runLater(()->{
button.setText(content);
});
}
/**
* To show a message of wait
*/
public void showWaitPane(){
waitPane.setVisible(true);
chooseResourcePane.setVisible(false);
}
/**
* To get the leader card image by the ID
* @param id the ID of the leader card in the model
* @return the leader card if the id exists
*/
private ImageView getLeaderCardViewByID(Integer id){
if(leaderCardWithID.keySet().contains(id)){
return leaderCardWithID.get(id);
}else{
return null;
}
}
/**
* @return a list of special cards images
*/
private ArrayList<ImageView> getSpecialCardsView(){
ArrayList<ImageView> specialCardsView=new ArrayList<>();
specialCardsView.add(specialCard1);
specialCardsView.add(specialCard2);
return specialCardsView;
}
/**
* To set an alert message because a player is disconnected
* @param msg CClientDisconnectedMsg
*/
public void setWarningPane(CClientDisconnectedMsg msg){
setLabelText(errorMessage,msg.getUsernameDisconnected()+" is disconnected!");
errorMessagePane.setVisible(true);
okButton.setDisable(false);
}
/**
* To set an alert message because the server is unable, every actions is interrupt and every pop-up or pane
* is hidden, then if the player clicks on the OK button the GUI closes automatically
* @param msg VServerUnableMsg
*/
public void setWarningPane(VServerUnableMsg msg){
setLabelText(errorMessage,"Server unable!\n Sorry the game ends here!");
actionButtons.setVisible(false);
errorMessagePane.setVisible(true);
okButton.setDisable(false);
setAllLeaderDisable();
disableActionButtons();
disableDepotPanes();
notVisibleDepotPanes();
actionButtons.setVisible(false);
strongBoxPane.setVisible(false);
strongBoxPane.setDisable(true);
disablePP();
disableCardSpaces();
stopPPPowerButton.setVisible(false);
stopPPPowerButton.setDisable(true);
chooseResourcePane.setVisible(false);
chooseOtherPlayerPane.setVisible(false);
disableOtherPlayersButtons();
}
public TurnAction getAction() {
return action;
}
public Label getActionLabel(){return actionLabel;}
public void setErrorMessage(String content) {
setLabelText(errorMessage,content);
errorMessagePane.setVisible(true);
okButton.setDisable(false);
}
public boolean isReturnToMarket() {return returnToMarket; }
}
| 39.952429 | 362 | 0.623325 |
dbead889488bc0a49bceb4aa17eb6859c05e6ac4 | 4,192 | /*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Creation Date: Feb 16, 2012
*
*******************************************************************************/
package org.oscm.ui.beans;
import java.io.Serializable;
import java.util.Calendar;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.oscm.ui.common.ExceptionHandler;
import org.oscm.ui.model.Discount;
import org.oscm.internal.types.exception.ObjectNotFoundException;
import org.oscm.internal.vo.VODiscount;
/**
* Backing bean for discount related actions.
*
* @author tokoda
*/
@ViewScoped
@ManagedBean(name="discountBean")
public class DiscountBean extends BaseBean implements Serializable {
private static final long serialVersionUID = -8252170979945981894L;
/**
* Returns the current logged-in customer discount, which is currently
* active or starting in the future.
*
* @param serviceKey
* the service key for which to get the discount
*
* @return the Discount (ui model wrapper) of the logged-in customer
*/
public Discount getDiscount(long serviceKey) {
Discount discount = null;
try {
VODiscount voDiscount = getDiscountService().getDiscountForService(
serviceKey);
if (voDiscount != null) {
if (isDiscountActive(voDiscount)) {
discount = new Discount(voDiscount);
}
}
} catch (ObjectNotFoundException ex) {
ExceptionHandler.execute(ex);
}
return discount;
}
/**
* Returns the customer discount of the current logged-in supplier, which is
* currently active or starting in the future.
*
* @param customerId
* the customer Id for which to get the discount
*
* @return the Discount (ui model wrapper) of the customer of the logged-in
* supplier
*/
public Discount getDiscountForCustomer(String customerId) {
Discount discount = null;
try {
VODiscount voDiscount = getDiscountService()
.getDiscountForCustomer(customerId);
if (voDiscount != null) {
if (isDiscountActive(voDiscount)) {
discount = new Discount(voDiscount);
}
}
} catch (ObjectNotFoundException ex) {
ExceptionHandler.execute(ex);
}
return discount;
}
private boolean isDiscountActive(VODiscount discount) {
if (discount == null) {
return false;
}
long currentTimeMonthYear = getTimeInMillisForFirstDay(System
.currentTimeMillis());
if (discount.getStartTime() == null
|| discount.getStartTime().longValue() > currentTimeMonthYear
|| (discount.getEndTime() != null && discount.getEndTime()
.longValue() < currentTimeMonthYear)) {
return false;
} else {
return true;
}
}
/**
* Getting millisecond of the first day in month.
*
* @param timeInMilis
* Time of any day of month.
* @return First millisecond of month.
*/
private long getTimeInMillisForFirstDay(long timeInMilis) {
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.setTimeInMillis(timeInMilis);
currentCalendar.set(Calendar.DAY_OF_MONTH, 1);
currentCalendar.set(Calendar.HOUR_OF_DAY, 0);
currentCalendar.set(Calendar.MINUTE, 0);
currentCalendar.set(Calendar.SECOND, 0);
currentCalendar.set(Calendar.MILLISECOND, 0);
return currentCalendar.getTimeInMillis();
}
}
| 33.269841 | 131 | 0.540553 |
5c4c4da77708a0aa16a0663a5a477904027f58be | 838 | package com.example.ecupcake;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class HomeActivity extends AppCompatActivity
{
private Button LogoutBtn;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
LogoutBtn = (Button) findViewById(R.id.logout_btn);
LogoutBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
Intent intent = new Intent(HomeActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
| 26.1875 | 83 | 0.644391 |
501344f4f6edbd74ba9b899449de1bfd2350c4cb | 1,503 | package com.example.univeristyligthhousekeeper.DatabaseModel;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import java.util.List;
public class Wydzial {
private int id;
private String wydzial;
private List<Kierunek> kierunki;
DatabaseAccess databaseAccess;
Context context;
public Wydzial() { }
public Wydzial(int id, String wydzial, Context context) {
this.id = id;
this.wydzial = wydzial;
this.context = context;
databaseAccess = DatabaseAccess.getInstance(context);
databaseAccess.open();
this.kierunki = databaseAccess.getKierunkidlaWydzialu(id);
databaseAccess.close();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getWydzial() {
return wydzial;
}
public void setWydzial(String wydzial) {
this.wydzial = wydzial;
}
public List<Kierunek> getKierunki() {
return kierunki;
}
public void setKierunki(List<Kierunek> kierunki) {
this.kierunki = kierunki;
}
public DatabaseAccess getDatabaseAccess() {
return databaseAccess;
}
public void setDatabaseAccess(DatabaseAccess databaseAccess) {
this.databaseAccess = databaseAccess;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
}
| 21.782609 | 66 | 0.648037 |
c501fdd9be7a0a956e774e770cacab8c47992677 | 20,663 | package com.newnil.cas.oauth2.provider.controller;
import com.newnil.cas.oauth2.provider.dao.entity.ClientDetailsToScopesXrefEntity;
import com.newnil.cas.oauth2.provider.dao.entity.RedirectUriEntity;
import com.newnil.cas.oauth2.provider.dao.repository.ClientDetailsRepository;
import com.newnil.cas.oauth2.provider.dao.repository.GrantTypeRepository;
import com.newnil.cas.oauth2.provider.dao.repository.ResourceIdRepository;
import com.newnil.cas.oauth2.provider.dao.repository.ScopeRepository;
import com.newnil.cas.oauth2.provider.service.OAuth2DatabaseClientDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.newnil.cas.oauth2.provider.webhelper.RedirectMessageHelper.*;
@Slf4j
@Controller
@RequestMapping("/clientDetails")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public class ClientDetailsAdminController {
@Autowired
private ClientDetailsRepository clientDetailsRepository;
@Autowired
private GrantTypeRepository grantTypeRepository;
@Autowired
private ScopeRepository scopeRepository;
@Autowired
private ResourceIdRepository resourceIdRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private OAuth2DatabaseClientDetailsService clientDetailsService;
@RequestMapping(method = RequestMethod.GET, produces = {MediaType.TEXT_HTML_VALUE, MediaType.APPLICATION_XHTML_XML_VALUE})
public String listAll(@RequestParam(name = "edit", required = false) String editClientDetails, Model model, Pageable pageable) {
if (!StringUtils.isEmpty(editClientDetails)) {
clientDetailsRepository.findOneByClientId(editClientDetails).map(clientDetailsEntity -> {
model.addAttribute("clientId", clientDetailsEntity.getClientId());
model.addAttribute("accessTokenValiditySeconds", clientDetailsEntity.getAccessTokenValiditySeconds());
model.addAttribute("refreshTokenValiditySeconds", clientDetailsEntity.getRefreshTokenValiditySeconds());
model.addAttribute("selectedGrantTypes", clientDetailsEntity.getAuthorizedGrantTypeXrefs().stream().map(
xref -> xref.getGrantType().getValue()
).collect(Collectors.toList()));
model.addAttribute("selectedScopes", clientDetailsEntity.getScopeXrefs().stream().map(
xref -> xref.getScope().getValue()
).collect(Collectors.toList()));
model.addAttribute("selectedAutoApproveScopes", clientDetailsEntity.getScopeXrefs().stream()
.filter(ClientDetailsToScopesXrefEntity::getAutoApprove).map(
xref -> xref.getScope().getValue()
).collect(Collectors.toList())
);
model.addAttribute("selectedResourceIds", clientDetailsEntity.getResourceIdXrefs().stream().map(
xref -> xref.getResourceId().getValue()
).collect(Collectors.toList()));
model.addAttribute("redirectUris", clientDetailsEntity.getRedirectUris().stream()
.map(RedirectUriEntity::getValue).collect(Collectors.joining(System.lineSeparator()))
);
return null;
});
}
model.addAttribute("clientDetailsList", clientDetailsRepository.findAll(pageable));
model.addAttribute("grantTypes", grantTypeRepository.findAll());
model.addAttribute("scopes", scopeRepository.findAll());
model.addAttribute("resourceIds", resourceIdRepository.findAll());
return "clients/clientDetails";
}
private static final Pattern CLIENT_ID_PATTERN = Pattern.compile("^[a-zA-Z0-9_]+$");
private static final Pattern PASSWORD_WORD_PATTERN = Pattern.compile("^[a-zA-Z0-9]{6,}$");
@RequestMapping(path = "/_create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = {MediaType.TEXT_HTML_VALUE, MediaType.APPLICATION_XHTML_XML_VALUE})
public String create(@RequestParam("clientId") String clientId,
@RequestParam("clientSecret") String clientSecret,
@RequestParam(name = "accessTokenValiditySeconds", required = false) Integer accessTokenValiditySeconds,
@RequestParam(name = "refreshTokenValiditySeconds", required = false) Integer refreshTokenValiditySeconds,
@RequestParam(name = "grantTypes", defaultValue = "") List<String> grantTypes,
@RequestParam(name = "scopes", defaultValue = "") List<String> scopes,
@RequestParam(name = "autoApproveAll", defaultValue = "false") boolean autoApproveAll,
@RequestParam(name = "autoApproveScopes", defaultValue = "") List<String> autoApproveScopes,
@RequestParam(name = "resourceIds", defaultValue = "") List<String> resourceIds,
@RequestParam("redirectUris") String redirectUris,
RedirectAttributes attributes) {
if (!CLIENT_ID_PATTERN.matcher(clientId).matches()) {
addErrorMessage(attributes, "客户端ID " + clientId + " 含有非法字符。(只能使用[a-zA-Z0-9_])");
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails";
}
if (clientDetailsRepository.findOneByClientId(clientId).isPresent()) {
addErrorMessage(attributes, "客户端ID " + clientId + " 已存在。");
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails";
}
if (!PASSWORD_WORD_PATTERN.matcher(clientSecret).matches()) {
addErrorMessage(attributes, "客户端密码含有非法字符。(只能使用[a-zA-Z0-9],至少6位)");
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails";
}
if (accessTokenValiditySeconds != null && accessTokenValiditySeconds < 0) {
addErrorMessage(attributes, "AccessToken有效秒数不能小于零。");
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails";
}
if (refreshTokenValiditySeconds != null && refreshTokenValiditySeconds < 0) {
addErrorMessage(attributes, "RefreshToken有效秒数不能小于零。");
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails";
}
// 检查授权方式
if (!checkGrantTypeValidation(grantTypes, attributes)) {
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails";
}
// 检查授权范围
if (!checkScopeValidation(scopes, attributes)) {
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails";
}
// 检查自动授权范围
if (!checkScopeValidation(autoApproveScopes, attributes)) {
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails";
}
// 检查资源ID
if (!checkResourceIdValidation(resourceIds, attributes)) {
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails";
}
Set<String> redirectUrisList = new HashSet<>();
if (!StringUtils.isEmpty(redirectUris)) {
LineNumberReader lineNumberReader = new LineNumberReader(new StringReader(redirectUris));
String line;
try {
while ((line = lineNumberReader.readLine()) != null) {
redirectUrisList.add(line);
}
} catch (IOException e) {
log.warn("IOException while parsing redirect Uris: " + redirectUris, e);
}
}
BaseClientDetails baseClientDetails = new BaseClientDetails();
baseClientDetails.setClientId(clientId);
baseClientDetails.setClientSecret(clientSecret);
baseClientDetails.setAccessTokenValiditySeconds(accessTokenValiditySeconds);
baseClientDetails.setRefreshTokenValiditySeconds(refreshTokenValiditySeconds);
baseClientDetails.setAuthorizedGrantTypes(grantTypes);
baseClientDetails.setScope(scopes);
if (autoApproveAll) {
baseClientDetails.setAutoApproveScopes(Collections.singleton("true"));
} else {
baseClientDetails.setAutoApproveScopes(autoApproveScopes);
}
baseClientDetails.setResourceIds(resourceIds);
baseClientDetails.setRegisteredRedirectUri(redirectUrisList);
clientDetailsService.addClientDetails(baseClientDetails);
addSuccessMessage(attributes, "客户端 " + clientId + " 注册成功。");
return "redirect:/clientDetails";
}
@RequestMapping(path = "/_update", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = {MediaType.TEXT_HTML_VALUE, MediaType.APPLICATION_XHTML_XML_VALUE})
public String update(@RequestParam("clientId") String clientId,
@RequestParam(name = "clientSecret", required = false) String clientSecret,
@RequestParam(name = "accessTokenValiditySeconds", required = false) Integer accessTokenValiditySeconds,
@RequestParam(name = "refreshTokenValiditySeconds", required = false) Integer refreshTokenValiditySeconds,
@RequestParam(name = "grantTypes", defaultValue = "") List<String> grantTypes,
@RequestParam(name = "scopes", defaultValue = "") List<String> scopes,
@RequestParam(name = "autoApproveAll", defaultValue = "false") boolean autoApproveAll,
@RequestParam(name = "autoApproveScopes", defaultValue = "") List<String> autoApproveScopes,
@RequestParam(name = "resourceIds", defaultValue = "") List<String> resourceIds,
@RequestParam("redirectUris") String redirectUris,
RedirectAttributes attributes) {
if (!clientDetailsRepository.findOneByClientId(clientId).isPresent()) {
addErrorMessage(attributes, "找不到客户端ID " + clientId);
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails?edit=" + clientId;
}
if (!StringUtils.isEmpty(clientSecret)) {
if (!PASSWORD_WORD_PATTERN.matcher(clientSecret).matches()) {
addErrorMessage(attributes, "客户端密码含有非法字符。(只能使用[a-zA-Z0-9],至少6位)");
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails?edit=" + clientId;
}
}
if (accessTokenValiditySeconds != null && accessTokenValiditySeconds < 0) {
addErrorMessage(attributes, "AccessToken有效秒数不能小于零。");
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails?edit=" + clientId;
}
if (refreshTokenValiditySeconds != null && refreshTokenValiditySeconds < 0) {
addErrorMessage(attributes, "RefreshToken有效秒数不能小于零。");
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails?edit=" + clientId;
}
// 检查授权方式
if (!checkGrantTypeValidation(grantTypes, attributes)) {
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails?edit=" + clientId;
}
// 检查授权范围
if (!checkScopeValidation(scopes, attributes)) {
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails?edit=" + clientId;
}
// 检查自动授权范围
if (!checkScopeValidation(autoApproveScopes, attributes)) {
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails?edit=" + clientId;
}
// 检查资源ID
if (!checkResourceIdValidation(resourceIds, attributes)) {
resetRequestParams(clientId, accessTokenValiditySeconds, refreshTokenValiditySeconds, grantTypes,
scopes, autoApproveAll, autoApproveScopes, resourceIds, redirectUris, attributes);
return "redirect:/clientDetails?edit=" + clientId;
}
Set<String> redirectUrisList = new HashSet<>();
if (!StringUtils.isEmpty(redirectUris)) {
LineNumberReader lineNumberReader = new LineNumberReader(new StringReader(redirectUris));
String line;
try {
while ((line = lineNumberReader.readLine()) != null) {
redirectUrisList.add(line);
}
} catch (IOException e) {
log.warn("IOException while parsing redirect Uris: " + redirectUris, e);
}
}
BaseClientDetails baseClientDetails = (BaseClientDetails) clientDetailsService.loadClientByClientId(clientId);
baseClientDetails.setClientId(clientId);
baseClientDetails.setAccessTokenValiditySeconds(accessTokenValiditySeconds);
baseClientDetails.setRefreshTokenValiditySeconds(refreshTokenValiditySeconds);
baseClientDetails.setAuthorizedGrantTypes(grantTypes);
baseClientDetails.setScope(scopes);
if (autoApproveAll) {
baseClientDetails.setAutoApproveScopes(Collections.singleton("true"));
} else {
baseClientDetails.setAutoApproveScopes(autoApproveScopes);
}
baseClientDetails.setResourceIds(resourceIds);
baseClientDetails.setRegisteredRedirectUri(redirectUrisList);
clientDetailsService.updateClientDetails(baseClientDetails);
if (!StringUtils.isEmpty(clientSecret)) {
clientDetailsService.updateClientSecret(clientId, clientSecret);
}
addSuccessMessage(attributes, "客户端 " + clientId + " 更新成功。");
return "redirect:/clientDetails";
}
private boolean checkGrantTypeValidation(List<String> grantTypes, RedirectAttributes attributes) {
List<String> invalidGrantTypes = new ArrayList<>();
grantTypes.forEach(grantType -> {
if (!grantTypeRepository.findOneByValue(grantType).isPresent()) {
invalidGrantTypes.add(grantType);
}
});
invalidGrantTypes.forEach(grantType -> addErrorMessage(attributes, "授权方式 " + grantType + " 无效。"));
return invalidGrantTypes.isEmpty();
}
private boolean checkScopeValidation(List<String> scopes, RedirectAttributes attributes) {
List<String> invalidScopes = new ArrayList<>();
scopes.forEach(scope -> {
if (!scopeRepository.findOneByValue(scope).isPresent()) {
invalidScopes.add(scope);
}
});
invalidScopes.forEach(scope -> addErrorMessage(attributes, "授权范围 " + scope + " 无效。"));
return invalidScopes.isEmpty();
}
private boolean checkResourceIdValidation(List<String> resourceIds, RedirectAttributes attributes) {
List<String> invalidResourceIds = new ArrayList<>();
resourceIds.forEach(resourceId -> {
if (!resourceIdRepository.findOneByValue(resourceId).isPresent()) {
invalidResourceIds.add(resourceId);
}
});
invalidResourceIds.forEach(resourceId -> addErrorMessage(attributes, "资源ID " + resourceId + " 无效。"));
return invalidResourceIds.isEmpty();
}
private void resetRequestParams(String clientId, Integer accessTokenValiditySeconds, Integer refreshTokenValiditySeconds,
List<String> grantTypes, List<String> scopes, boolean autoApproveAll, List<String> autoApproveScopes,
List<String> resourceIds, String redirectUris,
RedirectAttributes attributes) {
attributes.addFlashAttribute("clientId", clientId);
attributes.addFlashAttribute("accessTokenValiditySeconds", accessTokenValiditySeconds);
attributes.addFlashAttribute("refreshTokenValiditySeconds", refreshTokenValiditySeconds);
attributes.addFlashAttribute("selectedGrantTypes", grantTypes);
attributes.addFlashAttribute("selectedScopes", scopes);
attributes.addFlashAttribute("autoApproveAll", autoApproveAll);
attributes.addFlashAttribute("selectedAutoApproveScopes", autoApproveScopes);
attributes.addFlashAttribute("selectedResourceIds", resourceIds);
attributes.addFlashAttribute("redirectUris", redirectUris);
}
@RequestMapping(path = "/_remove/{clientId}", method = RequestMethod.GET, produces = {MediaType.TEXT_HTML_VALUE, MediaType.APPLICATION_XHTML_XML_VALUE})
public String delete(@PathVariable("clientId") String clientId, RedirectAttributes attributes) {
try {
clientDetailsService.removeClientDetails(clientId);
} catch (NoSuchClientException e) {
addWarningMessage(attributes, "没有找到客户端ID " + clientId + " 对应的客户端。");
}
return "redirect:/clientDetails";
}
}
| 52.444162 | 156 | 0.684025 |
147522c12631d4077719c6d3c575fd5427dfe8d3 | 1,919 | package com.giorgiofederici.sjp.security.handler;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;
@Component
public class SjpAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Autowired
private MessageSource messages;
@Autowired
private LocaleResolver localeResolver;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
setDefaultFailureUrl("/signin?error");
super.onAuthenticationFailure(request, response, exception);
Locale locale = this.localeResolver.resolveLocale(request);
String errorMessage = this.messages.getMessage("sjp.signin.validation.user.invalid", null, locale);
if (exception.getClass().isAssignableFrom(UsernameNotFoundException.class)) {
this.messages.getMessage("sjp.signin.validation.user.invalid", null, locale);
} else if (exception.getClass().isAssignableFrom(DisabledException.class)) {
errorMessage = this.messages.getMessage("sjp.signin.validation.user.disabled", null, locale);
}
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, errorMessage);
}
}
| 38.38 | 101 | 0.837415 |
1778a403a62348820f81aacc1cbb8b155393c5b0 | 385 | package cz.tul.entities;
/**
* Created by Marek on 27.09.2016.
*/
public enum AttributeType {
NUMBER("number"),
SELECT("select"),
TEXT("text"),
IMAGE("image");
private String attributeType;
AttributeType(String attributeType) {
this.attributeType = attributeType;
}
public String getAttributeType() {
return attributeType;
}
}
| 17.5 | 43 | 0.633766 |
fd317d154cd8cf160b53b6c2f1025258311171b4 | 576 | package main.java.br.com.illuminati.calculator;
public class InputTransformer {
private final static char ILLUMINATI_CHARACTER = '▲';
public String removeIlluminatiSymbol(String input){
return input.replaceAll((String.valueOf(ILLUMINATI_CHARACTER)), "");
}
public String[] splitByWhitespace(String input){
return input.split(" ");
}
public String[] transformInput(String input) {
String inputWithoutIlluminatiSymbol = removeIlluminatiSymbol(input);
return splitByWhitespace(inputWithoutIlluminatiSymbol);
}
}
| 26.181818 | 76 | 0.717014 |
ed9aaaf694f383170f399fc722927034f642db2d | 3,802 | package vid.automation.test.infra;
import java.time.LocalDate;
import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;
import org.togglz.core.context.StaticFeatureManagerProvider;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/*
This transformer skip test we want to ignore during running VID tests.
Pay attention that this listener shall be configured in the testng.xml (or command line)
It can't be used as Listener annotation of base class
FeatureTogglingTest:
There are 2 ways to annotate that tests required featureFlags to be active :
In method level - with @FeatureTogglingTest on the test method and list of Required Feature flags on
In Class level - with @FeatureTogglingTest on the test class and list of Required Feature flags on
For each test annotation of method level, we check if the test shall whole class shall run regards the features flag test.
SkipTestUntil:
If test annotated with SkipTestUntil the transformer check if the due date has already pass
*/
public class SkipTestsTestngTransformer implements IAnnotationTransformer {
@Override
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
if (testMethod!=null) {
try {
if (!annotation.getEnabled()) {
return;
}
if (isIgnoreFeatureToggledTest(testMethod)) {
disableTest(annotation, testMethod.getName());
return;
}
if (isIgnoreFeatureToggledTest(testMethod.getDeclaringClass())) {
disableTest(annotation, testMethod.getDeclaringClass().getName());
return;
}
if (isIgnoreSkipUntilTest(testMethod)) {
disableTest(annotation, testMethod.getName());
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private boolean isIgnoreFeatureToggledTest(AnnotatedElement annotatedElement) {
return (annotatedElement.isAnnotationPresent(FeatureTogglingTest.class) &&
shallDisableTest(annotatedElement.getAnnotation(FeatureTogglingTest.class)));
}
private boolean shallDisableTest(FeatureTogglingTest featureTogglingTest) {
if (featureTogglingTest.value().length==0) {
return false;
}
if (new StaticFeatureManagerProvider().getFeatureManager()==null) {
FeaturesTogglingConfiguration.initializeFeatureManager();
}
for (Features feature : featureTogglingTest.value()) {
if (!(feature.isActive()==featureTogglingTest.flagActive())) {
return true;
}
}
return false;
}
private void disableTest(ITestAnnotation annotation, String name) {
System.out.println("Ignore "+ name+" due to annotation");
annotation.setEnabled(false);
}
private boolean isIgnoreSkipUntilTest(AnnotatedElement annotatedElement) {
if (!annotatedElement.isAnnotationPresent(SkipTestUntil.class)) {
return false;
}
String dateAsStr = annotatedElement.getAnnotation(SkipTestUntil.class).value();
try {
return LocalDate.now().isBefore(LocalDate.parse(dateAsStr));
}
catch (RuntimeException exception) {
System.out.println("Failure during processing of SkipTestUntil annotation value is " + dateAsStr);
exception.printStackTrace();
return false;
}
}
}
| 36.557692 | 122 | 0.649395 |
d8fff5a1833092a6ab2e9535ca5543cbf638e4f0 | 718 | package scrame;
import java.io.Serializable;
/**
* A pair utility class
*
* @author abhishekbhagwat
*
* @param <L> The Left Component
* @param <R> The Right Component
* Code cloned and cleaned up from https://gist.github.com/anuvrat/370901.js git gist
* Java API docs link https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html
*/
public class Pair<L, R> implements Serializable {
public final L left;
public final R right;
/**
* Assignment of the parameter components to the field in the current buffer
* @param left
* @param right
*/
public Pair(L left, R right) {
this.left = left;
this.right = right;
}
}
| 24.758621 | 117 | 0.668524 |
00a691c08a190eecf0878ecc7e06a971993ecb7d | 2,892 | package mage.cards.p;
import java.util.UUID;
import mage.MageObject;
import mage.abilities.Ability;
import mage.abilities.effects.OneShotEffect;
import mage.cards.Card;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.Zone;
import mage.filter.FilterCard;
import mage.game.Game;
import mage.players.Player;
import mage.target.TargetCard;
import mage.target.common.TargetOpponent;
/**
*
* @author jeffwadsworth
*/
public final class PerishTheThought extends CardImpl {
public PerishTheThought(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{2}{B}");
// Target opponent reveals their hand. You choose a card from it. That player shuffles that card into their library.
this.getSpellAbility().addEffect(new PerishTheThoughtEffect());
this.getSpellAbility().addTarget(new TargetOpponent());
}
public PerishTheThought(final PerishTheThought card) {
super(card);
}
@Override
public PerishTheThought copy() {
return new PerishTheThought(this);
}
}
class PerishTheThoughtEffect extends OneShotEffect {
private static final FilterCard filter = new FilterCard("card in target opponent's hand");
public PerishTheThoughtEffect() {
super(Outcome.Neutral);
this.staticText = "Target opponent reveals their hand. You choose a card from it. That player shuffles that card into their library";
}
public PerishTheThoughtEffect(final PerishTheThoughtEffect effect) {
super(effect);
}
@Override
public PerishTheThoughtEffect copy() {
return new PerishTheThoughtEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Player targetOpponent = game.getPlayer(source.getFirstTarget());
MageObject sourceObject = source.getSourceObject(game);
if (targetOpponent != null && sourceObject != null) {
if (!targetOpponent.getHand().isEmpty()) {
targetOpponent.revealCards(sourceObject.getIdName(), targetOpponent.getHand(), game);
Player you = game.getPlayer(source.getControllerId());
if (you != null) {
TargetCard target = new TargetCard(Zone.HAND, filter);
target.setNotTarget(true);
if (you.choose(Outcome.Neutral, targetOpponent.getHand(), target, game)) {
Card chosenCard = targetOpponent.getHand().get(target.getFirstTarget(), game);
if (chosenCard != null) {
targetOpponent.shuffleCardsToLibrary(chosenCard, game, source);
}
}
}
}
return true;
}
return false;
}
}
| 33.627907 | 141 | 0.655602 |
c296d20da3c77e3613b597da7b64de761c067a77 | 824 | package com.insightsuen.stayfoolish.base;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import com.insightsuen.bindroid.component.BindActivity;
import com.insightsuen.bindroid.viewmodel.LifecycleViewModel;
/**
* Created by InSight Suen on 2017/7/12.
* Base Activity
*/
public abstract class BaseActivity<Binding extends ViewDataBinding> extends BindActivity<Binding> {
@Nullable
@Override
protected LifecycleViewModel createOrFindViewModel(@Nullable Bundle savedInstanceState) {
return null;
}
@Override
protected void onRestart() {
super.onRestart();
LifecycleViewModel viewModel = createOrFindViewModel(null);
if (viewModel != null) {
viewModel.onStart(this);
}
}
}
| 26.580645 | 99 | 0.730583 |
5cb8688499c13bccf1c272f1d95f6aab88a8d5c8 | 430 | package android.support.p000v4.graphics;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.support.annotation.RequiresApi;
@TargetApi(19)
@RequiresApi(19)
/* renamed from: android.support.v4.graphics.BitmapCompatKitKat */
class BitmapCompatKitKat {
BitmapCompatKitKat() {
}
static int getAllocationByteCount(Bitmap bitmap) {
return bitmap.getAllocationByteCount();
}
}
| 23.888889 | 66 | 0.767442 |
dd7e49eaf31f30f07ea0ac37945d5e17b88a5e1b | 2,717 | package dk.netdesign.common.osgi.config.wicket.jetty;
import org.apache.wicket.protocol.http.ContextParamWebApplicationFactory;
import org.apache.wicket.protocol.http.WicketFilter;
import org.eclipse.jetty.jmx.MBeanContainer;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import javax.management.MBeanServer;
import javax.servlet.DispatcherType;
import java.lang.management.ManagementFactory;
import java.util.EnumSet;
/**
* Separate startup class for people that want to run the examples directly. Use
* parameter -Dcom.sun.management.jmxremote to startup JMX (and e.g. connect
* with jconsole).
*/
public class EmbeddableJetty {
/**
* Main function, starts the jetty server.
*
* @param args
*/
public final static int PORT = 8080;
private Server server = new Server();
public EmbeddableJetty() {
System.setProperty("wicket.configuration", "development");
ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(new HttpConfiguration()));
http.setPort(PORT);
http.setIdleTimeout(1000 * 60 * 60);
server.addConnector(http);
ServletContextHandler sch = new ServletContextHandler(ServletContextHandler.SESSIONS);
FilterHolder fh2 = new FilterHolder(WicketFilter.class);
fh2.setInitParameter(ContextParamWebApplicationFactory.APP_CLASS_PARAM, WicketTestApplication.class.getName());
fh2.setInitParameter(WicketFilter.FILTER_MAPPING_PARAM, "/*");
sch.addFilter(fh2, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR));
server.setHandler(sch);
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
server.addEventListener(mBeanContainer);
server.addBean(mBeanContainer);
}
public static void main(String[] args) throws Exception {
EmbeddableJetty embeddableJettyWebTest = new EmbeddableJetty();
embeddableJettyWebTest.start();
}
public void start() throws Exception {
try {
server.start();
} catch (Exception e) {
e.printStackTrace();
System.exit(100);
}
}
public void stop() throws Exception {
try {
server.stop();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(100);
}
}
}
| 31.229885 | 119 | 0.699669 |
e58cc77f105d8e963df295bf1351962196664ff2 | 380 | package by.grsu.boldak.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* `user` page controller
*/
@Controller
@RequestMapping("/user")
public class UserController {
@GetMapping
public String userIndex() {
return "user/index";
}
}
| 21.111111 | 62 | 0.778947 |
828d36907082f05902dbf5cc6b0995f7399bae12 | 766 | package com.javaonlinecourse.b3lesson2.classwork;
/**
* Author: E_Mitrohin
* Date: 23.11.2016.
*/
public class CW01 {
public static void main(String[] args) {
boolean condition1 = true, condition2 = false;
// По правилам синтаксиса Java else относится к самому внутреннему if
if (condition1)
if (condition2) doSomething();
else doAnything();
// Если требуется другая логика, необходимо использовать составной оператор:
if (condition1) {
if (condition2) doSomething();
} else doAnything();
// либо
if (condition1 && condition2) doSomething();
else doAnything();
}
static void doSomething() {
}
static void doAnything() {
}
}
| 24.709677 | 84 | 0.605744 |
ba7e1b54fefd27756d2a62cd95c0ebc3379bcfb9 | 1,250 | package com.github.infobarbosa.scyllalabs;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import twitter4j.Status;
import twitter4j.TwitterException;
@RunWith(JUnit4.class)
public class AppTest {
App app = null;
ColetorTwitter coletor = null;
@Before
public void init() {
app = new App();
app.createKeyspace();
app.createTable();
coletor = new ColetorTwitter();
}
@Test
public void deveObterTweetsEPersistirNaTabela() {
System.out.println("Obtendo tweets...");
try {
List<Status> tweets = coletor.getTweets();
app.persisteTweets(tweets);
} catch (TwitterException e) {
e.printStackTrace();
assertTrue(false);
}
assertTrue(true);
}
@After
public void finalize(){
System.out.println("fechando sessao...");
app.dropKeyspace();
System.out.println("sessao fechada! fechando conexao...");
app.closeConnection();
System.out.println("conexao fechada!");
}
}
| 23.584906 | 66 | 0.636 |
bd22a1df1acbf25ea2deaf630eb49266b7369801 | 1,304 | package net.coding.ide.service;
import net.coding.ide.dto.FileDTO;
import net.coding.ide.entity.WorkspaceEntity;
import net.coding.ide.model.FileInfo;
import net.coding.ide.model.FileSearchResultEntry;
import net.coding.ide.model.Workspace;
import net.coding.ide.model.exception.GitCloneAuthFailException;
import org.eclipse.jgit.api.errors.GitAPIException;
import java.io.IOException;
import java.util.List;
public interface WorkspaceManager {
Workspace setup(String spaceKey);
Workspace createFromUrl(String gitUrl) throws GitCloneAuthFailException;
void delete(String spaceKey);
Workspace getWorkspace(String spaceKey);
List<WorkspaceEntity> list();
WorkspaceEntity getWorkspaceEntity(String spaceKey);
FileDTO readFile(Workspace ws, String path, String encoding, boolean base64) throws IOException, GitAPIException, Exception;
FileInfo getFileInfo(Workspace ws, String path) throws Exception;
List<FileInfo> listFiles(Workspace ws, String path, boolean order, boolean group) throws Exception;
List<FileSearchResultEntry> search(Workspace ws, String keyword, boolean includeNonProjectItems) throws IOException;
boolean isOnline(String spaceKey);
boolean isDeleted(String spaceKey);
void setEncoding(Workspace ws, String charSet);
}
| 30.325581 | 128 | 0.792945 |
e955564d26be9af0579d02d6405e302bea34dd41 | 343 | package br.com.basis.madre.repository.search;
import br.com.basis.madre.domain.Clinica;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Spring Data Elasticsearch repository for the {@link Clinica} entity.
*/
public interface ClinicaSearchRepository extends ElasticsearchRepository<Clinica, Long> {
}
| 34.3 | 89 | 0.819242 |
42fba5201cfb8b58b900cd672ddbe51093b7f1e7 | 13,441 | package com.medusa.gruul.common.core.util;
import org.apache.commons.lang.StringUtils;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.Math.*;
/**
* <p>
* 请求用户信息工具类
* </p>
*
* @author 王鹏
* @since 2019-1206-23
*/
public class StringUtil extends StringUtils {
// 一个空的字符串。
public static final String EMPTY_STRING = "";
// ================================将符号也作为常量,避免半角全角符号导致的狗血异常======================================
// 逗号
public static final String SYMBOL_COMMA = ",";
// 等于号
public static final String SYMBOL_EQUAL = "=";
// 点号
public static final String SYMBOL_DOT = ".";
// 问号
public static final String SYMBOL_QUESTION = "?";
// 分号
public static final String SYMBOL_SEMICOLON = ";";
/**
* 验证EMAIL正则表达式
*/
public static final String PATTERN_EMAIL = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
/**
* 如果传入的值是null,返回空字符串,如果不是null,返回本身。
*
* @param word 传入的源字符串。
* @return
*/
public static String getNotNullValue(String word) {
return (word == null || "null".equalsIgnoreCase(word)) ? "" : word;
}
/**
* 如果传入的值是null,返回空字符串,如果不是null,返回本身。
*
* @param word 传入的源字符串。
* @return
*/
public static String getNotNullValue(String word, String defaultWord) {
return (word == null || "null".equalsIgnoreCase(word)) ? defaultWord : word;
}
/**
* 根据分隔符从一段字符串拿到对应的列表。应用于以下场景。 2,3,4,5 ==> [2,3,4,5]
*
* @param originWord
* @param symbol
* @return
*/
public static List<String> getSplitListFromString(String originWord, String symbol) {
List<String> result = new ArrayList<String>();
if (isBlank(originWord)) {
return result;
}
String[] splitData = originWord.split(symbol);
if (splitData == null || splitData.length == 0) {
return result;
}
for (String word : splitData) {
if (isNotBlank(word)) {
result.add(word);
}
}
return result;
}
/**
* 将map转换成String
* @param map
* @return
*/
public static String mapToString(Map<String ,String > map){
Set<String> keySet = map.keySet();
StringBuffer strBuff = new StringBuffer();
for(String keyStr : keySet){
if(StringUtils.isNotBlank(map.get(keyStr))){
strBuff.append(keyStr).append("=").append(map.get(keyStr)).append("&");
}
}
return strBuff.substring(0,strBuff.length()-1).toString();
}
/**
* @param originalStr
* @param symbol
* @return
*/
public static List<Long> getLongListFromString(String originalStr, String symbol) {
List<Long> result = new ArrayList<Long>();
if (isBlank(originalStr)) {
return result;
}
String[] splitData = originalStr.split(symbol);
for (String word : splitData) {
if (isNotBlank(word)) {
result.add(Long.parseLong(word));
}
}
return result;
}
/**
* 移除左边的0, eg:00000jakjdkf89000988000 转换之后变为 jakjdkf89000988000
*
* @param str
* @return
*/
public static String removeLeftZero(String str) {
int start = 0;
if (isNotEmpty(str)) {
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] != '0') {
start = i;
break;
}
}
return str.substring(start);
}
return "";
}
/**
* 格式化大数据为len个小数
*
* @param obj
* @param len
* @return
*/
public static String formatLagerNumberToStr(Object obj, int len) {
if (obj != null) {
if (obj instanceof String) {
String str = String.valueOf(obj);
return str.substring(0, str.indexOf(".") + len + 1);
} else {
StringBuffer pattern = new StringBuffer("0");
for (int i = 0; i < len; i++) {
if (i == 0) {
pattern.append(".0");
continue;
}
pattern.append("0");
}
return new DecimalFormat(pattern.toString()).format(obj);
}
}
return "";
}
/**
* 金额格式化
*
* @param money 金额
* @param len 小数位数
* @return 格式后的金额
*/
public static String insertComma(String money, int len) {
if (money == null || money.length() < 1) {
return "";
}
NumberFormat formater = null;
double num = Double.parseDouble(money);
if (len == 0) {
formater = new DecimalFormat("###,###");
} else {
StringBuffer buff = new StringBuffer();
buff.append("###,###.");
for (int i = 0; i < len; i++) {
buff.append("#");
}
formater = new DecimalFormat(buff.toString());
}
return formater.format(num);
}
/**
* 金额去掉“,”
*
* @param money 金额
* @return 去掉“,”后的金额
*/
public static String delComma(String money) {
String formatString = "";
if (money != null && money.length() >= 1) {
formatString = money.replaceAll(",", "");
}
return formatString;
}
public static String toRMB(double money) {
char[] s1 = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' };
char[] s4 = { '分', '角', '元', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟', '万' };
String str = String.valueOf(round(money * 100 + 0.00001));
String result = "";
for (int i = 0; i < str.length(); i++) {
int n = str.charAt(str.length() - 1 - i) - '0';
result = s1[n] + "" + s4[i] + result;
}
result = result.replaceAll("零仟", "零");
result = result.replaceAll("零佰", "零");
result = result.replaceAll("零拾", "零");
result = result.replaceAll("零亿", "亿");
result = result.replaceAll("零万", "万");
result = result.replaceAll("零元", "元");
result = result.replaceAll("零角", "零");
result = result.replaceAll("零分", "零");
result = result.replaceAll("零零", "零");
result = result.replaceAll("零亿", "亿");
result = result.replaceAll("零零", "零");
result = result.replaceAll("零万", "万");
result = result.replaceAll("零零", "零");
result = result.replaceAll("零元", "元");
result = result.replaceAll("亿万", "亿");
result = result.replaceAll("零$", "");
result = result.replaceAll("元$", "元整");
return result;
}
public static boolean containStr(String rawStr, String containStr) {
if ((rawStr != null) && (containStr != null)) {
return rawStr.contains(containStr);
}
return false;
}
/**
* 判断是否为数字或小数
*
* @param number
* @return
*/
public static boolean checkNumber(String number) {
String str = "^[0-9]+(.[0-9]{2})?$";
Pattern pattern = Pattern.compile(str);
if (StringUtil.isNotBlank(number)) {
Matcher matcher = pattern.matcher(number);
return matcher.find();
}
return false;
}
/**
* 过程名称:ChineseLen(获得当前文字的长度,中文为2个字符)
*
* @param FromStr
* @return
*/
public static boolean checkChineseLen(String FromStr, int maxLen)
{
if (StringUtil.isBlank(FromStr)) {
return false;
}
int FromLen = FromStr.length();
int ChineseLen = 0;
for (int i = 0; i < FromLen; i++)
{
if (gbValue(FromStr.charAt(i)) > 0) {
ChineseLen = ChineseLen + 2;
} else {
ChineseLen++;
}
}
if (ChineseLen <= maxLen) {
return true;
} else {
return false;
}
}
/*******
* 过程名称:gbValue(返回GBK的编码)
*
* @param ch
* @return
*/
public static int gbValue(char ch)
{
String str = new String();
str += ch;
try
{
byte[] bytes = str.getBytes("GBK");
if (bytes.length < 2) {
return 0;
}
return (bytes[0] << 8 & 0xff00) + (bytes[1] & 0xff);
} catch (Exception e)
{
return 0;
}
}
/**
* 半角转全角
*
* @param input String.
* @return 全角字符串.
*/
public static String ToSBC(String input) {
char[] c = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
c[i] = '\u3000';
} else if (c[i] < '\177') {
c[i] = (char) (c[i] + 65248);
}
}
return new String(c);
}
/**
* 全角转半角
*
* @param input String.
* @return 半角字符串
*/
public static String ToDBC(String input) {
char[] c = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == '\u3000') {
c[i] = ' ';
} else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
c[i] = (char) (c[i] - 65248);
}
}
String returnString = new String(c);
return returnString;
}
/**
* LIST转换为字符串,转换时插入制定的分隔符
*
* @param list 字符串LIST
* @param symbol 分隔符
* @return
*/
public static String listToString(List<?> list, String symbol) {
String res = null;
if (null != list && 0 < list.size()) {
int size = list.size();
if (size == 1) {
return String.valueOf(list.get(0));
}
StringBuilder sb = new StringBuilder();
if (symbol == null) {
symbol = "";
}
for (int i = 0; i < size; i++) {
if (i > 0) {
sb.append(symbol);
}
sb.append(String.valueOf(list.get(i)));
}
res = sb.toString();
}
return res;
}
/**
* <p>
* 判断是否为数字格式
* </p>
*
* <pre>
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = false
* StringUtils.isNumeric(" ") = false
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("12 3") = false
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = true
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if only contains digits, and is non-null
*/
public static boolean isDoubleNumeric(String str) {
if (str == null) {
return false;
}
try {
Double.parseDouble(str.replace(",", ""));
} catch (Exception e) {
return false;
}
return true;
}
/**
* 判断是否为数字(有小数位或者有千分位)
*
* @param str
* @return
*/
public static boolean isNumericDecimal(String str) {
return isDoubleNumeric(str) && (str.indexOf(".") > 0 || str.indexOf(",") > 0);
}
/**
* 判断是否为email格式
*
* @param email 验证字符串
* @return true|false
*/
public static boolean isEmail(String email) {
Pattern p = Pattern.compile(PATTERN_EMAIL);
Matcher m = p.matcher(email);
return m.matches();
}
/**
* 字符数组转化为字符串
*
* @param strs 字符数组
* @param symbol 分隔符
* @return
*/
public static String arrayToStr(String[] strs, String symbol) {
return getString(strs, symbol);
}
public static String arrayToStr(String symbol, String... strs) {
return getString(strs, symbol);
}
private static String getString(String[] strs, String symbol) {
if (strs == null || strs.length == 0) {
return null;
}
if (symbol == null) {
symbol = "";
}
StringBuilder sb = new StringBuilder();
for (String str : strs) {
if (sb.length() > 0) {
sb.append(symbol);
}
sb.append(str);
}
return sb.toString();
}
/**
* 首字母大写
*
* @param s
* @return
*/
public static String toUpperCaseFirstOne(String s) {
if (Character.isUpperCase(s.charAt(0))) {
return s;
} else {
return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
}
}
public static String genNumberRandomCode(int fix) {
String chars = "0123456789";
char[] rands = new char[fix];
for (int i = 0; i < fix; i++) {
int rand = (int) (random() * 10);
rands[i] = chars.charAt(rand);
}
return new String(rands);
}
}
| 24.707721 | 157 | 0.480917 |
12f10991c54d318cf64b63b559cbcf1aa990a70d | 4,821 | /*
* $Id: PWPdfFile.java 2014/02/09 8:36:29 masamitsu $
*
* ===============================================================================
*
* Copyright (C) 2013 Masamitsu Oikawa <[email protected]>
*
* 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 pw.core.pdf;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import pw.core.PWError;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;
/**
* @author masamitsu
*
*/
public class PWPdfFile {
// Page Size
public enum Size {
POSTCARD,
A4,
}
private static Rectangle[] rectangles = { PageSize.POSTCARD, PageSize.A4, PageSize.A4};
// Font
public enum Font {
KOZMINPRO_REGULAR,
HEISEI_MIN_W3,
HEISEI_KAKUGO_W5,
}
private static final String[] FONT_NAMES = { "KozMinPro-Regular", "HeiseiMin-W3", "HeiseiKakuGo-W5", "HeiseiKakuGo-W5" };
// Encoding
public enum Encoding {
UNIJIS_UCS2_H,
UNIJIS_UCS2_V,
UNIJIS_UCS2_HW_H,
UNIJIS_UCS2_HW_V,
}
private static final String[] ENCODING_NAMES = { "UniJIS-UCS2-H", "UniJIS-UCS2-V", "UniJIS-UCS2-HW-H", "UniJIS-UCS2-HW-V", "UniJIS-UCS2-H" };
private Document document;
private PdfWriter writer;
public static PWPdfFile create(File file, Size size) {
return create(file, size, 0.0f, 0.0f, 0.0f, 0.0f);
}
public static PWPdfFile create(File file, Size size, float marginTop, float marginLeft, float marginBottom, float marginRight) {
return new PWPdfFile(file, size, marginTop, marginLeft, marginBottom, marginRight);
}
protected PWPdfFile(File file, Size size, float marginTop, float marginLeft, float marginBottom, float marginRight) {
Rectangle rect = size.ordinal() < rectangles.length ? rectangles[size.ordinal()] : rectangles[rectangles.length - 1];
document = new Document(rect, marginLeft, marginRight, marginTop, marginBottom);
try {
writer = PdfWriter.getInstance(document, new FileOutputStream(file));
} catch (FileNotFoundException e) {
throw new PWError(e, "Failed to create PDF Writer");
} catch (DocumentException e) {
throw new PWError(e, "Failed to create PDF Writer");
}
}
public void open() {
document.open();
}
public void open(String athor, String subject) {
document.addAuthor(athor);
document.addSubject(subject);
document.open();
}
public void close() {
document.close();
}
protected BaseFont getFont(Font font, Encoding encoding, boolean isEmbedded) {
String fontName = font.ordinal() < FONT_NAMES.length ? FONT_NAMES[font.ordinal()] : FONT_NAMES[FONT_NAMES.length - 1];
String encodingName = encoding.ordinal() < ENCODING_NAMES.length ? ENCODING_NAMES[encoding.ordinal()] : ENCODING_NAMES[ENCODING_NAMES.length - 1];
try {
return BaseFont.createFont(fontName, encodingName, isEmbedded ? BaseFont.EMBEDDED : BaseFont.NOT_EMBEDDED);
} catch (DocumentException e) {
throw new PWError(e, "Failed to get font.");
} catch (IOException e) {
throw new PWError(e, "Failed to get font.");
}
}
public void addField(PWPdfField field) {
PdfContentByte contentByte = writer.getDirectContent();
contentByte.beginText();
BaseFont baseFont = getFont(field.font, field.encoding, field.isEmbedded);
contentByte.setFontAndSize(baseFont, field.fontSize);
contentByte.setTextMatrix(field.x, field.y);
contentByte.showText(field.text);
contentByte.endText();
}
public void insertNewPage() {
document.newPage();
}
}
| 34.934783 | 148 | 0.707737 |
5239c257588fefc6212a353059018953e6788f6f | 30,220 | package cwms.radar.data.dao;
import java.io.StringReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.persistence.criteria.JoinType;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import cwms.radar.api.NotFoundException;
import cwms.radar.data.dto.Catalog;
import cwms.radar.data.dto.CwmsDTOPaginated;
import cwms.radar.data.dto.RecentValue;
import cwms.radar.data.dto.TimeSeries;
import cwms.radar.data.dto.TimeSeriesExtents;
import cwms.radar.data.dto.Tsv;
import cwms.radar.data.dto.TsvDqu;
import cwms.radar.data.dto.TsvDquId;
import cwms.radar.data.dto.TsvId;
import cwms.radar.data.dto.VerticalDatumInfo;
import cwms.radar.data.dto.catalog.CatalogEntry;
import cwms.radar.data.dto.catalog.TimeseriesCatalogEntry;
import org.jetbrains.annotations.NotNull;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Record1;
import org.jooq.Record3;
import org.jooq.Record8;
import org.jooq.Result;
import org.jooq.SQL;
import org.jooq.SelectConditionStep;
import org.jooq.SelectHavingStep;
import org.jooq.SelectQuery;
import org.jooq.SelectSelectStep;
import org.jooq.Table;
import org.jooq.conf.ParamType;
import org.jooq.impl.DSL;
import org.jooq.impl.*;
import usace.cwms.db.dao.ifc.ts.CwmsDbTs;
import usace.cwms.db.dao.util.services.CwmsDbServiceLookup;
import usace.cwms.db.jooq.codegen.packages.CWMS_LOC_PACKAGE;
import usace.cwms.db.jooq.codegen.packages.CWMS_ROUNDING_PACKAGE;
import usace.cwms.db.jooq.codegen.packages.CWMS_TS_PACKAGE;
import usace.cwms.db.jooq.codegen.packages.CWMS_UTIL_PACKAGE;
import usace.cwms.db.jooq.codegen.tables.AV_CWMS_TS_ID2;
import usace.cwms.db.jooq.codegen.tables.AV_LOC;
import usace.cwms.db.jooq.codegen.tables.AV_LOC2;
import usace.cwms.db.jooq.codegen.tables.AV_TSV;
import usace.cwms.db.jooq.codegen.tables.AV_TSV_DQU;
import usace.cwms.db.jooq.codegen.tables.AV_TS_GRP_ASSGN;
import static org.jooq.impl.DSL.asterisk;
import static org.jooq.impl.DSL.count;
import static org.jooq.impl.DSL.field;
import static org.jooq.impl.DSL.max;
import static org.jooq.impl.DSL.partitionBy;
import static org.jooq.impl.DSL.condition;
import static usace.cwms.db.jooq.codegen.tables.AV_CWMS_TS_ID2.AV_CWMS_TS_ID2;
import static usace.cwms.db.jooq.codegen.tables.AV_TS_EXTENTS_UTC.AV_TS_EXTENTS_UTC;
public class TimeSeriesDaoImpl extends JooqDao<TimeSeries> implements TimeSeriesDao
{
private static final Logger logger = Logger.getLogger(TimeSeriesDaoImpl.class.getName());
public static final boolean OVERRIDE_PROTECTION = true;
public TimeSeriesDaoImpl(DSLContext dsl)
{
super(dsl);
}
public String getTimeseries(String format, String names, String office, String units, String datum, String begin,
String end, String timezone) {
return CWMS_TS_PACKAGE.call_RETRIEVE_TIME_SERIES_F(dsl.configuration(),
names, format, units, datum, begin, end, timezone, office);
}
public TimeSeries getTimeseries(String page, int pageSize, String names, String office, String units, String datum, String begin, String end, String timezone) {
// Looks like the datum field is currently being ignored by this method.
// Should we warn if the datum is not null?
ZoneId zone;
if(timezone == null)
{
zone = ZoneOffset.UTC.normalized();
}
else
{
zone = ZoneId.of(timezone);
}
ZonedDateTime beginTime = getZonedDateTime(begin, zone, ZonedDateTime.now().minusDays(1));
ZonedDateTime endTime = getZonedDateTime(end, beginTime.getZone(), ZonedDateTime.now());
return getTimeseries(page, pageSize, names, office, units, beginTime, endTime);
}
public ZonedDateTime getZonedDateTime(String begin, ZoneId fallbackZone, ZonedDateTime beginFallback)
{
// May need to revisit the date time formats.
// ISO_DATE_TIME format is like: 2021-10-05T15:26:23.658-07:00[America/Los_Angeles]
// Swagger doc claims we expect: 2021-06-10T13:00:00-0700[PST8PDT]
// The getTimeSeries that calls a stored procedure and returns a string may be what expects
// the format given as an example in the swagger doc.
if(begin == null)
{
begin = beginFallback.toLocalDateTime().toString();
}
// Parse the date time in the best format it can find. Timezone is optional, but use it if it's found.
TemporalAccessor beginParsed = DateTimeFormatter.ISO_DATE_TIME.parseBest(begin, ZonedDateTime::from,
LocalDateTime::from);
if(beginParsed instanceof ZonedDateTime)
{
return ZonedDateTime.from(beginParsed);
}
return LocalDateTime.from(beginParsed).atZone(fallbackZone);
}
protected TimeSeries getTimeseries(String page, int pageSize, String names, String office, String units,
ZonedDateTime beginTime, ZonedDateTime endTime)
{
TimeSeries retval = null;
String cursor = null;
Timestamp tsCursor = null;
Integer total = null;
if(page != null && !page.isEmpty())
{
String[] parts = CwmsDTOPaginated.decodeCursor(page);
logger.fine("Decoded cursor");
for( String p: parts){
logger.finest(p);
}
if(parts.length > 1)
{
cursor = parts[0];
tsCursor = Timestamp.from(Instant.ofEpochMilli(Long.parseLong(parts[0])));
if(parts.length > 2)
total = Integer.parseInt(parts[1]);
// Use the pageSize from the original cursor, for consistent paging
pageSize = Integer.parseInt(parts[parts.length - 1]); // Last item is pageSize
}
}
final String recordCursor = cursor;
final int recordPageSize = pageSize;
try
{
Field<String> officeId = CWMS_UTIL_PACKAGE.call_GET_DB_OFFICE_ID(office != null ? DSL.val(office) : CWMS_UTIL_PACKAGE.call_USER_OFFICE_ID());
Field<String> tsId = CWMS_TS_PACKAGE.call_GET_TS_ID__2(DSL.val(names), officeId);
Field<BigDecimal> tsCode = CWMS_TS_PACKAGE.call_GET_TS_CODE__2(tsId, officeId);
Field<String> unit = units.compareToIgnoreCase("SI") == 0 || units.compareToIgnoreCase(
"EN") == 0 ? CWMS_UTIL_PACKAGE.call_GET_DEFAULT_UNITS(CWMS_TS_PACKAGE.call_GET_BASE_PARAMETER_ID(tsCode), DSL.val(units, String.class)) : DSL.val(units,
String.class);
// This code assumes the database timezone is in UTC (per Oracle recommendation)
// Wrap in table() so JOOQ can parse the result
@SuppressWarnings("deprecated") SQL retrieveTable = DSL.sql(
"table(" + CWMS_TS_PACKAGE.call_RETRIEVE_TS_OUT_TAB(tsId, unit, CWMS_UTIL_PACKAGE.call_TO_TIMESTAMP__2(DSL.val(beginTime.toInstant().toEpochMilli())),
CWMS_UTIL_PACKAGE.call_TO_TIMESTAMP__2(DSL.val(endTime.toInstant().toEpochMilli())),
DSL.inline("UTC", String.class),
// All times are sent as UTC to the database, regardless of requested timezone.
null, null, null, null, null, null, null, officeId) + ")");
Field<String> loc = CWMS_UTIL_PACKAGE.call_SPLIT_TEXT(tsId,
DSL.val(BigInteger.valueOf(1L)), DSL.val("."),
DSL.val(BigInteger.valueOf(6L)));
Field<String> param = DSL.upper(CWMS_UTIL_PACKAGE.call_SPLIT_TEXT(tsId,
DSL.val(BigInteger.valueOf(2L)), DSL.val("."),
DSL.val(BigInteger.valueOf(6L))));
SelectSelectStep<Record8<String, String, String, BigDecimal, String, String, String, Integer>> metadataQuery = dsl.select(
tsId.as("NAME"),
officeId.as("OFFICE_ID"),
unit.as("UNITS"),
CWMS_TS_PACKAGE.call_GET_INTERVAL(tsId).as("INTERVAL"),
loc.as("LOC_PART"),
param.as("PARM_PART"),
DSL.choose(param)
.when("ELEV", CWMS_LOC_PACKAGE.call_GET_VERTICAL_DATUM_INFO_F__2(loc, unit, officeId))
.otherwise("")
.as("VERTICAL_DATUM"),
// If we don't know the total, fetch it from the database (only for first fetch).
// Total is only an estimate, as it can change if fetching current data, or the timeseries otherwise changes between queries.
total != null ? DSL.val(total).as("TOTAL") : DSL.selectCount().from(retrieveTable).asField("TOTAL"));
logger.finest(() -> metadataQuery.getSQL(ParamType.INLINED));
TimeSeries timeseries = metadataQuery.fetchOne(tsMetadata -> {
String vert = (String)tsMetadata.getValue("VERTICAL_DATUM");
VerticalDatumInfo verticalDatumInfo= parseVerticalDatumInfo(vert);
return new TimeSeries(recordCursor, recordPageSize, tsMetadata.getValue("TOTAL", Integer.class),
tsMetadata.getValue("NAME", String.class), tsMetadata.getValue("OFFICE_ID", String.class),
beginTime, endTime, tsMetadata.getValue("UNITS", String.class),
Duration.ofMinutes(tsMetadata.get("INTERVAL") == null ? 0 : tsMetadata.getValue("INTERVAL", Long.class)),
verticalDatumInfo
);
});
if(pageSize != 0)
{
SelectConditionStep<Record3<Timestamp, Double, BigDecimal>> query = dsl.select(
DSL.field("DATE_TIME", Timestamp.class).as("DATE_TIME"),
CWMS_ROUNDING_PACKAGE.call_ROUND_DD_F(DSL.field("VALUE", Double.class), DSL.inline("5567899996"), DSL.inline('T')).as("VALUE"),
CWMS_TS_PACKAGE.call_NORMALIZE_QUALITY(DSL.nvl(DSL.field("QUALITY_CODE", Integer.class), DSL.inline(5))).as("QUALITY_CODE")
)
.from(retrieveTable)
.where(DSL.field("DATE_TIME", Timestamp.class)
.greaterOrEqual(CWMS_UTIL_PACKAGE.call_TO_TIMESTAMP__2(
DSL.nvl(DSL.val(tsCursor == null ? null : tsCursor.toInstant().toEpochMilli()),
DSL.val(beginTime.toInstant().toEpochMilli())))))
.and(DSL.field("DATE_TIME", Timestamp.class)
.lessOrEqual(CWMS_UTIL_PACKAGE.call_TO_TIMESTAMP__2(DSL.val(endTime.toInstant().toEpochMilli())))
);
if(pageSize > 0)
query.limit(DSL.val(pageSize + 1));
logger.finest(() -> query.getSQL(ParamType.INLINED));
query.fetchInto(tsRecord -> timeseries.addValue(
tsRecord.getValue("DATE_TIME", Timestamp.class),
tsRecord.getValue("VALUE", Double.class),
tsRecord.getValue("QUALITY_CODE", Integer.class)
)
);
retval = timeseries;
}
} catch(org.jooq.exception.DataAccessException e){
if(isNotFound(e.getCause())){
throw new NotFoundException(e.getCause());
}
throw e;
}
return retval;
}
// datumInfo comes back like:
// <vertical-datum-info office="LRL" unit="m">
// <location>Buckhorn</location>
// <native-datum>NGVD-29</native-datum>
// <elevation>230.7</elevation>
// <offset estimate="true">
// <to-datum>NAVD-88</to-datum>
// <value>-.1666</value>
// </offset>
// </vertical-datum-info>
public static VerticalDatumInfo parseVerticalDatumInfo(String body)
{
VerticalDatumInfo retval = null;
if(body != null && !body.isEmpty())
{
try
{
JAXBContext jaxbContext = JAXBContext.newInstance(VerticalDatumInfo.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
retval = (VerticalDatumInfo) unmarshaller.unmarshal(new StringReader(body));
}
catch(JAXBException e)
{
logger.log(Level.WARNING, "Failed to parse:" + body, e);
}
}
return retval;
}
private boolean isNotFound(Throwable cause)
{
boolean retval = false;
if(cause instanceof SQLException){
SQLException sqlException = (SQLException) cause;
// When we type in a garbage tsId the cause is a SQLException. Its cause is an OracleDatabaseException.
// Note: The message I saw looked like this:
//ORA-20001: TS_ID_NOT_FOUND: The timeseries identifier "%1" was not found for office "%2"
//ORA-06512: at "CWMS_20.CWMS_ERR", line 59
//ORA-06512: at "CWMS_20.CWMS_TS", line 48
//ORA-01403: no data found
//ORA-06512: at "CWMS_20.CWMS_TS", line 41
//ORA-06512: at "CWMS_20.CWMS_TS", line 26
int errorCode = sqlException.getErrorCode();
// 20001 happens when the ts id doesn't exist
// 20025 happens when the location doesn't exist
retval = (20001 == errorCode || 20025 == errorCode);
}
return retval;
}
@Override
public Catalog getTimeSeriesCatalog(String page, int pageSize, Optional<String> office){
return getTimeSeriesCatalog(page, pageSize, office, ".*", null, null, null, null);
}
@Override
public Catalog getTimeSeriesCatalog(String page, int pageSize, Optional<String> office,
String idLike, String locCategoryLike, String locGroupLike,
String tsCategoryLike, String tsGroupLike){
int total = 0;
String tsCursor = "*";
if( page == null || page.isEmpty() ){
Condition condition = AV_CWMS_TS_ID2.CWMS_TS_ID.likeRegex(idLike)
.and(AV_CWMS_TS_ID2.ALIASED_ITEM.isNull());
if( office.isPresent() ){
condition = condition.and(AV_CWMS_TS_ID2.DB_OFFICE_ID.eq(office.get()));
}
if(locCategoryLike != null){
condition.and(AV_CWMS_TS_ID2.LOC_ALIAS_CATEGORY.likeRegex(locCategoryLike));
}
if(locGroupLike != null){
condition.and(AV_CWMS_TS_ID2.LOC_ALIAS_GROUP.likeRegex(locGroupLike));
}
if(tsCategoryLike != null){
condition.and(AV_CWMS_TS_ID2.TS_ALIAS_CATEGORY.likeRegex(tsCategoryLike));
}
if(tsGroupLike != null){
condition.and(AV_CWMS_TS_ID2.TS_ALIAS_GROUP.likeRegex(tsGroupLike));
}
SelectConditionStep<Record1<Integer>> count = dsl.select(count(asterisk()))
.from(AV_CWMS_TS_ID2)
.where(condition);
total = count.fetchOne().value1();
} else {
logger.fine("getting non-default page");
// get totally from page
String[] parts = CwmsDTOPaginated.decodeCursor(page, "|||");
logger.fine("decoded cursor: " + String.join("|||", parts));
for( String p: parts){
logger.finest(p);
}
if(parts.length > 1) {
tsCursor = parts[0].split("/")[1];
total = Integer.parseInt(parts[1]);
}
}
SelectQuery<?> primaryDataQuery = dsl.selectQuery();
primaryDataQuery.addSelect(AV_CWMS_TS_ID2.DB_OFFICE_ID);
primaryDataQuery.addSelect(AV_CWMS_TS_ID2.CWMS_TS_ID);
primaryDataQuery.addSelect(AV_CWMS_TS_ID2.TS_CODE);
primaryDataQuery.addSelect(AV_CWMS_TS_ID2.UNIT_ID);
primaryDataQuery.addSelect(AV_CWMS_TS_ID2.INTERVAL_ID);
primaryDataQuery.addSelect(AV_CWMS_TS_ID2.INTERVAL_UTC_OFFSET);
if( this.getDbVersion() >= Dao.CWMS_21_1_1) {
primaryDataQuery.addSelect(AV_CWMS_TS_ID2.TIME_ZONE_ID);
}
primaryDataQuery.addFrom(AV_CWMS_TS_ID2);
primaryDataQuery.addConditions(AV_CWMS_TS_ID2.ALIASED_ITEM.isNull());
// add the regexp_like clause.
primaryDataQuery.addConditions(AV_CWMS_TS_ID2.CWMS_TS_ID.likeRegex(idLike));
if( office.isPresent() ){
primaryDataQuery.addConditions(AV_CWMS_TS_ID2.DB_OFFICE_ID.upper().eq(office.get().toUpperCase()));
}
if(locCategoryLike != null){
primaryDataQuery.addConditions(AV_CWMS_TS_ID2.LOC_ALIAS_CATEGORY.likeRegex(locCategoryLike));
}
if(locGroupLike != null){
primaryDataQuery.addConditions(AV_CWMS_TS_ID2.LOC_ALIAS_GROUP.likeRegex(locGroupLike));
}
if(tsCategoryLike != null){
primaryDataQuery.addConditions(AV_CWMS_TS_ID2.TS_ALIAS_CATEGORY.likeRegex(tsCategoryLike));
}
if(tsGroupLike != null){
primaryDataQuery.addConditions(AV_CWMS_TS_ID2.TS_ALIAS_GROUP.likeRegex(tsGroupLike));
}
primaryDataQuery.addConditions(AV_CWMS_TS_ID2.CWMS_TS_ID.upper().gt(tsCursor));
primaryDataQuery.addOrderBy(AV_CWMS_TS_ID2.CWMS_TS_ID);
Table<?> dataTable = primaryDataQuery.asTable("data");
//query.addConditions(field("rownum").lessOrEqual(pageSize));
//query.addConditions(condition("rownum < 500"));
SelectQuery<?> limitQuery = dsl.selectQuery();
//limitQuery.addSelect(field("rownum"));
limitQuery.addSelect(dataTable.fields());
limitQuery.addFrom(dataTable);//.limit(pageSize);
limitQuery.addConditions(field("rownum").lessOrEqual(pageSize));
Table<?> limitTable = limitQuery.asTable("limiter");
SelectQuery<?> overallQuery = dsl.selectQuery();
overallQuery.addSelect(limitTable.fields());
overallQuery.addSelect(AV_TS_EXTENTS_UTC.VERSION_TIME);
overallQuery.addSelect(AV_TS_EXTENTS_UTC.EARLIEST_TIME);
overallQuery.addSelect(AV_TS_EXTENTS_UTC.LATEST_TIME);
overallQuery.addFrom(limitTable);
overallQuery.addJoin(AV_TS_EXTENTS_UTC,org.jooq.JoinType.LEFT_OUTER_JOIN,
condition("\"CWMS_20\".\"AV_TS_EXTENTS_UTC\".\"TS_CODE\" = " + field("\"limiter\".\"TS_CODE\"")));
logger.info( () -> overallQuery.getSQL(ParamType.INLINED));
Result<?> result = overallQuery.fetch();
HashMap<String, TimeseriesCatalogEntry.Builder> tsIdExtentMap= new HashMap<>();
result.forEach( row -> {
String tsId = row.get(AV_CWMS_TS_ID2.CWMS_TS_ID);
if( !tsIdExtentMap.containsKey(tsId) ) {
TimeseriesCatalogEntry.Builder builder = new TimeseriesCatalogEntry.Builder()
.officeId(row.get(AV_CWMS_TS_ID2.DB_OFFICE_ID))
.cwmsTsId(row.get(AV_CWMS_TS_ID2.CWMS_TS_ID))
.units(row.get(AV_CWMS_TS_ID2.UNIT_ID) )
.interval(row.get(AV_CWMS_TS_ID2.INTERVAL_ID))
.intervalOffset(row.get(AV_CWMS_TS_ID2.INTERVAL_UTC_OFFSET));
if( this.getDbVersion() > TimeSeriesDaoImpl.CWMS_21_1_1){
builder.timeZone(row.get("TIME_ZONE_ID",String.class));
}
tsIdExtentMap.put(tsId, builder);
}
if( row.get(AV_TS_EXTENTS_UTC.EARLIEST_TIME) != null ){
//tsIdExtentMap.get(tsId)
TimeSeriesExtents extents = new TimeSeriesExtents(row.get(AV_TS_EXTENTS_UTC.VERSION_TIME),
row.get(AV_TS_EXTENTS_UTC.EARLIEST_TIME),
row.get(AV_TS_EXTENTS_UTC.LATEST_TIME)
);
tsIdExtentMap.get(tsId).withExtent(extents);
}
});
List<? extends CatalogEntry> entries = tsIdExtentMap.entrySet().stream()
.sorted( (left,right) -> left.getKey().compareTo(right.getKey()) )
.map( e -> {
return e.getValue().build();
}
)
.collect(Collectors.toList());
return new Catalog(tsCursor, total, pageSize, entries);
}
// Finds the single most recent TsvDqu within the time window.
public TsvDqu findMostRecent(String tOfficeId, String tsId, String unit, Timestamp twoWeeksFromNow, Timestamp twoWeeksAgo)
{
TsvDqu retval = null;
AV_TSV_DQU view = AV_TSV_DQU.AV_TSV_DQU;
Condition nestedCondition = view.ALIASED_ITEM.isNull()
.and(view.VALUE.isNotNull())
.and(view.CWMS_TS_ID.eq(tsId))
.and(view.OFFICE_ID.eq(tOfficeId));
if(twoWeeksFromNow != null){
nestedCondition = nestedCondition.and(view.DATE_TIME.lt(twoWeeksFromNow));
}
// Is this really optional?
if(twoWeeksAgo != null){
nestedCondition = nestedCondition.and(view.DATE_TIME.gt(twoWeeksAgo));
}
String maxFieldName = "MAX_DATE_TIME";
SelectHavingStep<Record1<Timestamp>> select = dsl.select(max(view.DATE_TIME).as(maxFieldName)).from(
view).where(nestedCondition).groupBy(view.TS_CODE);
Record dquRecord = dsl.select(asterisk()).from(view).where(view.DATE_TIME.in(select)).and(
view.CWMS_TS_ID.eq(tsId)).and(view.OFFICE_ID.eq(tOfficeId)).and(view.UNIT_ID.eq(unit)).and(
view.VALUE.isNotNull()).and(view.ALIASED_ITEM.isNull()).fetchOne();
if(dquRecord != null)
{
retval = dquRecord.map(r -> {
usace.cwms.db.jooq.codegen.tables.records.AV_TSV_DQU dqu = r.into(view);
TsvDqu tsv = null;
if(r != null)
{
TsvDquId id = new TsvDquId(dqu.getOFFICE_ID(), dqu.getTS_CODE(), dqu.getUNIT_ID(), dqu.getDATE_TIME());
tsv = new TsvDqu(id, dqu.getCWMS_TS_ID(), dqu.getVERSION_DATE(), dqu.getDATA_ENTRY_DATE(), dqu.getVALUE(), dqu.getQUALITY_CODE(), dqu.getSTART_DATE(), dqu.getEND_DATE());
}
return tsv;
});
}
return retval;
}
// This is similar to the code used for sparklines...
// Finds all the Tsv data points in the time range for all the specified tsIds.
public List<Tsv> findInDateRange(Collection<String> tsIds, Date startDate, Date endDate) {
List<Tsv> retval = Collections.emptyList();
if (tsIds != null && !tsIds.isEmpty()) {
Timestamp start = new Timestamp(startDate.getTime());
Timestamp end = new Timestamp(endDate.getTime());
AV_TSV tsvView = AV_TSV.AV_TSV;
usace.cwms.db.jooq.codegen.tables.AV_CWMS_TS_ID2 tsView = AV_CWMS_TS_ID2;
retval = dsl.select(tsvView.asterisk(), tsView.CWMS_TS_ID)
.from(tsvView.join(tsView).on(tsvView.TS_CODE.eq(tsView.TS_CODE.cast(Long.class))))
.where(
tsView.CWMS_TS_ID.in(tsIds).and(tsvView.DATE_TIME.ge(start)).and(tsvView.DATE_TIME.lt(end)).and(
tsvView.START_DATE.le(end)).and(tsvView.END_DATE.gt(start))).orderBy(tsvView.DATE_TIME).fetch(
jrecord -> buildTsvFromViewRow(jrecord.into(tsvView)));
}
return retval;
}
@NotNull
private Tsv buildTsvFromViewRow(usace.cwms.db.jooq.codegen.tables.records.AV_TSV into)
{
TsvId id = new TsvId(into.getTS_CODE(), into.getDATE_TIME(), into.getVERSION_DATE(), into.getDATA_ENTRY_DATE());
return new Tsv(id, into.getVALUE(), into.getQUALITY_CODE(), into.getSTART_DATE(), into.getEND_DATE());
}
// Finds single most recent value within the window for each of the tsCodes
public List<RecentValue> findMostRecentsInRange(List<String> tsIds, Timestamp pastdate, Timestamp futuredate) {
final List<RecentValue> retval = new ArrayList<>();
if (tsIds != null && !tsIds.isEmpty()) {
AV_TSV_DQU tsvView = AV_TSV_DQU.AV_TSV_DQU;
AV_CWMS_TS_ID2 tsView = AV_CWMS_TS_ID2;
SelectConditionStep<Record> innerSelect
= dsl.select(
tsvView.asterisk(),
max(tsvView.DATE_TIME).over(partitionBy(tsvView.TS_CODE)).as("max_date_time"),
tsView.CWMS_TS_ID)
.from(tsvView.join(tsView).on(tsvView.TS_CODE.eq(tsView.TS_CODE.cast(Long.class))))
.where(
tsView.CWMS_TS_ID.in(tsIds)
.and(tsvView.VALUE.isNotNull())
.and(tsvView.DATE_TIME.lt(futuredate))
.and(tsvView.DATE_TIME.gt(pastdate))
.and(tsvView.START_DATE.le(futuredate))
.and(tsvView.END_DATE.gt(pastdate)));
Field[] queryFields = new Field[]{
tsView.CWMS_TS_ID,
tsvView.OFFICE_ID,
tsvView.TS_CODE,
tsvView.UNIT_ID,
tsvView.DATE_TIME,
tsvView.VERSION_DATE,
tsvView.DATA_ENTRY_DATE,
tsvView.VALUE,
tsvView.QUALITY_CODE,
tsvView.START_DATE,
tsvView.END_DATE,
};
// look them back up by name b/c we are using them on results of innerselect.
List<Field<Object>> fields = Arrays.stream(queryFields)
.map(Field::getName)
.map(DSL::field).collect(
Collectors.toList());
// I want to select tsvView.asterisk but we are selecting from an inner select and
// even though the inner select selects tsvView.asterisk it isn't the same.
// So we will just select the fields we want. Unfortunately that means our results
// won't map into AV_TSV.AV_TSV
dsl.select(fields)
.from(innerSelect)
.where(field("DATE_TIME").eq(innerSelect.field("max_date_time")))
.forEach( jrecord -> {
RecentValue recentValue = buildRecentValue(tsvView, tsView, jrecord);
retval.add(recentValue);
});
}
return retval;
}
@NotNull
private RecentValue buildRecentValue(AV_TSV_DQU tsvView, usace.cwms.db.jooq.codegen.tables.AV_CWMS_TS_ID2 tsView,
Record jrecord)
{
return buildRecentValue(tsvView, jrecord, tsView.CWMS_TS_ID.getName());
}
@NotNull
private RecentValue buildRecentValue(AV_TSV_DQU tsvView, AV_TS_GRP_ASSGN tsView, Record jrecord)
{
return buildRecentValue(tsvView, jrecord, tsView.TS_ID.getName());
}
@NotNull
private RecentValue buildRecentValue(AV_TSV_DQU tsvView, Record jrecord, String tsColumnName)
{
Timestamp dataEntryDate;
// TODO:
// !!! skipping DATA_ENTRY_DATE for now. Need to figure out how to fix mapping in jooq.
// !! dataEntryDate= jrecord.getValue("data_entry_date", Timestamp.class); // maps to oracle.sql.TIMESTAMP
// !!!
dataEntryDate = null;
// !!!
TsvDqu tsv = buildTsvDqu(tsvView, jrecord, dataEntryDate);
String tsId = jrecord.getValue(tsColumnName, String.class);
return new RecentValue(tsId, tsv);
}
@NotNull
private TsvDqu buildTsvDqu(AV_TSV_DQU tsvView, Record jrecord, Timestamp dataEntryDate)
{
TsvDquId id = buildDquId(tsvView, jrecord);
return new TsvDqu(id, jrecord.getValue(tsvView.CWMS_TS_ID.getName(), String.class),
jrecord.getValue(tsvView.VERSION_DATE.getName(), Timestamp.class), dataEntryDate,
jrecord.getValue(tsvView.VALUE.getName(), Double.class),
jrecord.getValue(tsvView.QUALITY_CODE.getName(), Long.class),
jrecord.getValue(tsvView.START_DATE.getName(), Timestamp.class),
jrecord.getValue(tsvView.END_DATE.getName(), Timestamp.class));
}
public List<RecentValue> findRecentsInRange(String office, String categoryId, String groupId, Timestamp pastLimit, Timestamp futureLimit)
{
List<RecentValue> retval = new ArrayList<>();
if (categoryId != null && groupId != null) {
AV_TSV_DQU tsvView = AV_TSV_DQU.AV_TSV_DQU; // should we look at the daterange and possible use 30D view?
AV_TS_GRP_ASSGN tsView = AV_TS_GRP_ASSGN.AV_TS_GRP_ASSGN;
SelectConditionStep<Record> innerSelect
= dsl.select(tsvView.asterisk(), tsView.TS_ID, tsView.ATTRIBUTE,
max(tsvView.DATE_TIME).over(partitionBy(tsvView.TS_CODE)).as("max_date_time"), tsView.TS_ID)
.from(tsvView.join(tsView).on(tsvView.TS_CODE.eq(tsView.TS_CODE.cast(Long.class))))
.where(
tsView.DB_OFFICE_ID.eq(office)
.and(tsView.CATEGORY_ID.eq(categoryId))
.and(tsView.GROUP_ID.eq(groupId))
.and(tsvView.VALUE.isNotNull())
.and(tsvView.DATE_TIME.lt(futureLimit))
.and(tsvView.DATE_TIME.gt(pastLimit))
.and(tsvView.START_DATE.le(futureLimit))
.and(tsvView.END_DATE.gt(pastLimit)));
Field[] queryFields = new Field[]{
tsvView.OFFICE_ID,
tsvView.TS_CODE,
tsvView.DATE_TIME,
tsvView.VERSION_DATE,
tsvView.DATA_ENTRY_DATE,
tsvView.VALUE,
tsvView.QUALITY_CODE,
tsvView.START_DATE,
tsvView.END_DATE,
tsvView.UNIT_ID,
tsView.TS_ID, tsView.ATTRIBUTE};
List<Field<Object>> fields = Arrays.stream(queryFields)
.map(Field::getName)
.map(DSL::field).collect(
Collectors.toList());
// I want to select tsvView.asterisk but we are selecting from an inner select and
// even though the inner select selects tsvView.asterisk it isn't the same.
// So we will just select the fields we want.
// Unfortunately that means our results won't map into AV_TSV.AV_TSV
dsl.select(fields)
.from(innerSelect)
.where(field(tsvView.DATE_TIME.getName()).eq(innerSelect.field("max_date_time")))
.orderBy(field(tsView.ATTRIBUTE.getName()))
.forEach( jrecord -> {
RecentValue recentValue = buildRecentValue(tsvView, tsView, jrecord);
retval.add(recentValue);
});
}
return retval;
}
@NotNull
private TsvDquId buildDquId(AV_TSV_DQU tsvView, Record jrecord)
{
return new TsvDquId(jrecord.getValue(tsvView.OFFICE_ID.getName(), String.class),
jrecord.getValue(tsvView.TS_CODE.getName(), Long.class),
jrecord.getValue(tsvView.UNIT_ID.getName(), String.class),
jrecord.getValue(tsvView.DATE_TIME.getName(), Timestamp.class));
}
public void create(TimeSeries input)
{
dsl.connection(connection -> {
CwmsDbTs tsDao = CwmsDbServiceLookup.buildCwmsDb(CwmsDbTs.class, connection);
int utcOffsetMinutes = 0;
int intervalForward = 0;
int intervalBackward = 0;
boolean versionedFlag = false;
boolean activeFlag = true;
BigInteger tsCode = tsDao.createTsCodeBigInteger(connection, input.getOfficeId(), input.getName(),
utcOffsetMinutes, intervalForward, intervalBackward, versionedFlag, activeFlag);
});
}
public void store(TimeSeries input, Timestamp versionDate)
{
dsl.connection(connection ->
store(connection, input.getOfficeId(), input.getName(), input.getUnits(), versionDate, input.getValues())
);
}
public void update(TimeSeries input) throws SQLException
{
String name = input.getName();
if(!timeseriesExists(name)){
throw new SQLException("Cannot update a non-existant Timeseries. Create " + name + " first.");
}
dsl.connection(connection -> {
store(connection, input.getOfficeId(), name, input.getUnits(), NON_VERSIONED, input.getValues());
});
}
public void store(Connection connection, String officeId, String tsId, String units, Timestamp versionDate,
List<TimeSeries.Record> values) throws SQLException
{
CwmsDbTs tsDao = CwmsDbServiceLookup.buildCwmsDb(CwmsDbTs.class, connection);
final int count = values == null ? 0 : values.size();
final long[] timeArray = new long[count];
final double[] valueArray = new double[count];
final int[] qualityArray = new int[count];
if(values != null && !values.isEmpty())
{
Iterator<TimeSeries.Record> iter = values.iterator();
for(int i = 0; iter.hasNext(); i++)
{
TimeSeries.Record value = iter.next();
timeArray[i] = value.getDateTime().getTime();
valueArray[i] = value.getValue();
qualityArray[i] = value.getQualityCode();
}
}
final boolean createAsLrts = false;
StoreRule storeRule = StoreRule.DELETE_INSERT;
long completedAt = tsDao.store(connection, officeId, tsId, units, timeArray, valueArray, qualityArray, count,
storeRule.getRule(), OVERRIDE_PROTECTION, versionDate, createAsLrts);
}
public void delete(String officeId, String tsId)
{
dsl.connection(connection -> {
CwmsDbTs tsDao = CwmsDbServiceLookup.buildCwmsDb(CwmsDbTs.class, connection);
tsDao.deleteAll(connection, officeId, tsId);
});
}
protected BigDecimal retrieveTsCode(String tsId)
{
return dsl.select(AV_CWMS_TS_ID2.AV_CWMS_TS_ID2.TS_CODE).from(
AV_CWMS_TS_ID2.AV_CWMS_TS_ID2).where(AV_CWMS_TS_ID2.AV_CWMS_TS_ID2.CWMS_TS_ID.eq(tsId))
.fetchOptional(AV_CWMS_TS_ID2.AV_CWMS_TS_ID2.TS_CODE).orElse(null);
}
public boolean timeseriesExists(String tsId)
{
return retrieveTsCode(tsId) != null;
}
}
| 37.170972 | 175 | 0.724818 |
b183f63101e9c3067b8abea02dfb9f7bd71cc705 | 318 | package com.rbkmoney.fistful.reporter.handler.source;
import com.rbkmoney.fistful.reporter.handler.EventHandler;
import com.rbkmoney.fistful.source.TimestampedChange;
import com.rbkmoney.machinegun.eventsink.MachineEvent;
public interface SourceEventHandler extends EventHandler<TimestampedChange, MachineEvent> {
}
| 35.333333 | 91 | 0.858491 |
0f787e0f57083504153a2c3e3984ef40e567c638 | 4,012 | /*****************************************************************
* 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.cayenne.map;
import java.util.Collection;
import java.util.Collections;
import junit.framework.TestCase;
import org.apache.art.Artist;
import org.apache.cayenne.CayenneRuntimeException;
import org.apache.cayenne.remote.hessian.service.HessianUtil;
public class ClientEntityResolverTest extends TestCase {
public void testSerializabilityWithHessian() throws Exception {
ObjEntity entity = new ObjEntity("test_entity");
entity.setClassName(Artist.class.getName());
DataMap dataMap = new DataMap("test");
dataMap.addObjEntity(entity);
Collection<DataMap> maps = Collections.singleton(dataMap);
EntityResolver resolver = new EntityResolver(maps);
// 1. simple case
Object c1 = HessianUtil.cloneViaClientServerSerialization(
resolver,
new EntityResolver());
assertNotNull(c1);
assertTrue(c1 instanceof EntityResolver);
EntityResolver cr1 = (EntityResolver) c1;
assertNotSame(resolver, cr1);
assertEquals(1, cr1.getObjEntities().size());
assertNotNull(cr1.getObjEntity(entity.getName()));
// 2. with descriptors resolved...
assertNotNull(resolver.getClassDescriptor(entity.getName()));
EntityResolver cr2 = (EntityResolver) HessianUtil
.cloneViaClientServerSerialization(resolver, new EntityResolver());
assertNotNull(cr2);
assertEquals(1, cr2.getObjEntities().size());
assertNotNull(cr2.getObjEntity(entity.getName()));
assertNotNull(cr2.getClassDescriptor(entity.getName()));
}
public void testConstructor() {
ObjEntity entity = new ObjEntity("test_entity");
entity.setClassName("java.lang.String");
DataMap dataMap = new DataMap("test");
dataMap.addObjEntity(entity);
Collection<DataMap> maps = Collections.singleton(dataMap);
EntityResolver resolver = new EntityResolver(maps);
assertSame(entity, resolver.getObjEntity(entity.getName()));
assertNotNull(resolver.getObjEntity(entity.getName()));
}
public void testInheritance() {
ObjEntity superEntity = new ObjEntity("super_entity");
superEntity.setClassName("java.lang.Object");
ObjEntity subEntity = new ObjEntity("sub_entity");
subEntity.setClassName("java.lang.String");
subEntity.setSuperEntityName(superEntity.getName());
try {
subEntity.getSuperEntity();
fail("hmm... superentity can't possibly be resolved at this point.");
}
catch (CayenneRuntimeException e) {
// expected
}
DataMap dataMap = new DataMap("test");
dataMap.addObjEntity(superEntity);
dataMap.addObjEntity(subEntity);
Collection<DataMap> maps = Collections.singleton(dataMap);
new EntityResolver(maps);
// after registration with resolver super entity should resolve just fine
assertSame(superEntity, subEntity.getSuperEntity());
}
}
| 38.209524 | 83 | 0.6665 |
15b1def62ebd2155114df47c54bf898fd30e8f4c | 392 | package com.stefan.ypinmall.coupon.dao;
import com.stefan.ypinmall.coupon.entity.SpuBoundsEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 商品spu积分设置
*
* @author Stefan_Yang
* @email [email protected]
* @date 2020-06-01 12:29:22
*/
@Mapper
public interface SpuBoundsDao extends BaseMapper<SpuBoundsEntity> {
}
| 21.777778 | 67 | 0.77551 |
bc89821daad3fc993dc6d8b7483fafe9286a58fc | 1,674 | package com.ishland.c2me.compatibility.mixin.betterend;
import com.ishland.c2me.compatibility.common.betterend.ThreadLocalMutableBlockPos;
import net.minecraft.util.math.BlockPos;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import ru.betterend.world.features.FullHeightScatterFeature;
import ru.betterend.world.features.InvertedScatterFeature;
import ru.betterend.world.features.ScatterFeature;
import ru.betterend.world.features.SilkMothNestFeature;
import ru.betterend.world.features.UnderwaterPlantScatter;
import ru.betterend.world.features.terrain.DesertLakeFeature;
import ru.betterend.world.features.terrain.EndLakeFeature;
import ru.betterend.world.features.terrain.SulphuricLakeFeature;
@Pseudo
@Mixin({DesertLakeFeature.class,
EndLakeFeature.class,
FullHeightScatterFeature.class,
InvertedScatterFeature.class,
ScatterFeature.class,
SilkMothNestFeature.class,
SulphuricLakeFeature.class,
UnderwaterPlantScatter.class})
public class MixinModifyPoses {
@Mutable
@Shadow(remap = false)
@Final
private static BlockPos.Mutable POS;
@Dynamic
@Inject(method = "<clinit>", at = @At("RETURN"))
private static void onCLInit(CallbackInfo info) {
POS = new ThreadLocalMutableBlockPos();
}
}
| 36.391304 | 82 | 0.792712 |
3e8e682cb37f3e2018bb3c9e2a7ba51af99b0cc5 | 14,329 | /*
* Copyright (c) 2004 The University of Maryland. All Rights Reserved.
*
*/
package edu.umd.lib.dspace.authenticate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.apache.log4j.Logger;
import org.dspace.content.MetadataSchema;
import org.dspace.core.LogManager;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
import org.dspace.eperson.Unit;
import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.EPersonService;
import org.dspace.eperson.service.GroupService;
import org.dspace.eperson.service.UnitService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/*********************************************************************
Use Ldap to provide authorizations for CAS authentication.
@author Ben Wallberg
*********************************************************************/
public class Ldap {
/** log4j category */
private static Logger log = Logger.getLogger(Ldap.class);
private org.dspace.core.Context context = null;
private DirContext ctx = null;
private String strUid = null;
private SearchResult entry = null;
private static final String[] strRequestAttributes =
new String[]{"givenname", "sn", "mail", "umfaculty", "telephonenumber",
"ou", "umappointment"};
private final static ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService();
private final static EPersonService epersonService = EPersonServiceFactory.getInstance().getEPersonService();
private final static GroupService groupService = EPersonServiceFactory.getInstance().getGroupService();
// Begin UMD Customization
private final static UnitService unitService = EPersonServiceFactory.getInstance().getUnitService();
// End UMD Customization
/**
* Wild card for Dublin Core metadata qualifiers/languages
*/
public static final String ANY = "*";
/******************************************************************* Ldap */
/**
* Create an ldap connection
*/
public
Ldap(org.dspace.core.Context context)
throws NamingException
{
this.context = context;
String strUrl = configurationService.getProperty("drum.ldap.url");
String strBindAuth = configurationService.getProperty("drum.ldap.bind.auth");
String strBindPassword = configurationService.getProperty("drum.ldap.bind.password");
String strConnectTimeout = configurationService.getProperty("drum.ldap.connect.timeout");
String strReadTimeout = configurationService.getProperty("drum.ldap.read.timeout");
// Setup the JNDI environment
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.REFERRAL, "follow");
env.put(Context.PROVIDER_URL, strUrl);
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put(javax.naming.Context.SECURITY_PRINCIPAL, strBindAuth);
env.put(javax.naming.Context.SECURITY_CREDENTIALS, strBindPassword);
env.put("com.sun.jndi.ldap.connect.timeout", strConnectTimeout);
env.put("com.sun.jndi.ldap.read.timeout", strReadTimeout);
// Create the directory context
log.debug("Initailizing new LDAP context");
ctx = new InitialDirContext(env);
}
/*************************************************************** checkUid */
/**
* Check if a user supplied uid is valid.
*/
public boolean
checkUid(String strUid)
throws NamingException
{
if (ctx == null)
return false;
this.strUid = strUid;
String strFilter = "uid=" + strUid;
// Setup the search controls
SearchControls sc = new SearchControls();
sc.setReturningAttributes(strRequestAttributes);
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
// Search
NamingEnumeration entries = ctx.search("", strFilter, sc);
// Make sure we got something
if (entries == null) {
log.warn(LogManager.getHeader(context,
"null returned on ctx.search for " + strFilter,
""));
return false;
}
// Check for a match
if (!entries.hasMore()) {
log.debug(LogManager.getHeader(context,
"no matching entries for " + strFilter,
""));
return false;
}
// Get entry
entry = (SearchResult)entries.next();
log.debug(LogManager.getHeader(context,
"matching entry for " + strUid + ": " + entry.getName(),
""));
// Check for another match
if (entries.hasMore()) {
entry = null;
log.warn(LogManager.getHeader(context,
"multiple matching entries for " + strFilter,
""));
return false;
}
log.debug(LogManager.getHeader(context,
"ldap entry:\n" + entry,
""));
return true;
}
/********************************************************** checkPassword */
/**
* Check if a user supplied password is valid.
*/
public boolean
checkPassword(String strPassword)
throws NamingException
{
if (checkAdmin(strPassword)) {
log.info(LogManager.getHeader(context,
"admin password override for uid=" + strUid,
""));
return true;
}
if (ctx == null || entry == null)
return false;
String strCompare = "(userpassword=" + strPassword.trim() + ")";
// Set up search controls
SearchControls sc = new SearchControls();
sc.setReturningAttributes(new String[0]); // return no attrs
sc.setSearchScope(SearchControls.OBJECT_SCOPE); // search object only
// Perform the compare
NamingEnumeration compare = ctx.search(entry.getName(), strCompare, sc);
// Make sure we got something
if (compare == null) {
log.warn(LogManager.getHeader(context,
"compare on userpassword failed for " + strUid,
""));
return false;
}
boolean ret = compare.hasMore();
log.debug(LogManager.getHeader(context,
"password compared '" + ret + "' for uid=" + strUid,
""));
return ret;
}
/*********************************************************** checkAdmin */
/**
* Check for an admin user override.
*/
public boolean
checkAdmin(String strLdapPassword)
{
try {
int i;
if ((i = strLdapPassword.indexOf(':')) > -1) {
// Extract email, password
String strEmail = strLdapPassword.substring(0,i);
String strPassword = strLdapPassword.substring(i+1);
// Find the eperson
EPerson eperson = epersonService.findByEmail(context, strEmail.toLowerCase());
if (eperson != null && epersonService.checkPassword(context, eperson, strPassword)) {
// Is the eperson an admin?
if (groupService.isMember(context, eperson, Group.ADMIN)) {
return true;
}
}
}
}
catch (Exception e) {
log.error(LogManager.getHeader(context,
"Error looking up eperson: " + e,
""));
}
return false;
}
/***************************************************************** close */
/**
* Close the ldap connection
*/
public void
close()
{
if (ctx != null) {
try {
ctx.close();
ctx = null;
}
catch (NamingException e) {};
}
}
/************************************************************** finalize */
/**
* Close the ldap connection
*/
public void
finalize()
{
close();
}
/****************************************************** getAttributeAll */
/**
* get all instances of an attribute.
*/
public List<String> getAttributeAll(String strName)
throws NamingException
{
List<String> attributes = new ArrayList<>();
if (entry != null) {
Attributes as = entry.getAttributes();
Attribute a = as.get(strName);
if (a != null) {
NamingEnumeration e = a.getAll();
while (e.hasMore()) {
attributes.add((String)e.next());
}
}
}
return attributes;
}
/********************************************************* getAttribute */
/**
* get an attribute (first instance).
*/
public String getAttribute(String strName)
throws NamingException
{
List l = getAttributeAll(strName);
if (l.size() > 0)
return (String)l.get(0);
else
return null;
}
/************************************************************* getEmail */
/**
* user's email address
*/
public String getEmail()
throws NamingException
{
return getAttribute("mail");
}
/************************************************************* getPhone */
/**
* user's phone
*/
public String getPhone()
throws NamingException
{
return getAttribute("telephonenumber");
}
/********************************************************* getFirstName */
/**
* user's first name
*/
public String getFirstName()
throws NamingException
{
return getAttribute("givenname");
}
/********************************************************** getLastName */
/**
* user's last name
*/
public String getLastName()
throws NamingException
{
return getAttribute("sn");
}
/************************************************************** getUnits */
/**
* organization units
*/
public List<String> getUnits()
throws NamingException
{
return getAttributeAll("ou");
}
/************************************************************* getGroups */
/**
* Groups mapped by the Units for faculty.
*/
public List<Group> getGroups() throws NamingException, java.sql.SQLException
{
HashSet<Group> ret = new HashSet();
for (Iterator i = getUnits().iterator(); i.hasNext(); ) {
String strUnit = (String) i.next();
Unit unit = unitService.findByName(context, strUnit);
if (unit != null && (!unit.getFacultyOnly() || isFaculty())) {
ret.addAll(unit.getGroups());
}
}
return new ArrayList<Group>(ret);
}
/************************************************************ isFaculty */
/**
* is the user CP faculty with an acceptable status?
*/
public boolean isFaculty()
throws NamingException
{
if (strUid.equals("tstusr2")) {
return true;
}
List l = getAttributeAll("umappointment");
if (l != null) {
Iterator i = l.iterator();
while (i.hasNext()) {
String strAppt = (String)i.next();
String strInst = strAppt.substring(0,2);
String strCat = strAppt.substring(24,26);
String strStatus = strAppt.substring(27,28);
if ((strCat.equals("01") ||
strCat.equals("02") ||
strCat.equals("03") ||
strCat.equals("15") ||
strCat.equals("25") ||
strCat.equals("36") ||
strCat.equals("37") ||
strCat.equals("EA"))
&&
((strStatus.equals("A") ||
strStatus.equals("E") ||
strStatus.equals("N") ||
strStatus.equals("Q") ||
strStatus.equals("T") ||
strStatus.equals("F")))
&&
(strInst.equals("01")))
{
return true;
}
}
}
return false;
}
/****************************************************** registerEPerson */
/**
* Register this ldap user as an EPerson
*/
public EPerson registerEPerson(String uid) throws Exception {
// Save the current dspace user
EPerson user = context.getCurrentUser();
try {
// Use the admin account to create the eperson
EPerson admin = epersonService.findByEmail(context, "[email protected]");
context.setCurrentUser(admin);
// Create a new eperson
EPerson eperson = epersonService.create(context);
String strFirstName = getFirstName();
if (strFirstName == null)
strFirstName = "??";
String strLastName = getLastName();
if (strLastName == null)
strLastName = "??";
String strPhone = getPhone();
if (strPhone == null)
strPhone = "??";
eperson.setNetid(uid);
eperson.setEmail(uid + "@umd.edu");
eperson.setFirstName(context, strFirstName);
eperson.setLastName(context, strLastName);
epersonService.setMetadata(context, eperson, "phone", strPhone);
eperson.setCanLogIn(true);
eperson.setRequireCertificate(false);
epersonService.update(context, eperson);
context.commit();
log.info(LogManager.getHeader(context,
"create_um_eperson",
"eperson_id="+eperson.getID() +
", uid=" + strUid));
return eperson;
}
finally {
context.setCurrentUser(user);
}
}
/*********************************************************** setContext */
/**
* Reset the context. We lost it after every request.
*/
public void setContext(org.dspace.core.Context context) {
this.context = context;
}
public String toString() {
if (entry == null) return "null";
return strUid + " (" + entry.getName() + ")";
}
}
| 26.633829 | 129 | 0.550562 |
0e19b226d170603701569eded2727f274a83dbf5 | 17,814 | /*
* 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.
*
* Contributions from 2013-2017 where performed either by US government
* employees, or under US Veterans Health Administration contracts.
*
* US Veterans Health Administration contributions by government employees
* are work of the U.S. Government and are not subject to copyright
* protection in the United States. Portions contributed by government
* employees are USGovWork (17USC §105). Not subject to copyright.
*
* Contribution by contractors to the US Veterans Health Administration
* during this period are contractually contributed under the
* Apache License, Version 2.0.
*
* See: https://www.usa.gov/government-works
*
* Contributions prior to 2013:
*
* Copyright (C) International Health Terminology Standards Development Organisation.
* Licensed under the Apache License, Version 2.0.
*
*/
package sh.isaac.model.semantic;
//~--- JDK imports ------------------------------------------------------------
import java.util.NoSuchElementException;
import java.util.UUID;
//~--- non-JDK imports --------------------------------------------------------
import sh.isaac.api.Get;
import sh.isaac.api.Status;
import sh.isaac.api.chronicle.Version;
import sh.isaac.api.chronicle.VersionType;
import sh.isaac.api.component.semantic.SemanticChronology;
import sh.isaac.api.component.semantic.version.DescriptionVersion;
import sh.isaac.api.component.semantic.version.MutableSemanticVersion;
import sh.isaac.api.coordinate.EditCoordinate;
import sh.isaac.api.externalizable.ByteArrayDataBuffer;
import sh.isaac.api.externalizable.IsaacExternalizable;
import sh.isaac.api.externalizable.IsaacObjectType;
import sh.isaac.api.identity.StampedVersion;
import sh.isaac.model.ChronologyImpl;
import sh.isaac.model.semantic.version.AbstractVersionImpl;
import sh.isaac.model.semantic.version.ComponentNidVersionImpl;
import sh.isaac.model.semantic.version.DescriptionVersionImpl;
import sh.isaac.model.semantic.version.DynamicImpl;
import sh.isaac.model.semantic.version.ImageVersionImpl;
import sh.isaac.model.semantic.version.LogicGraphVersionImpl;
import sh.isaac.model.semantic.version.LongVersionImpl;
import sh.isaac.model.semantic.version.SemanticVersionImpl;
import sh.isaac.model.semantic.version.StringVersionImpl;
import sh.isaac.model.semantic.version.brittle.Int1_Int2_Str3_Str4_Str5_Nid6_Nid7_VersionImpl;
import sh.isaac.model.semantic.version.brittle.Nid1_Int2_Str3_Str4_Nid5_Nid6_VersionImpl;
import sh.isaac.model.semantic.version.brittle.Nid1_Int2_VersionImpl;
import sh.isaac.model.semantic.version.brittle.Nid1_Nid2_Int3_VersionImpl;
import sh.isaac.model.semantic.version.brittle.Nid1_Nid2_Str3_VersionImpl;
import sh.isaac.model.semantic.version.brittle.Nid1_Nid2_VersionImpl;
import sh.isaac.model.semantic.version.brittle.Nid1_Str2_VersionImpl;
import sh.isaac.model.semantic.version.brittle.Rf2RelationshipImpl;
import sh.isaac.model.semantic.version.brittle.Str1_Nid2_Nid3_Nid4_VersionImpl;
import sh.isaac.model.semantic.version.brittle.Str1_Str2_Nid3_Nid4_Nid5_VersionImpl;
import sh.isaac.model.semantic.version.brittle.Str1_Str2_Nid3_Nid4_VersionImpl;
import sh.isaac.model.semantic.version.brittle.Str1_Str2_Str3_Str4_Str5_Str6_Str7_VersionImpl;
import sh.isaac.model.semantic.version.brittle.Str1_Str2_VersionImpl;
//~--- classes ----------------------------------------------------------------
/**
* The Class SemanticChronologyImpl.
*
* @author kec
*/
public class SemanticChronologyImpl
extends ChronologyImpl
implements SemanticChronology, IsaacExternalizable {
/** The referenced component nid. */
int referencedComponentNid = Integer.MAX_VALUE;
//~--- constructors --------------------------------------------------------
/**
* Instantiates a new semantic chronology impl.
*/
private SemanticChronologyImpl() {}
/**
* Instantiates a new semantic chronology impl.
*
* @param semanticType the semantic type
* @param primordialUuid the primordial uuid
* @param assemblageNid the assemblage sequence
* @param referencedComponentNid the referenced component nid
*/
public SemanticChronologyImpl(VersionType semanticType,
UUID primordialUuid,
int assemblageNid,
int referencedComponentNid) {
super(primordialUuid, assemblageNid, semanticType);
this.referencedComponentNid = referencedComponentNid;
}
//~--- methods -------------------------------------------------------------
/**
* Creates the mutable version.
*
* @param <V> the generic type
* @param stampSequence the stamp sequence
* @return the m
*/
@Override
public <V extends Version> V createMutableVersion(int stampSequence) {
final V version = createMutableVersionInternal(stampSequence);
addVersion(version);
return version;
}
/**
* Creates the mutable version.
*
* @param <V> the generic type
* @param status the status
* @param ec the ec
* @return the m
*/
@Override
public <V extends Version> V createMutableVersion(Status status, EditCoordinate ec) {
final int stampSequence = Get.stampService()
.getStampSequence(
status,
Long.MAX_VALUE,
ec.getAuthorNid(),
ec.getModuleNid(),
ec.getPathNid());
final V version = createMutableVersionInternal(stampSequence);
addVersion(version);
return version;
}
/**
* Creates the semantic.
*
* @param chronology the container
* @param stampSequence the stamp sequence
* @param bb the bb
* @return the semantic version impl
*/
public static AbstractVersionImpl createSemantic(
SemanticChronologyImpl chronology,
int stampSequence,
ByteArrayDataBuffer bb) {
switch (chronology.versionType) {
case MEMBER:
return new SemanticVersionImpl(chronology, stampSequence);
case COMPONENT_NID:
return new ComponentNidVersionImpl(chronology, stampSequence, bb);
case LONG:
return new LongVersionImpl(chronology, stampSequence, bb);
case LOGIC_GRAPH:
return new LogicGraphVersionImpl(chronology, stampSequence, bb);
case IMAGE:
return new ImageVersionImpl(chronology, stampSequence, bb);
case DYNAMIC:
return new DynamicImpl(chronology, stampSequence, bb);
case STRING:
return new StringVersionImpl(chronology, stampSequence, bb);
case DESCRIPTION:
return (new DescriptionVersionImpl(chronology, stampSequence, bb));
case RF2_RELATIONSHIP:
return new Rf2RelationshipImpl(chronology, stampSequence, bb);
case Int1_Int2_Str3_Str4_Str5_Nid6_Nid7:
return new Int1_Int2_Str3_Str4_Str5_Nid6_Nid7_VersionImpl(chronology, stampSequence, bb);
case Nid1_Int2:
return new Nid1_Int2_VersionImpl(chronology, stampSequence, bb);
case Nid1_Int2_Str3_Str4_Nid5_Nid6:
return new Nid1_Int2_Str3_Str4_Nid5_Nid6_VersionImpl(chronology, stampSequence, bb);
case Nid1_Nid2_Int3:
return new Nid1_Nid2_Int3_VersionImpl(chronology, stampSequence, bb);
case Nid1_Nid2:
return new Nid1_Nid2_VersionImpl(chronology, stampSequence, bb);
case Nid1_Nid2_Str3:
return new Nid1_Nid2_Str3_VersionImpl(chronology, stampSequence, bb);
case Nid1_Str2:
return new Nid1_Str2_VersionImpl(chronology, stampSequence, bb);
case Str1_Str2:
return new Str1_Str2_VersionImpl(chronology, stampSequence, bb);
case Str1_Str2_Nid3_Nid4:
return new Str1_Str2_Nid3_Nid4_VersionImpl(chronology, stampSequence, bb);
case Str1_Str2_Str3_Str4_Str5_Str6_Str7:
return new Str1_Str2_Str3_Str4_Str5_Str6_Str7_VersionImpl(chronology, stampSequence, bb);
case Str1_Nid2_Nid3_Nid4:
return new Str1_Nid2_Nid3_Nid4_VersionImpl(chronology, stampSequence, bb);
case Str1_Str2_Nid3_Nid4_Nid5:
return new Str1_Str2_Nid3_Nid4_Nid5_VersionImpl(chronology, stampSequence, bb);
default:
throw new UnsupportedOperationException("ae Can't handle: " + chronology.versionType);
}
}
/**
* Make.
*
* @param data the data
* @return the semantic chronology impl
*/
public static SemanticChronologyImpl make(ByteArrayDataBuffer data) {
if (IsaacObjectType.SEMANTIC.getDataFormatVersion() != data.getObjectDataFormatVersion()) {
throw new UnsupportedOperationException(
"Data format version not supported: " + data.getObjectDataFormatVersion());
}
final SemanticChronologyImpl semanticChronology = new SemanticChronologyImpl();
semanticChronology.readData(data);
// ModelGet.identifierService()
// .addToSemanticIndex(semanticChronology.referencedComponentNid, semanticChronology.getNid());
return semanticChronology;
}
/**
* To string.
*
* @return the string
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
toString(builder, true);
return builder.toString();
}
@Override
public void toString(StringBuilder builder, boolean addAttachments) {
builder.append("SemanticChronology{");
if (this.versionType == null) {
builder.append("versionType not initialized");
} else {
builder.append(versionType);
switch (versionType) {
case DESCRIPTION:
try {
SemanticChronology descriptionChronology = Get.assemblageService().getSemanticChronology(this.getNid());
DescriptionVersion descriptionVersion = (DescriptionVersion) descriptionChronology.getVersionList().get(0);
builder.append(": ");
builder.append(descriptionVersion.getText());
} catch (Throwable e) {
LOG.warn("Unexpected error in toString for Semantic: " + e);
}
break;
}
}
builder.append("\n assemblage:")
.append(Get.conceptDescriptionText(getAssemblageNid()))
.append(" <")
.append(getAssemblageNid())
.append(">\n rc:");
switch (Get.identifierService()
.getObjectTypeForComponent(this.referencedComponentNid)) {
case CONCEPT:
builder.append("CONCEPT: ")
.append(Get.conceptDescriptionText(this.referencedComponentNid));
break;
case SEMANTIC:
try {
SemanticChronologyImpl semanticChronicle = (SemanticChronologyImpl) Get.assemblageService()
.getSemanticChronology(
this.referencedComponentNid);
builder.append("SEMANTIC: ")
.append(semanticChronicle.getVersionType())
.append("\n from assemblage:")
.append(Get.conceptDescriptionText(semanticChronicle.getAssemblageNid()))
.append(" <")
.append(semanticChronicle.getAssemblageNid())
.append(">\n");
} catch (NoSuchElementException e) {
builder.append("SEMANTIC: ");
builder.append(this.referencedComponentNid);
builder.append(" is primordial. ");
}
break;
default:
builder.append(Get.identifierService()
.getObjectTypeForComponent(this.referencedComponentNid))
.append(" ")
.append(this.referencedComponentNid);
}
builder.append(" <")
.append(this.referencedComponentNid)
.append(">\n ");
super.toString(builder, addAttachments);
}
/**
* Write chronicle data.
*
* @param data the data
*/
@Override
public void writeChronicleData(ByteArrayDataBuffer data) {
super.writeChronicleData(data);
}
/**
* Creates the mutable version internal.
*
* @param <M> the generic type
* @param stampSequence the stamp sequence
* @return the m
* @throws UnsupportedOperationException the unsupported operation exception
*/
protected <M extends MutableSemanticVersion> M createMutableVersionInternal(int stampSequence)
throws UnsupportedOperationException {
switch (getVersionType()) {
case COMPONENT_NID:
return (M) new ComponentNidVersionImpl((SemanticChronology) this, stampSequence);
case LONG:
return (M) new LongVersionImpl((SemanticChronologyImpl) this, stampSequence);
case DYNAMIC:
return (M) new DynamicImpl((SemanticChronologyImpl) this, stampSequence);
case LOGIC_GRAPH:
return (M) new LogicGraphVersionImpl((SemanticChronologyImpl) this, stampSequence);
case IMAGE:
return (M) new ImageVersionImpl((SemanticChronologyImpl) this, stampSequence);
case STRING:
return (M) new StringVersionImpl((SemanticChronology) this, stampSequence);
case MEMBER:
return (M) new SemanticVersionImpl(this, stampSequence);
case DESCRIPTION:
return (M) new DescriptionVersionImpl((SemanticChronology) this, stampSequence);
case RF2_RELATIONSHIP:
return (M) new Rf2RelationshipImpl((SemanticChronology) this, stampSequence);
case Int1_Int2_Str3_Str4_Str5_Nid6_Nid7:
return (M) new Int1_Int2_Str3_Str4_Str5_Nid6_Nid7_VersionImpl((SemanticChronology) this, stampSequence);
case Nid1_Int2:
return (M) new Nid1_Int2_VersionImpl((SemanticChronology) this, stampSequence);
case Nid1_Int2_Str3_Str4_Nid5_Nid6:
return (M) new Nid1_Int2_Str3_Str4_Nid5_Nid6_VersionImpl((SemanticChronology) this, stampSequence);
case Nid1_Nid2_Int3:
return (M) new Nid1_Nid2_Int3_VersionImpl((SemanticChronology) this, stampSequence);
case Nid1_Nid2:
return (M) new Nid1_Nid2_VersionImpl((SemanticChronology) this, stampSequence);
case Nid1_Nid2_Str3:
return (M) new Nid1_Nid2_Str3_VersionImpl((SemanticChronology) this, stampSequence);
case Nid1_Str2:
return (M) new Nid1_Str2_VersionImpl((SemanticChronology) this, stampSequence);
case Str1_Str2:
return (M) new Str1_Str2_VersionImpl((SemanticChronology) this, stampSequence);
case Str1_Str2_Nid3_Nid4:
return (M) new Str1_Str2_Nid3_Nid4_VersionImpl((SemanticChronology) this, stampSequence);
case Str1_Str2_Str3_Str4_Str5_Str6_Str7:
return (M) new Str1_Str2_Str3_Str4_Str5_Str6_Str7_VersionImpl((SemanticChronology) this, stampSequence);
case Str1_Nid2_Nid3_Nid4:
return (M) new Str1_Nid2_Nid3_Nid4_VersionImpl((SemanticChronology) this, stampSequence);
case Str1_Str2_Nid3_Nid4_Nid5:
return (M) new Str1_Str2_Nid3_Nid4_Nid5_VersionImpl((SemanticChronology) this, stampSequence);
default:
throw new UnsupportedOperationException("af Can't handle: " + getVersionType());
}
}
/**
* Make version.
*
* @param stampSequence the stamp sequence
* @param db the db
* @return the v
*/
@Override
protected <V extends StampedVersion> V makeVersion(int stampSequence, ByteArrayDataBuffer db) {
return (V) createSemantic(this, stampSequence, db);
}
/**
* Put additional chronicle fields.
*
* @param out the out
*/
@Override
protected void putAdditionalChronicleFields(ByteArrayDataBuffer out) {
out.putNid(this.referencedComponentNid);
}
/**
* Skip additional chronicle fields.
*
* @param in the in
*/
@Override
protected void skipAdditionalChronicleFields(ByteArrayDataBuffer in) {
in.getNid(); // referencedComponentNid =
}
//~--- set methods ---------------------------------------------------------
/**
* Gets the additional chronicle fields.
*
* @param in the in
*/
@Override
protected void setAdditionalChronicleFieldsFromBuffer(ByteArrayDataBuffer in) {
this.referencedComponentNid = in.getNid();
}
//~--- get methods ---------------------------------------------------------
/**
* Gets the ochre object type.
*
* @return the ochre object type
*/
@Override
public IsaacObjectType getIsaacObjectType() {
return IsaacObjectType.SEMANTIC;
}
/**
* Gets the referenced component nid.
*
* @return the referenced component nid
*/
@Override
public int getReferencedComponentNid() {
return this.referencedComponentNid;
}
/**
* Gets the semantic type.
*
* @return the semantic type
*/
@Override
public VersionType getVersionType() {
if (this.versionType == null) {
throw new IllegalStateException();
}
return this.versionType;
}
}
| 34.590291 | 128 | 0.665095 |
52cbdaf03e45a20682e5a0f6036c9cdeeb861808 | 1,117 | package dev.tigr.clantags.api.screen;
import dev.tigr.clantags.api.Utils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.GlStateManager;
/**
* @author Tigermouthbear
* @since 12/30/19
*/
class DiscordButton extends GuiButton {
private String discord;
DiscordButton(Minecraft mc, int x, int y, String discord) {
//only should be 1 discord button per clanscreen
super(69, x, y, mc.fontRenderer.getStringWidth("discord.gg/" + discord), mc.fontRenderer.FONT_HEIGHT + 2, "");
this.discord = discord;
}
String getDiscord() {
return discord;
}
@Override
public void drawButton(Minecraft mc, int mouseX, int mouseY, float partialTicks) {
drawString(mc.fontRenderer, "discord.gg/" + discord, x, y, Integer.parseInt(Utils.colors.get("blue"), 16));
GlStateManager.color(1, 1, 1, 1);
Gui.drawRect(x, y + mc.fontRenderer.FONT_HEIGHT, x + width, y + 1, 5526783);
drawTexturedModalRect(x, y + mc.fontRenderer.FONT_HEIGHT, 0, 0, width, 1);
GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f);
}
}
| 31.914286 | 112 | 0.728738 |
8bad94cbc4efb2704b098468a068cb1c67327eb3 | 1,232 | package spms.controls;
import java.util.Map;
import javax.servlet.http.HttpSession;
import spms.annotation.Component;
import spms.bind.DataBinding;
import spms.dao.MemberDao;
import spms.vo.Member;
@Component("/auth/login.do")
public class LogInController implements Controller, DataBinding {
MemberDao memberDao;
public LogInController setMemberDao(MemberDao memberDao) {
this.memberDao = memberDao;
return this;
}
public Object[] getDataBinders() {
return new Object[] { "loginInfo", spms.vo.Member.class };
}
@Override
public String execute(Map<String, Object> model) throws Exception {
Member member = (Member)model.get("loginInfo");
if(member.getEmail() == null) {
return "/auth/LogInForm.jsp";
} else {
Member logIn = memberDao.exist(
((Member)model.get("loginInfo")).getEmail(),
((Member)model.get("loginInfo")).getPassword() );
if(logIn != null) {
HttpSession session = (HttpSession)model.get("session");
session.setAttribute("logIn", logIn);
return "redirect:../member/list.do";
} else {
return "LogInFail.jsp";
}
}
}
}
| 26.782609 | 70 | 0.627435 |
f5cac96be91f2de87f03075d7a513aa85e4d68d0 | 562 | package net.minecraft.commands;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.network.chat.Component;
public class CommandRuntimeException extends RuntimeException {
private final Component message;
public CommandRuntimeException(Component p_79225_) {
super(p_79225_.getString(), (Throwable)null, CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES, CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES);
this.message = p_79225_;
}
public Component getComponent() {
return this.message;
}
} | 33.058824 | 155 | 0.797153 |
f6f648dd38b6618a5d3557bc01886861aa439a81 | 4,037 | package io.github.ph1lou.werewolfplugin.commands.roles;
import io.github.ph1lou.werewolfapi.Commands;
import io.github.ph1lou.werewolfapi.PlayerWW;
import io.github.ph1lou.werewolfapi.enumlg.State;
import io.github.ph1lou.werewolfapi.enumlg.StateLG;
import io.github.ph1lou.werewolfapi.events.ProtectionEvent;
import io.github.ph1lou.werewolfapi.rolesattributs.AffectedPlayers;
import io.github.ph1lou.werewolfapi.rolesattributs.Power;
import io.github.ph1lou.werewolfapi.rolesattributs.Roles;
import io.github.ph1lou.werewolfplugin.Main;
import io.github.ph1lou.werewolfplugin.game.GameManager;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.UUID;
public class CommandProtector implements Commands {
private final Main main;
public CommandProtector(Main main) {
this.main = main;
}
@Override
public void execute(CommandSender sender, String[] args) {
GameManager game = main.getCurrentGame();
if (!(sender instanceof Player)) {
sender.sendMessage(game.translate("werewolf.check.console"));
return;
}
Player player = (Player) sender;
UUID uuid = player.getUniqueId();
if(!game.getPlayersWW().containsKey(uuid)) {
player.sendMessage(game.translate("werewolf.check.not_in_game"));
return;
}
PlayerWW plg = game.getPlayersWW().get(uuid);
if (!game.isState(StateLG.GAME)) {
player.sendMessage(game.translate("werewolf.check.game_not_in_progress"));
return;
}
if (!(plg.getRole().isDisplay("werewolf.role.protector.display"))){
player.sendMessage(game.translate("werewolf.check.role", game.translate("werewolf.role.protector.display")));
return;
}
Roles protector = plg.getRole();
if (args.length!=1) {
player.sendMessage(game.translate("werewolf.check.player_input"));
return;
}
if(!plg.isState(State.ALIVE)){
player.sendMessage(game.translate("werewolf.check.death"));
return;
}
if(!((Power)protector).hasPower()) {
player.sendMessage(game.translate("werewolf.check.power"));
return;
}
if(Bukkit.getPlayer(args[0])==null){
player.sendMessage(game.translate("werewolf.check.offline_player"));
return;
}
UUID argUUID = Bukkit.getPlayer(args[0]).getUniqueId();
if(!game.getPlayersWW().containsKey(argUUID) || !game.getPlayersWW().get(argUUID).isState(State.ALIVE)) {
player.sendMessage(game.translate("werewolf.check.player_not_found"));
return;
}
if(((AffectedPlayers)protector).getAffectedPlayers().contains(argUUID)){
player.sendMessage(game.translate("werewolf.check.already_get_power"));
return;
}
ProtectionEvent protectionEvent=new ProtectionEvent(uuid,argUUID);
Bukkit.getPluginManager().callEvent(protectionEvent);
if(protectionEvent.isCancelled()){
player.sendMessage(game.translate("werewolf.check.cancel"));
return;
}
((AffectedPlayers) protector).clearAffectedPlayer();
((Power) protector).setPower(false);
((AffectedPlayers) protector).addAffectedPlayer(argUUID);
Player playerProtected = Bukkit.getPlayer(args[0]);
playerProtected.removePotionEffect(PotionEffectType.DAMAGE_RESISTANCE);
playerProtected.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE,Integer.MAX_VALUE,0,false,false));
game.getPlayersWW().get(argUUID).setSalvation(true);
playerProtected.sendMessage(game.translate("werewolf.role.protector.get_protection"));
player.sendMessage(game.translate("werewolf.role.protector.protection_perform",args[0]));
}
}
| 34.801724 | 126 | 0.675749 |
e8b238d05c32f30ff40a5ce84b1dd8f92666f988 | 9,094 | package com.simple.mrchip.app;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.simple.mrchip.core.HttpAccess;
import com.simple.mrchip.core.HttpAccessListener;
import java.security.cert.TrustAnchor;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link AttendFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link AttendFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class AttendFragment extends Fragment implements HttpAccessListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
// TODO: Rename and change types of parameters
private Button mAttendButton;
private TextView mInfoText;
private SharedPreferences sharedPreferences;
private OnFragmentInteractionListener mListener;
private String mUUID;
private boolean mbAttend;
private HttpAccess httpAccess;
private float mAttendTime;
private float mLeaveTime;
public AttendFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment AttendFragment.
*/
// TODO: Rename and change types and number of parameters
public static AttendFragment newInstance(String param1, String param2) {
AttendFragment fragment = new AttendFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
String attendDate = sharedPreferences.getString("AttendDate", "");
String leaveDate = sharedPreferences.getString("LeaveDate", "");
switch (msg.what) {
case 0:
mAttendButton.setText("Leave");
if (!attendDate.isEmpty()) {
mInfoText.setText("AttendTime:"+attendDate+"\nLeaveTime:");
}
break;
case 1:
if (!attendDate.isEmpty() && !leaveDate.isEmpty()) {
mInfoText.setText("AttendTime:"+attendDate+"\nLeaveTime:"+leaveDate);
}
break;
case 2:
if (!attendDate.isEmpty() && !leaveDate.isEmpty()) {
mInfoText.setText("AttendTime:"+attendDate+"\nLeaveTime:"+leaveDate);
}
mAttendButton.setClickable(false);
mAttendButton.setEnabled(false);
Toast.makeText(getContext(), "No Additional Leave Opportunity", Toast.LENGTH_SHORT).show();
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
httpAccess = HttpAccess.getInstance();
httpAccess.setResponser("Attend", this);
httpAccess.setResponser("Leave", this);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
mUUID = sharedPreferences.getString("UUID", "");
mbAttend = false;
if (mUUID.isEmpty()) {
Toast.makeText(getContext(), "UUID is Empty.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), AppActivity.class);
startActivity(intent);
getActivity().finish();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_attend, container, false);
mAttendButton = view.findViewById(R.id.btAttend);
mInfoText = view.findViewById(R.id.txtAttendTime);
long time = sharedPreferences.getLong("AttendTime", 0);
System.out.println(time);
if (time > 0) {
long now = new Date().getTime();
now = now / (3600 * 24 *1000);
time = time / (3600 * 24 *1000);
if(now == time) {
mbAttend = true;
mAttendButton.setText("Leave");
String attendDate = sharedPreferences.getString("AttendDate", "");
String leaveDate = sharedPreferences.getString("LeaveDate", "");
if (!attendDate.isEmpty() && !leaveDate.isEmpty()) {
mInfoText.setText("AttendTime:"+attendDate+"\nLeaveTime:"+leaveDate);
}
int count = sharedPreferences.getInt("LeaveTime", 0);
if (count > 3) {
mAttendButton.setClickable(false);
mAttendButton.setEnabled(false);
}
}
}
mAttendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mbAttend) {
httpAccess.leave(mUUID);
} else {
httpAccess.attend(mUUID);
}
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void getHttpData(String response) {
if (response.equals("Error")) {
Toast.makeText(getContext(), "Attend Error", Toast.LENGTH_SHORT).show();
return;
}
if (response.equals("Exist")) {
mbAttend = true;
handler.sendEmptyMessage(0);
return;
}
if (mbAttend) {
int count = sharedPreferences.getInt("LeaveTime", 0);
if(count > 3) {
handler.sendEmptyMessage(2);
return;
}
mLeaveTime = Float.valueOf(response);
Calendar calender = Calendar.getInstance(Locale.CHINA);
calender.setTimeInMillis((long)(mLeaveTime * 1000));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("LeaveTime", ++count);
editor.putString("LeaveDate", DateFormat.format("dd-MM-yyyy hh:mm:ss", calender).toString());
editor.apply();
handler.sendEmptyMessage(1);
}
if(!mbAttend) {
Date date = new Date();
long time = date.getTime();
mAttendTime = Float.valueOf(response);
Calendar calender = Calendar.getInstance(Locale.CHINA);
calender.setTimeInMillis((long)(mAttendTime * 1000));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putLong("AttendTime", time);
editor.putInt("LeaveTime", 0);
editor.putString("AttendDate", DateFormat.format("dd-MM-yyyy hh:mm:ss", calender).toString());
editor.apply();
mbAttend = true;
handler.sendEmptyMessage(0);
}
System.out.println(response);
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| 37.270492 | 111 | 0.608313 |
5332ab404d1dedea6012541747d733e2213383e4 | 434 | package com.example.java_db_06_lab.services;
import com.example.java_db_06_lab.exceptions.InsufficientFundsException;
import java.math.BigDecimal;
public interface AccountService {
void transferBetweenAccounts(Long from, Long to, BigDecimal amount) throws InsufficientFundsException;
void withdrawMoney(BigDecimal amount, Long id) throws InsufficientFundsException;
void transferMoney(BigDecimal amount, Long id);
}
| 28.933333 | 106 | 0.822581 |
ec54cc419ccc2654dbda08617f8e38c3ba81b2e6 | 1,912 | package com.perunlabs.tool.jvalgen.var.spec;
import static com.perunlabs.tool.jvalgen.Utils.list;
import static com.perunlabs.tool.jvalgen.var.spec.AllVTypes.VINT;
import static com.perunlabs.tool.jvalgen.var.type.BasicVFunction.involutary;
import static com.perunlabs.tool.jvalgen.var.type.BasicVFunction.simple;
import com.google.common.collect.ImmutableList;
import com.perunlabs.common.jval.oper.IntOps;
import com.perunlabs.tool.jvalgen.var.type.BasicVFunction;
public class IntSpec {
private IntSpec() {}
public static final BasicVFunction ADD = func("add");
public static final BasicVFunction SUB = func("sub");
public static final BasicVFunction MUL = func("mul");
public static final BasicVFunction DIV = func("div");
public static final BasicVFunction NEG = funcI("neg");
public static final BasicVFunction DIF = func("dif");
public static final BasicVFunction INC = func("inc");
public static final BasicVFunction DEC = func("dec");
public static final BasicVFunction MODULO = func("modulo");
public static final BasicVFunction MAX = func("max");
public static final BasicVFunction MIN = func("min");
public static final BasicVFunction IS_EQ = func("isEq");
public static final BasicVFunction IS_LT = func("isLt");
public static final BasicVFunction IS_LTEQ = func("isLtEq");
public static final BasicVFunction IS_GT = func("isGt");
public static final BasicVFunction IS_GTEQ = func("isGtEq");
public static final BasicVFunction TO_FLOAT = func("toFloat");
private static BasicVFunction func(String name) {
return simple(VINT, IntOps.class, name);
}
private static BasicVFunction funcI(String name) {
return involutary(VINT, IntOps.class, name);
}
public static final ImmutableList<BasicVFunction> ALL_OPERATIONS = list(ADD, SUB, MUL, DIV, NEG,
DIF, INC, DEC, MODULO, MAX, MIN, IS_EQ, IS_LT, IS_LTEQ, IS_GT, IS_GTEQ, TO_FLOAT);
}
| 39.833333 | 98 | 0.755753 |
6bddae2cc5144f22ce1ab9daedd85da4ba8668af | 4,020 | package com.emerchantpay.gateway.util;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
/*
* 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 NON-INFRINGEMENT.
* 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.
*
* @license http://opensource.org/licenses/MIT The MIT License
*/
public abstract class NodeWrapper implements Serializable {
public static final String DATE_FORMAT = "yyyy-MM-dd";
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static final String UTC_DESCRIPTOR = "UTC";
public abstract List<NodeWrapper> findAll(String expression);
public List<String> findAllStrings(String expression) {
List<String> strings = new ArrayList<String>();
for (NodeWrapper node : findAll(expression)) {
strings.add(node.findString("."));
}
return strings;
}
public BigDecimal findBigDecimal(String expression) {
String value = findString(expression);
return value == null ? null : new BigDecimal(value);
}
public boolean findBoolean(String expression) {
String value = findString(expression);
return Boolean.valueOf(value);
}
public Calendar findDate(String expression) {
try {
String dateString = findString(expression);
if (dateString == null) {
return null;
}
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
dateFormat.setTimeZone(TimeZone.getTimeZone(UTC_DESCRIPTOR));
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(UTC_DESCRIPTOR));
calendar.setTime(dateFormat.parse(dateString));
return calendar;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Calendar findDateTime(String expression) {
try {
String dateString = findString(expression);
if (dateString == null) {
return null;
}
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
dateTimeFormat.setTimeZone(TimeZone.getTimeZone(UTC_DESCRIPTOR));
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(UTC_DESCRIPTOR));
calendar.setTime(dateTimeFormat.parse(dateString));
return calendar;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Integer findInteger(String expression) {
String value = findString(expression);
return value == null ? null : Integer.valueOf(value);
}
public abstract NodeWrapper findFirst(String expression);
public abstract String findString(String expression);
public abstract String getElementName(); // TODO MDM Rename to getName
public boolean isSuccess() {
return !(getElementName().equals("error"));
}
public Map<String, String> findMap(String expression) {
Map<String, String> map = new HashMap<String, String>();
for (NodeWrapper mapNode : findAll(expression)) {
map.put(StringUtils.underscore(mapNode.getElementName()), mapNode.findString("."));
}
return map;
}
public abstract Map<String, String> getFormParameters();
public abstract boolean isBlank();
public abstract List<NodeWrapper> getChildNodes(String nodeName);
}
| 32.95082 | 86 | 0.749751 |
9a57fcc0314ec891b7e07d2f62c60d669998b021 | 2,339 | /*
* 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.facebook.presto.operator.aggregation;
import com.facebook.presto.block.Block;
import com.facebook.presto.block.BlockBuilder;
import com.facebook.presto.block.BlockCursor;
public interface VariableWidthAggregationFunction<T>
extends AggregationFunction
{
/**
* @return the initial value for the aggregation
*/
T initialize();
/**
* Add all of the values in the specified block to the aggregation.
*
* @param positionCount number of positions in this page
* @param blocks the blocks containing values for the aggregation; empty for no-arg aggregations
* @param fields
*/
T addInput(int positionCount, Block[] blocks, int[] fields, T currentValue);
/**
* Add the current value of the specified cursor to the aggregation.
*
* @param cursors the values to add to the aggregation; empty for no-arg aggregations
* @param fields
*/
T addInput(BlockCursor[] cursors, int[] fields, T currentValue);
/**
* Add the intermediate value at specified cursor to the aggregation.
* The intermediate value is a value produced by the <code>evaluateIntermediate</code> function.
*
* @param cursors the values to add to the aggregation; empty for no-arg aggregations
* @param fields
*/
T addIntermediate(BlockCursor[] cursors, int[] fields, T currentValue);
/**
* Converts the current value to an intermediate value and adds it to the specified output.
*/
void evaluateIntermediate(T currentValue, BlockBuilder output);
/**
* Converts the current value to a final value and adds it to the specified output.
*/
void evaluateFinal(T currentValue, BlockBuilder output);
long estimateSizeInBytes(T value);
}
| 35.439394 | 100 | 0.707995 |
c399d2bb4a1d674e7d9a0f67e6f9340180dc484b | 1,386 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.org.gdt.service;
import br.org.gdt.dao.CsbffPessoaBeneficioDAO;
import br.org.gdt.model.CsbffPessoaBeneficio;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author Juliano
*/
@Service("csbffPessoaBeneficioService")
public class CsbffPessoaBeneficioService {
@Autowired
private CsbffPessoaBeneficioDAO csbffPessoaBeneficioDAO;
@Transactional
public void save(CsbffPessoaBeneficio csbffPessoaBeneficio) {
csbffPessoaBeneficioDAO.save(csbffPessoaBeneficio);
}
@Transactional
public void update(CsbffPessoaBeneficio csbffPessoaBeneficio) {
csbffPessoaBeneficioDAO.update(csbffPessoaBeneficio);
}
@Transactional
public void delete(long id) {
csbffPessoaBeneficioDAO.delete(id);
}
public CsbffPessoaBeneficio findById(long id) {
return csbffPessoaBeneficioDAO.findById(id);
}
public List<CsbffPessoaBeneficio> findAll() {
return csbffPessoaBeneficioDAO.findAll();
}
}
| 26.653846 | 80 | 0.726551 |
54e250b9da472dab4ed823109d738c7dcbc1d2bc | 7,697 | /*
* Copyright 2016 Anno van Vliet
*
* 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.jivesoftware.openfire.plugin;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Logger;
import org.jivesoftware.openfire.roster.Roster;
import org.jivesoftware.openfire.roster.RosterItem;
import org.jivesoftware.openfire.roster.RosterItem.AskType;
import org.jivesoftware.openfire.roster.RosterItem.RecvType;
import org.jivesoftware.openfire.roster.RosterItem.SubType;
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.openfire.user.UserAlreadyExistsException;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.jivesoftware.openfire.user.UserProvider;
import org.xmpp.packet.JID;
/**
* A Dummy implementation for the UserProvider for testing purposes.
*
* @author Anno van Vliet
*
*/
public class TestUserProvider implements UserProvider {
public class TestRoster extends Roster {
private final Collection<RosterItem> rosteritems;
/**
*/
public TestRoster() {
rosteritems = new ArrayList<RosterItem>();
JID jid = new JID("[email protected]");
SubType subStatus = SubType.BOTH;
AskType askStatus = AskType.NONE;
RecvType recvStatus = RecvType.SUBSCRIBE;
String nickname = "nick";
List<String> groups = null;
rosteritems.add(new RosterItem(1, jid, subStatus, askStatus, recvStatus, nickname, groups));
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.roster.Roster#getRosterItems()
*/
@Override
public Collection<RosterItem> getRosterItems() {
logger.finest("getRosterItems");
return rosteritems;
}
}
public class TestUser extends User {
private final Roster roster;
/**
* @param username
* @param name
* @param email
* @param creationDate
* @param modificationDate
*/
public TestUser(String username, String name, String email, Date creationDate, Date modificationDate) {
super(username, name, email, creationDate, modificationDate);
roster = new TestRoster();
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.User#getRoster()
*/
@Override
public Roster getRoster() {
logger.finest("getRoster");
return roster;
}
}
private static Logger logger = Logger.getLogger(TestUserProvider.class.getName());
private final Map<String,User> userList;
/**
*/
public TestUserProvider() {
userList = new TreeMap<String,User>();
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#loadUser(java.lang.String)
*/
@Override
public User loadUser(String username) throws UserNotFoundException {
logger.finest("loadUser");
return userList.get(username);
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#createUser(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public User createUser(String username, String password, String name, String email) throws UserAlreadyExistsException {
logger.finest("createUser");
Date creationDate = new Date();
Date modificationDate = new Date();
User u = new TestUser(username, name, email, creationDate, modificationDate);
userList.put(username, u);
return u;
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#deleteUser(java.lang.String)
*/
@Override
public void deleteUser(String username) {
logger.finest("deleteUser");
userList.remove(username);
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#getUserCount()
*/
@Override
public int getUserCount() {
logger.finest("getUserCount");
return userList.size();
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#getUsers()
*/
@Override
public Collection<User> getUsers() {
logger.finest("getUsers");
return userList.values();
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#getUsernames()
*/
@Override
public Collection<String> getUsernames() {
logger.finest("getUsernames");
return userList.keySet();
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#getUsers(int, int)
*/
@Override
public Collection<User> getUsers(int startIndex, int numResults) {
logger.finest("getUsers");
return null;
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#setName(java.lang.String, java.lang.String)
*/
@Override
public void setName(String username, String name) throws UserNotFoundException {
logger.finest("setName");
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#setEmail(java.lang.String, java.lang.String)
*/
@Override
public void setEmail(String username, String email) throws UserNotFoundException {
logger.finest("setEmail");
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#setCreationDate(java.lang.String, java.util.Date)
*/
@Override
public void setCreationDate(String username, Date creationDate) throws UserNotFoundException {
logger.finest("setCreationDate");
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#setModificationDate(java.lang.String, java.util.Date)
*/
@Override
public void setModificationDate(String username, Date modificationDate) throws UserNotFoundException {
logger.finest("setModificationDate");
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#getSearchFields()
*/
@Override
public Set<String> getSearchFields() throws UnsupportedOperationException {
logger.finest("getSearchFields");
return null;
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#findUsers(java.util.Set, java.lang.String)
*/
@Override
public Collection<User> findUsers(Set<String> fields, String query) throws UnsupportedOperationException {
logger.finest("findUsers");
return null;
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#findUsers(java.util.Set, java.lang.String, int, int)
*/
@Override
public Collection<User> findUsers(Set<String> fields, String query, int startIndex, int numResults) throws UnsupportedOperationException {
logger.finest("findUsers");
return null;
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#isReadOnly()
*/
@Override
public boolean isReadOnly() {
logger.finest("isReadOnly");
return false;
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#isNameRequired()
*/
@Override
public boolean isNameRequired() {
logger.finest("isNameRequired");
return false;
}
/* (non-Javadoc)
* @see org.jivesoftware.openfire.user.UserProvider#isEmailRequired()
*/
@Override
public boolean isEmailRequired() {
logger.finest("isEmailRequired");
return false;
}
}
| 28.297794 | 140 | 0.706119 |
09a4298c742f4db0e2e40d470568db26d554d9aa | 5,430 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2007-2008 SOARS Project.
* <author> Hiroshi Deguchi(SOARS Project.)
* <author> Li Hou(SOARS Project.)
* <author> Yasunari Ishizuka(PieCake.inc,)
*/
/*
* @(#)ExTimeKeyFactory.java 0.93 2007/09/03
* - modified by Y.Ishizuka(PieCake.inc,)
* @(#)ExTimeKeyFactory.java 0.91 2007/08/09
* - created by Y.Ishizuka(PieCake.inc,)
*/
package exalge2.util;
import java.util.HashMap;
import java.util.Iterator;
/**
* 時間キー文字列から時間キーユーティリティクラスを生成するためのユーティリティクラス。
* <br>
* 時間キー文字列を指定して {@link #createTimeKey(String)} メソッドを呼び出すと、
* 時間キー文字列のフォーマットに適したクラスインスタンスを生成する。
* 生成されたクラスインスタンスに対して、{@link ExTimeKey} インタフェースによる操作を
* 行うことで、値として時間キーを操作できる。
* <br>
* 操作後の時間キー文字列は、{@link ExTimeKey#toString()} メソッドで取得できる。
*
* @version 0.93 2007/09/03
*
* @author H.Deguchi(SOARS Project.)
* @author Y.Ishizuka(PieCake.inc,)
*
* @since 0.91
*/
public class ExTimeKeyFactory
{
//------------------------------------------------------------
// Constants
//------------------------------------------------------------
//------------------------------------------------------------
// Fields
//------------------------------------------------------------
private static ExTimeKeyFactory _instance = null;
private HashMap<Class, ExTimeKey> _entry = new HashMap<Class, ExTimeKey>();
//------------------------------------------------------------
// Constructions
//------------------------------------------------------------
protected ExTimeKeyFactory() {
// デフォルトの登録プロセス
this._entry.put(ExYearTimeKey.class, new ExYearTimeKey());
this._entry.put(ExMonthTimeKey.class, new ExMonthTimeKey());
this._entry.put(ExQuarterTimeKey.class, new ExQuarterTimeKey());
this._entry.put(ExFiscalYearTimeKey.class, new ExFiscalYearTimeKey());
}
/**
* <code>ExTimeKeyFactory</code> クラスの唯一のインスタンスを取得する。
*
* @return <code>ExTimeKeyFactory</code> インスタンス
*/
static public ExTimeKeyFactory getInstance() {
if (_instance == null) {
_instance = new ExTimeKeyFactory();
}
return _instance;
}
//------------------------------------------------------------
// Public interfaces
//------------------------------------------------------------
/**
* 時間キー文字列から、そのフォーマットに適した {@link ExTimeKey} インタフェース実装クラスの
* インスタンスを生成する。
*
* @param timeKeyString 時間キー文字列
*
* @return 時間キー文字列のフォーマットに適したクラスのインスタンス
*
* @throws NullPointerException 引数が <tt>null</tt> の場合
* @throws IllegalArgumentException サポートされない形式か、値が有効範囲にない場合
*/
static public ExTimeKey createTimeKey(String timeKeyString)
{
ExTimeKeyFactory factory = getInstance();
ExTimeKey newInstance = null;
try {
newInstance = factory.createClassByTimeKeyString(timeKeyString);
}
catch (IllegalAccessException ex) {
throw new IllegalArgumentException("Failed to create instance", ex);
}
catch (InstantiationException ex) {
throw new IllegalArgumentException("Failed to create instance", ex);
}
return newInstance;
}
/**
* 時間キーユーティリティクラスを登録する。
* <br>
* {@link ExYearTimeKey}、{@link ExMonthTimeKey}、{@link ExQuarterTimeKey}、{@link ExFiscalYearTimeKey} クラスは、
* すでに登録済みとなる。
*
* @param timekeyFormatClass 登録するクラス。このクラスは、{@link ExTimeKey} インタフェースを
* 実装している必要がある。
*
* @throws ClassCastException 指定されたクラスが {@link ExTimeKey} インタフェースを実装していない場合
* @throws IllegalAccessException 指定されたクラスのデフォルトコンストラクタにアクセスできない場合
* @throws InstantiationException 指定されたクラスがインタフェースまたは abstract クラスの場合
* @throws IllegalArgumentException 指定されたクラスが既に登録済みの場合
*/
public void registFormatClass(Class timekeyFormatClass)
throws ClassCastException, IllegalAccessException, InstantiationException, IllegalArgumentException
{
if (!ExTimeKey.class.isAssignableFrom(timekeyFormatClass)) {
throw new ClassCastException();
}
// チェック
if (this._entry.containsKey(timekeyFormatClass)) {
// すでに存在する
throw new IllegalArgumentException("Already exist class");
}
// 生成
ExTimeKey newInstance = (ExTimeKey)timekeyFormatClass.newInstance();
// 登録
this._entry.put(timekeyFormatClass, newInstance);
}
//------------------------------------------------------------
// Internal methods
//------------------------------------------------------------
protected ExTimeKey createClassByTimeKeyString(String timeKeyString)
throws IllegalAccessException, InstantiationException, IllegalArgumentException
{
ExTimeKey target = null;
// フォーマット判定
Iterator<Class> it = this._entry.keySet().iterator();
while (it.hasNext()) {
Class type = it.next();
ExTimeKey inst = this._entry.get(type);
//--- チェック
if (inst.isSupported(timeKeyString)) {
// 適したフォーマット
target = (ExTimeKey)type.newInstance();
break;
}
}
// フォーマットなし
if (target == null) {
throw new IllegalArgumentException("Not supportted fomat");
}
// 値設定
target.set(timeKeyString);
return target;
}
}
| 29.835165 | 107 | 0.639595 |
041cdf9577aa734e22e9ff024ab89c06b5f9e7f5 | 235 | package com.yonyou.etl.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.yonyou.etl.entity.FiBindSubject;
/**
* @author yhao
*/
public interface IFiBindSubjectService extends IService<FiBindSubject> {
}
| 21.363636 | 72 | 0.804255 |
a87be890e591f75b8e2ea3a21e6f48b0a76ba9d0 | 1,356 | /**
* (c) 2006 Cordys R&D B.V. All rights reserved. The computer program(s) is the
* proprietary information of Cordys B.V. and provided under the relevant
* License Agreement containing restrictions on use and disclosure. Use is
* subject to the License Agreement.
*/
package com.cordys.coe.util.template;
import java.util.ArrayList;
import java.util.Collection;
/**
* A list that contains objects that need to be cleaned up at a later time.
*
* @param <T> List item type.
*
* @author mpoyhone
*/
public class ObjectCleanupList<T extends ICleanupObject> extends ArrayList<T>
{
/**
* Constructor for ObjectCleanupList.
*/
public ObjectCleanupList()
{
super();
}
/**
* Constructor for ObjectCleanupList.
*
* @param c
*/
public ObjectCleanupList(Collection<? extends T> c)
{
super(c);
}
/**
* Constructor for ObjectCleanupList.
*
* @param initialCapacity
*/
public ObjectCleanupList(int initialCapacity)
{
super(initialCapacity);
}
/**
* Calls the cleanup method for all objects on this list.
*/
public void cleanupObjects()
{
for (T coObj : this)
{
coObj.cleanup();
}
clear();
}
}
| 21.870968 | 80 | 0.584071 |
61555b4e2b892cddecdda28b98338e21517c7a82 | 9,595 | /**
* Copyright (c) 2016, The National Archives <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the The National Archives nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.gov.nationalarchives.droid.report;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import uk.gov.nationalarchives.droid.core.interfaces.filter.Filter;
import uk.gov.nationalarchives.droid.core.interfaces.filter.FilterCriterion;
import uk.gov.nationalarchives.droid.core.interfaces.filter.RestrictionFactory;
import uk.gov.nationalarchives.droid.core.interfaces.filter.expressions.Criterion;
import uk.gov.nationalarchives.droid.core.interfaces.filter.expressions.Junction;
import uk.gov.nationalarchives.droid.core.interfaces.filter.expressions.Restrictions;
import uk.gov.nationalarchives.droid.profile.AbstractProfileResource;
import uk.gov.nationalarchives.droid.profile.ProfileInstance;
import uk.gov.nationalarchives.droid.report.dao.ReportLineItem;
import uk.gov.nationalarchives.droid.report.interfaces.ProfileReportData;
/**
* @author rflitcroft
*
*/
public final class ReportUtils {
private static final String ROOT_FOLDER = "/";
// This map of resources is only used to copy in the pre-built reports and transforms
// to the droid user folder. Reports and transforms used by the application are dynamically
// picked up from the droid user folder, so new reports and transforms can be added by the user.
private static final Map<String, List<String>> REPORT_DEFS;
static {
List<String> noTransforms = new ArrayList<String>();
List<String> generalFiles = new ArrayList<String>();
List<String> planetTransforms = new ArrayList<String>();
generalFiles.add("Web page.html.xsl");
generalFiles.add("Text.txt.xsl");
//generalFiles.add("droidlogo.gif");
planetTransforms.add("Planets XML.xml.xsl");
REPORT_DEFS = new HashMap<String, List<String>>();
REPORT_DEFS.put(ROOT_FOLDER, generalFiles);
REPORT_DEFS.put("Total count of files and folders.xml", noTransforms);
REPORT_DEFS.put("Total unreadable files.xml", noTransforms);
REPORT_DEFS.put("Total unreadable folders.xml", noTransforms);
REPORT_DEFS.put("File count and sizes.xml", noTransforms);
REPORT_DEFS.put("File count and sizes by file extension.xml", noTransforms);
REPORT_DEFS.put("File count and sizes by file format PUID.xml", noTransforms);
REPORT_DEFS.put("File count and sizes by mime type.xml", noTransforms);
REPORT_DEFS.put("File count and sizes by year last modified.xml", noTransforms);
REPORT_DEFS.put("File count and sizes by month last modified.xml", noTransforms);
REPORT_DEFS.put("File count and sizes by year and month last modified.xml", noTransforms);
REPORT_DEFS.put("Comprehensive breakdown.xml", planetTransforms);
}
private ReportUtils() { }
/**
* Transforms a List of resources to a List of resource paths.
* @param resources the resources to transform
* @return List of resource Paths
*/
static List<String> toResourcePaths(List<AbstractProfileResource> resources) {
List<String> profileResourcePaths = new ArrayList<String>();
for (AbstractProfileResource resource : resources) {
profileResourcePaths.add(new File(resource.getUri()).getPath());
}
return profileResourcePaths;
}
/**
* Builds a new ProfileReportData object from a ReportLineItem.
* @param profile the profile
* @param reportLineItem the report line item.
* @return a new ProfileReportData object
*/
static ProfileReportData buildProfileReportData(ProfileInstance profile, ReportLineItem reportLineItem) {
ProfileReportData data = new ProfileReportData();
data.setProfileName(profile.getName());
data.setProfileId(profile.getUuid());
data.setCount(reportLineItem.getCount());
data.setSum(reportLineItem.getSum());
data.setAverage(reportLineItem.getAverage());
data.setMin(reportLineItem.getMinimum());
data.setMax(reportLineItem.getMaximum());
return data;
}
/**
* Builds a criterion filter from the filters supplied.
* @param f1 filter 1
* @param f2 filter 2
* @return a criterion
*/
static Criterion buildFilter(Filter f1, Filter f2) {
Junction outerConjunction = Restrictions.conjunction();
// Add the profile filter criteria
if (f1 != null && f1.isEnabled()) {
Junction profileCriteria = f1.isNarrowed() ? Restrictions.conjunction()
: Restrictions.disjunction();
for (FilterCriterion profileCriterion : f1.getCriteria()) {
profileCriteria.add(RestrictionFactory.forFilterCriterion(profileCriterion));
}
outerConjunction.add(profileCriteria);
}
// Add the profile filter criteria
if (f2 != null) {
Junction reportItemCriteria = f2.isNarrowed() ? Restrictions.conjunction()
: Restrictions.disjunction();
for (FilterCriterion profileCriterion : f2.getCriteria()) {
reportItemCriteria.add(RestrictionFactory.forFilterCriterion(profileCriterion));
}
outerConjunction.add(reportItemCriteria);
}
return outerConjunction;
}
/**
* Populates the destinationDirectoey with the resources specified, using the classloader given.
* @param destinationDir destination directory
* @param classLoader the classloader used to locate resources
* @throws IOException if a resource could not be copied
*/
static void populateReportDefinitionsDirectory(File destinationDir, ClassLoader classLoader)
throws IOException {
for (String reportDefFilename : REPORT_DEFS.keySet()) {
List<String> transformList = REPORT_DEFS.get(reportDefFilename);
// Root - no reports, just transforms:
if (ROOT_FOLDER.equals(reportDefFilename)) {
copyTransforms(destinationDir, transformList, classLoader);
} else {
String reportDirName = FilenameUtils.getBaseName(reportDefFilename);
File reportDir = new File(destinationDir, reportDirName);
reportDir.mkdir();
copyResourceToFile(reportDefFilename, reportDir, classLoader);
copyTransforms(reportDir, transformList, classLoader);
}
}
}
private static void copyTransforms(File destinationDir,
List<String> transformNames, ClassLoader classLoader) throws IOException {
for (String transformName : transformNames) {
copyResourceToFile(transformName, destinationDir, classLoader);
}
}
// Copies a resource if the file doesn't already exist.
private static void copyResourceToFile(String resourceName,
File destinationDir, ClassLoader classLoader) throws IOException {
File reportDefFile = new File(destinationDir, resourceName);
if (!reportDefFile.exists()) {
reportDefFile.createNewFile();
OutputStream out = new FileOutputStream(reportDefFile);
InputStream in = classLoader.getResourceAsStream(resourceName);
IOUtils.copy(in, out);
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
| 44.836449 | 110 | 0.676707 |
538d0f17142d8a8d2b62a958b35c8a4085e25c6a | 2,243 | /**
* A class representing a link between two nodes.
*/
public class Link {
/**
* Create a new link.
*
* @param a The address of one endpoint.
* @param b The address of the other endpoint.
* @param speed The speed, in bits per second.
* @param latency The latency, in seconds.
*/
public Link(int nodeA, int nodeB, int speed, double latency, int cost) {
this.nodeA = nodeA;
this.nodeB = nodeB;
this.speed = speed;
this.latency = latency;
this.cost = cost;
up = true;
}
/**
* Returns the time required to transmit a packet of a given size over
* this link.
*
* @param bits The size of the packet, in bytes.
*/
public double timeToTransmit(int bytes) {
return latency + bytes * 8 / (double) speed;
}
/**
* Returns the address of the first endpoint.
*/
public final int getEndpointA() {
return nodeA;
}
/**
* Returns the address of the second endpoint.
*/
public final int getEndpointB() {
return nodeB;
}
/**
* Returns one endpoint given the other.
*/
public final int getDest(int addr) {
if (addr == nodeA)
return nodeB;
else if (addr == nodeB)
return nodeA;
else
return -1;
}
/**
* Returns the per-packet cost of using the link.
*/
public final int getCost() {
return cost;
}
/**
* Returns <b>true</b> if the link is up.
*/
public final boolean isUp() {
return up;
}
/**
* Brings the link up.
*/
public final void up() {
up = true;
}
/**
* Brings the link down
*/
public final void down() {
up = false;
}
/**
* The addresses of the endpoints.
*/
private int nodeA, nodeB;
/**
* The link speed, in bits per second.
*/
private int speed;
/**
* The link latency, in seconds.
*/
private double latency;
/**
* The per-packet cost of using the link.
*/
private int cost;
/**
* Whether or not the link is up.
*/
private boolean up;
}
| 20.962617 | 76 | 0.521177 |
43d26bc7e3efa71d38d981413db00ca720ff7857 | 1,293 | package com.soecode.lyf.demo.test.io.nio.nio.demo.chat;
import java.io.IOException;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
/**
* Created on 2018/6/15.
*
* @author dubber
* 服务器收到消息,进行广播
*/
public class NIOReceiveBroadcast {
//信道选择器
private Selector selector;
public NIOReceiveBroadcast(Selector selector) {
this.selector = selector;
}
public void serverReceive() {
}
/**
* 广播消息
* @param clientChannel 当前信道
* @param content 广播消息内容
*/
public void broadcast(SocketChannel clientChannel,String content) {
//广播数据到所有的SocketChannel中
for (SelectionKey key : selector.keys()) {
Channel targetchannel = key.channel();
//如果client不为空,不回发给发送此内容的客户端
if (targetchannel instanceof SocketChannel && targetchannel != clientChannel) {
SocketChannel target = (SocketChannel) targetchannel;
try {
target.write(Charset.forName("UTF-16").encode(content));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
| 24.865385 | 91 | 0.614849 |
48c49f5029401c7e94f94b6f79fd1b8f949c678c | 52,759 | package org.xms.g.maps;
/**
* Defines configuration PanoramaOptions for a StreetViewPanorama .<br/>
* Combination of com.huawei.hms.maps.StreetViewPanoramaOptions and com.google.android.gms.maps.StreetViewPanoramaOptions.<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions: Defines configuration PanoramaOptions for a StreetViewPanorama.<br/>
* com.google.android.gms.maps.StreetViewPanoramaOptions: Defines configuration PanoramaOptions for a StreetViewPanorama. These options can be used when adding a panorama to your application programmatically. If you are using a StreetViewPanoramaFragment, you can pass these options in using the static factory method newInstance(StreetViewPanoramaOptions). If you are using a StreetViewPanoramaView, you can pass these options in using the constructor StreetViewPanoramaView(Context, StreetViewPanoramaOptions).<br/>
*/
public final class StreetViewPanoramaOptions extends org.xms.g.utils.XObject {
/**
* org.xms.g.maps.StreetViewPanoramaOptions.StreetViewPanoramaOptions(org.xms.g.utils.XBox) Defines configuration PanoramaOptions for a StreetViewPanorama.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.StreetViewPanoramaOptions()
* com.google.android.gms.maps.StreetViewPanoramaOptions.StreetViewPanoramaOptions(): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions</a><br/>
*
* @param param0 the param should instanceof utils XBox
*/
public StreetViewPanoramaOptions(org.xms.g.utils.XBox param0) {
super(param0);
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.StreetViewPanoramaOptions() Defines configuration PanoramaOptions for a StreetViewPanorama.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.StreetViewPanoramaOptions()
* com.google.android.gms.maps.StreetViewPanoramaOptions.StreetViewPanoramaOptions(): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions</a><br/>
*
*/
public StreetViewPanoramaOptions() {
super(((org.xms.g.utils.XBox) null));
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
this.setHInstance(new com.huawei.hms.maps.StreetViewPanoramaOptions());
} else {
this.setGInstance(new com.google.android.gms.maps.StreetViewPanoramaOptions());
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.getPanningGesturesEnabled() true if users are initially able to pan via gestures on Street View panoramas.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.getPanningGesturesEnabled()
* com.google.android.gms.maps.StreetViewPanoramaOptions.getPanningGesturesEnabled(): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-boolean-getpanninggesturesenabled">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-boolean-getpanninggesturesenabled</a><br/>
*
* @return true if users are initially able to pan via gestures on Street View panoramas
*/
public final java.lang.Boolean getPanningGesturesEnabled() {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getPanningGesturesEnabled()");
return ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getPanningGesturesEnabled();
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getPanningGesturesEnabled()");
return ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getPanningGesturesEnabled();
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.getPanoramaId() The initial panorama ID for the Street View panorama, or null if unspecified.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.getPanoramaId()
* com.google.android.gms.maps.StreetViewPanoramaOptions.getPanoramaId(): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-string-getpanoramaid">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-string-getpanoramaid</a><br/>
*
* @return The initial panorama ID for the Street View panorama, or null if unspecified
*/
public final java.lang.String getPanoramaId() {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getPanoramaId()");
return ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getPanoramaId();
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getPanoramaId()");
return ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getPanoramaId();
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.getPosition() The initial position for the Street View panorama, or null if unspecified.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.getPosition()
* com.google.android.gms.maps.StreetViewPanoramaOptions.getPosition(): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-latlng-getposition">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-latlng-getposition</a><br/>
*
* @return The initial position for the Street View panorama, or null if unspecified
*/
public final org.xms.g.maps.model.LatLng getPosition() {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getPosition()");
com.huawei.hms.maps.model.LatLng hReturn = ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getPosition();
return ((hReturn) == null ? null : (new org.xms.g.maps.model.LatLng(new org.xms.g.utils.XBox(null, hReturn))));
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getPosition()");
com.google.android.gms.maps.model.LatLng gReturn = ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getPosition();
return ((gReturn) == null ? null : (new org.xms.g.maps.model.LatLng(new org.xms.g.utils.XBox(gReturn, null))));
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.getRadius() The initial radius used to search for a Street View panorama, or null if unspecified.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.getRadius()
* com.google.android.gms.maps.StreetViewPanoramaOptions.getRadius(): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-integer-getradius">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-integer-getradius</a><br/>
*
* @return The initial radius used to search for a Street View panorama, or null if unspecified
*/
public final java.lang.Integer getRadius() {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getRadius()");
return ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getRadius();
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getRadius()");
return ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getRadius();
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.getSource() The source filter used to search for a Street View panorama, or DEFAULT if unspecified.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.getSource()
* com.google.android.gms.maps.StreetViewPanoramaOptions.getSource(): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewsource-getsource">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewsource-getsource</a><br/>
*
* @return The source filter used to search for a Street View panorama, or DEFAULT if unspecified
*/
public final org.xms.g.maps.model.StreetViewSource getSource() {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getSource()");
com.huawei.hms.maps.model.StreetViewSource hReturn = ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getSource();
return ((hReturn) == null ? null : (new org.xms.g.maps.model.StreetViewSource(new org.xms.g.utils.XBox(null, hReturn))));
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getSource()");
com.google.android.gms.maps.model.StreetViewSource gReturn = ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getSource();
return ((gReturn) == null ? null : (new org.xms.g.maps.model.StreetViewSource(new org.xms.g.utils.XBox(gReturn, null))));
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.getStreetNamesEnabled() true if users are initially able to see street names on Street View panoramas.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.getStreetNamesEnabled()
* com.google.android.gms.maps.StreetViewPanoramaOptions.getStreetNamesEnabled(): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-boolean-getstreetnamesenabled">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-boolean-getstreetnamesenabled</a><br/>
*
* @return true if users are initially able to see street names on Street View panoramas
*/
public final java.lang.Boolean getStreetNamesEnabled() {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getStreetNamesEnabled()");
return ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getStreetNamesEnabled();
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getStreetNamesEnabled()");
return ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getStreetNamesEnabled();
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.getStreetViewPanoramaCamera() The initial camera for the Street View panorama, or null if unspecified.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.getStreetViewPanoramaCamera()
* com.google.android.gms.maps.StreetViewPanoramaOptions.getStreetViewPanoramaCamera(): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramacamera-getstreetviewpanoramacamera">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramacamera-getstreetviewpanoramacamera</a><br/>
*
* @return The initial camera for the Street View panorama, or null if unspecified
*/
public final org.xms.g.maps.model.StreetViewPanoramaCamera getStreetViewPanoramaCamera() {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getStreetViewPanoramaCamera()");
com.huawei.hms.maps.model.StreetViewPanoramaCamera hReturn = ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getStreetViewPanoramaCamera();
return ((hReturn) == null ? null : (new org.xms.g.maps.model.StreetViewPanoramaCamera(new org.xms.g.utils.XBox(null, hReturn))));
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getStreetViewPanoramaCamera()");
com.google.android.gms.maps.model.StreetViewPanoramaCamera gReturn = ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getStreetViewPanoramaCamera();
return ((gReturn) == null ? null : (new org.xms.g.maps.model.StreetViewPanoramaCamera(new org.xms.g.utils.XBox(gReturn, null))));
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.getUseViewLifecycleInFragment() the useViewLifecycleInFragment option, or null if unspecified.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.getUseViewLifecycleInFragment()
* com.google.android.gms.maps.StreetViewPanoramaOptions.getUseViewLifecycleInFragment(): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-boolean-getuseviewlifecycleinfragment">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-boolean-getuseviewlifecycleinfragment</a><br/>
*
* @return the useViewLifecycleInFragment option, or null if unspecified
*/
public final java.lang.Boolean getUseViewLifecycleInFragment() {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getUseViewLifecycleInFragment()");
return ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getUseViewLifecycleInFragment();
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getUseViewLifecycleInFragment()");
return ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getUseViewLifecycleInFragment();
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.getUserNavigationEnabled() true if users are initially able to move to different Street View panoramas.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.getUserNavigationEnabled()
* com.google.android.gms.maps.StreetViewPanoramaOptions.getUserNavigationEnabled(): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-boolean-getusernavigationenabled">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-boolean-getusernavigationenabled</a><br/>
*
* @return true if users are initially able to move to different Street View panoramas
*/
public final java.lang.Boolean getUserNavigationEnabled() {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getUserNavigationEnabled()");
return ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getUserNavigationEnabled();
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getUserNavigationEnabled()");
return ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getUserNavigationEnabled();
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.getZoomGesturesEnabled() true if users are initially able to zoom via gestures on Street View panoramas.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.getZoomGesturesEnabled()
* com.google.android.gms.maps.StreetViewPanoramaOptions.getZoomGesturesEnabled(): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-boolean-getzoomgesturesenabled">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-boolean-getzoomgesturesenabled</a><br/>
*
* @return true if users are initially able to zoom via gestures on Street View panoramas
*/
public final java.lang.Boolean getZoomGesturesEnabled() {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getZoomGesturesEnabled()");
return ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).getZoomGesturesEnabled();
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getZoomGesturesEnabled()");
return ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).getZoomGesturesEnabled();
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.panningGesturesEnabled(boolean) Toggles the ability for users to use pan around on panoramas using gestures. See setPanningGesturesEnabled(boolean)for more details. The default is true.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.panningGesturesEnabled(boolean)
* com.google.android.gms.maps.StreetViewPanoramaOptions.panningGesturesEnabled(boolean): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-panninggesturesenabled-boolean-enabled">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-panninggesturesenabled-boolean-enabled</a><br/>
*
* @param param0 the param should instanceof boolean
* @return the return object is maps StreetViewPanoramaOptions
*/
public final org.xms.g.maps.StreetViewPanoramaOptions panningGesturesEnabled(boolean param0) {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).panningGesturesEnabled(param0)");
com.huawei.hms.maps.StreetViewPanoramaOptions hReturn = ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).panningGesturesEnabled(param0);
return ((hReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(null, hReturn))));
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).panningGesturesEnabled(param0)");
com.google.android.gms.maps.StreetViewPanoramaOptions gReturn = ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).panningGesturesEnabled(param0);
return ((gReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(gReturn, null))));
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.panoramaCamera(org.xms.g.maps.model.StreetViewPanoramaCamera) Specifies the initial camera for the Street View panorama.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.panoramaCamera(com.huawei.hms.maps.model.StreetViewPanoramaCamera)
* com.google.android.gms.maps.StreetViewPanoramaOptions.panoramaCamera(com.google.android.gms.maps.model.StreetViewPanoramaCamera): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-panoramacamera-streetviewpanoramacamera-camera">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-panoramacamera-streetviewpanoramacamera-camera</a><br/>
*
* @param param0 the param should instanceof maps model StreetViewPanoramaCamera
* @return the return object is maps StreetViewPanoramaOptions
*/
public final org.xms.g.maps.StreetViewPanoramaOptions panoramaCamera(org.xms.g.maps.model.StreetViewPanoramaCamera param0) {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).panoramaCamera(((com.huawei.hms.maps.model.StreetViewPanoramaCamera) ((param0) == null ? null : (param0.getHInstance()))))");
com.huawei.hms.maps.StreetViewPanoramaOptions hReturn = ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).panoramaCamera(((com.huawei.hms.maps.model.StreetViewPanoramaCamera) ((param0) == null ? null : (param0.getHInstance()))));
return ((hReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(null, hReturn))));
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).panoramaCamera(((com.google.android.gms.maps.model.StreetViewPanoramaCamera) ((param0) == null ? null : (param0.getGInstance()))))");
com.google.android.gms.maps.StreetViewPanoramaOptions gReturn = ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).panoramaCamera(((com.google.android.gms.maps.model.StreetViewPanoramaCamera) ((param0) == null ? null : (param0.getGInstance()))));
return ((gReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(gReturn, null))));
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.panoramaId(java.lang.String) Specifies the initial position for the Street View panorama based on a panorama id. The position set by the panoramaID takes precedence over a position set by a LatLng.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.panoramaId(java.lang.String)
* com.google.android.gms.maps.StreetViewPanoramaOptions.panoramaId(java.lang.String): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-panoramaid-string-panoid">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-panoramaid-string-panoid</a><br/>
*
* @param param0 the param should instanceof java lang String
* @return the return object is maps StreetViewPanoramaOptions
*/
public final org.xms.g.maps.StreetViewPanoramaOptions panoramaId(java.lang.String param0) {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).panoramaId(param0)");
com.huawei.hms.maps.StreetViewPanoramaOptions hReturn = ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).panoramaId(param0);
return ((hReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(null, hReturn))));
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).panoramaId(param0)");
com.google.android.gms.maps.StreetViewPanoramaOptions gReturn = ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).panoramaId(param0);
return ((gReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(gReturn, null))));
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.position(org.xms.g.maps.model.LatLng) Specifies the initial position for the Street View panorama based upon location. The position set by the panoramaID, if set, takes precedence over a position set by a LatLng.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.position(com.huawei.hms.maps.model.LatLng)
* com.google.android.gms.maps.StreetViewPanoramaOptions.position(com.google.android.gms.maps.model.LatLng): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-position-latlng-position">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-position-latlng-position</a><br/>
*
* @param param0 the param should instanceof maps model LatLng
* @return the return object is maps StreetViewPanoramaOptions
*/
public final org.xms.g.maps.StreetViewPanoramaOptions position(org.xms.g.maps.model.LatLng param0) {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).position(((com.huawei.hms.maps.model.LatLng) ((param0) == null ? null : (param0.getHInstance()))))");
com.huawei.hms.maps.StreetViewPanoramaOptions hReturn = ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).position(((com.huawei.hms.maps.model.LatLng) ((param0) == null ? null : (param0.getHInstance()))));
return ((hReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(null, hReturn))));
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).position(((com.google.android.gms.maps.model.LatLng) ((param0) == null ? null : (param0.getGInstance()))))");
com.google.android.gms.maps.StreetViewPanoramaOptions gReturn = ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).position(((com.google.android.gms.maps.model.LatLng) ((param0) == null ? null : (param0.getGInstance()))));
return ((gReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(gReturn, null))));
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.position(org.xms.g.maps.model.LatLng,java.lang.Integer,org.xms.g.maps.model.StreetViewSource) Specifies the initial position for the Street View panorama based upon location, radius and source. The position set by the panoramaID, if set, takes precedence over a position set by a LatLng.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.position(com.huawei.hms.maps.model.LatLng,java.lang.Integer,com.huawei.hms.maps.model.StreetViewSource)
* com.google.android.gms.maps.StreetViewPanoramaOptions.position(com.google.android.gms.maps.model.LatLng,java.lang.Integer,com.google.android.gms.maps.model.StreetViewSource): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-position-latlng-position,-integer-radius,-streetviewsource-source">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-position-latlng-position,-integer-radius,-streetviewsource-source</a><br/>
*
* @param param0 the param should instanceof maps model LatLng
* @param param1 the param should instanceof java lang Integer
* @param param2 the param should instanceof maps model StreetViewSource
* @return the return object is maps StreetViewPanoramaOptions
*/
public final org.xms.g.maps.StreetViewPanoramaOptions position(org.xms.g.maps.model.LatLng param0, java.lang.Integer param1, org.xms.g.maps.model.StreetViewSource param2) {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).position(((com.huawei.hms.maps.model.LatLng) ((param0) == null ? null : (param0.getHInstance()))), param1, ((com.huawei.hms.maps.model.StreetViewSource) ((param2) == null ? null : (param2.getHInstance()))))");
com.huawei.hms.maps.StreetViewPanoramaOptions hReturn = ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).position(((com.huawei.hms.maps.model.LatLng) ((param0) == null ? null : (param0.getHInstance()))), param1, ((com.huawei.hms.maps.model.StreetViewSource) ((param2) == null ? null : (param2.getHInstance()))));
return ((hReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(null, hReturn))));
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).position(((com.google.android.gms.maps.model.LatLng) ((param0) == null ? null : (param0.getGInstance()))), param1, ((com.google.android.gms.maps.model.StreetViewSource) ((param2) == null ? null : (param2.getGInstance()))))");
com.google.android.gms.maps.StreetViewPanoramaOptions gReturn = ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).position(((com.google.android.gms.maps.model.LatLng) ((param0) == null ? null : (param0.getGInstance()))), param1, ((com.google.android.gms.maps.model.StreetViewSource) ((param2) == null ? null : (param2.getGInstance()))));
return ((gReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(gReturn, null))));
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.position(org.xms.g.maps.model.LatLng,java.lang.Integer) Specifies the initial position for the Street View panorama based upon location and radius. The position set by the panoramaID, if set, takes precedence over a position set by a LatLng.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.position(com.huawei.hms.maps.model.LatLng,java.lang.Integer)
* com.google.android.gms.maps.StreetViewPanoramaOptions.position(com.google.android.gms.maps.model.LatLng,java.lang.Integer): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-position-latlng-position,-integer-radius">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-position-latlng-position,-integer-radius</a><br/>
*
* @param param0 the param should instanceof maps model LatLng
* @param param1 the param should instanceof java lang Integer
* @return the return object is maps StreetViewPanoramaOptions
*/
public final org.xms.g.maps.StreetViewPanoramaOptions position(org.xms.g.maps.model.LatLng param0, java.lang.Integer param1) {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).position(((com.huawei.hms.maps.model.LatLng) ((param0) == null ? null : (param0.getHInstance()))), param1)");
com.huawei.hms.maps.StreetViewPanoramaOptions hReturn = ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).position(((com.huawei.hms.maps.model.LatLng) ((param0) == null ? null : (param0.getHInstance()))), param1);
return ((hReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(null, hReturn))));
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).position(((com.google.android.gms.maps.model.LatLng) ((param0) == null ? null : (param0.getGInstance()))), param1)");
com.google.android.gms.maps.StreetViewPanoramaOptions gReturn = ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).position(((com.google.android.gms.maps.model.LatLng) ((param0) == null ? null : (param0.getGInstance()))), param1);
return ((gReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(gReturn, null))));
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.position(org.xms.g.maps.model.LatLng,org.xms.g.maps.model.StreetViewSource) Specifies the initial position for the Street View panorama based upon location and source. The position set by the panoramaID, if set, takes precedence over a position set by a LatLng.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.position(com.huawei.hms.maps.model.LatLng,com.huawei.hms.maps.model.StreetViewSource)
* com.google.android.gms.maps.StreetViewPanoramaOptions.position(com.google.android.gms.maps.model.LatLng,com.google.android.gms.maps.model.StreetViewSource): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-position-latlng-position,-streetviewsource-source">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-position-latlng-position,-streetviewsource-source</a><br/>
*
* @param param0 the param should instanceof maps model LatLng
* @param param1 the param should instanceof maps model StreetViewSource
* @return the return object is maps StreetViewPanoramaOptions
*/
public final org.xms.g.maps.StreetViewPanoramaOptions position(org.xms.g.maps.model.LatLng param0, org.xms.g.maps.model.StreetViewSource param1) {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).position(((com.huawei.hms.maps.model.LatLng) ((param0) == null ? null : (param0.getHInstance()))), ((com.huawei.hms.maps.model.StreetViewSource) ((param1) == null ? null : (param1.getHInstance()))))");
com.huawei.hms.maps.StreetViewPanoramaOptions hReturn = ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).position(((com.huawei.hms.maps.model.LatLng) ((param0) == null ? null : (param0.getHInstance()))), ((com.huawei.hms.maps.model.StreetViewSource) ((param1) == null ? null : (param1.getHInstance()))));
return ((hReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(null, hReturn))));
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).position(((com.google.android.gms.maps.model.LatLng) ((param0) == null ? null : (param0.getGInstance()))), ((com.google.android.gms.maps.model.StreetViewSource) ((param1) == null ? null : (param1.getGInstance()))))");
com.google.android.gms.maps.StreetViewPanoramaOptions gReturn = ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).position(((com.google.android.gms.maps.model.LatLng) ((param0) == null ? null : (param0.getGInstance()))), ((com.google.android.gms.maps.model.StreetViewSource) ((param1) == null ? null : (param1.getGInstance()))));
return ((gReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(gReturn, null))));
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.streetNamesEnabled(boolean) Toggles the ability for users to see street names on panoramas. See setStreetNamesEnabled(boolean)for more details. The default is true.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.streetNamesEnabled(boolean)
* com.google.android.gms.maps.StreetViewPanoramaOptions.streetNamesEnabled(boolean): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-streetnamesenabled-boolean-enabled">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-streetnamesenabled-boolean-enabled</a><br/>
*
* @param param0 the param should instanceof boolean
* @return the return object is maps StreetViewPanoramaOptions
*/
public final org.xms.g.maps.StreetViewPanoramaOptions streetNamesEnabled(boolean param0) {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).streetNamesEnabled(param0)");
com.huawei.hms.maps.StreetViewPanoramaOptions hReturn = ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).streetNamesEnabled(param0);
return ((hReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(null, hReturn))));
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).streetNamesEnabled(param0)");
com.google.android.gms.maps.StreetViewPanoramaOptions gReturn = ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).streetNamesEnabled(param0);
return ((gReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(gReturn, null))));
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.toString() to String.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.toString()
* com.google.android.gms.maps.StreetViewPanoramaOptions.toString(): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-string-tostring">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-string-tostring</a><br/>
*
* @return the return object is java lang String
*/
public final java.lang.String toString() {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).toString()");
return ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).toString();
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).toString()");
return ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).toString();
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.useViewLifecycleInFragment(boolean) When using a StreetViewPanoramaFragment, this flag specifies whether the lifecycle of the Street View panorama should be tied to the fragment's view or the fragment itself. The default value is false, tying the lifecycle of the Street View panorama to the fragment.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.useViewLifecycleInFragment(boolean)
* com.google.android.gms.maps.StreetViewPanoramaOptions.useViewLifecycleInFragment(boolean): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-useviewlifecycleinfragment-boolean-useviewlifecycleinfragment">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-useviewlifecycleinfragment-boolean-useviewlifecycleinfragment</a><br/>
*
* @param param0 the param should instanceof boolean
* @return the return object is maps StreetViewPanoramaOptions
*/
public final org.xms.g.maps.StreetViewPanoramaOptions useViewLifecycleInFragment(boolean param0) {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).useViewLifecycleInFragment(param0)");
com.huawei.hms.maps.StreetViewPanoramaOptions hReturn = ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).useViewLifecycleInFragment(param0);
return ((hReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(null, hReturn))));
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).useViewLifecycleInFragment(param0)");
com.google.android.gms.maps.StreetViewPanoramaOptions gReturn = ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).useViewLifecycleInFragment(param0);
return ((gReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(gReturn, null))));
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.userNavigationEnabled(boolean) Toggles the ability for users to move between panoramas. See setUserNavigationEnabled(boolean)for more details. The default is true.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.userNavigationEnabled(boolean)
* com.google.android.gms.maps.StreetViewPanoramaOptions.userNavigationEnabled(boolean): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-usernavigationenabled-boolean-enabled">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-usernavigationenabled-boolean-enabled</a><br/>
*
* @param param0 the param should instanceof boolean
* @return the return object is maps StreetViewPanoramaOptions
*/
public final org.xms.g.maps.StreetViewPanoramaOptions userNavigationEnabled(boolean param0) {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).userNavigationEnabled(param0)");
com.huawei.hms.maps.StreetViewPanoramaOptions hReturn = ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).userNavigationEnabled(param0);
return ((hReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(null, hReturn))));
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).userNavigationEnabled(param0)");
com.google.android.gms.maps.StreetViewPanoramaOptions gReturn = ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).userNavigationEnabled(param0);
return ((gReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(gReturn, null))));
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.writeToParcel(android.os.Parcel,int) write To Parcel.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.writeToParcel(android.os.Parcel,int)
* com.google.android.gms.maps.StreetViewPanoramaOptions.writeToParcel(android.os.Parcel,int): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-void-writetoparcel-parcel-out,-int-flags">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-void-writetoparcel-parcel-out,-int-flags</a><br/>
*
* @param param0 the param should instanceof android os Parcel
* @param param1 the param should instanceof int
*/
public final void writeToParcel(android.os.Parcel param0, int param1) {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).writeToParcel(param0, param1)");
((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).writeToParcel(param0, param1);
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).writeToParcel(param0, param1)");
((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).writeToParcel(param0, param1);
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.zoomGesturesEnabled(boolean) Toggles the ability for users to zoom on panoramas using gestures. See setZoomGesturesEnabled(boolean)for more details. The default is true.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
* Below are the references of HMS apis and GMS apis respectively:<br/>
* com.huawei.hms.maps.StreetViewPanoramaOptions.zoomGesturesEnabled(boolean)
* com.google.android.gms.maps.StreetViewPanoramaOptions.zoomGesturesEnabled(boolean): <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-zoomgesturesenabled-boolean-enabled">https://developers.google.com/android/reference/com/google/android/gms/maps/StreetViewPanoramaOptions#public-streetviewpanoramaoptions-zoomgesturesenabled-boolean-enabled</a><br/>
*
* @param param0 the param should instanceof boolean
* @return the return object is maps StreetViewPanoramaOptions
*/
public final org.xms.g.maps.StreetViewPanoramaOptions zoomGesturesEnabled(boolean param0) {
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).zoomGesturesEnabled(param0)");
com.huawei.hms.maps.StreetViewPanoramaOptions hReturn = ((com.huawei.hms.maps.StreetViewPanoramaOptions) this.getHInstance()).zoomGesturesEnabled(param0);
return ((hReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(null, hReturn))));
} else {
org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).zoomGesturesEnabled(param0)");
com.google.android.gms.maps.StreetViewPanoramaOptions gReturn = ((com.google.android.gms.maps.StreetViewPanoramaOptions) this.getGInstance()).zoomGesturesEnabled(param0);
return ((gReturn) == null ? null : (new org.xms.g.maps.StreetViewPanoramaOptions(new org.xms.g.utils.XBox(gReturn, null))));
}
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.dynamicCast(java.lang.Object) dynamic cast the input object to org.xms.g.maps.StreetViewPanoramaOptions.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
*
* @param param0 the param should instanceof java lang Object
* @return cast maps StreetViewPanoramaOptions object
*/
public static org.xms.g.maps.StreetViewPanoramaOptions dynamicCast(java.lang.Object param0) {
return ((org.xms.g.maps.StreetViewPanoramaOptions) param0);
}
/**
* org.xms.g.maps.StreetViewPanoramaOptions.isInstance(java.lang.Object) judge whether the Object is XMS instance or not.<br/>
* Support running environments including both HMS and GMS which are chosen by users.<br/>
*
* @param param0 the input object
* @return true if the Object is XMS instance, otherwise false
*/
public static boolean isInstance(java.lang.Object param0) {
if (!(param0 instanceof org.xms.g.utils.XGettable)) {
return false;
}
if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
return ((org.xms.g.utils.XGettable) param0).getHInstance() instanceof com.huawei.hms.maps.StreetViewPanoramaOptions;
} else {
return ((org.xms.g.utils.XGettable) param0).getGInstance() instanceof com.google.android.gms.maps.StreetViewPanoramaOptions;
}
}
} | 95.925455 | 602 | 0.739533 |
424ac9b7052c92930a6793b35117dbe52b148714 | 1,011 | package sergey.zhuravel.munchkin.manager;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmResults;
import rx.Observable;
import sergey.zhuravel.munchkin.model.Player;
public class RealmManager {
private Realm mRealm;
public RealmManager() {
mRealm = Realm.getDefaultInstance();
}
public Realm getRealm() {
return mRealm;
}
public void addMunchkin(Player player) {
mRealm.executeTransaction(realm -> mRealm.copyToRealmOrUpdate(player));
}
public Observable<List<Player>> getMunchkin() {
return Observable.fromCallable(() -> mRealm.where(Player.class).findAll());
}
public int getCountMunchkin() {
return mRealm.where(Player.class).findAll().size();
}
public void deleteMunchkin(int id) {
mRealm.executeTransaction(realm -> {
RealmResults<Player> results = realm.where(Player.class).equalTo("id", id).findAll();
results.deleteAllFromRealm();
});
}
}
| 23.511628 | 97 | 0.663699 |
f9b801ff098be6031f172c563ef17b9c6222ee74 | 341 | package jdepend.core.serviceproxy.framework;
/**
* 后台服务代理工厂
*
* @author <b>Abner</b>
*
*/
public interface JDependServiceProxyFactory {
/**
* 得到后台服务
*
* @param groupName
* @param commandName
* @return
*/
public JDependServiceProxy createJDependServiceProxy(String groupName, String commandName);
}
| 17.05 | 93 | 0.659824 |
e60088fbde29240603e93b8087a5a38d4c4a2eb8 | 1,780 | package io.confluent.avro.random.generator;
import com.telefonica.baikal.utils.Validations;
import io.confluent.avro.random.generator.util.ResourceUtil;
import org.apache.avro.generic.GenericRecord;
import org.apache.commons.validator.routines.EmailValidator;
import org.junit.Test;
import java.util.UUID;
import static io.confluent.avro.random.generator.util.ResourceUtil.generateRecordWithSchema;
import static org.junit.Assert.*;
public class KindGeneratorTest {
private static final String UUID_SCHEMA =
ResourceUtil.loadContent("test-schemas/kinds/uuid.json");
@Test
public void shouldCreateValidUUIDForStrings() {
GenericRecord record = generateRecordWithSchema("test-schemas/kinds/uuid.json");
String field = "user_id";
assertNotNull(record.get(field));
String value = record.get(field).toString();
System.out.println("Generated value is: " + value);
try {
UUID.fromString(value);
} catch (IllegalArgumentException e) {
fail("user_id is not a valid UUID: " + value);
}
}
@Test
public void shouldCreateValidNameForStrings() {
GenericRecord record = generateRecordWithSchema("test-schemas/kinds/name.json");
String field = "name";
assertNotNull(record.get(field));
String value = record.get(field).toString();
System.out.println("Generated value is: " + value);
}
@Test
public void shouldCreateValidEmailForStrings() {
GenericRecord record = generateRecordWithSchema("test-schemas/kinds/email.json");
String field = "email";
assertNotNull(record.get(field));
String value = record.get(field).toString();
System.out.println("Generated value is: " + value);
assertTrue("Invalid iso-date: " + value, EmailValidator.getInstance().isValid(value));
}
}
| 30.689655 | 92 | 0.732022 |
cc9aec3f9088f16ea226816a9954ed8a0aab6d79 | 527 | import java.util.Scanner;
public class p01_DebitCardNumber {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int firstNumber = Integer.parseInt(scanner.nextLine());
int secondNumber = Integer.parseInt(scanner.nextLine());
int thirdNumber = Integer.parseInt(scanner.nextLine());
int forthNumber = Integer.parseInt(scanner.nextLine());
System.out.printf("%04d %04d %04d %04d%n",firstNumber, secondNumber, thirdNumber, forthNumber);
}
}
| 35.133333 | 103 | 0.688805 |
e933c97173234efcac1be242ad42917a4968ab46 | 478 | package com.packtpub.microservices.ch02;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.netflix.sidecar.EnableSidecar;
import org.springframework.stereotype.Controller;
@EnableSidecar
@Controller
@EnableAutoConfiguration
public class SidecarController {
public static void main(String[] args) {
SpringApplication.run(SidecarController.class, args);
}
} | 31.866667 | 70 | 0.824268 |
8635fc61ce6c92c0c52f9e47ce9d0d2c431fd1ca | 2,999 | package com.google.bitcoin.bouncycastle.asn1.crmf;
import com.google.bitcoin.bouncycastle.asn1.ASN1Encodable;
import com.google.bitcoin.bouncycastle.asn1.ASN1EncodableVector;
import com.google.bitcoin.bouncycastle.asn1.ASN1Sequence;
import com.google.bitcoin.bouncycastle.asn1.ASN1TaggedObject;
import com.google.bitcoin.bouncycastle.asn1.DERBitString;
import com.google.bitcoin.bouncycastle.asn1.DERObject;
import com.google.bitcoin.bouncycastle.asn1.DERSequence;
import com.google.bitcoin.bouncycastle.asn1.x509.AlgorithmIdentifier;
public class POPOSigningKey
extends ASN1Encodable
{
private POPOSigningKeyInput poposkInput;
private AlgorithmIdentifier algorithmIdentifier;
private DERBitString signature;
private POPOSigningKey(ASN1Sequence seq)
{
int index = 0;
if (seq.getObjectAt(0) instanceof ASN1TaggedObject)
{
poposkInput = POPOSigningKeyInput.getInstance(seq.getObjectAt(index++));
}
algorithmIdentifier = AlgorithmIdentifier.getInstance(seq.getObjectAt(index++));
signature = DERBitString.getInstance(seq.getObjectAt(index));
}
public static POPOSigningKey getInstance(Object o)
{
if (o instanceof POPOSigningKey)
{
return (POPOSigningKey)o;
}
if (o instanceof ASN1Sequence)
{
return new POPOSigningKey((ASN1Sequence)o);
}
throw new IllegalArgumentException("Invalid object: " + o.getClass().getName());
}
public static POPOSigningKey getInstance(ASN1TaggedObject obj, boolean explicit)
{
return getInstance(ASN1Sequence.getInstance(obj, explicit));
}
/**
* <pre>
* POPOSigningKey ::= SEQUENCE {
* poposkInput [0] POPOSigningKeyInput OPTIONAL,
* algorithmIdentifier AlgorithmIdentifier,
* signature BIT STRING }
* -- The signature (using "algorithmIdentifier") is on the
* -- DER-encoded value of poposkInput. NOTE: If the CertReqMsg
* -- certReq CertTemplate contains the subject and publicKey values,
* -- then poposkInput MUST be omitted and the signature MUST be
* -- computed on the DER-encoded value of CertReqMsg certReq. If
* -- the CertReqMsg certReq CertTemplate does not contain the public
* -- key and subject values, then poposkInput MUST be present and
* -- MUST be signed. This strategy ensures that the public key is
* -- not present in both the poposkInput and CertReqMsg certReq
* -- CertTemplate fields.
* </pre>
* @return a basic ASN.1 object representation.
*/
public DERObject toASN1Object()
{
ASN1EncodableVector v = new ASN1EncodableVector();
if (poposkInput != null)
{
v.add(poposkInput);
}
v.add(algorithmIdentifier);
v.add(signature);
return new DERSequence(v);
}
}
| 35.282353 | 88 | 0.667556 |
e26a8b9fab54f6554567304566f0c34d5dae3b84 | 893 | package com.java.eternity;
import java.util.ArrayList;
/**
* @author Fati CHEN <[email protected]>
*/
public class gameFactory {
public static Piece piece(short number, byte[] couleurs) {
return new Piece(number, couleurs);
}
public static Piece piece(short number, String[] couleurs) {
return new Piece(number, couleurs);
}
public static Piece piece(short number, byte[] couleurs, byte top) {
return new Piece(number, couleurs, top);
}
public static Piece piece(short number, String[] couleurs, byte top) {
return new Piece(number, couleurs, top);
}
public static EternityII eternity(ArrayList<Piece> pieces, int size) {
return new EternityII(pieces, size);
}
public static EternityII eternity(ArrayList<Piece> pieces, Piece[][] plateau) {
return new EternityII(pieces, plateau);
}
}
| 26.264706 | 83 | 0.664054 |
5967cb7ff1afefff866411286cb0410bb54d55ac | 1,766 | package com.mygame.pure.utils;
import java.io.File;
import android.content.Context;
import com.mygame.pure.log.MyLog;
public class FileCache {
private static final String tag = FileCache.class.getSimpleName();
private File cacheDir; // the directory to save images
/**
* Constructor
*
* @param context
* The context related to this cache.
* */
public FileCache(Context context) {
// Find the directory to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"fellowship");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
MyLog.i(tag, "cache dir: " + cacheDir.getAbsolutePath());
}
public String getFilePath(String key) {
return android.os.Environment.getExternalStorageDirectory() + "/"
+ "fellowship" + "/" + key;
}
/**
* Search the specific image file with a unique key.
*
* @param key
* Should be unique.
* @return Returns the image file corresponding to the key.
* */
public File getFile(String key) {
File f = new File(cacheDir, key);
MyLog.i(tag, "key:" + key);
if (f.exists()) {
MyLog.i(tag, "the file you wanted exists " + f.getAbsolutePath());
return f;
} else {
MyLog.i(tag,
"the file you wanted does not exists: "
+ f.getAbsolutePath());
}
return null;
}
public File getFileDirCache() {
return cacheDir;
}
/**
* Clear the cache directory on sdcard.
* */
public void clear() {
File[] files = cacheDir.listFiles();
for (File f : files)
f.delete();
}
} | 23.864865 | 70 | 0.630238 |
5c5cacc8b846af4b10ee12f5204897a7e588b0b4 | 838 | package net.kaunghtetlin.ted.data.vos;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import com.google.gson.annotations.SerializedName;
import net.kaunghtetlin.ted.data.db.DBConstants;
/**
* Created by Kaung Htet Lin on 1/25/2018.
*/
@Entity(tableName = DBConstants.SPEAKER_TABLE)
public class SpeakerVO {
@PrimaryKey
@SerializedName("speaker_id")
private String speakerId;
@SerializedName("name")
private String speakerName;
public String getSpeakerId() {
return speakerId;
}
public String getSpeakerName() {
return speakerName;
}
public void setSpeakerId(String speakerId) {
this.speakerId = speakerId;
}
public void setSpeakerName(String speakerName) {
this.speakerName = speakerName;
}
}
| 20.439024 | 52 | 0.706444 |
3b91e7ee921057467d790fc1ed80a7ba857cc0e6 | 2,506 | package org.fbla.geason.ideacentrum;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.room.Room;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import static org.fbla.geason.ideacentrum.LoginActivity.PREFS_NAME;
import static org.fbla.geason.ideacentrum.LoginActivity.database;
public class MainActivity extends AppCompatActivity {
RecyclerView nodeView;
StaggeredGridLayoutManager mLayoutManager;
CentroidAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set nav bar
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add:
Intent toNewCentroidActivity = new Intent(MainActivity.this, NewCentroidActivity.class);
startActivity(toNewCentroidActivity);
break;
case R.id.action_home:
Intent toMainActivity = new Intent(MainActivity.this, MainActivity.class);
startActivity(toMainActivity);
break;
case R.id.action_profile:
Intent toProfileActivity = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(toProfileActivity);
break;
}
return true;
}
});
// Set up recyclerview
nodeView = findViewById(R.id.nodeView);
mAdapter = new CentroidAdapter(this);
mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
nodeView.setAdapter(mAdapter);
nodeView.setLayoutManager(mLayoutManager);
// Reload adapter
mAdapter.reload();
}
}
| 38.553846 | 126 | 0.674781 |
096917001959b03fab3499b14a102a9949c47e13 | 18,230 | /*
* 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.sis.referencing.operation.projection;
import java.util.Collections;
import org.opengis.util.FactoryException;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.operation.TransformException;
import org.apache.sis.internal.referencing.NilReferencingObject;
import org.apache.sis.internal.referencing.provider.SatelliteTracking;
import org.apache.sis.measure.Units;
import org.apache.sis.referencing.datum.DefaultEllipsoid;
import org.apache.sis.referencing.operation.transform.MathTransformFactoryMock;
import org.junit.Test;
import static java.lang.StrictMath.sin;
import static java.lang.StrictMath.toRadians;
import static org.junit.Assert.assertTrue;
/**
* Tests coordinates computed by applying a satellite-tracking projection with {@link SatelliteTracking}.
*
* @author Matthieu Bastianelli (Geomatys)
* @author Martin Desruisseaux (Geomatys)
* @version 1.1
* @since 1.1
* @module
*/
public final strictfp class SatelliteTrackingTest extends MapProjectionTestCase {
/**
* Creates a new instance of {@link SatelliteTracking} concatenated with the (de)normalization matrices.
* The new instance is stored in the inherited {@link #transform} field.
* This methods uses projection parameters for Landsat 3 satellite, namely:
*
* <table class="sis">
* <caption>Hard-coded projection parameters</caption>
* <tr><th>Symbol</th> <th>Value</th> <th>Meaning</th></tr>
* <tr><td>i</td> <td>99.092°</td> <td>Angle of inclination between the plane of the Earth's Equator and the plane of the satellite orbit.</td></tr>
* <tr><td>P1</td> <td>1440 minutes</td> <td>Length of Earth's rotation with respect to the precessed ascending node.</td></tr>
* <tr><td>P2</td> <td>103.267 minutes</td> <td>Time required for revolution of the satellite.</td></tr>
* </table>
*
* The Earth radius is set to 1.
*
* @param λ0 central meridian.
* @param φ0 latitude crossing the central meridian at the desired origin of rectangular coordinates.
* @param φ1 first parallel of conformality (with true scale).
* @param φ2 second parallel of conformality (without true scale), or -φ1 for a cylindrical projection.
*/
private void createForLandsat(final double λ0, final double φ0, final double φ1, final double φ2)
throws FactoryException
{
final SatelliteTracking provider = new SatelliteTracking();
final ParameterValueGroup values = provider.getParameters().createValue();
final DefaultEllipsoid sphere = DefaultEllipsoid.createEllipsoid(
Collections.singletonMap(DefaultEllipsoid.NAME_KEY, NilReferencingObject.UNNAMED), 1, 1, Units.METRE);
values.parameter("semi_major") .setValue(sphere.getSemiMajorAxis());
values.parameter("semi_minor") .setValue(sphere.getSemiMinorAxis());
values.parameter("central_meridian") .setValue(λ0);
values.parameter("latitude_of_origin") .setValue(φ0);
values.parameter("standard_parallel_1") .setValue(φ1);
values.parameter("standard_parallel_2") .setValue(φ2);
values.parameter("satellite_orbit_inclination").setValue( 99.092);
values.parameter("satellite_orbital_period") .setValue( 103.267, Units.MINUTE);
values.parameter("ascending_node_period") .setValue(1440.0, Units.MINUTE);
transform = new MathTransformFactoryMock(provider).createParameterizedTransform(values);
validate();
/*
* Assuming that tolerance has been set to the number of fraction digits published in Snyder tables,
* relax the tolerance during inverse transforms for taking in account the increase in magnitude of
* coordinate values. The transform results are between 0 and 1, while the inverse transform results
* are between -90° and 90°, which is an increase in magnitude close to ×100.
*/
tolerance *= 50; // Finer tolerance setting require GeoAPI 3.1.
}
/**
* Tests the projection of a few points using spherical formulas.
* Test based on the numerical example given by Snyder pages 360 to 363
* of <cite>Map Projections - A working Manual</cite>.
*
* @throws FactoryException if an error occurred while creating the map projection.
* @throws TransformException if an error occurred while projecting a point.
*/
@Test
public void testCylindricalTransform() throws FactoryException, TransformException {
tolerance = 1E-7; // Number of digits in the output values provided by Snyder.
createForLandsat(-90, 0, 30, -30);
assertTrue(isInverseTransformSupported);
verifyTransform(
new double[] { // (λ,φ) coordinates in degrees to project.
-75, 40
},
new double[] { // Expected (x,y) results on a unit sphere.
0.2267249, 0.6459071
});
}
/**
* Tests the projection of a few points using conic formulas.
* Test based on the numerical example given by Snyder pages 360 to 363
* of <cite>Map Projections - A working Manual</cite>.
*
* @throws FactoryException if an error occurred while creating the map projection.
* @throws TransformException if an error occurred while projecting a point.
*/
@Test
public void testConicTransform() throws FactoryException, TransformException {
tolerance = 1E-7; // Number of digits in the output values provided by Snyder.
createForLandsat(-90, 30, 45, 70);
assertTrue(isInverseTransformSupported);
verifyTransform(
new double[] { // (λ,φ) coordinates in degrees to project.
-75, 40
},
new double[] { // Expected (x,y) results on a unit sphere.
0.2001910, 0.2121685
});
/*
* Expected intermediate values (can be checked in a debugger):
*
* F₀ = 13.9686735°
* F₁ = 15.7111447°
* F₂ = 28.7497148°
*/
}
/**
* Compares the projection of a few points against expected values computed from intermediate values
* published by Snyder. Snyder tables in chapter 28 do not give directly the (x,y) values. Instead
* the tables give some intermediate values like <var>F₁</var>, which are verified in debugger.
* This method converts intermediate values to final coordinate values to compare.
*
* @param xScale scale to apply on <var>x</var> values.
* @param coordinates the points to transform.
* @param internal the expected intermediate transformation results.
* @throws TransformException if the transformation failed.
*/
private void verifyCylindricInternal(final double xScale, final double[] coordinates, final double[] internal)
throws TransformException
{
for (int i=0; i<internal.length; i += 2) {
internal[i] *= xScale;
}
verifyTransform(coordinates, internal);
}
/**
* Compares the projection of a few points against expected values computed from intermediate values
* published by Snyder. Snyder tables in chapter 28 do not give directly the (x,y) values. Instead
* the tables give some intermediate values like <var>F₁</var> and <var>n</var>, which are verified
* in debugger. This method converts intermediate values to final coordinate values to compare.
*
* @param λ0 central meridian.
* @param n cone factor <var>n</var>.
* @param coordinates the points to transform.
* @param internal the expected intermediate transformation results.
* @throws TransformException if the transformation failed.
*/
private void verifyConicInternal(final double λ0, final double n, final double[] coordinates, final double[] internal)
throws TransformException
{
for (int i=0; i<internal.length; i += 2) {
internal[i] *= sin(n * toRadians(coordinates[i] - λ0));
}
verifyTransform(coordinates, internal);
}
/**
* Tests the projection of a few points using cylindrical formulas.
* Test based on the sample coordinates for several of the Satellite-Tracking projections
* shown in table 38 of <cite>Map Projections - A working Manual</cite>.
*
* @throws FactoryException if an error occurred while creating the map projection.
* @throws TransformException if an error occurred while projecting a point.
*/
@Test
public void testCylindricalInternal() throws FactoryException, TransformException {
/*
* First group of 3 columns in Snyder table 38, for φ₁ = 0°.
* Snyder gives the following values, which can be verified in a debugger:
*
* F₁ = 13.09724° can be verified with toDegrees(atan(1/cotF))
* x = 0.017453⋅λ° can be verified with toRadians(cosφ1)
*
* Accuracy is set to the number of fraction digits published by Snyder (5 digits)
* with tolerance relaxed on the last digit. The verifyCylindricInternal(…) first
* argument is the factor in above x equation, with additional digits obtained by
* inspecting the value in a debugging session.
*/
tolerance = 4E-5;
createForLandsat(0, 0, 0, 0);
verifyCylindricInternal(0.017453292519943295, // See x in above comment.
new double[] { // (λ,φ) coordinates in degrees to project.
0, 0,
10, 0,
-10, 10,
60, 40,
80, 70,
-120, 80.908 // Tracking limit.
},
new double[] { // Expected (x,y) results on a unit sphere.
0, 0,
10, 0,
-10, 0.17579,
60, 0.79741,
80, 2.34465,
-120, 7.23571 // Projection of tracking limit.
});
/*
* Second group of 3 columns for φ₁ = -30°.
*
* F₁ = 13.96868°
* x = 0.015115⋅λ°
*/
createForLandsat(0, 0, -30, 30);
verifyCylindricInternal(0.015114994701951816, // See x in above comment.
new double[] {
0, 0,
10, 0,
-10, 10,
60, 40,
80, 70,
-120, 80.908 // Tracking limit.
},
new double[] {
0, 0,
10, 0,
-10, 0.14239,
60, 0.64591,
80, 1.89918,
-120, 5.86095
});
/*
* Third group of 3 columns for φ₁ = 45°
*
* F₁ = 15.71115°
* x = 0.012341⋅λ°
*/
createForLandsat(0, 0, 45, -45);
verifyCylindricInternal(0.012341341494884351, // See x in above comment.
new double[] {
0, 0,
10, 0,
-10, 10,
60, 40,
80, 70,
-120, 80.908 // Tracking limit.
},
new double[] {
0, 0,
10, 0,
-10, 0.10281,
60, 0.46636,
80, 1.37124,
-120, 4.23171
});
}
/**
* Tests the projection of a few points using conic formulas.
* Test based on the sample coordinates for several of the Satellite-Tracking projections
* shown in table 39 of <cite>Map Projections - A working Manual</cite>, page 238.
*
* @throws FactoryException if an error occurred while creating the map projection.
* @throws TransformException if an error occurred while projecting a point.
*/
@Test
public void testConicInternal() throws FactoryException, TransformException {
/*
* First group of 3 columns in Snyder table 38, for φ₁ = 30° and φ₂ = 60°.
* Snyder gives the following values, which can be verified in a debugger:
*
* F₁ = 13.96868° can be verified with toDegrees(F1)
* n = 0.49073
*
* Accuracy is set to the number of fraction digits published by Snyder (5 digits)
* with tolerance relaxed on the last digit. The verifyCylindricInternal(…) first
* argument is the factor in above x equation, with additional digits obtained by
* inspecting the value in a debugging session.
*/
tolerance = 3E-5;
createForLandsat(-90, 0, 30, 60);
verifyConicInternal(-90, 0.4907267554554259, // See n in above comment.
new double[] { // (λ,φ) coordinates in degrees to project.
0, -10,
0, 0,
0, 10,
0, 70,
-120, 80.908 // Tracking limit.
},
new double[] { // Expected (x,y) results on a unit sphere.
2.67991, 0.46093,
2.38332, 0.67369,
2.14662, 0.84348,
0.98470, 1.67697,
0.50439, 1.89549 // Projection of tracking limit.
});
/*
* Second group of 3 columns for φ₁ = 45° and φ₂ = 70°.
*
* F₁ = 15.71115°
* n = 0.69478
*/
createForLandsat(-90, 0, 45, 70);
verifyConicInternal(-90, 0.6947829166657693, // See n in above comment.
new double[] {
0, -10,
0, 0,
0, 10,
0, 70,
-120, 80.908 // Tracking limit.
},
new double[] {
2.92503, 0.90110,
2.25035, 1.21232,
1.82978, 1.40632,
0.57297, 1.98605,
0.28663, 1.982485
});
/*
* Second group of 3 columns for φ₁ = 45° and φ₂ = 80.908° (the tracking limit).
*
* F₁ = 15.71115°
* n = 0.88475
*/
createForLandsat(-90, 0, 45, 80.908);
verifyConicInternal(-90, 0.8847514352390218, // See n in above comment.
new double[] {
0, -10,
0, 0,
0, 10,
0, 70,
-120, 80.908 // Tracking limit.
},
new double[] {
4.79153, 1.80001,
2.66270, 2.18329,
1.84527, 2.33046,
0.40484, 2.58980,
0.21642, 2.46908
});
}
/**
* Tests the derivatives at a few points for cylindrical case. This method compares the derivatives computed
* by the projection with an estimation of derivatives computed by the finite differences method.
*
* @throws FactoryException if an error occurred while creating the map projection.
* @throws TransformException if an error occurred while projecting a point.
*/
@Test
public void testCylindricalDerivative() throws FactoryException, TransformException {
createForLandsat(-90, 0, 30, -30);
final double delta = (1.0 / 60) / 1852; // Approximately 1 metre.
derivativeDeltas = new double[] {delta, delta};
tolerance = 1E-4;
verifyDerivative( -75, 40);
verifyDerivative(-100, 3);
verifyDerivative( -56, 50);
verifyDerivative( -20, 47);
}
/**
* Tests the derivatives at a few points for conic case. This method compares the derivatives computed
* by the projection with an estimation of derivatives computed by the finite differences method.
*
* @throws FactoryException if an error occurred while creating the map projection.
* @throws TransformException if an error occurred while projecting a point.
*/
@Test
public void testConicDerivative() throws FactoryException, TransformException {
createForLandsat(-90, 30, 45, 70);
final double delta = (1.0 / 60) / 1852; // Approximately 1 metre.
derivativeDeltas = new double[] {delta, delta};
tolerance = 1E-4;
verifyDerivative( -75, 40);
verifyDerivative(-100, 3);
verifyDerivative( -56, 50);
verifyDerivative( -20, 47);
}
}
| 45.689223 | 163 | 0.567636 |
93fb149b1a239ea59bf4f669e5b8ee70161edf5d | 344 | package com.half.nock.springbootstartup;
import com.half.nock.quartz.spring.quartz.SchedulerFactoryBean;
import org.quartz.Scheduler;
//@Component
public class SchedulerBean {
private Scheduler scheduler;
public SchedulerBean() {
}
public SchedulerBean(Scheduler scheduler) {
this.scheduler = scheduler;
}
}
| 16.380952 | 63 | 0.726744 |
a22e3e3a97f41ab1bdc758faeaa07375b66ef08b | 570 | package us.ihmc.humanoidRobotics.footstep.footstepGenerator;
import us.ihmc.robotics.geometry.FramePose2d;
import us.ihmc.robotics.geometry.AbstractReferenceFrameHolder;
import us.ihmc.robotics.referenceFrames.ReferenceFrame;
/**
* Created by agrabertilton on 2/19/15.
*/
public abstract class FootstepOverheadPath extends AbstractReferenceFrameHolder
{
public abstract FramePose2d getPoseAtDistance(double distanceAlongPath);
public abstract double getTotalDistance();
public abstract FootstepOverheadPath changeFrameCopy(ReferenceFrame desiredFrame);
}
| 31.666667 | 85 | 0.836842 |
401bd86958e1660541ebdfa45edea54ae5221b73 | 1,061 | package com.google.gson.jpush.internal;
import com.google.gson.jpush.af;
import com.google.gson.jpush.b.a;
import com.google.gson.jpush.b.d;
import com.google.gson.jpush.internal.a.z;
import com.google.gson.jpush.w;
import com.google.gson.jpush.x;
import com.google.gson.jpush.y;
import java.io.Writer;
public final class ag {
public static w a(a aVar) {
Object obj = 1;
try {
aVar.f();
obj = null;
return (w) z.P.a(aVar);
} catch (Throwable e) {
if (obj != null) {
return y.a;
}
throw new af(e);
} catch (Throwable e2) {
throw new af(e2);
} catch (Throwable e22) {
throw new x(e22);
} catch (Throwable e222) {
throw new af(e222);
}
}
public static Writer a(Appendable appendable) {
return appendable instanceof Writer ? (Writer) appendable : new ah(appendable, (byte) 0);
}
public static void a(w wVar, d dVar) {
z.P.a(dVar, wVar);
}
}
| 25.878049 | 97 | 0.557022 |
12bc57b2ba4a1acfe17464e330b0b491d8a292a0 | 1,796 | package com.gjxaiou.dto;
import com.gjxaiou.entity.ShopCategory;
import com.gjxaiou.enums.OperationStatusEnum;
import com.gjxaiou.enums.ShopCategoryStateEnum;
import java.util.List;
/**
* @Description: 店铺类别类别返回结果信息
*/
public class ShopCategoryExecution {
// 结果状态
private int state;
// 状态标识
private String stateInfo;
// 操作的shopCategory(增删改店铺类别的时候用)
private ShopCategory shopCategory;
// 获取的shopCategory列表(查询店铺类别列表的时候用)
private List<ShopCategory> shopCategoryList;
public ShopCategoryExecution() {
}
// 店铺类别操作失败的时候使用的构造器
public ShopCategoryExecution(ShopCategoryStateEnum stateEnum) {
this.state = stateEnum.getState();
this.stateInfo = stateEnum.getStateInfo();
}
// 店铺类别操作成功的时候使用的构造器,基本操作
public ShopCategoryExecution(OperationStatusEnum stateEnum, ShopCategory shopCategory) {
this.state = stateEnum.getState();
this.stateInfo = stateEnum.getStateInfo();
this.shopCategory = shopCategory;
}
// 店铺类别操作成功的时候使用的构造器
public ShopCategoryExecution(OperationStatusEnum stateEnum, List<ShopCategory> shopCategoryList) {
this.state = stateEnum.getState();
this.stateInfo = stateEnum.getStateInfo();
this.shopCategoryList = shopCategoryList;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getStateInfo() {
return stateInfo;
}
public void setStateInfo(String stateInfo) {
this.stateInfo = stateInfo;
}
public ShopCategory getShopCategory() {
return shopCategory;
}
public void setShopCategory(ShopCategory shopCategory) {
this.shopCategory = shopCategory;
}
public List<ShopCategory> getShopCategoryList() {
return shopCategoryList;
}
public void setShopCategoryList(List<ShopCategory> shopCategoryList) {
this.shopCategoryList = shopCategoryList;
}
} | 21.638554 | 99 | 0.769488 |
4d436e61187c626b0047be31cc2817b4507623c7 | 6,439 | package com.zhbit.entity.excel;
import java.sql.Timestamp;
import org.zhbit.excel.annotation.Lang;
/**
* 项目名称:ElecRecord
* 类名称:Teacher
* 类描述: 教师信息实体类
* 创建人:谭柳
* 创建时间:2016年6月12日 上午12:39:28
* 修改人:TanLiu
* 修改时间:2016年6月12日 上午12:39:28
* 修改备注:
* @version
*/
public class TeachExcel extends BaseExcelBean implements java.io.Serializable,Cloneable {
private String id;
@Lang(value="职工号",isNull=Lang.TYPE_NONULL,isNum=Lang.TYPE_ISNUM)
private String employNo;
@Lang(value="姓名",isNull=Lang.TYPE_NONULL)
private String employName;
@Lang(value="性别")
private String sex;
@Lang(value="出生日期")
private String birthday;
@Lang(value="部门(学院)")
private String orgName;
@Lang(value="科室(系)")
private String department;
@Lang(value="联系电话",type="(1([\\d]{10})|((\\+[0-9]{2,4})?\\(?[0-9]+\\)?-?)?[0-9]{7,8})|(^\\d{6})")
private String telNo;
@Lang(value="E_mail地址",type=Lang.TYPE_EMAIL)
private String email;
@Lang(value="教职工类别")
private String category;
@Lang(value="学历")
private String education;
@Lang(value="学位")
private String degree;
@Lang(value="职务")
private String duty;
@Lang(value="职称")
private String acdemicTitle;
@Lang(value="派监考老师可用否")
private String invigilatorFlag;
@Lang(value="教学研究方向")
private String researchDirection;
@Lang(value="教师简介")
private String summary;
@Lang(value="专业名称")
private String major;
@Lang(value="毕业院校")
private String graduate;
@Lang(value="教师资格",toExcle={"有","无"},toEntity={"Y","N"})
private String qualificationFlag;
@Lang(value="教师级别")
private String level;
@Lang(value="是否实验室人员",toExcle={"是","否"},toEntity={"Y","N"})
private String isLab;
@Lang(value="是否外聘")
private String isOutHire;
@Lang(value="政治面貌")
private String politicalStatus;
@Lang(value="民族")
private String nation;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public TeachExcel() {
}
public TeachExcel(String id, String employNo, String employName, String sex, String birthday, String orgName,
String department, String telNo, String email, String category, String education, String degree,
String duty, String acdemicTitle, String invigilatorFlag, String researchDirection, String summary,
String major, String graduate, String qualificationFlag, String level, String isLab, String isOutHire,
String politicalStatus, String nation) {
super();
this.id = id;
this.employNo = employNo;
this.employName = employName;
this.sex = sex;
this.birthday = birthday;
this.orgName = orgName;
this.department = department;
this.telNo = telNo;
this.email = email;
this.category = category;
this.education = education;
this.degree = degree;
this.duty = duty;
this.acdemicTitle = acdemicTitle;
this.invigilatorFlag = invigilatorFlag;
this.researchDirection = researchDirection;
this.summary = summary;
this.major = major;
this.graduate = graduate;
this.qualificationFlag = qualificationFlag;
this.level = level;
this.isLab = isLab;
this.isOutHire = isOutHire;
this.politicalStatus = politicalStatus;
this.nation = nation;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmployNo() {
return employNo;
}
public void setEmployNo(String employNo) {
this.employNo = employNo;
}
public String getEmployName() {
return employName;
}
public void setEmployName(String employName) {
this.employName = employName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getTelNo() {
return telNo;
}
public void setTelNo(String telNo) {
this.telNo = telNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getDegree() {
return degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getDuty() {
return duty;
}
public void setDuty(String duty) {
this.duty = duty;
}
public String getAcdemicTitle() {
return acdemicTitle;
}
public void setAcdemicTitle(String acdemicTitle) {
this.acdemicTitle = acdemicTitle;
}
public String getInvigilatorFlag() {
return invigilatorFlag;
}
public void setInvigilatorFlag(String invigilatorFlag) {
this.invigilatorFlag = invigilatorFlag;
}
public String getResearchDirection() {
return researchDirection;
}
public void setResearchDirection(String researchDirection) {
this.researchDirection = researchDirection;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public String getGraduate() {
return graduate;
}
public void setGraduate(String graduate) {
this.graduate = graduate;
}
public String getQualificationFlag() {
return qualificationFlag;
}
public void setQualificationFlag(String qualificationFlag) {
this.qualificationFlag = qualificationFlag;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getIsLab() {
return isLab;
}
public void setIsLab(String isLab) {
this.isLab = isLab;
}
public String getIsOutHire() {
return isOutHire;
}
public void setIsOutHire(String isOutHire) {
this.isOutHire = isOutHire;
}
public String getPoliticalStatus() {
return politicalStatus;
}
public void setPoliticalStatus(String politicalStatus) {
this.politicalStatus = politicalStatus;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
} | 17.355795 | 110 | 0.707719 |
e29629722afdc99f7f5a261b01611445857418e4 | 471 | package rainbow.kuzwlu.core.annotation;
import java.lang.annotation.*;
/**
* @Author kuzwlu
* @Description 切换数据库注解, 默认master
* 一、无Service层
* 1、需要mapper接口上 标明@DataSource注解
* 二、有Service层
* 3、需要在service接口或者service接口的实现类 标明@DataSource注解
* @Date 2020/12/15 00:50
* @Email [email protected]
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
String value() default "master";
}
| 21.409091 | 51 | 0.73673 |
90f1263d7233a7bf801ceee1c2e778262bd1bc5f | 1,986 | package com.carr3r.waltsnspiders.lightbox;
import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import com.carr3r.waltsnspiders.R;
import com.carr3r.waltsnspiders.listeners.OnLightboxFinishes;
/**
* Created by wneto on 27/10/2015.
*/
public class LightboxWin extends DialogFragment implements View.OnClickListener {
protected OnLightboxFinishes listener;
public void setListener(OnLightboxFinishes newListener) {
listener = newListener;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.lightbox_win, container,
false);
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0));
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().setCancelable(false);
getDialog().getWindow().setDimAmount(0f);
getDialog().setCanceledOnTouchOutside(false);
((Button) rootView.findViewById(R.id.closeButton)).setOnClickListener(this);
// Do something else
return rootView;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new Dialog(getActivity(), getTheme()) {
@Override
public void onBackPressed() {
//do your stuff
System.exit(1);
}
};
}
public void setOnFinishListener(OnLightboxFinishes newListener) {
listener = newListener;
}
@Override
public void onClick(View v) {
getDialog().dismiss();
if (listener != null)
listener.onLightBoxFinishes(LightboxWin.class);
}
} | 29.641791 | 84 | 0.681269 |
14c5c0f9fb592796815359ccd43fcd1b610ad079 | 12,654 | /*
* Copyright (c) 2017 m2049r
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ////////////////
*
* Copyright (c) 2020 Scala
*
* Please see the included LICENSE file for more information.*/
package io.scalaproject.vault.data;
import android.net.Uri;
import io.scalaproject.vault.model.Wallet;
import io.scalaproject.vault.util.BitcoinAddressValidator;
import io.scalaproject.vault.util.OpenAliasHelper;
import io.scalaproject.vault.util.PaymentProtocolHelper;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import timber.log.Timber;
public class BarcodeData {
public static final String XLA_SCHEME = "scala:";
public static final String XLA_PAYMENTID = "tx_payment_id";
public static final String XLA_AMOUNT = "tx_amount";
public static final String XLA_DESCRIPTION = "tx_description";
public static final String OA_XLA_ASSET = "xla";
public static final String OA_BTC_ASSET = "btc";
static final String BTC_SCHEME = "bitcoin";
static final String BTC_DESCRIPTION = "message";
static final String BTC_AMOUNT = "amount";
static final String BTC_BIP70_PARM = "r";
public enum Asset {
XLA, BTC
}
public enum Security {
NORMAL,
OA_NO_DNSSEC,
OA_DNSSEC,
BIP70
}
final public Asset asset;
final public String address;
final public String addressName;
final public String amount;
final public String description;
final public Security security;
final public String bip70;
public BarcodeData(Asset asset, String address) {
this(asset, address, null, null, null, Security.NORMAL);
}
public BarcodeData(Asset asset, String address, String amount) {
this(asset, address, null, null, amount, Security.NORMAL);
}
public BarcodeData(Asset asset, String address, String amount, String description, Security security) {
this(asset, address, null, description, amount, security);
}
public BarcodeData(Asset asset, String address, String paymentId, String description, String amount) {
this(asset, address, null, description, amount, Security.NORMAL);
}
public BarcodeData(Asset asset, String address, String addressName, String description, String amount, Security security) {
this(asset, address, addressName, null, description, amount, security);
}
public BarcodeData(Asset asset, String address, String addressName, String bip70, String description, String amount, Security security) {
this.asset = asset;
this.address = address;
this.bip70 = bip70;
this.addressName = addressName;
this.description = description;
this.amount = amount;
this.security = security;
}
public Uri getUri() {
return Uri.parse(getUriString());
}
public String getUriString() {
if (asset != Asset.XLA) throw new IllegalStateException("We can only do XLA stuff!");
StringBuilder sb = new StringBuilder();
sb.append(BarcodeData.XLA_SCHEME).append(address);
boolean first = true;
if ((description != null) && !description.isEmpty()) {
sb.append(first ? "?" : "&");
first = false;
sb.append(BarcodeData.XLA_DESCRIPTION).append('=').append(Uri.encode(description));
}
if ((amount != null) && !amount.isEmpty()) {
sb.append(first ? "?" : "&");
sb.append(BarcodeData.XLA_AMOUNT).append('=').append(amount);
}
return sb.toString();
}
static public BarcodeData fromQrCode(String qrCode) {
// check for scala uri
BarcodeData bcData = parseScalaUri(qrCode);
// check for naked scala address / integrated address
if (bcData == null) {
bcData = parseScalaNaked(qrCode);
}
// check for btc uri
if (bcData == null) {
bcData = parseBitcoinUri(qrCode);
}
// check for btc payment uri (like bitpay)
if (bcData == null) {
bcData = parseBitcoinPaymentUrl(qrCode);
}
// check for naked btc address
if (bcData == null) {
bcData = parseBitcoinNaked(qrCode);
}
// check for OpenAlias
if (bcData == null) {
bcData = parseOpenAlias(qrCode, false);
}
return bcData;
}
/**
* Parse and decode a scala scheme string. It is here because it needs to validate the data.
*
* @param uri String containing a scala URL
* @return BarcodeData object or null if uri not valid
*/
static public BarcodeData parseScalaUri(String uri) {
Timber.d("parseScalaUri=%s", uri);
if (uri == null) return null;
if (!uri.startsWith(XLA_SCHEME)) return null;
String noScheme = uri.substring(XLA_SCHEME.length());
Uri scala = Uri.parse(noScheme);
Map<String, String> parms = new HashMap<>();
String query = scala.getEncodedQuery();
if (query != null) {
String[] args = query.split("&");
for (String arg : args) {
String[] namevalue = arg.split("=");
if (namevalue.length == 0) {
continue;
}
parms.put(Uri.decode(namevalue[0]).toLowerCase(),
namevalue.length > 1 ? Uri.decode(namevalue[1]) : "");
}
}
String address = scala.getPath();
String paymentId = parms.get(XLA_PAYMENTID);
// no support for payment ids!
if (paymentId != null) {
Timber.e("no support for payment ids!");
return null;
}
String description = parms.get(XLA_DESCRIPTION);
String amount = parms.get(XLA_AMOUNT);
if (amount != null) {
try {
Double.parseDouble(amount);
} catch (NumberFormatException ex) {
Timber.d(ex.getLocalizedMessage());
return null; // we have an amount but its not a number!
}
}
if (!Wallet.isAddressValid(address)) {
Timber.d("address invalid");
return null;
}
return new BarcodeData(Asset.XLA, address, paymentId, description, amount);
}
static public BarcodeData parseScalaNaked(String address) {
Timber.d("parseScalaNaked=%s", address);
if (address == null) return null;
if (!Wallet.isAddressValid(address)) {
Timber.d("address invalid");
return null;
}
return new BarcodeData(Asset.XLA, address);
}
// bitcoin:mpQ84J43EURZHkCnXbyQ4PpNDLLBqdsMW2?amount=0.01
// bitcoin:?r=https://bitpay.com/i/xxx
static public BarcodeData parseBitcoinUri(String uriString) {
Timber.d("parseBitcoinUri=%s", uriString);
if (uriString == null) return null;
URI uri;
try {
uri = new URI(uriString);
} catch (URISyntaxException ex) {
return null;
}
if (!uri.isOpaque() ||
!uri.getScheme().equals(BTC_SCHEME)) return null;
String[] parts = uri.getRawSchemeSpecificPart().split("[?]");
if ((parts.length <= 0) || (parts.length > 2)) {
Timber.d("invalid number of parts %d", parts.length);
return null;
}
Map<String, String> parms = new HashMap<>();
if (parts.length == 2) {
String[] args = parts[1].split("&");
for (String arg : args) {
String[] namevalue = arg.split("=");
if (namevalue.length == 0) {
continue;
}
parms.put(Uri.decode(namevalue[0]).toLowerCase(),
namevalue.length > 1 ? Uri.decode(namevalue[1]) : "");
}
}
String description = parms.get(BTC_DESCRIPTION);
String address = parts[0]; // no need to decode as there can bo no special characters
if (address.isEmpty()) { // possibly a BIP72 uri
String bip70 = parms.get(BTC_BIP70_PARM);
if (bip70 == null) {
Timber.d("no address and can't find pp url");
return null;
}
if (!PaymentProtocolHelper.isHttp(bip70)) {
Timber.d("[%s] is not http url", bip70);
return null;
}
return new BarcodeData(BarcodeData.Asset.BTC, null, null, bip70, description, null, Security.NORMAL);
}
if (!BitcoinAddressValidator.validate(address)) {
Timber.d("BTC address (%s) invalid", address);
return null;
}
String amount = parms.get(BTC_AMOUNT);
if ((amount != null) && (!amount.isEmpty())) {
try {
Double.parseDouble(amount);
} catch (NumberFormatException ex) {
Timber.d(ex.getLocalizedMessage());
return null; // we have an amount but its not a number!
}
}
return new BarcodeData(BarcodeData.Asset.BTC, address, null, description, amount);
}
// https://bitpay.com/invoice?id=xxx
// https://bitpay.com/i/KbMdd4EhnLXSbpWGKsaeo6
static public BarcodeData parseBitcoinPaymentUrl(String url) {
Timber.d("parseBitcoinUri=%s", url);
if (url == null) return null;
if (!PaymentProtocolHelper.isHttp(url)) {
Timber.d("[%s] is not http url", url);
return null;
}
return new BarcodeData(Asset.BTC, url);
}
static public BarcodeData parseBitcoinNaked(String address) {
Timber.d("parseBitcoinNaked=%s", address);
if (address == null) return null;
if (!BitcoinAddressValidator.validate(address)) {
Timber.d("address invalid");
return null;
}
return new BarcodeData(BarcodeData.Asset.BTC, address);
}
static public BarcodeData parseOpenAlias(String oaString, boolean dnssec) {
Timber.d("parseOpenAlias=%s", oaString);
if (oaString == null) return null;
Map<String, String> oaAttrs = OpenAliasHelper.parse(oaString);
if (oaAttrs == null) return null;
String oaAsset = oaAttrs.get(OpenAliasHelper.OA1_ASSET);
if (oaAsset == null) return null;
String address = oaAttrs.get(OpenAliasHelper.OA1_ADDRESS);
if (address == null) return null;
Asset asset;
if (OA_XLA_ASSET.equals(oaAsset)) {
if (!Wallet.isAddressValid(address)) {
Timber.d("XLA address invalid");
return null;
}
asset = Asset.XLA;
} else if (OA_BTC_ASSET.equals(oaAsset)) {
if (!BitcoinAddressValidator.validate(address)) {
Timber.d("BTC address invalid");
return null;
}
asset = Asset.BTC;
} else {
Timber.i("Unsupported OpenAlias asset %s", oaAsset);
return null;
}
String paymentId = oaAttrs.get(OpenAliasHelper.OA1_PAYMENTID);
String description = oaAttrs.get(OpenAliasHelper.OA1_DESCRIPTION);
if (description == null) {
description = oaAttrs.get(OpenAliasHelper.OA1_NAME);
}
String amount = oaAttrs.get(OpenAliasHelper.OA1_AMOUNT);
String addressName = oaAttrs.get(OpenAliasHelper.OA1_NAME);
if (amount != null) {
try {
Double.parseDouble(amount);
} catch (NumberFormatException ex) {
Timber.d(ex.getLocalizedMessage());
return null; // we have an amount but its not a number!
}
}
if ((paymentId != null) && !Wallet.isPaymentIdValid(paymentId)) {
Timber.d("paymentId invalid");
return null;
}
Security sec = dnssec ? BarcodeData.Security.OA_DNSSEC : BarcodeData.Security.OA_NO_DNSSEC;
return new BarcodeData(asset, address, addressName, paymentId, description, amount, sec);
}
} | 34.668493 | 141 | 0.593567 |
ee64132ad9e634528df03da47180f7c0a83b94f1 | 1,139 | package net.volus.ronwalf.phs2010.networking.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import net.volus.ronwalf.phs2010.networking.raw.RawMessageCodecFactory;
import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.logging.MdcInjectionFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
public class SampleServer {
public static void main(String... args) throws IOException {
int localPort = Integer.parseInt(args[0]);
IoFilter LOGGING_FILTER = new LoggingFilter();
IoAcceptor acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast("mdc", new MdcInjectionFilter());
acceptor.getFilterChain().addLast(
"codec",
new ProtocolCodecFilter( new RawMessageCodecFactory() ));
acceptor.getFilterChain().addLast("logger", LOGGING_FILTER);
acceptor.setHandler(new SampleServerHandler(new SampleServer()));
acceptor.bind( new InetSocketAddress( localPort ) );
}
}
| 32.542857 | 71 | 0.788411 |
0b927be8f40556a24488e7cf9e38ecf4a4151403 | 1,832 | import java.io.*;
import java.util.*;
public class Sln {
// An entry in queue used in BFS
static class qentry {
int v;// Vertex number
int dist;// Distance of this vertex from source
}
static int getMinDiceThrows(int move[], int n) {
boolean visited[] = new boolean[n];
Queue<qentry> q = new LinkedList<>();
qentry qe = new qentry();
qe.v = 0;
qe.dist = 0;
// Mark the node 0 as visited and enqueue it.
visited[0] = true;
q.add(qe);
// Do a BFS starting from vertex at index 0
while (!q.isEmpty()) {
qe = q.remove();
int v = qe.v;
if (v == n - 1){
return qe.dist;
}
for (int j = v + 1; j <= (v + 6) && j < n; j++) {
// If this cell is already visited, then ignore
if (visited[j] == false) {
qentry a = new qentry();
a.dist = (qe.dist + 1);
visited[j] = true;
if (move[j] != -1)
a.v = move[j];
else
a.v = j;
q.add(a);
}
}
}
//not ordinarily reach
return -1;
}
public static void main(String[] args) {
// Let us construct the board given in above diagram
int N = 25;
int moves[] = new int[N];
Arrays.fill(moves,-1);
// Ladders
moves[2] = 21;
moves[4] = 7;
moves[10] = 25;
moves[19] = 28;
// Snakes
moves[26] = 0;
moves[20] = 8;
moves[16] = 3;
moves[18] = 6;
System.out.println("Min Dice throws required is " +
getMinDiceThrows(moves, N));
}
} | 28.625 | 63 | 0.42631 |
be42168500abb2abaa28c7c3c68880820fb018e5 | 724 | import javax.swing.text.html.parser.Entity;
public class Homework3 {
public static void main(String[] args) {
// 3. 1, 1, 1, 2, 3, 4, 6, 9, 13, 19, 28, 41, 88, 129 ,,,
// 이와 같은 숫자의 규칙을 찾아 25번째 항을 구하도록 프로그램 해보자!
/*
1. 수열의 패턴 파악후 상자만들기 (상자 4개)
2. 루프돌리기 end값 25
3. 값출력하기
*/
int first = 1;
int second = 1;
int third = 1;
int result = 0, i;
final int Start = 3;
final int End = 25;
for (i = Start; i < End; i++) {
result = first + third;
first = second;
second = third;
third = result;
}
System.out.printf("%d번째 항 %d\n", i , result);
}
}
| 22.625 | 65 | 0.455801 |
66b72b7a7a121468644b21ee3f3ed2c2a76ec841 | 1,471 | /*******************************************************************************
* Copyright 2014 The MITRE Corporation
* and the MIT Kerberos and Internet Trust Consortium
*
* 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.mitre.oauth2.service;
import java.util.Set;
import org.springframework.security.oauth2.provider.ClientDetails;
/**
* Strategy interface used for authorizing token introspection.
*/
public interface IntrospectionAuthorizer {
/**
* @param authClient the authenticated client wanting to perform token introspection
* @param tokenClient the client the token was issued to
* @param tokenScope the scope associated with the token
* @return {@code true} in case introspection is permitted; {@code false} otherwise
*/
boolean isIntrospectionPermitted(ClientDetails authClient, ClientDetails tokenClient, Set<String> tokenScope);
}
| 39.756757 | 111 | 0.683209 |
6e0538a583299055cd0aa672520fd981a0c71f64 | 512 | package com.eg.test;
/*
有一家农场,养了一群小动物。养的有鸡40只,羊10只,牛2头。
其中鸡全是母鸡,每只母鸡每个月有20天下蛋,每次下蛋1颗,其余时间休息。
每年2月份农夫会人工孵化鸡蛋剩余数的20%,其余鸡蛋全部出售,并且会出售或宰杀20%母鸡。
孵化出来的小鸡全是母鸡,小鸡一年之后开始下蛋。
羊群里面有8只母羊,2只公羊。每只母羊每年10月生产5只小羊,性别随机。
每年2月农夫出售20%羊,公羊母羊各一半(若为20%的羊数为奇数,多的那一头羊为公羊)。
小羊2年后开始生产,性别随机。
公牛和母牛各1头,每2年生产1只小牛。小牛2年会后开始生产,小牛的性别随机。
现在是2017年9月1日,请问10年后农产有多少只鸡,多少头养,多少头牛?
请问10年后动物的头和脚的数量各是多少。同时请注意闰年天数。
*/
public abstract class Animal {
public int mHead = 1;
public int mFeet = 2;
public abstract void procreate(int month, int year);
}
| 21.333333 | 54 | 0.798828 |
1e73580ec68e5895b52e4f27528d2a77c1afcdb1 | 3,911 | package com.qunar.im.base.util;
import android.util.Base64;
import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class CodeUtil {
public static final String PASSWORD_ENC_SECRET = "mythmayor";
public static String decodeString(String str) {
if (str == null) {
return "转换失败";
}
byte[] s = pack(str); //十六进制转byte数组
String gbk;
try {
gbk = new String(s, "gbk"); //byte数组转中文字符串
} catch (UnsupportedEncodingException ignored) {
gbk = "转换失败";
}
return gbk;
}
public static byte[] pack(String str) {
int nibbleshift = 4;
int position = 0;
int len = str.length() / 2 + str.length() % 2;
byte[] output = new byte[len];
for (char v : str.toCharArray()) {
byte n = (byte) v;
if (n >= '0' && n <= '9') {
n -= '0';
} else if (n >= 'A' && n <= 'F') {
n -= ('A' - 10);
} else if (n >= 'a' && n <= 'f') {
n -= ('a' - 10);
} else {
continue;
}
output[position] |= (n << nibbleshift);
if (nibbleshift == 0) {
position++;
}
nibbleshift = (nibbleshift + 4) & 7;
}
return output;
}
/**
* 2 * 中文字符串转十六进制
* 3
*/
public static String decodeShiLiu(String str) {
if (str == null) {
return "转换失败";
}
String gbk;
try {
byte[] sss = str.getBytes("GBK"); //中文字符串转byte数组
gbk = unpack(sss); // byte数组转十六进制
} catch (Exception E) {
gbk = "转换失败";
}
return gbk;
}
/**
* 2 * byte数组转十六进制,模拟php中unpack
* 3
*/
public static String unpack(byte[] bytes) {
StringBuilder stringBuilder = new StringBuilder("");
if (bytes == null || bytes.length <= 0) {
return null;
}
for (int i = 0; i < bytes.length; i++) {
int v = bytes[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* 加密
**/
public static String encryptPassword(String clearText) {
try {
DESKeySpec keySpec = new DESKeySpec(
PASSWORD_ENC_SECRET.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
String encrypedPwd = Base64.encodeToString(cipher.doFinal(clearText
.getBytes("UTF-8")), Base64.DEFAULT);
return encrypedPwd;
} catch (Exception e) {
}
return clearText;
}
/**
* 解密
**/
public static String decryptPassword(String encryptedPwd) {
try {
DESKeySpec keySpec = new DESKeySpec(PASSWORD_ENC_SECRET.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
byte[] encryptedWithoutB64 = Base64.decode(encryptedPwd, Base64.DEFAULT);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainTextPwdBytes = cipher.doFinal(encryptedWithoutB64);
return new String(plainTextPwdBytes);
} catch (Exception e) {
}
return encryptedPwd;
}
}
| 27.737589 | 87 | 0.516748 |
4fefdff0934aa3fe8cd8737839dbc6b84fb4a0ee | 823 | package io.smallrye.openapi.runtime.io.link;
/**
* Constants related to Link
*
* @see <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#linkObject">linkObject</a>
*
* @author Phillip Kruger ([email protected])
* @author Eric Wittmann ([email protected])
*/
public class LinkConstant {
static final String PROP_OPERATION_ID = "operationId";
static final String PROP_PARAMETERS = "parameters";
static final String PROP_NAME = "name";
static final String PROP_OPERATION_REF = "operationRef";
static final String PROP_SERVER = "server";
static final String PROP_EXPRESSION = "expression";
static final String PROP_DESCRIPTION = "description";
static final String PROP_REQUEST_BODY = "requestBody";
private LinkConstant() {
}
}
| 32.92 | 118 | 0.72661 |
525c684e55f0f4c91025c87f1017c722e0102f4a | 95,619 | /*
* Interpreter.java
* Copyright © 1993-2018, The Avail Foundation, LLC.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.avail.interpreter;
import com.avail.AvailRuntime;
import com.avail.AvailRuntime.HookType;
import com.avail.AvailRuntimeConfiguration;
import com.avail.AvailTask;
import com.avail.AvailThread;
import com.avail.annotations.InnerAccess;
import com.avail.descriptor.*;
import com.avail.exceptions.AvailErrorCode;
import com.avail.exceptions.AvailException;
import com.avail.exceptions.AvailRuntimeException;
import com.avail.interpreter.Primitive.Result;
import com.avail.interpreter.levelTwo.L1InstructionStepper;
import com.avail.interpreter.levelTwo.L2Chunk;
import com.avail.interpreter.levelTwo.L2Instruction;
import com.avail.interpreter.levelTwo.operation.L2_INVOKE;
import com.avail.interpreter.levelTwo.operation.L2_REIFY.StatisticCategory;
import com.avail.interpreter.primitive.controlflow.P_CatchException;
import com.avail.interpreter.primitive.fibers.P_AttemptJoinFiber;
import com.avail.interpreter.primitive.fibers.P_ParkCurrentFiber;
import com.avail.interpreter.primitive.variables.P_SetValue;
import com.avail.io.TextInterface;
import com.avail.optimizer.StackReifier;
import com.avail.optimizer.jvm.ReferencedInGeneratedCode;
import com.avail.performance.PerInterpreterStatistic;
import com.avail.performance.Statistic;
import com.avail.performance.StatisticReport;
import com.avail.utility.MutableOrNull;
import com.avail.utility.Strings;
import com.avail.utility.evaluation.Continuation0;
import com.avail.utility.evaluation.Continuation1;
import com.avail.utility.evaluation.Continuation1NotNull;
import com.avail.utility.evaluation.Continuation2NotNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.avail.AvailRuntime.HookType.STRINGIFICATION;
import static com.avail.AvailRuntime.currentRuntime;
import static com.avail.AvailRuntimeSupport.captureNanos;
import static com.avail.descriptor.CompiledCodeDescriptor.newPrimitiveRawFunction;
import static com.avail.descriptor.FiberDescriptor.*;
import static com.avail.descriptor.FiberDescriptor.ExecutionState.*;
import static com.avail.descriptor.FiberDescriptor.InterruptRequestFlag.REIFICATION_REQUESTED;
import static com.avail.descriptor.FiberDescriptor.SynchronizationFlag.BOUND;
import static com.avail.descriptor.FiberDescriptor.SynchronizationFlag.PERMIT_UNAVAILABLE;
import static com.avail.descriptor.FiberDescriptor.TraceFlag.TRACE_VARIABLE_READS_BEFORE_WRITES;
import static com.avail.descriptor.FiberDescriptor.TraceFlag.TRACE_VARIABLE_WRITES;
import static com.avail.descriptor.FunctionDescriptor.createFunction;
import static com.avail.descriptor.NilDescriptor.nil;
import static com.avail.descriptor.ObjectTupleDescriptor.tupleFromList;
import static com.avail.descriptor.StringDescriptor.formatString;
import static com.avail.descriptor.StringDescriptor.stringFrom;
import static com.avail.descriptor.TupleDescriptor.emptyTuple;
import static com.avail.descriptor.TupleTypeDescriptor.stringType;
import static com.avail.exceptions.AvailErrorCode.*;
import static com.avail.interpreter.Interpreter.FakeStackTraceSlots.*;
import static com.avail.interpreter.Primitive.Flag.CanSuspend;
import static com.avail.interpreter.Primitive.Flag.CannotFail;
import static com.avail.interpreter.Primitive.Result.*;
import static com.avail.interpreter.levelTwo.operation.L2_REIFY.StatisticCategory.ABANDON_BEFORE_RESTART_IN_L2;
import static com.avail.interpreter.primitive.variables.P_SetValue.instance;
import static com.avail.utility.Nulls.stripNull;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
/**
* This class is used to execute {@linkplain L2Chunk Level Two code}, which is a
* translation of the Level One nybblecodes found in {@linkplain
* CompiledCodeDescriptor compiled code}.
*
* <p>
* Level One nybblecodes are designed to be compact and very simple, but not
* particularly efficiently executable. Level Two is designed for a clean model
* for optimization, including:
* </p>
* <ul>
* <li>primitive folding.</li>
* <li>register coloring/allocation.</li>
* <li>inlining.</li>
* <li>common sub-expression elimination.</li>
* <li>side-effect analysis.</li>
* <li>object escape analysis.</li>
* <li>a variant of keyhole optimization that involves building the loosest
* possible Level Two instruction dependency graph, then "pulling" eligible
* instruction sequences that are profitably rewritten.</li>
* <li>further translation to native code – although the current plan is to
* generate Java bytecodes to leverage the enormous amount of effort that went
* into the bytecode verifier, concurrency semantics, and HotSpot's low-level
* optimizations.</li>
* </ul>
*
* <p>
* As of 2011.05.09, only the first of these optimizations has been implemented,
* although a translation into Smalltalk blocks was implemented experimentally
* by Mark van Gulik in the mid-1990s.
* </p>
*
* <p>
* To accomplish these goals, the stack-oriented architecture of Level One maps
* onto a register transfer language for Level Two. At runtime the idealized
* {@code Interpreter interpreter} has an arbitrarily large bank of
* pointer registers (that point to {@linkplain AvailObject Avail objects}),
* plus a separate bank for {@code int}s (unboxed 32-bit signed integers), and a
* similar bank for {@code double}s (unboxed double-precision floating point
* numbers). Ideally these will map to machine registers, but more likely they
* will spill into physical arrays of the appropriate type. Register spilling is
* a well studied art, and essentially a solved problem. Better yet, the Java
* HotSpot optimizer should be able to do at least as good a job as we can, so
* we should be able to just generate Java bytecodes and leave it at that.
* </p>
*
* <p>
* One of the less intuitive aspects of the Level One / Level Two mapping is how
* to handle the call stack. The Level One view is of a chain of continuations,
* but Level Two doesn't even have a stack! We bridge this disconnect by
* reserving a register to hold the Level One continuation of the
* <em>caller</em> of the current method. This is at least vaguely analogous to
* the way that high level languages typically implement their calling
* conventions using stack frames and such.
* </p>
*
* <p>
* However, our target is not assembly language (nor something that purports to
* operate at that level in some platform-neutral way). Instead, our target
* language, Level Two, is designed for representing and performing
* optimization. With this in mind, the Level Two instruction set includes an
* instruction that constructs a new continuation from a list of registers. A
* corresponding instruction "explodes" a continuation into registers reserved
* as part of the calling convention (strictly enforced). During transition from
* caller to callee (and vice-versa), the only registers that hold usable state
* are the "architectural" registers – those that hold the state of a
* continuation being constructed or deconstructed. This sounds brutally
* inefficient, but time will tell. Also, I have devised and implemented
* mechanisms to allow deeper inlining than would normally be possible in a
* traditional system, the explicit construction and deconstruction of
* continuations being one such mechanism.
* </p>
*
* <p>
* Note that unlike languages like C and C++, optimizations below Level One are
* always transparent – other than observations about performance and memory
* use. Also note that this was a design constraint for Avail as far back as
* 1993, after <span style="font-variant: small-caps;">Self</span>, but before
* its technological successor Java. The way in which this is accomplished (or
* will be more fully accomplished) in Avail is by allowing the generated level
* two code itself to define how to maintain the "accurate fiction" of a level
* one interpreter. If a method is inlined ten layers deep inside an outer
* method, a non-inlined call from that inner method requires ten layers of
* continuations to be constructed prior to the call (to accurately maintain the
* fiction that it was always simply interpreting Level One nybblecodes). There
* are ways to avoid or at least postpone this phase transition, but I don't
* have any solid plans for introducing such a mechanism any time soon.
* </p>
*
* <p>
* Finally, note that the Avail control structures are defined in terms of
* multimethod dispatch and continuation resumption. As of 2011.05.09 they are
* also <em>implemented</em> that way, but a goal is to perform object escape
* analysis in such a way that it deeply favors chasing continuations. If
* successful, a continuation resumption can basically be rewritten as a jump,
* leading to a more traditional control flow in the typical case, which should
* be much easier to further optimize (say with SSA) than code which literally
* passes and resumes continuations. In those cases that the continuation
* actually escapes (say, if the continuations are used for backtracking) then
* it can't dissolve into a simple jump – but it will still execute correctly,
* just not as quickly.
* </p>
*
* @author Mark van Gulik <[email protected]>
* @author Todd L Smith <[email protected]>
*/
public final class Interpreter
{
/** Whether to print detailed Level One debug information. */
public static volatile boolean debugL1 = false;
/** Whether to print detailed Level Two debug information. */
public static volatile boolean debugL2 = false;
/** Whether to print detailed Primitive debug information. */
public static volatile boolean debugPrimitives = false;
/**
* Whether to print detailed debug information related to compiler/lexer
* work unit tracking.
* */
public static volatile boolean debugWorkUnits = false;
/**
* Whether to divert logging into fibers' {@link A_Fiber#debugLog()}, which
* is simply a length-bounded StringBuilder. This is <em>by far</em> the
* fastest available way to log, although message pattern substitution is
* still unnecessarily slow.
*
* <p>Note that this only has an effect if one of the above debug flags is
* set.</p>
*/
public static final boolean debugIntoFiberDebugLog = true;
/**
* Whether to print debug information related to a specific problem being
* debugged with a custom VM. This is a convenience flag and will be
* inaccessible in a production VM.
*/
public static volatile boolean debugCustom = false;
/** A {@linkplain Logger logger}. */
private static final Logger mainLogger =
Logger.getLogger(Interpreter.class.getCanonicalName());
/** A {@linkplain Logger logger}. */
public static final Logger loggerDebugL1 =
Logger.getLogger(Interpreter.class.getCanonicalName() + ".debugL1");
/** A {@linkplain Logger logger}. */
public static final Logger loggerDebugL2 =
Logger.getLogger(Interpreter.class.getCanonicalName() + ".debugL2");
/** A {@linkplain Logger logger}. */
public static final Logger loggerDebugJVM =
Logger.getLogger(Interpreter.class.getCanonicalName() + ".debugJVM");
/** A {@linkplain Logger logger}. */
private static final Logger loggerDebugPrimitives =
Logger.getLogger(
Interpreter.class.getCanonicalName() + ".debugPrimitives");
/**
* Set the current logging level for interpreters.
*
* @param level The new logging {@link Level}.
*/
public static void setLoggerLevel (final Level level)
{
mainLogger.setLevel(level);
loggerDebugL1.setLevel(level);
loggerDebugL2.setLevel(level);
loggerDebugJVM.setLevel(level);
loggerDebugPrimitives.setLevel(level);
}
/**
* Log a message.
*
* @param logger The logger on which to log.
* @param level The verbosity level at which to log.
* @param message The message pattern to log.
* @param arguments The arguments to fill into the message pattern.
*/
public static void log (
final Logger logger,
final Level level,
final String message,
final Object... arguments)
{
if (logger.isLoggable(level))
{
log(
AvailThread.currentOrNull() != null
? Interpreter.current().fiber
: null,
logger,
level,
message,
arguments);
}
}
/**
* The approximate maximum number of bytes to log per fiber before throwing
* away the earliest 25%.
*/
private static final int maxFiberLogLength = 1_000_000;
/**
* Log a message.
*
* @param affectedFiber The affected fiber or null.
* @param logger The logger on which to log.
* @param level The verbosity level at which to log.
* @param message The message pattern to log.
* @param arguments The arguments to fill into the message pattern.
*/
public static void log (
final @Nullable A_Fiber affectedFiber,
final Logger logger,
final Level level,
final String message,
final Object... arguments)
{
if (logger.isLoggable(level))
{
final @Nullable Interpreter interpreter = currentOrNull();
final @Nullable A_Fiber runningFiber = interpreter != null
? interpreter.fiberOrNull()
: null;
if (debugIntoFiberDebugLog)
{
// Write into a StringBuilder in each fiber's debugLog().
if (runningFiber != null)
{
// Log to the fiber.
final StringBuilder log = runningFiber.debugLog();
Strings.tab(log, interpreter.unreifiedCallDepth);
if (log.length() > maxFiberLogLength)
{
log.delete(0, maxFiberLogLength >> 4);
}
log.append(MessageFormat.format(message, arguments));
log.append('\n');
}
// Ignore the bit of logging not tied to a specific fiber.
return;
}
@SuppressWarnings("StringBufferReplaceableByString")
final StringBuilder builder = new StringBuilder();
builder.append(
runningFiber != null
? format("%6d ", runningFiber.uniqueId())
: "?????? ");
builder.append("→ ");
builder.append(
affectedFiber != null
? format("%6d ", affectedFiber.uniqueId())
: "?????? ");
logger.log(level, builder + message, arguments);
}
}
/**
* Answer the Avail interpreter associated with the {@linkplain
* Thread#currentThread() current thread}. If this thread is not an {@link
* AvailThread}, then fail.
*
* @return The current Level Two interpreter.
*/
public static Interpreter current ()
{
return AvailThread.current().interpreter;
}
/**
* Answer the unique {@link #interpreterIndex} of the Avail interpreter
* associated with the {@linkplain Thread#currentThread() current thread}.
* If this thread is not an {@link AvailThread}, then fail.
*
* @return The current Avail {@code Interpreter}'s unique index.
*/
public static int currentIndex ()
{
return AvailThread.current().interpreter.interpreterIndex;
}
/**
* The {@linkplain FiberDescriptor fiber} that is currently locked for this
* interpreter, or {@code null} if no fiber is currently locked. This
* information is used to prevent multiple fibers from being locked
* simultaneously within a thread, which can lead to deadlock.
*
* This does not have to be volatile or atomic, since only this interpreter
* can access the field, and this interpreter can only be accessed from the
* single dedicated AvailThread that it's permanently associated with.
*/
private @Nullable A_Fiber currentlyLockedFiber = null;
/**
* Lock the specified fiber for the duration of evaluation of the provided
* {@link Supplier}. Answer the result produced by the supplier.
*
* @param aFiber The fiber to lock.
* @param supplier What to execute while the fiber is locked
* @param <T> The type of value that the supplier will return.
* @return The value produced by the supplier.
*/
public <T> T lockFiberWhile (
final A_Fiber aFiber,
final Supplier<T> supplier)
{
final @Nullable A_Fiber previousFiber = currentlyLockedFiber;
assert previousFiber == null || previousFiber == aFiber;
currentlyLockedFiber = aFiber;
try
{
return supplier.get();
}
finally
{
currentlyLockedFiber = previousFiber;
}
}
/**
* Answer the Avail interpreter associated with the {@linkplain
* Thread#currentThread() current thread}. If this thread is not an {@link
* AvailThread}, then answer {@code null}.
*
* @return The current Avail {@code Interpreter}, or {@code null} if the
* current {@link Thread} is not an {@link AvailThread}.
*/
public static @Nullable Interpreter currentOrNull ()
{
final @Nullable AvailThread current = AvailThread.currentOrNull();
if (current != null)
{
return current.interpreter;
}
return null;
}
/**
* Answer how many continuations would be created from Java stack frames at
* the current execution point (or the nearest place reification may be
* triggered).
*
* @return The current number of unreified frames.
*/
public int unreifiedCallDepth ()
{
return unreifiedCallDepth;
}
/**
* Add the delta to the current count of how many frames would be reified
* into continuations at the current execution point.
*
* @param delta How much to add.
*/
public void adjustUnreifiedCallDepthBy (final int delta)
{
if (debugL1 || debugL2)
{
log(
loggerDebugL2,
Level.FINER,
"{0}Depth: {1} → {2}",
debugModeString,
unreifiedCallDepth,
unreifiedCallDepth + delta);
}
unreifiedCallDepth += delta;
}
/**
* Fake slots used to show stack traces in the Eclipse Java debugger.
*/
enum FakeStackTraceSlots
implements ObjectSlotsEnum, IntegerSlotsEnum
{
/**
* The offset of the current L2 instruction.
*/
L2_OFFSET,
/**
* The current frame's L2 instructions.
*/
L2_INSTRUCTIONS,
/**
* The function that was being executed.
*/
CURRENT_FUNCTION,
/**
* The chain of {@linkplain ContinuationDescriptor continuations} of the
* {@linkplain FiberDescriptor fiber} bound to this
* {@linkplain Interpreter interpreter}.
*/
FRAMES,
/** The current {@link AvailLoader}, if any. */
LOADER
}
/**
* Utility method for decomposing this object in the debugger. See
* {@link AvailObjectFieldHelper} for instructions to enable this
* functionality in Eclipse.
*
* <p>
* In particular, an Interpreter should present (possible among other
* things) a complete stack trace of the current fiber, converting the deep
* continuation structure into a list of continuation substitutes that
* <em>do not</em> recursively print the caller chain.
* </p>
*
* @return An array of {@link AvailObjectFieldHelper} objects that help
* describe the logical structure of the receiver to the debugger.
*/
@SuppressWarnings("unused")
public AvailObjectFieldHelper[] describeForDebugger ()
{
final Object[] outerArray =
new Object[FakeStackTraceSlots.values().length];
// Extract the current L2 offset...
outerArray[L2_OFFSET.ordinal()] = new AvailIntegerValueHelper(offset);
// Produce the current chunk's L2 instructions...
outerArray[L2_INSTRUCTIONS.ordinal()] = chunk != null
? chunk.instructions
: emptyList();
// Produce the current function being executed...
outerArray[CURRENT_FUNCTION.ordinal()] = function;
// Build the stack frames...
@Nullable A_Continuation frame = reifiedContinuation;
if (frame != null)
{
final List<A_Continuation> frames = new ArrayList<>(50);
while (!frame.equalsNil())
{
frames.add(frame);
frame = frame.caller();
}
outerArray[FRAMES.ordinal()] = tupleFromList(frames);
}
outerArray[LOADER.ordinal()] = availLoaderOrNull();
// Now put all the top level constructs together...
final AvailObjectFieldHelper[] helpers =
new AvailObjectFieldHelper[FakeStackTraceSlots.values().length];
for (final FakeStackTraceSlots field : FakeStackTraceSlots.values())
{
helpers[field.ordinal()] = new AvailObjectFieldHelper(
nil,
field,
-1,
outerArray[field.ordinal()]);
}
return helpers;
}
/**
* This {@linkplain Interpreter interpreter}'s {@linkplain AvailRuntime
* Avail runtime}
*/
private final AvailRuntime runtime;
/**
* Answer the {@link AvailRuntime} permanently used by this interpreter.
*
* @return This interpreter's runtime.
*/
@ReferencedInGeneratedCode
public AvailRuntime runtime ()
{
return runtime;
}
/**
* Capture a unique ID between 0 and {@link
* AvailRuntimeConfiguration#maxInterpreters} minus one.
*/
public final int interpreterIndex;
/** Text to show at the starts of lines in debug traces. */
public String debugModeString = "";
/**
* Construct a new {@code Interpreter}.
*
* @param runtime
* An {@link AvailRuntime}.
*/
public Interpreter (final AvailRuntime runtime)
{
this.runtime = runtime;
interpreterIndex = runtime.allocateInterpreterIndex();
}
/**
* The {@link AvailLoader} associated with the {@link A_Fiber fiber}
* currently running on this interpreter. This is {@code null} if there is
* no fiber, or if it is not associated with an AvailLoader.
*
* <p>This field is a consistent cache of the AvailLoader found in the
* fiber, which is authoritative. Multiple fibers may share the same
* AvailLoader.</p>
*/
private @Nullable AvailLoader availLoader;
/**
* Answer the {@link AvailLoader} associated with the {@link A_Fiber fiber}
* currently running on this interpreter. This interpreter must be bound
* to a fiber having an AvailLoader.
*
* @return The current fiber's {@link AvailLoader}.
*/
public AvailLoader availLoader ()
{
return stripNull(availLoader);
}
/**
* Answer the {@link AvailLoader} associated with the {@link A_Fiber fiber}
* currently running on this interpreter. Answer {@code null} if there is
* no AvailLoader for the current fiber.
*
* @return The current fiber's {@link AvailLoader}.
*/
public @Nullable AvailLoader availLoaderOrNull ()
{
return availLoader;
}
/**
* The {@link FiberDescriptor} being executed by this interpreter.
*/
private @Nullable A_Fiber fiber;
/**
* Answer the current {@link A_Fiber fiber} bound to this interpreter, or
* {@code null} if there is none.
*
* @return The current fiber or null.
*/
public @Nullable A_Fiber fiberOrNull ()
{
return fiber;
}
/**
* Return the current {@linkplain FiberDescriptor fiber}.
*
* @return The current executing fiber.
*/
public A_Fiber fiber ()
{
return stripNull(fiber);
}
/**
* Bind the specified {@linkplain ExecutionState#RUNNING running}
* {@linkplain FiberDescriptor fiber} to the {@code Interpreter}, or unbind
* the current fiber.
*
* @param newFiber
* The fiber to run, or {@code null} to unbind the current fiber.
* @param tempDebug
* A string describing the context of this operation.
*/
public void fiber (final @Nullable A_Fiber newFiber, final String tempDebug)
{
if (debugPrimitives)
{
@SuppressWarnings("StringBufferReplaceableByString")
final StringBuilder builder = new StringBuilder();
builder
.append("[")
.append(interpreterIndex)
.append("] fiber: ")
.append(fiber == null
? "null"
: fiber.uniqueId() + "[" + fiber.executionState() + "]")
.append(" -> ")
.append(newFiber == null
? "null"
: newFiber.uniqueId()
+ "[" + newFiber.executionState() + "]")
.append(" (").append(tempDebug).append(")");
log(
loggerDebugPrimitives,
Level.INFO,
"{0}",
builder.toString());
}
assert fiber == null ^ newFiber == null;
assert newFiber == null || newFiber.executionState() == RUNNING;
fiber = newFiber;
reifiedContinuation = null;
if (newFiber != null)
{
availLoader = newFiber.availLoader();
final boolean readsBeforeWrites =
newFiber.traceFlag(TRACE_VARIABLE_READS_BEFORE_WRITES);
traceVariableReadsBeforeWrites = readsBeforeWrites;
traceVariableWrites =
readsBeforeWrites || newFiber.traceFlag(TRACE_VARIABLE_WRITES);
}
else
{
availLoader = null;
traceVariableReadsBeforeWrites = false;
traceVariableWrites = false;
}
}
/**
* Should the {@code Interpreter} record which {@link A_Variable}s are read
* before written while running its current {@link A_Fiber}?
*/
private boolean traceVariableReadsBeforeWrites = false;
/**
* Should the {@code Interpreter} record which {@link A_Variable}s are read
* before written while running its current {@link A_Fiber}?
*
* @return {@code true} if the interpreter should record variable accesses,
* {@code false} otherwise.
*/
public boolean traceVariableReadsBeforeWrites ()
{
return traceVariableReadsBeforeWrites;
}
/**
* Set the variable trace flag.
*
* @param traceVariableReadsBeforeWrites
* {@code true} if the {@code Interpreter} should record which {@link
* A_Variable}s are read before written while running its current
* {@link A_Fiber}, {@code false} otherwise.
*/
public void setTraceVariableReadsBeforeWrites (
final boolean traceVariableReadsBeforeWrites)
{
if (traceVariableReadsBeforeWrites)
{
fiber().setTraceFlag(TRACE_VARIABLE_READS_BEFORE_WRITES);
}
else
{
fiber().clearTraceFlag(TRACE_VARIABLE_READS_BEFORE_WRITES);
}
this.traceVariableReadsBeforeWrites = traceVariableReadsBeforeWrites;
this.traceVariableWrites = traceVariableReadsBeforeWrites;
}
/**
* Should the {@code Interpreter} record which {@link A_Variable}s are
* written while running its current {@link A_Fiber}?
*/
private boolean traceVariableWrites = false;
/**
* Should the {@code Interpreter} record which {@link A_Variable}s are
* written while running its current {@link A_Fiber}?
*
* @return {@code true} if the interpreter should record variable accesses,
* {@code false} otherwise.
*/
public boolean traceVariableWrites ()
{
return traceVariableWrites;
}
/**
* Set the variable trace flag.
*
* @param traceVariableWrites
* {@code true} if the {@code Interpreter} should record which {@link
* A_Variable}s are written while running its current {@link
* A_Fiber}, {@code false} otherwise.
*/
public void setTraceVariableWrites (final boolean traceVariableWrites)
{
if (traceVariableWrites)
{
fiber().setTraceFlag(TRACE_VARIABLE_WRITES);
}
else
{
fiber().clearTraceFlag(TRACE_VARIABLE_WRITES);
}
this.traceVariableWrites = traceVariableWrites;
}
/**
* Answer the {@link A_Module} being loaded by this interpreter's loader. If
* there is no {@linkplain AvailLoader loader} then answer {@code nil}.
*
* @return The current loader's module under definition, or {@code nil} if
* loading is not taking place via this interpreter.
*/
public A_Module module()
{
final @Nullable AvailLoader loader = fiber().availLoader();
if (loader == null)
{
return nil;
}
return loader.module();
}
/**
* The latest result produced by a {@linkplain Result#SUCCESS successful}
* {@linkplain Primitive primitive}, or the latest {@linkplain
* AvailErrorCode error code} produced by a {@linkplain Result#FAILURE
* failed} primitive.
*/
@ReferencedInGeneratedCode
private @Nullable AvailObject latestResult;
/**
* Set the latest result due to a {@linkplain Result#SUCCESS successful}
* {@linkplain Primitive primitive}, or the latest {@linkplain
* AvailErrorCode error code} produced by a {@linkplain Result#FAILURE
* failed} primitive.
*
* <p>The value may be Java's {@code null} to indicate this field should be
* cleared, to detect accidental use.</p>
*
* @param newResult The latest result to record.
*/
@ReferencedInGeneratedCode
public void latestResult (final @Nullable A_BasicObject newResult)
{
assert newResult != null || !returnNow;
latestResult = (AvailObject) newResult;
if (debugL2)
{
log(
loggerDebugL2,
Level.INFO,
debugModeString + "Set latestResult: " +
(latestResult == null
? "null"
: latestResult.typeTag().name()));
}
}
/**
* Answer the latest result produced by a {@linkplain Result#SUCCESS
* successful} {@linkplain Primitive primitive}, or the latest {@linkplain
* AvailErrorCode error code} produced by a
* {@linkplain Result#FAILURE failed} primitive.
*
* @return The latest result.
*/
@ReferencedInGeneratedCode
public AvailObject latestResult ()
{
return stripNull(latestResult);
}
/**
* Answer the latest result produced by a {@linkplain Result#SUCCESS
* successful} {@linkplain Primitive primitive}, or the latest {@linkplain
* AvailErrorCode error code} produced by a {@linkplain Result#FAILURE
* failed} primitive. Answer null if no such value is available. This is
* useful for saving/restoring without knowing whether the value is valid.
*
* @return The latest result (or primitive failure value) or {@code null}.
*/
public @Nullable AvailObject latestResultOrNull ()
{
return latestResult;
}
/**
* A field that captures which {@link A_Function} is returning. This is
* used for statistics collection and reporting errors when returning a
* value that disagrees with semantic restrictions.
*/
@ReferencedInGeneratedCode
public @Nullable A_Function returningFunction;
/**
* Some operations like {@link L2_INVOKE} instructions have statistics that
* shouldn't include the {@link L2Instruction}s executed while the invoked
* function is running (e.g., other L2_INVOKE instructions). Accumulate
* those here. When an L2_INVOKE completes its invocation, replace the
* portion representing the sub-tasks accumulated during the call with a
* value representing the actual elapsed time for the call, but exclude the
* prior value from the reported L2_INVOKE.
*/
public long nanosToExclude = 0L;
/**
* Suspend the current fiber, evaluating the provided action. The action is
* passed two additional actions, one indicating how to resume from the
* suspension in the future (taking the result of the primitive), and the
* other indicating how to cause the primitive to fail (taking an
* AvailErrorCode).
*
* @param action
* The action supplied by the client that itself takes two actions
* for succeeding and failing the primitive at a later time.
* @return The value FIBER_SUSPENDED.
*/
public Result suspendAndDo (
final Continuation2NotNull<
Continuation1NotNull<A_BasicObject>,
Continuation1NotNull<AvailErrorCode>>
action)
{
final List<AvailObject> copiedArgs = new ArrayList<>(argsBuffer);
final AvailRuntime theRuntime = currentRuntime();
final A_Function primitiveFunction = stripNull(function);
final @Nullable Primitive prim = primitiveFunction.code().primitive();
assert prim != null && prim.hasFlag(CanSuspend);
final A_Fiber currentFiber = fiber();
final AtomicBoolean once = new AtomicBoolean(false);
postExitContinuation(() ->
action.value(
result ->
{
assert !once.getAndSet(true);
resumeFromSuccessfulPrimitive(
theRuntime,
currentFiber,
prim,
result);
},
failureCode ->
{
assert !once.getAndSet(true);
resumeFromFailedPrimitive(
theRuntime,
currentFiber,
failureCode.numericCode(),
primitiveFunction,
copiedArgs);
}));
return primitiveSuspend(primitiveFunction);
}
/**
* Set the resulting value of a primitive invocation. Answer primitive
* {@linkplain Result#SUCCESS success}.
*
* @param result
* The result of performing a {@linkplain Primitive primitive}.
* @return Primitive {@linkplain Result#SUCCESS success}.
*/
public Result primitiveSuccess (final A_BasicObject result)
{
assert fiber().executionState() == RUNNING;
latestResult(result);
return SUCCESS;
}
/**
* Set the resulting value of a primitive invocation to the {@linkplain
* AvailErrorCode#numericCode() numeric code} of the specified {@link
* AvailErrorCode}. Answer primitive {@linkplain Result#FAILURE failure}.
*
* @param code
* An {@link AvailErrorCode}.
* @return Primitive {@linkplain Result#FAILURE failure}.
*/
public Result primitiveFailure (final AvailErrorCode code)
{
assert fiber().executionState() == RUNNING;
latestResult(code.numericCode());
return FAILURE;
}
/**
* Set the resulting value of a primitive invocation to the {@linkplain
* AvailErrorCode#numericCode() numeric code} of the {@link AvailErrorCode}
* embedded within the specified {@linkplain AvailException exception}.
* Answer primitive {@linkplain Result#FAILURE failure}.
*
* @param exception
* An {@linkplain AvailException exception}.
* @return Primitive {@linkplain Result#FAILURE failure}.
*/
public Result primitiveFailure (final AvailException exception)
{
assert fiber().executionState() == RUNNING;
latestResult(exception.numericCode());
return FAILURE;
}
/**
* Set the resulting value of a primitive invocation to the {@linkplain
* AvailErrorCode#numericCode() numeric code} of the {@link AvailErrorCode}
* embedded within the specified {@linkplain AvailRuntimeException
* runtime exception}. Answer primitive {@linkplain Result#FAILURE
* failure}.
*
* @param exception
* A {@linkplain AvailRuntimeException runtime exception}.
* @return Primitive {@linkplain Result#FAILURE failure}.
*/
public Result primitiveFailure (final AvailRuntimeException exception)
{
assert fiber().executionState() == RUNNING;
latestResult(exception.numericCode());
return FAILURE;
}
/**
* Set the resulting value of a primitive invocation. Answer primitive
* {@linkplain Result#FAILURE failure}.
*
* @param result
* The result of performing a {@linkplain Primitive primitive}.
* @return Primitive {@linkplain Result#FAILURE failure}.
*/
public Result primitiveFailure (final A_BasicObject result)
{
assert fiber().executionState() == RUNNING;
latestResult(result);
return FAILURE;
}
/**
* Should the current executing chunk return to its caller? The value to
* return is in {@link #latestResult}. If the outer interpreter loop
* detects this, it should resume the top reified continuation's chunk,
* giving it an opportunity to accept the return value and de-reify.
*/
@ReferencedInGeneratedCode
public boolean returnNow = false;
/**
* Should the {@linkplain Interpreter interpreter} exit its {@linkplain
* #run() run loop}? This can happen when the fiber has completed, failed,
* or been suspended.
*/
public boolean exitNow = true;
/**
* A {@linkplain Continuation0 continuation} to run after a {@linkplain
* FiberDescriptor fiber} exits and is unbound.
*/
private @Nullable Continuation0 postExitContinuation;
/**
* Answer the {@linkplain Continuation0 continuation}, if any, to run after
* a {@linkplain FiberDescriptor fiber} exits and is unbound.
*
* @return A continuation, or {@code null} if no such continuation has been
* established.
*/
public @Nullable Continuation0 postExitContinuation ()
{
return postExitContinuation;
}
/**
* Set the post-exit {@linkplain Continuation0 continuation}. The affected
* fiber will be locked around the evaluation of this continuation.
*
* @param continuation
* What to do after a {@linkplain FiberDescriptor fiber} has exited
* and been unbound, or {@code null} if nothing should be done.
*/
public void postExitContinuation (
final @Nullable Continuation0 continuation)
{
assert postExitContinuation == null || continuation == null;
postExitContinuation = continuation;
}
/**
* Suspend the current {@link A_Fiber} within a {@link Primitive}
* invocation. The reified {@link A_Continuation} will be available in
* {@link #reifiedContinuation}, and will be installed into the current
* fiber.
*
* @param state
* The suspension {@linkplain ExecutionState state}.
* @return {@link Result#FIBER_SUSPENDED}, for convenience.
*/
private Result primitiveSuspend (final ExecutionState state)
{
assert !exitNow;
assert state.indicatesSuspension();
assert unreifiedCallDepth() == 0;
final A_Fiber aFiber = fiber();
aFiber.lock(() ->
{
assert aFiber.executionState() == RUNNING;
aFiber.executionState(state);
aFiber.continuation(stripNull(reifiedContinuation));
reifiedContinuation = null;
final boolean bound = aFiber.getAndSetSynchronizationFlag(
BOUND, false);
assert bound;
fiber(null, "primitiveSuspend");
});
startTick = -1L;
if (debugL2)
{
log(
loggerDebugL2,
Level.INFO,
"{0}Set exitNow (primitiveSuspend), clear latestResult",
debugModeString);
}
exitNow = true;
latestResult(null);
levelOneStepper.wipeRegisters();
return FIBER_SUSPENDED;
}
/**
* {@linkplain ExecutionState#SUSPENDED Suspend} the current {@link A_Fiber}
* from within a {@link Primitive} invocation. The reified {@link
* A_Continuation} will be available in {@link #reifiedContinuation}, and
* will be installed into the current fiber.
*
* @param suspendingFunction
* The primitive {@link A_Function} causing the fiber suspension.
* @return {@link Result#FIBER_SUSPENDED}, for convenience.
*/
public Result primitiveSuspend (final A_Function suspendingFunction)
{
final Primitive prim = stripNull(suspendingFunction.code().primitive());
assert prim.hasFlag(CanSuspend);
fiber().suspendingFunction(suspendingFunction);
function = null; // Safety
return primitiveSuspend(SUSPENDED);
}
/**
* {@linkplain ExecutionState#PARKED Park} the current {@link A_Fiber}
* from within a {@link Primitive} invocation. The reified {@link
* A_Continuation} will be available in {@link #reifiedContinuation}, and
* will be installed into the current fiber.
*
* @param suspendingFunction
* The primitive {@link A_Function} parking the fiber.
* @return {@link Result#FIBER_SUSPENDED}, for convenience.
*/
public Result primitivePark (final A_Function suspendingFunction)
{
fiber().suspendingFunction(suspendingFunction);
return primitiveSuspend(PARKED);
}
/**
* Terminate the {@linkplain #fiber() current} {@linkplain FiberDescriptor
* fiber}, using the specified {@linkplain AvailObject object} as its final
* result.
*
* @param finalObject
* The fiber's result, or {@linkplain NilDescriptor#nil nil} if none.
* @param state
* An {@linkplain ExecutionState execution state} that {@linkplain
* ExecutionState#indicatesTermination() indicates termination}.
*/
private void exitFiber (
final A_BasicObject finalObject,
final ExecutionState state)
{
assert !exitNow;
assert state.indicatesTermination();
final A_Fiber aFiber = fiber();
aFiber.lock(() ->
{
assert aFiber.executionState() == RUNNING;
aFiber.executionState(state);
aFiber.continuation(nil);
aFiber.fiberResult(finalObject);
final boolean bound = aFiber.getAndSetSynchronizationFlag(
BOUND, false);
assert bound;
fiber(null, "exitFiber");
});
startTick = -1L;
exitNow = true;
if (debugL2)
{
log(
loggerDebugL2,
Level.INFO,
debugModeString
+ "Set exitNow and clear latestResult (exitFiber)");
}
latestResult(null);
levelOneStepper.wipeRegisters();
postExitContinuation(() ->
{
final A_Set joining = aFiber.lock(() ->
{
final A_Set temp = aFiber.joiningFibers().makeShared();
aFiber.joiningFibers(nil);
return temp;
});
// Wake up all fibers trying to join this one.
for (final A_Fiber joiner : joining)
{
joiner.lock(() ->
{
// Restore the permit. Resume the fiber if it was parked.
joiner.getAndSetSynchronizationFlag(
PERMIT_UNAVAILABLE, false);
if (joiner.executionState() == PARKED)
{
// Unpark it, whether it's still parked because of an
// attempted join on this fiber, an attempted join on
// another fiber (due to a spurious wakeup and giving up
// on the first join), or a park (same). A retry loop
// in the public joining methods should normally deal
// with spurious unparks, but there's no mechanism yet
// to eject the stale joiner from the set.
joiner.executionState(SUSPENDED);
final Primitive suspended =
stripNull(
joiner.suspendingFunction().code().primitive());
assert suspended == P_AttemptJoinFiber.instance
|| suspended == P_ParkCurrentFiber.instance;
Interpreter.resumeFromSuccessfulPrimitive(
currentRuntime(),
joiner,
suspended,
nil);
}
});
}
});
}
/**
* {@linkplain ExecutionState#TERMINATED Terminate} the {@linkplain
* #fiber() current} {@linkplain FiberDescriptor fiber}, using the specified
* {@linkplain AvailObject object} as its final result.
*
* @param value
* The fiber's result.
*/
public void terminateFiber (final A_BasicObject value)
{
exitFiber(value, TERMINATED);
}
/**
* {@linkplain ExecutionState#ABORTED Abort} the {@linkplain #fiber()
* current} {@linkplain FiberDescriptor fiber}.
*/
public void abortFiber ()
{
exitFiber(nil, ABORTED);
}
/**
* Invoke an Avail primitive. The primitive is passed, and the arguments
* are provided in {@link #argsBuffer}. If the primitive fails, use {@link
* Interpreter#primitiveFailure(A_BasicObject)} to set the primitiveResult
* to some object indicating what the problem was, and return
* primitiveFailed immediately. If the primitive causes the continuation to
* change (e.g., through block invocation, continuation restart, exception
* throwing, etc), answer continuationChanged. Otherwise the primitive
* succeeded, and we simply capture the resulting value with {@link
* Interpreter#primitiveSuccess(A_BasicObject)} and return {@link
* Result#SUCCESS}.
*
* @param primitive
* The {@link Primitive} to invoke.
* @return The resulting status of the primitive attempt.
*/
@ReferencedInGeneratedCode
public Result attemptPrimitive (
final Primitive primitive)
{
final long timeBefore = beforeAttemptPrimitive(primitive);
final Result success = primitive.attempt(this);
afterAttemptPrimitive(primitive, timeBefore, success);
return success;
}
/**
* Prepare to execute the given primitive. Answer the current time in
* nanoseconds.
*
* @param primitive
* The {@link Primitive} that is about to run.
* @return The current time in nanoseconds, as a {@code long}.
*/
@ReferencedInGeneratedCode
public long beforeAttemptPrimitive (final Primitive primitive)
{
if (debugPrimitives)
{
log(
loggerDebugPrimitives,
Level.FINER,
"{0}attempt {1} (and clear latestResult)",
debugModeString,
primitive.name());
}
returnNow = false;
latestResult(null);
assert current() == this;
return captureNanos();
}
/**
* The given primitive has just executed; do any necessary post-processing.
*
* @param primitive
* The primitive that just ran.
* @param timeBefore
* The time in nanoseconds just prior to the primitive running.
* @param success
* The {@link Result} of running the primitive, indicating whether
* it succeeded, failed, etc.
* @return The same {@link Result} that was passed, to make calling simpler.
*/
@ReferencedInGeneratedCode
public Result afterAttemptPrimitive (
final Primitive primitive,
final long timeBefore,
final Result success)
{
final long timeAfter = captureNanos();
primitive.addNanosecondsRunning(
timeAfter - timeBefore, interpreterIndex);
assert success != FAILURE || !primitive.hasFlag(CannotFail);
if (debugPrimitives)
{
if (loggerDebugPrimitives.isLoggable(Level.FINER))
{
@Nullable AvailErrorCode errorCode = null;
if (success == FAILURE)
{
if (latestResult().isInt())
{
final int errorInt = latestResult().extractInt();
errorCode = byNumericCode(errorInt);
}
}
final String failPart = errorCode != null
? " (" + errorCode + ")"
: "";
log(
loggerDebugPrimitives,
Level.FINER,
"{0}... completed primitive {1} => {2}{3}",
debugModeString,
primitive.name(),
success.name(),
failPart);
if (success != SUCCESS)
{
log(
loggerDebugPrimitives,
Level.FINER,
"{0} ({1})",
debugModeString,
success.name());
}
}
}
return success;
}
/**
* The (bottom) portion of the call stack that has been reified. This must
* always be either an {@link A_Continuation} or {@code null}, but it's
* typed as {@link AvailObject} to avoid potential JVM runtime checks.
*/
@ReferencedInGeneratedCode
public @Nullable AvailObject reifiedContinuation = null;
/**
* The number of stack frames that reification would transform into
* continuations.
*/
private int unreifiedCallDepth = 0;
/**
* The maximum depth of the Java call stack, measured in unreified chunks.
*/
private static final int maxUnreifiedCallDepth = 50;
/** The {@link A_Function} being executed. */
@ReferencedInGeneratedCode
public @Nullable A_Function function;
/** The {@link L2Chunk} being executed. */
@ReferencedInGeneratedCode
public @Nullable L2Chunk chunk;
/**
* The current zero-based L2 offset within the current L2Chunk's
* instructions.
*/
@ReferencedInGeneratedCode
public int offset;
/**
* Jump to a new position in the L2 instruction stream.
*
* @param newOffset
* The new position in the L2 instruction stream.
*/
public void offset (final int newOffset)
{
offset = newOffset;
}
/**
* A reusable temporary buffer used to hold arguments during method
* invocations.
*/
@ReferencedInGeneratedCode
public final List<AvailObject> argsBuffer = new ArrayList<>();
/**
* Assert that the number of arguments in the {@link #argsBuffer} agrees
* with the given expected number.
*
* @param expectedCount
* The exact number of arguments that should be present.
*/
public void checkArgumentCount (final int expectedCount)
{
assert argsBuffer.size() == expectedCount;
}
/**
* Answer the specified element of argsBuffer.
*
* @param zeroBasedIndex
* The zero-based index at which to extract an argument being passed
* in an invocation.
* @return The actual argument.
*/
public AvailObject argument (final int zeroBasedIndex)
{
return argsBuffer.get(zeroBasedIndex);
}
/**
* The {@link L1InstructionStepper} used to simulate execution of Level One
* nybblecodes.
*/
@SuppressWarnings("ThisEscapedInObjectConstruction")
@ReferencedInGeneratedCode
public final L1InstructionStepper levelOneStepper =
new L1InstructionStepper(this);
/**
* The value of the {@linkplain AvailRuntime#clock clock} when the
* {@linkplain #run() interpreter loop} started running.
*/
public long startTick = -1L;
/**
* The size of a {@linkplain FiberDescriptor fiber}'s time slice, in ticks.
*/
private static final int timeSliceTicks = 20;
/**
* Answer true if an interrupt has been requested. The interrupt may be
* specific to the {@linkplain #fiber() current} {@linkplain FiberDescriptor
* fiber} or global to the {@linkplain AvailRuntime runtime}.
*
* @return {@code true} if an interrupt is pending, {@code false} otherwise.
*/
@ReferencedInGeneratedCode
public boolean isInterruptRequested ()
{
return runtime.levelOneSafetyRequested()
|| unreifiedCallDepth > maxUnreifiedCallDepth
|| runtime.clock.get() - startTick >= timeSliceTicks
|| fiber().interruptRequestFlag(REIFICATION_REQUESTED);
}
/**
* The {@linkplain #fiber() current} {@linkplain FiberDescriptor fiber} has
* been asked to pause for an inter-nybblecode interrupt for some reason. It
* has possibly executed several more L2 instructions since that time, to
* place the fiber into a state that's consistent with naive Level One
* execution semantics. That is, a naive Level One interpreter should be
* able to resume the fiber later (although most of the time the Level Two
* interpreter will kick in).
*
* @param continuation
* The reified continuation to save into the current fiber.
*/
public void processInterrupt (final A_Continuation continuation)
{
assert !exitNow;
assert !returnNow;
final A_Fiber aFiber = fiber();
final MutableOrNull<A_Set> waiters = new MutableOrNull<>();
aFiber.lock(() ->
{
synchronized (aFiber)
{
assert aFiber.executionState() == RUNNING;
aFiber.executionState(INTERRUPTED);
aFiber.continuation(continuation);
if (aFiber.getAndClearInterruptRequestFlag(
REIFICATION_REQUESTED))
{
continuation.makeShared();
waiters.value = aFiber.getAndClearReificationWaiters();
assert waiters.value().setSize() > 0;
}
final boolean bound = fiber().getAndSetSynchronizationFlag(
BOUND, false);
assert bound;
fiber(null, "processInterrupt");
}
});
assert !exitNow;
returnNow = false;
exitNow = true;
offset = Integer.MAX_VALUE;
if (debugL2)
{
log(
loggerDebugL2,
Level.FINER,
"{0}Set exitNow (processInterrupt)",
debugModeString);
}
startTick = -1L;
latestResult(null);
levelOneStepper.wipeRegisters();
postExitContinuation(() ->
{
if (waiters.value != null)
{
for (final A_BasicObject pojo : waiters.value)
{
final Continuation1<A_Continuation> waiter =
pojo.javaObjectNotNull();
waiter.value(continuation);
}
}
resumeFromInterrupt(aFiber);
});
}
/**
* Raise an exception. Scan the stack of continuations (which must have been
* reified already) until one is found for a function whose code specifies
* {@linkplain P_CatchException}. Get that continuation's second argument
* (a handler block of one argument), and check if that handler block will
* accept the exceptionValue. If not, keep looking. If it will accept it,
* unwind the continuation stack so that the primitive catch method is the
* top entry, and invoke the handler block with exceptionValue. If there is
* no suitable handler block, fail the primitive.
*
* @param exceptionValue The exception object being raised.
* @return The {@linkplain Result success state}.
*/
public Result searchForExceptionHandler (final AvailObject exceptionValue)
{
// Replace the contents of the argument buffer with "exceptionValue",
// an exception augmented with stack information.
assert argsBuffer.size() == 1;
argsBuffer.set(0, exceptionValue);
final int primNum = P_CatchException.instance.primitiveNumber;
AvailObject continuation = stripNull(reifiedContinuation);
int depth = 0;
while (!continuation.equalsNil())
{
final A_RawFunction code = continuation.function().code();
if (code.primitiveNumber() == primNum)
{
assert code.numArgs() == 3;
final A_Variable failureVariable =
continuation.argOrLocalOrStackAt(4);
// Scan a currently unmarked frame.
if (failureVariable.value().value().equalsInt(0))
{
final A_Tuple handlerTuple =
continuation.argOrLocalOrStackAt(2);
assert handlerTuple.isTuple();
for (final A_Function handler : handlerTuple)
{
if (exceptionValue.isInstanceOf(
handler.kind().argsTupleType().typeAtIndex(1)))
{
// Mark this frame: we don't want it to handle an
// exception raised from within one of its handlers.
if (debugL2)
{
log(
loggerDebugPrimitives,
Level.FINER,
"{0}Raised (->handler) at depth {1}",
debugModeString,
depth);
}
failureVariable.value().setValueNoCheck(
E_HANDLER_SENTINEL.numericCode());
// Run the handler. Since the Java stack has been
// fully reified, simply jump into the chunk. Note
// that the argsBuffer was already set up with just
// the exceptionValue.
reifiedContinuation = continuation;
function = handler;
chunk = handler.code().startingChunk();
offset = 0; // Invocation
levelOneStepper.wipeRegisters();
returnNow = false;
latestResult(null);
return CONTINUATION_CHANGED;
}
}
}
}
continuation = (AvailObject) continuation.caller();
depth++;
}
// If no handler was found, then return the unhandled exception.
return primitiveFailure(exceptionValue);
}
/**
* Assume the entire stack has been reified. Scan the stack of
* continuations until one is found for a function whose code specifies
* {@link P_CatchException}. Write the specified marker into its primitive
* failure variable to indicate the current exception handling state.
*
* @param guardVariable The primitive failure variable to update.
* @param marker An exception handling state marker (integer).
* @return The {@link Result success state}.
*/
public Result markGuardVariable (
final A_Variable guardVariable,
final A_Number marker)
{
// Only allow certain state transitions.
final int oldState = guardVariable.value().extractInt();
if (marker.equals(E_HANDLER_SENTINEL.numericCode())
&& oldState != 0)
{
return primitiveFailure(E_CANNOT_MARK_HANDLER_FRAME);
}
if (marker.equals(E_UNWIND_SENTINEL.numericCode())
&& oldState != E_HANDLER_SENTINEL.nativeCode())
{
return primitiveFailure(E_CANNOT_MARK_HANDLER_FRAME);
}
// Mark this frame. Depending on the marker, we don't want it to handle
// exceptions or unwinds anymore.
if (debugL2)
{
log(
loggerDebugL2,
Level.FINER,
"{0}Marked guard var {1}",
debugModeString,
marker);
}
guardVariable.setValueNoCheck(marker);
return primitiveSuccess(nil);
}
/**
* Assume the entire stack has been reified. Scan the stack of
* continuations until one is found for a function whose code specifies
* {@link P_CatchException}. Write the specified marker into its primitive
* failure variable to indicate the current exception handling state.
*
* @param marker An exception handling state marker.
* @return The {@link Result success state}.
*/
public Result markNearestGuard (final A_Number marker)
{
final int primNum = P_CatchException.instance.primitiveNumber;
A_Continuation continuation = stripNull(reifiedContinuation);
int depth = 0;
while (!continuation.equalsNil())
{
final A_RawFunction code = continuation.function().code();
if (code.primitiveNumber() == primNum)
{
assert code.numArgs() == 3;
final A_Variable failureVariable =
continuation.argOrLocalOrStackAt(4);
final A_Variable guardVariable = failureVariable.value();
final int oldState = guardVariable.value().extractInt();
// Only allow certain state transitions.
if (marker.equals(E_HANDLER_SENTINEL.numericCode())
&& oldState != 0)
{
return primitiveFailure(E_CANNOT_MARK_HANDLER_FRAME);
}
if (marker.equals(E_UNWIND_SENTINEL.numericCode())
&& oldState != E_HANDLER_SENTINEL.nativeCode())
{
return primitiveFailure(E_CANNOT_MARK_HANDLER_FRAME);
}
// Mark this frame: we don't want it to handle exceptions
// anymore.
guardVariable.setValueNoCheck(marker);
if (debugL2)
{
log(
loggerDebugL2,
Level.FINER,
"{0}Marked {1} at depth {2}",
debugModeString,
marker,
depth);
}
return primitiveSuccess(nil);
}
continuation = continuation.caller();
depth++;
}
return primitiveFailure(E_NO_HANDLER_FRAME);
}
/**
* Check if the current chunk is still valid. If so, return {@code true}.
* Otherwise, set the current chunk to the {@link L2Chunk#unoptimizedChunk},
* set the offset to the specified offset within that chunk, and return
* {@code false}.
*
* @param offsetInDefaultChunkIfInvalid
* The offset within the {@link L2Chunk#unoptimizedChunk} to resume
* execution at if the current chunk is found to be invalid.
* @return Whether the current chunk is still {@link L2Chunk#isValid()
* valid} (i.e., has not been invalidated by a code change).
*/
@ReferencedInGeneratedCode
public boolean checkValidity (
final int offsetInDefaultChunkIfInvalid)
{
assert chunk != null;
if (!chunk.isValid())
{
chunk = L2Chunk.unoptimizedChunk;
offset = offsetInDefaultChunkIfInvalid;
return false;
}
return true;
}
/**
* Obtain an appropriate {@link StackReifier} for restarting the specified
* {@linkplain A_Continuation continuation}.
*
* @param continuation
* The {@link A_Continuation} to restart.
* @return The requested {@code StackReifier}.
*/
@SuppressWarnings("unused")
@ReferencedInGeneratedCode
public StackReifier reifierToRestart (
final A_Continuation continuation)
{
return abandonStackThen(
ABANDON_BEFORE_RESTART_IN_L2.statistic,
() ->
{
final A_Function whichFunction = continuation.function();
final int numArgs = whichFunction.code().numArgs();
argsBuffer.clear();
for (int i = 1; i <= numArgs; i++)
{
argsBuffer.add(
continuation.argOrLocalOrStackAt(i));
}
reifiedContinuation = (AvailObject) continuation.caller();
function = whichFunction;
chunk = continuation.levelTwoChunk();
offset = continuation.levelTwoOffset();
returnNow = false;
latestResult(null);
});
}
/**
* Answer a {@link StackReifier} which can be used for reifying the current
* stack by returning it out to Interpreter{@link #run()}. When it reaches
* there, a lambda embedded in this reifier will run, performing an action
* suitable to the provided flags.
*
* @param actuallyReify
* Whether to actually record the stack frames as {@link
* A_Continuation}s.
* @param processInterrupt
* Whether a pending interrupt should be processed after reification.
* @param categoryIndex
* The ordinal of a {@link StatisticCategory} under which to record
* reification statistics.
* @return The new {@link StackReifier}.
*/
@SuppressWarnings("unused")
@ReferencedInGeneratedCode
public StackReifier reify (
final boolean actuallyReify,
final boolean processInterrupt,
final int categoryIndex)
{
if (processInterrupt)
{
// Reify-and-interrupt.
return new StackReifier(
actuallyReify,
unreifiedCallDepth(),
StatisticCategory.lookup(categoryIndex).statistic,
() ->
{
returnNow = false;
processInterrupt(stripNull(reifiedContinuation));
});
}
else
{
// Capture the interpreter's state, reify the frames, and as an
// after-reification action, restore the interpreter's state.
final A_Function savedFunction = stripNull(function);
final boolean newReturnNow = returnNow;
final @Nullable AvailObject newReturnValue =
newReturnNow ? latestResult() : null;
// Reify-and-continue. The current frame is also reified.
return new StackReifier(
actuallyReify,
unreifiedCallDepth(),
StatisticCategory.lookup(categoryIndex).statistic,
() ->
{
final A_Continuation continuation =
stripNull(reifiedContinuation);
function = savedFunction;
chunk = continuation.levelTwoChunk();
offset = continuation.levelTwoOffset();
returnNow = newReturnNow;
latestResult(newReturnValue);
// Return into the Interpreter's run loop.
});
}
}
/**
* Obtain an appropriate {@link StackReifier} for restarting the specified
* {@linkplain A_Continuation continuation} with the given arguments.
*
* @param continuation
* The continuation to restart.
* @param arguments
* The arguments with which to restart the continuation.
* @return The requested {@code StackReifier}.
*/
@SuppressWarnings("unused")
@ReferencedInGeneratedCode
public StackReifier reifierToRestartWithArguments (
final A_Continuation continuation,
final AvailObject[] arguments)
{
return abandonStackThen(
ABANDON_BEFORE_RESTART_IN_L2.statistic,
() ->
{
final A_Function whichFunction = continuation.function();
final int numArgs = whichFunction.code().numArgs();
assert arguments.length == numArgs;
argsBuffer.clear();
Collections.addAll(argsBuffer, arguments);
reifiedContinuation = (AvailObject) continuation.caller();
function = whichFunction;
chunk = continuation.levelTwoChunk();
offset = continuation.levelTwoOffset();
returnNow = false;
latestResult(null);
});
}
/**
* Perform the actual {@link A_Function function} invocation with zero
* arguments.
*
* @param calledFunction
* The function to call.
* @return The {@link StackReifier}, if any.
*/
@ReferencedInGeneratedCode
public @Nullable StackReifier invoke0 (
final A_Function calledFunction)
{
final A_Function savedFunction = stripNull(function);
final L2Chunk savedChunk = stripNull(chunk);
argsBuffer.clear();
function = calledFunction;
chunk = calledFunction.code().startingChunk();
offset = 0;
final @Nullable StackReifier reifier = runChunk();
function = savedFunction;
chunk = savedChunk;
returnNow = false;
assert !exitNow;
return reifier;
}
/**
* Perform the actual {@link A_Function function} invocation with a single
* argument.
*
* @param calledFunction
* The function to call.
* @param arg1
* The sole argument to the function.
* @return The {@link StackReifier}, if any.
*/
@ReferencedInGeneratedCode
public @Nullable StackReifier invoke1 (
final A_Function calledFunction,
final AvailObject arg1)
{
final A_Function savedFunction = stripNull(function);
final L2Chunk savedChunk = stripNull(chunk);
argsBuffer.clear();
argsBuffer.add(arg1);
function = calledFunction;
chunk = calledFunction.code().startingChunk();
offset = 0;
final @Nullable StackReifier reifier = runChunk();
function = savedFunction;
chunk = savedChunk;
returnNow = false;
assert !exitNow;
return reifier;
}
/**
* Perform the actual {@link A_Function function} invocation with exactly
* two arguments.
*
* @param calledFunction
* The function to call.
* @param arg1
* The first argument to the function.
* @param arg2
* The second argument to the function.
* @return The {@link StackReifier}, if any.
*/
@ReferencedInGeneratedCode
public @Nullable StackReifier invoke2 (
final A_Function calledFunction,
final AvailObject arg1,
final AvailObject arg2)
{
final A_Function savedFunction = stripNull(function);
final L2Chunk savedChunk = stripNull(chunk);
argsBuffer.clear();
argsBuffer.add(arg1);
argsBuffer.add(arg2);
function = calledFunction;
chunk = calledFunction.code().startingChunk();
offset = 0;
final @Nullable StackReifier reifier = runChunk();
function = savedFunction;
chunk = savedChunk;
returnNow = false;
assert !exitNow;
return reifier;
}
/**
* Perform the actual {@link A_Function function} invocation with exactly
* three arguments.
*
* @param calledFunction
* The function to call.
* @param arg1
* The first argument to the function.
* @param arg2
* The second argument to the function.
* @param arg3
* The third argument to the function.
* @return The {@link StackReifier}, if any.
*/
@ReferencedInGeneratedCode
public @Nullable StackReifier invoke3 (
final A_Function calledFunction,
final AvailObject arg1,
final AvailObject arg2,
final AvailObject arg3)
{
final A_Function savedFunction = stripNull(function);
final L2Chunk savedChunk = stripNull(chunk);
argsBuffer.clear();
argsBuffer.add(arg1);
argsBuffer.add(arg2);
argsBuffer.add(arg3);
function = calledFunction;
chunk = calledFunction.code().startingChunk();
offset = 0;
final @Nullable StackReifier reifier = runChunk();
function = savedFunction;
chunk = savedChunk;
returnNow = false;
assert !exitNow;
return reifier;
}
/**
* Perform the actual {@link A_Function function} invocation.
*
* @param calledFunction
* The function to call.
* @param args
* The {@linkplain AvailObject arguments} to the function.
* @return The {@link StackReifier}, if any.
*/
@ReferencedInGeneratedCode
public @Nullable StackReifier invoke (
final A_Function calledFunction,
final AvailObject[] args)
{
final A_Function savedFunction = stripNull(function);
final L2Chunk savedChunk = stripNull(chunk);
argsBuffer.clear();
Collections.addAll(argsBuffer, args);
function = calledFunction;
chunk = calledFunction.code().startingChunk();
offset = 0;
final @Nullable StackReifier reifier = runChunk();
function = savedFunction;
chunk = savedChunk;
returnNow = false;
assert !exitNow;
return reifier;
}
/**
* Prepare the {@code Interpreter} to execute the given {@link
* FunctionDescriptor function} with the arguments provided in {@link
* #argsBuffer}.
*
* @param aFunction
* The function to begin executing.
* @return Either {@code null} to indicate the function returned normally,
* leaving its result in the interpreter's latestResult field, or
* a {@link StackReifier} used to indicate the stack is being
* unwound (and the Avail function is <em>not</em> returning).
*/
public @Nullable StackReifier invokeFunction (final A_Function aFunction)
{
assert !exitNow;
function = aFunction;
final A_RawFunction code = aFunction.code();
assert code.numArgs() == argsBuffer.size();
chunk = code.startingChunk();
// Note that a chunk can only be invalidated by a method change, which
// can only happen when all fibers are suspended (level-one safe zone),
// so this test is entirely stable. Also, the chunk will be
// disconnected from the L1 code during invalidation, although
// existing continuations will still refer to it. Re-entry into those
// continuations always checks for validity.
assert chunk.isValid();
offset = 0;
returnNow = false;
return runChunk();
}
/**
* Run the interpreter until it completes the fiber, is suspended, or is
* interrupted, perhaps by exceeding its time-slice.
*/
@InnerAccess void run ()
{
assert unreifiedCallDepth() == 0;
assert fiber != null;
assert !exitNow;
assert !returnNow;
nanosToExclude = 0L;
startTick = runtime.clock.get();
if (debugL2)
{
debugModeString = "Fib=" + fiber.uniqueId() + " ";
log(
loggerDebugPrimitives,
Level.FINER,
"\n{0}Run: ({1})",
debugModeString,
fiber.fiberName());
}
while (true)
{
// Run the chunk to completion (dealing with reification).
// The chunk will do its own invalidation checks and off-ramp
// to L1 if needed.
final A_Function calledFunction = stripNull(function);
final @Nullable StackReifier reifier = runChunk();
assert unreifiedCallDepth() <= 1;
returningFunction = calledFunction;
if (reifier != null)
{
// Reification has been requested, and the exception has already
// collected all the continuations.
reifiedContinuation =
reifier.actuallyReify()
? reifier.assembleContinuation(
stripNull(reifiedContinuation))
: nil;
reifier.recordCompletedReification(interpreterIndex);
chunk = null; // The postReificationAction should set this up.
reifier.postReificationAction().value();
if (exitNow)
{
// The fiber has been dealt with. Exit the interpreter loop.
assert fiber == null;
if (debugL2)
{
log(
loggerDebugL2,
Level.FINER,
"{0}Exit1 run\n",
debugModeString);
}
return;
}
if (!returnNow)
{
continue;
}
// Fall through to accomplish the return.
}
// We're returning from the outermost non-reified frame, either into
// the top reified frame or right out of the fiber.
assert returnNow;
assert latestResult != null;
returnNow = false;
if (stripNull(reifiedContinuation).equalsNil())
{
// The reified stack is empty, too. We must have returned from
// the outermost frame. The fiber runner will deal with it.
terminateFiber(latestResult());
exitNow = true;
if (debugL2)
{
log(
loggerDebugL2,
Level.FINER,
"{0}Exit2 run and set exitNow "
+ "(fall off Interpreter.run)\n",
debugModeString);
}
return;
}
// Resume the top reified frame. It should be at an on-ramp that
// expects nothing of the current registers, but is able to create
// them and explode the current reified continuation into them
// (popping the continuation as it does so).
final A_Continuation frame = reifiedContinuation;
function = frame.function();
chunk = frame.levelTwoChunk();
offset = frame.levelTwoOffset();
}
}
/**
* Run the current L2Chunk to completion. Note that a reification request
* may cut this short. Also note that this interpreter indicates the offset
* at which to start executing. For an initial invocation, the argsBuffer
* will have been set up for the call. For a return into this continuation,
* the offset will refer to code that will rebuild the register set from the
* top reified continuation, using the {@link Interpreter#latestResult()}.
* For resuming the continuation, the offset will point to code that also
* rebuilds the register set from the top reified continuation, but it won't
* expect a return value. These re-entry points should perform validity
* checks on the chunk, allowing an orderly off-ramp into the {@link
* L2Chunk#unoptimizedChunk} (which simply interprets the L1 nybblecodes).
*
* @return {@code null} if returning normally, otherwise a {@link
* StackReifier} to effect reification.
*/
public @Nullable StackReifier runChunk ()
{
adjustUnreifiedCallDepthBy(1);
assert !exitNow;
@Nullable StackReifier reifier = null;
while (!returnNow && !exitNow && reifier == null)
{
reifier = stripNull(chunk).runChunk(this, offset);
}
adjustUnreifiedCallDepthBy(-1);
return reifier;
}
/**
* Throw a {@link StackReifier} to reify the Java stack into {@link
* A_Continuation}s, then invoke the given {@link A_Function} with the given
* three arguments.
*
* @param functionToCall
* What three-argument function to invoke after reification.
* @param reificationStatistic
* The {@link Statistic} under which to record this reification.
* @param shouldReturnNow
* Whether an Avail return should happen after reification.
* @param arg1
* The first argument of the function.
* @param arg2
* The second argument of the function.
* @param arg3
* The third argument of the function.
* @return The {@link StackReifier} that collects reified continuations on
* the way out to {@link #run()}.
*/
public StackReifier reifyThenCall3 (
final A_Function functionToCall,
final Statistic reificationStatistic,
final boolean shouldReturnNow,
final A_BasicObject arg1,
final A_BasicObject arg2,
final A_BasicObject arg3)
{
return reifyThen(
reificationStatistic,
() ->
{
argsBuffer.clear();
argsBuffer.add((AvailObject) arg1);
argsBuffer.add((AvailObject) arg2);
argsBuffer.add((AvailObject) arg3);
function = functionToCall;
chunk = functionToCall.code().startingChunk();
offset = 0;
returnNow = shouldReturnNow;
});
}
/**
* Create and return a {@link StackReifier}. This will get returned all the
* way out to the {@link #run()} method, accumulating reified stack frames
* along the way. The run() method will then invoke the given
* postReificationAction and resume execution.
*
* @param reificationStatistic
* The {@link Statistic} under which to record this reification.
* @param postReificationAction
* The action to perform (in the outer interpreter loop) after the
* entire stack is reified.
* @return The {@link StackReifier} that collects reified continuations on
* the way out to {@link #run()}.
*/
public StackReifier reifyThen (
final Statistic reificationStatistic,
final Continuation0 postReificationAction)
{
// Note that the *current* frame isn't reified, so subtract one.
return new StackReifier(
true,
unreifiedCallDepth() - 1,
reificationStatistic,
postReificationAction);
}
/**
* Immediately throw a {@link StackReifier} with its {@code actuallyReify}
* flag set to false. This abandons the Java stack (out to {@link #run()})
* before running the postReificationAction, which should set up the
* interpreter to continue running.
*
* @param reificationStatistic
* The {@link Statistic} under which to record this stack
* abandonment.
* @param postReificationAction
* The action to perform (in the outer interpreter loop) after the
* entire stack is reified.
* @return The {@link StackReifier} that <em>abandons</em> stack frames on
* the way out to {@link #run()}.
*/
@SuppressWarnings("MethodMayBeStatic")
public StackReifier abandonStackThen (
final Statistic reificationStatistic,
final Continuation0 postReificationAction)
{
return new StackReifier(
false, 0, reificationStatistic, postReificationAction);
}
/**
* Schedule the specified {@linkplain ExecutionState#indicatesSuspension()
* suspended} {@linkplain FiberDescriptor fiber} to execute for a while as a
* {@linkplain AvailRuntime#whenLevelOneUnsafeDo(int, Continuation0)} Level
* One-unsafe task}. If the fiber completes normally, then call its
* {@linkplain A_Fiber#resultContinuation() result continuation} with its
* final answer. If the fiber terminates abnormally, then call its
* {@linkplain A_Fiber#failureContinuation() failure continuation} with the
* terminal {@linkplain Throwable throwable}.
*
* @param runtime
* An {@linkplain AvailRuntime Avail runtime}.
* @param aFiber
* The fiber to run.
* @param continuation
* How to set up the {@code Interpreter interpreter} prior to running
* the fiber for a while. Pass in the interpreter to use.
*/
private static void executeFiber (
final AvailRuntime runtime,
final A_Fiber aFiber,
final Continuation1NotNull<Interpreter> continuation)
{
assert aFiber.executionState().indicatesSuspension();
// We cannot simply run the specified function, we must queue a task to
// run when Level One safety is no longer required.
runtime.whenLevelOneUnsafeDo(
aFiber.priority(),
AvailTask.forFiberResumption(
aFiber,
() ->
{
final Interpreter interpreter = current();
assert aFiber == interpreter.fiberOrNull();
assert aFiber.executionState() == RUNNING;
continuation.value(interpreter);
if (interpreter.exitNow)
{
assert stripNull(interpreter.reifiedContinuation)
.equalsNil();
interpreter.terminateFiber(interpreter.latestResult());
}
else
{
// Run the interpreter for a while.
interpreter.run();
}
assert interpreter.fiber == null;
}));
}
/**
* Schedule the specified {@linkplain FiberDescriptor fiber} to run the
* given {@linkplain FunctionDescriptor function}. This function is run as
* an outermost function, and must correspond to a top-level action. The
* fiber must be in the {@linkplain ExecutionState#UNSTARTED unstarted}
* state. This method is an entry point.
*
* <p>If the function successfully runs to completion, then the fiber's
* "on success" {@linkplain Continuation1 continuation} will be invoked with
* the function's result.</p>
*
* <p>If the function fails for any reason, then the fiber's "on failure"
* {@linkplain Continuation1 continuation} will be invoked with the
* terminal {@linkplain Throwable throwable}.</p>
*
* @param runtime
* An {@linkplain AvailRuntime Avail runtime}.
* @param aFiber
* The fiber to run.
* @param function
* A {@linkplain FunctionDescriptor function} to run.
* @param arguments
* The arguments for the function.
*/
public static void runOutermostFunction (
final AvailRuntime runtime,
final A_Fiber aFiber,
final A_Function function,
final List<? extends A_BasicObject> arguments)
{
assert aFiber.executionState() == UNSTARTED;
aFiber.fiberNameSupplier(
() ->
{
final A_RawFunction code = function.code();
return formatString("Outermost %s @ %s:%d",
code.methodName().asNativeString(),
code.module().equalsNil()
? "«vm»"
: code.module().moduleName().asNativeString(),
code.startingLineNumber());
});
executeFiber(
runtime,
aFiber,
interpreter ->
{
assert aFiber == interpreter.fiberOrNull();
assert aFiber.executionState() == RUNNING;
assert aFiber.continuation().equalsNil();
// Invoke the function. If it's a primitive and it
// succeeds, then immediately invoke the fiber's
// result continuation with the primitive's result.
interpreter.exitNow = false;
interpreter.returnNow = false;
interpreter.reifiedContinuation = nil;
interpreter.function = function;
interpreter.argsBuffer.clear();
for (final A_BasicObject arg : arguments)
{
interpreter.argsBuffer.add((AvailObject) arg);
}
interpreter.chunk = function.code().startingChunk();
interpreter.offset = 0;
});
}
/**
* Schedule resumption of the specified {@linkplain FiberDescriptor fiber}
* following {@linkplain ExecutionState#INTERRUPTED suspension} due to an
* interrupt. This method is an entry point.
*
* <p>If the function successfully runs to completion, then the fiber's
* "on success" {@linkplain Continuation1 continuation} will be invoked with
* the function's result.</p>
*
* <p>If the function fails for any reason, then the fiber's "on failure"
* {@linkplain Continuation1 continuation} will be invoked with the
* terminal {@linkplain Throwable throwable}.</p>
*
* @param aFiber The fiber to run.
*/
public static void resumeFromInterrupt (final A_Fiber aFiber)
{
assert aFiber.executionState() == INTERRUPTED;
assert !aFiber.continuation().equalsNil();
executeFiber(
currentRuntime(),
aFiber,
interpreter ->
{
assert aFiber == interpreter.fiberOrNull();
assert aFiber.executionState() == RUNNING;
final A_Continuation con = aFiber.continuation();
assert !con.equalsNil();
interpreter.exitNow = false;
interpreter.returnNow = false;
interpreter.reifiedContinuation = (AvailObject) con;
interpreter.function = con.function();
interpreter.latestResult(null);
interpreter.chunk = con.levelTwoChunk();
interpreter.offset = con.levelTwoOffset();
interpreter.levelOneStepper.wipeRegisters();
aFiber.continuation(nil);
});
}
/**
* Schedule resumption of the specified {@linkplain FiberDescriptor fiber}
* following {@linkplain ExecutionState#SUSPENDED suspension} by a
* {@linkplain Result#SUCCESS successful} {@linkplain Primitive primitive}.
* This method is an entry point.
*
* @param runtime
* An {@linkplain AvailRuntime Avail runtime}.
* @param aFiber
* The fiber to run.
* @param resumingPrimitive
* The suspended primitive that is resuming. This must agree with
* the fiber's {@link A_Fiber#suspendingFunction}'s raw function's
* primitive.
* @param result
* The result of the primitive.
*/
public static void resumeFromSuccessfulPrimitive (
final AvailRuntime runtime,
final A_Fiber aFiber,
final Primitive resumingPrimitive,
final A_BasicObject result)
{
assert !aFiber.continuation().equalsNil();
assert aFiber.executionState() == SUSPENDED;
assert aFiber.suspendingFunction().code().primitive()
== resumingPrimitive;
executeFiber(
runtime,
aFiber,
interpreter ->
{
assert aFiber == interpreter.fiberOrNull();
assert aFiber.executionState() == RUNNING;
final A_Continuation continuation = aFiber.continuation();
interpreter.reifiedContinuation = (AvailObject) continuation;
interpreter.latestResult(result);
interpreter.returningFunction = aFiber.suspendingFunction();
interpreter.exitNow = false;
if (continuation.equalsNil())
{
// Return from outer function, which was the (successful)
// suspendable primitive itself.
interpreter.returnNow = true;
interpreter.function = null;
interpreter.chunk = null;
interpreter.offset = Integer.MAX_VALUE;
}
else
{
interpreter.returnNow = false;
interpreter.function = continuation.function();
interpreter.chunk = continuation.levelTwoChunk();
interpreter.offset = continuation.levelTwoOffset();
// Clear the fiber's continuation slot while it's active.
aFiber.continuation(nil);
}
});
}
/**
* Schedule resumption of the specified {@linkplain FiberDescriptor fiber}
* following {@linkplain ExecutionState#SUSPENDED suspension} by a
* {@linkplain Result#FAILURE failed} {@linkplain Primitive primitive}. This
* method is an entry point.
*
* @param runtime
* An {@linkplain AvailRuntime Avail runtime}.
* @param aFiber
* The fiber to run.
* @param failureValue
* The failure value produced by the failed primitive attempt.
* @param failureFunction
* The primitive failure {@linkplain FunctionDescriptor function}.
* @param args
* The arguments to the primitive.
*/
public static void resumeFromFailedPrimitive (
final AvailRuntime runtime,
final A_Fiber aFiber,
final A_BasicObject failureValue,
final A_Function failureFunction,
final List<AvailObject> args)
{
assert !aFiber.continuation().equalsNil();
assert aFiber.executionState() == SUSPENDED;
assert aFiber.suspendingFunction().equals(failureFunction);
executeFiber(
runtime,
aFiber,
interpreter ->
{
final A_RawFunction code = failureFunction.code();
final @Nullable Primitive prim = code.primitive();
assert prim != null;
assert !prim.hasFlag(CannotFail);
assert prim.hasFlag(CanSuspend);
assert args.size() == code.numArgs();
assert interpreter.reifiedContinuation == null;
interpreter.reifiedContinuation =
(AvailObject) aFiber.continuation();
aFiber.continuation(nil);
interpreter.function = failureFunction;
interpreter.argsBuffer.clear();
interpreter.argsBuffer.addAll(args);
interpreter.latestResult(failureValue);
final L2Chunk chunk = code.startingChunk();
interpreter.chunk = chunk;
interpreter.offset = chunk.offsetAfterInitialTryPrimitive();
interpreter.exitNow = false;
interpreter.returnNow = false;
});
}
/**
* Stringify an {@linkplain AvailObject Avail value}, using the {@link
* HookType#STRINGIFICATION} hook in the specified {@linkplain AvailRuntime
* runtime}. Stringification will run in a new {@linkplain FiberDescriptor
* fiber}. If stringification fails for any reason, then the built-in
* mechanism, available via {@link AvailObject#toString()} will be used.
* Invoke the specified continuation with the result.
*
* @param runtime
* An Avail runtime.
* @param textInterface
* The {@linkplain TextInterface text interface} for {@linkplain
* A_Fiber fibers} started due to stringification. This need not be
* the {@linkplain AvailRuntime#textInterface() default text
* interface}.
* @param value
* An Avail value.
* @param continuation
* What to do with the stringification of {@code value}.
*/
public static void stringifyThen (
final AvailRuntime runtime,
final TextInterface textInterface,
final A_BasicObject value,
final Continuation1NotNull<String> continuation)
{
final A_Function stringifierFunction = STRINGIFICATION.get(runtime);
// If the stringifier function is not defined, then use the basic
// mechanism for stringification.
// Create the fiber that will execute the function.
final A_Fiber fiber = newFiber(
stringType(),
stringificationPriority,
() -> stringFrom("Stringification"));
fiber.textInterface(textInterface);
fiber.setSuccessAndFailureContinuations(
string -> continuation.value(string.asNativeString()),
e -> continuation.value(format(
"(stringification failed [%s]) %s",
e.getClass().getSimpleName(),
value.toString())));
// Stringify!
Interpreter.runOutermostFunction(
runtime,
fiber,
stringifierFunction,
singletonList(value));
}
/**
* Stringify a {@linkplain List list} of {@linkplain AvailObject Avail
* values}, using the {@link HookType#STRINGIFICATION} hook associated with
* the specified {@linkplain AvailRuntime runtime}. Stringification will run
* in parallel, with each value being processed by its own new {@linkplain
* FiberDescriptor fiber}. If stringification fails for a value for any
* reason, then the built-in mechanism, available via {@link
* AvailObject#toString()} will be used for that value. Invoke the specified
* continuation with the resulting list, preserving the original order.
*
* @param runtime
* An Avail runtime.
* @param textInterface
* The {@linkplain TextInterface text interface} for {@linkplain
* A_Fiber fibers} started due to stringification. This need not be
* the {@linkplain AvailRuntime#textInterface() default text
* interface}.
* @param values
* Some Avail values.
* @param continuation
* What to do with the resulting list.
*/
public static void stringifyThen (
final AvailRuntime runtime,
final TextInterface textInterface,
final List<? extends A_BasicObject> values,
final Continuation1NotNull<List<String>> continuation)
{
final int valuesCount = values.size();
if (valuesCount == 0)
{
continuation.value(emptyList());
return;
}
// Deduplicate the list of values for performance…
final Map<A_BasicObject, List<Integer>> map =
new HashMap<>(valuesCount);
for (int i = 0; i < values.size(); i++)
{
final A_BasicObject value = values.get(i);
final List<Integer> indices = map.computeIfAbsent(
value,
k -> new ArrayList<>());
indices.add(i);
}
final AtomicInteger outstanding = new AtomicInteger(map.size());
final String[] strings = new String[valuesCount];
for (final Entry<A_BasicObject, List<Integer>> entry
: map.entrySet())
{
final List<Integer> indicesToWrite = entry.getValue();
stringifyThen(
runtime,
textInterface,
entry.getKey(),
arg ->
{
for (final int indexToWrite : indicesToWrite)
{
strings[indexToWrite] = arg;
}
if (outstanding.decrementAndGet() == 0)
{
final List<String> stringList = asList(strings);
continuation.value(stringList);
}
});
}
}
@Override
public String toString ()
{
final StringBuilder builder = new StringBuilder();
builder.append(getClass().getSimpleName());
builder.append(" #");
builder.append(interpreterIndex);
if (fiber == null)
{
builder.append(" [«unbound»]");
}
else
{
builder.append(formatString(" [%s]", fiber.fiberName()));
if (reifiedContinuation == null)
{
builder.append(formatString("%n\t«null stack»"));
}
else if (reifiedContinuation.equalsNil())
{
builder.append(formatString("%n\t«empty call stack»"));
}
builder.append("\n\n");
}
return builder.toString();
}
/**
* {@link Statistic} measuring the performance of dynamic lookups, keyed by
* the number of definitions in the method being looked up. Tho name of the
* statistic includes this count, as well as the name of the first bundle
* encountered which had that count.
*/
@GuardedBy("dynamicLookupStatsLock")
private static final Map<Integer, Statistic>
dynamicLookupStatsByCount = new HashMap<>();
/**
* The lock that protects access to {@link #dynamicLookupStatsByCount}.
*/
private static final ReadWriteLock dynamicLookupStatsLock =
new ReentrantReadWriteLock();
/**
* A <em>non-static</em> field of this interpreter that holds a mapping from
* the number of definitions considered in a lookup, to a {@link
* PerInterpreterStatistic} specific to this interpreter. This is accessed
* without a lock, and only by the thread accessing this interpreter (other
* than to view the momentary statistics).
*
* <p>If the desired key is not found, acquire the {@link
* #dynamicLookupStatsLock} with read access, extracting the {@link
* PerInterpreterStatistic} from the {@link Statistic} in {@link
* #dynamicLookupStatsByCount}. If the key was not present, release the
* lock, acquire it for write access, try looking it up again (in case the
* map changed while the lock wasn't held), and if necessary add a new entry
* for that size, including the bundle name as an example in the name of the
* statistic.</p>
*/
private final Map<Integer, PerInterpreterStatistic>
dynamicLookupPerInterpreterStat = new HashMap<>();
/**
* Record the fact that a lookup in the specified {@link
* MessageBundleDescriptor message bundle} has just taken place, and that it
* took the given time in nanoseconds.
*
* <p>At the moment, we only record the duration of the lookup, and we do so
* under a statistic tied to the number of definitions in the bundle's
* method. We do, however, record the name of the first looked up bundle
* having that number of definitions.</p>
*
* <p>Before 2017.12, we used to do this:</p>
*
* <p>Multiple runs will create distinct message bundles, but we'd like them
* aggregated. Therefore we store each statistic not only under the bundle
* but under the bundle's message's print representation. We first look for
* an exact match by bundle, then fall back by the slower string search,
* making the same statistic available under the new bundle for the next
* time it occurs.</p>
*
* @param bundle A message bundle in which a lookup has just taken place.
* @param nanos A {@code double} indicating how many nanoseconds it took.
*/
public void recordDynamicLookup (
final A_Bundle bundle,
final double nanos)
{
final int size = bundle.bundleMethod().definitionsTuple().tupleSize();
@Nullable PerInterpreterStatistic perInterpreterStat =
dynamicLookupPerInterpreterStat.get(size);
if (perInterpreterStat == null)
{
// See if we can find it in the global map.
dynamicLookupStatsLock.readLock().lock();
@Nullable Statistic globalStat;
try
{
globalStat = dynamicLookupStatsByCount.get(size);
}
finally
{
dynamicLookupStatsLock.readLock().unlock();
}
if (globalStat == null)
{
// It didn't exist when we looked for it while holding the read
// lock. Having released the read lock, grab the write lock,
// double-check for the element, then if necessary create it.
dynamicLookupStatsLock.writeLock().lock();
try
{
globalStat = dynamicLookupStatsByCount.get(size);
if (globalStat == null)
{
// Create it.
globalStat = new Statistic(
"Dynamic lookup time for size "
+ size
+ " (example: "
+ bundle.message().atomName()
+ ")",
StatisticReport.DYNAMIC_LOOKUP_TIME);
dynamicLookupStatsByCount.put(size, globalStat);
}
}
finally
{
dynamicLookupStatsLock.writeLock().unlock();
}
}
perInterpreterStat =
stripNull(globalStat).statistics[interpreterIndex];
dynamicLookupPerInterpreterStat.put(size, perInterpreterStat);
}
perInterpreterStat.record(nanos);
}
/**
* Top-level statement evaluation statistics, keyed by module.
*/
private static final Map<A_Module, Statistic>
topStatementEvaluationStats = new WeakHashMap<>();
/**
* Record the fact that a statement starting at the given line number in the
* given module just took some number of nanoseconds to run.
*
* <p>As of 2017.12, we no longer record a separate statistic for each
* top-level statement, so the line number is ignored.</p>
*
* @param sample The number of nanoseconds.
* @param module The module containing the top-level statement that ran.
* @param lineNumber The line number of the statement that ran. Ignored.
*/
public void recordTopStatementEvaluation (
final double sample,
final A_Module module,
@SuppressWarnings("unused") final int lineNumber)
{
final Statistic statistic;
//noinspection SynchronizationOnStaticField
synchronized (topStatementEvaluationStats)
{
final A_Module moduleTraversed = module.traversed();
statistic = topStatementEvaluationStats.computeIfAbsent(
moduleTraversed,
mod -> new Statistic(
mod.moduleName().asNativeString(),
StatisticReport.TOP_LEVEL_STATEMENTS));
}
statistic.record(sample, interpreterIndex);
}
/**
* The bootstrapped {@linkplain P_SetValue assignment function} used to
* restart implicitly observed assignments.
*/
private static final A_Function assignmentFunction =
createFunction(
newPrimitiveRawFunction(instance, nil, 0),
emptyTuple()
).makeShared();
/**
* Answer the bootstrapped {@linkplain P_SetValue assignment function}
* used to restart implicitly observed assignments.
*
* @return The assignment function.
*/
public static A_Function assignmentFunction ()
{
return assignmentFunction;
}
}
| 32.870058 | 111 | 0.710696 |
Subsets and Splits