repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
inkstand-io/scribble | scribble-jcr/src/main/java/io/inkstand/scribble/jcr/rules/builder/MockContentRepositoryBuilder.java | 1098 | /*
* Copyright 2015-2016 DevCon5 GmbH, info@devcon5.ch
*
* 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 io.inkstand.scribble.jcr.rules.builder;
import io.inkstand.scribble.Builder;
import io.inkstand.scribble.jcr.rules.MockContentRepository;
/**
* A builder for a {@link MockContentRepository}
*
* @author <a href="mailto:gerald.muecke@gmail.com">Gerald Mücke</a>
*/
public class MockContentRepositoryBuilder implements Builder<MockContentRepository> {
@Override
public MockContentRepository build() {
return new MockContentRepository();
}
}
| apache-2.0 |
forgeide/forgeide | src/main/java/org/forgeide/model/ProjectAccess.java | 1749 | package org.forgeide.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
/**
* Controls access levels for projects
*
* @author Shane Bryzak
*
*/
@Entity
@Table(name = "PROJECT_ACCESS", uniqueConstraints = {
@UniqueConstraint(columnNames={"PROJECT_ID", "userId"})
})
public class ProjectAccess implements Serializable
{
private static final long serialVersionUID = 6539427720605504095L;
public enum AccessLevel {OWNER, READ, READ_WRITE, RESTRICTED};
@Id @GeneratedValue
private Long id;
@ManyToOne
@JoinColumn(name = "PROJECT_ID")
private Project project;
private String userId;
// Indicates whether the user currently has this project open
private boolean open;
// Access level
private AccessLevel accessLevel;
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public Project getProject()
{
return project;
}
public void setProject(Project project)
{
this.project = project;
}
public String getUserId()
{
return userId;
}
public void setUserId(String userId)
{
this.userId = userId;
}
public boolean isOpen()
{
return open;
}
public void setOpen(boolean open)
{
this.open = open;
}
public AccessLevel getAccessLevel()
{
return accessLevel;
}
public void setAccessLevel(AccessLevel accessLevel)
{
this.accessLevel = accessLevel;
}
}
| apache-2.0 |
liulhdarks/darks-orm | src/darks/orm/core/cache/scope/SessionCacheFactory.java | 12044 | /**
*
* Copyright 2014 The Darks ORM Project (Liu lihua)
*
* 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 darks.orm.core.cache.scope;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.servlet.http.HttpSession;
import net.sf.ehcache.CacheException;
import darks.orm.core.cache.CacheContext.CacheKeyType;
import darks.orm.core.cache.CacheController;
import darks.orm.core.cache.CacheKey;
import darks.orm.core.cache.CacheList;
import darks.orm.core.cache.CacheObject;
import darks.orm.core.cache.control.CacheControllerFactroy;
import darks.orm.core.cache.strategy.CopyStrategy;
import darks.orm.core.config.CacheConfiguration;
import darks.orm.core.config.Configuration;
import darks.orm.core.data.EntityData;
import darks.orm.core.data.FieldData;
import darks.orm.core.data.xml.CacheConfigData;
import darks.orm.core.session.SessionContext;
import darks.orm.log.Logger;
import darks.orm.log.LoggerFactory;
import darks.orm.util.ByteHelper;
import darks.orm.web.context.RequestContext;
@SuppressWarnings("unchecked")
public class SessionCacheFactory implements CacheFactory
{
private static final Logger logger = LoggerFactory.getLogger(SessionCacheFactory.class);
private static final String SESSION_KEYLIST_KEY = "DARKS$SESSION$KEYLIST_KEY";
private static final String SESSION_ENTITYMAP_KEY = "DARKS$SESSION$ENTITYMAP_KEY";
private static final String SESSION_ENTITYLISTMAP_KEY = "DARKS$SESSION$ENTITYLISTMAP_KEY";
private static final String SESSION_CONTROLLER_KEY = "DARKS$SESSION$CONTROLLER_KEY";
private static volatile SessionCacheFactory instace = null;
private static final ReadWriteLock rwlock = new ReentrantReadWriteLock();
private static final Lock rlock = rwlock.readLock();
private static final Lock wlock = rwlock.writeLock();
private CacheConfigData sessionConfigData;
private CopyStrategy copyStrategy;
private SessionCacheFactory()
{
try
{
Configuration cfg = SessionContext.getConfigure();
CacheConfiguration cacheCfg = cfg.getCacheConfig();
if (cacheCfg == null)
return;
sessionConfigData = cacheCfg.getSessionCacheData();
if (sessionConfigData == null)
return;
copyStrategy = sessionConfigData.getCopyStrategy();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static CacheFactory getInstance()
{
Configuration cfg = SessionContext.getConfigure();
if (cfg == null)
return null;
CacheConfiguration cacheCfg = cfg.getCacheConfig();
if (cacheCfg == null)
return null;
CacheConfigData data = cacheCfg.getThreadCacheData();
if (data == null)
return null;
if (instace == null)
{
instace = new SessionCacheFactory();
}
return instace;
}
/**
* »º´æ¶ÔÏó
*
* @param key »º´æKEY
* @param obj ¶ÔÏóʵÀý
* @throws Exception
*/
public void cacheObject(CacheKey key, Object obj)
throws Exception
{
if (key == null || obj == null)
return;
EntityData data = key.getData();
if (data == null || !ByteHelper.isSerializable(data))
return;
Map<CacheKey, CacheList> listMap = getListMap();
CacheController controller = getCacheController();
wlock.lock();
try
{
if (obj instanceof List && !sessionConfigData.isEntirety())
{
List list = (List)obj;
if (list.size() > sessionConfigData.getMaxObject())
{
throw new CacheException("the size of list cacheing is flowover the max limit");
}
FieldData pkfdata = data.getPkField();
Map<CacheKey, Object> map = new ConcurrentHashMap<CacheKey, Object>();
List<CacheKey> clist = new ArrayList<CacheKey>();
for (Object ob : list)
{
int piId = (Integer)pkfdata.getValue(ob);
CacheKey newkey = new CacheKey(data, piId, CacheKeyType.SingleKey);
Object value = new CacheObject(copyStrategy, newkey, ob);// new
// SoftReference<Object>(ob);//(Object)ByteHelper.ObjectToByte(ob);
controller.cacheObject(newkey, value);
map.put(newkey, value);
clist.add(newkey);
}
CacheList cacheList = new CacheList(map, clist);
listMap.put(key, cacheList);
}
else
{
Object value = new CacheObject(copyStrategy, key, obj);// new
// SoftReference<Object>(obj);//(Object)ByteHelper.ObjectToByte(obj);
controller.cacheObject(key, value);
}
}
catch (Exception e)
{
throw new CacheException(e.getMessage(), e);
}
finally
{
wlock.unlock();
}
}
/**
* »ñµÃ¶ÔÏó
*
* @param key »º´æKEY
* @return ¶ÔÏóʵÀý
* @throws Exception
*/
public Object getObject(CacheKey key)
throws Exception
{
if (key.getData() == null)
return false;
if (!key.getData().isSerializable())
return false;
Map<CacheKey, CacheList> listMap = getListMap();
CacheController controller = getCacheController();
rlock.lock();
try
{
if ((key.getCacheKeyType() == CacheKeyType.ListKey || key.getCacheKeyType() == CacheKeyType.PageKey)
&& !sessionConfigData.isEntirety())
{
CacheList cacheList = listMap.get(key);
if (cacheList == null)
return null;
key.setCount(cacheList.getCount());
List<CacheKey> clist = cacheList.getList();
List<Object> list = new ArrayList<Object>(clist.size());
for (CacheKey ckey : clist)
{
CacheObject val = (CacheObject)controller.getObject(ckey);
if (val == null)
return null;
val.setLastIdleTime(System.currentTimeMillis());
list.add(val.getObject());
}
return list;
}
CacheObject value = (CacheObject)controller.getObject(key);
if (value == null)
return null;
key.setCount(value.getKey().getCount());
value.setLastIdleTime(System.currentTimeMillis());
return value.getObject();
}
catch (Exception e)
{
throw e;
}
finally
{
rlock.unlock();
}
}
/**
* »º´æÖÐÊÇ·ñ´æÔÚÓµÓд˻º´æKEYµÄ¶ÔÏó
*
* @param key »º´æKEY
* @return true´æÔÚ false²»´æÔÚ
*/
public boolean containKey(CacheKey key)
{
Map<CacheKey, Object> entityMap = getEntityMap();
Map<CacheKey, CacheList> listMap = getListMap();
rlock.lock();
try
{
if ((key.getCacheKeyType() == CacheKeyType.ListKey || key.getCacheKeyType() == CacheKeyType.PageKey)
&& !sessionConfigData.isEntirety())
{
return listMap.containsKey(key);
}
return entityMap.containsKey(key);
}
finally
{
rlock.unlock();
}
}
/**
* »ñµÃ¼üÖµÁбí
*
* @return ¼üÖµ¶ÓÁÐ
*/
private Queue<CacheKey> getKeysList()
{
HttpSession session = RequestContext.getInstance().getSession();
Queue<CacheKey> keysList = (Queue<CacheKey>)session.getAttribute(SESSION_KEYLIST_KEY);
if (keysList == null)
{
keysList = new ConcurrentLinkedQueue<CacheKey>();
session.setAttribute(SESSION_KEYLIST_KEY, keysList);
}
return keysList;
}
/**
* »ñµÃʵÌåMAP
*
* @return MAP
*/
private Map<CacheKey, Object> getEntityMap()
{
HttpSession session = RequestContext.getInstance().getSession();
Map<CacheKey, Object> entityMap = (Map<CacheKey, Object>)session.getAttribute(SESSION_ENTITYMAP_KEY);
if (entityMap == null)
{
int initnum = 0;
int max = sessionConfigData.getMaxObject();
if (max < 1000)
{
initnum = max * 2 / 3;
}
else if (max < 10000)
{
initnum = max * 1 / 5;
}
else if (max > 10000)
{
initnum = max * 1 / 100;
}
entityMap = new ConcurrentHashMap<CacheKey, Object>(initnum);
session.setAttribute(SESSION_ENTITYMAP_KEY, entityMap);
}
return entityMap;
}
private Map<CacheKey, CacheList> getListMap()
{
HttpSession session = RequestContext.getInstance().getSession();
Map<CacheKey, CacheList> listMap = (Map<CacheKey, CacheList>)session.getAttribute(SESSION_ENTITYLISTMAP_KEY);
if (listMap == null)
{
listMap = new ConcurrentHashMap<CacheKey, CacheList>(64);
session.setAttribute(SESSION_ENTITYLISTMAP_KEY, listMap);
}
return listMap;
}
private CacheController getCacheController()
{
HttpSession session = RequestContext.getInstance().getSession();
CacheController ctrl = (CacheController)session.getAttribute(SESSION_CONTROLLER_KEY);
if (ctrl == null)
{
Queue<CacheKey> keysList = getKeysList();
Map<CacheKey, Object> entityMap = getEntityMap();
Map<CacheKey, CacheList> listMap = getListMap();
ctrl = CacheControllerFactroy.getCacheController(sessionConfigData, keysList, entityMap, listMap);
session.setAttribute(SESSION_CONTROLLER_KEY, ctrl);
}
return ctrl;
}
public void debug()
{
Queue<CacheKey> keysList = getKeysList();
Map<CacheKey, Object> entityMap = getEntityMap();
Map<CacheKey, CacheList> listMap = getListMap();
System.out.println(keysList.size() + " " + entityMap.size() + " " + listMap.size());
for (CacheKey key : keysList)
{
System.out.println(key.getId() + " " + key.getCacheKeyType());
}
}
public void flush()
{
Queue<CacheKey> keysList = getKeysList();
Map<CacheKey, Object> entityMap = getEntityMap();
Map<CacheKey, CacheList> listMap = getListMap();
wlock.lock();
try
{
listMap.clear();
keysList.clear();
entityMap.clear();
}
catch (Exception e)
{
}
finally
{
wlock.unlock();
}
}
} | apache-2.0 |
SENA-CEET/1349397-Trimestre-4 | java/JDBC/jdbc/src/main/java/co/edu/sena/jdbc/basic/interfacepreparedstatement/Ejemplo03.java | 1627 | package co.edu.sena.jdbc.basic.interfacepreparedstatement;
import java.sql.*;
public class Ejemplo03 {
public static void main(String[] args) throws SQLException {
String url = "jdbc:mysql://localhost:4306?database=observador_de_proyectos";
String usuarioBaseDatos = "pepito";
String passwordDatabase = "123456789";
Connection conexion = null;
PreparedStatement sentencia = null;
String sql = "INSERT INTO `observador_de_proyectos`.`cliente`\n" +
"(`tipo_documento`,\n" +
"`numero_documento`,\n" +
"`primer_nombre`,\n" +
"`segundo_nombre`,\n" +
"`primer_apellido`,\n" +
"`segundo_apellido`\n" +
")\n" +
"VALUES\n" +
"(?,?,?,?,?,?);";
try {
conexion = DriverManager.getConnection(url, usuarioBaseDatos, passwordDatabase);
sentencia = conexion.prepareStatement(sql);
sentencia.setString(1, "CC");
sentencia.setString(2, "88888");
sentencia.setString(3, "sdfasd");
sentencia.setString(4, "80013833");
sentencia.setString(5, "80013833");
sentencia.setString(6, "80013833");
int rs = sentencia.executeUpdate();
System.out.println(rs);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (sentencia != null)
sentencia.close();
if (conexion != null) {
conexion.close();
}
}
}
}
| apache-2.0 |
dbflute-session/erflute | src/org/dbflute/erflute/editor/view/action/line/ResizeModelAction.java | 2600 | package org.dbflute.erflute.editor.view.action.line;
import java.util.ArrayList;
import java.util.List;
import org.dbflute.erflute.Activator;
import org.dbflute.erflute.core.DisplayMessages;
import org.dbflute.erflute.core.ImageKey;
import org.dbflute.erflute.editor.MainDiagramEditor;
import org.dbflute.erflute.editor.controller.command.diagram_contents.element.node.MoveElementCommand;
import org.dbflute.erflute.editor.controller.editpart.element.node.DiagramWalkerEditPart;
import org.dbflute.erflute.editor.controller.editpart.element.node.ERTableEditPart;
import org.dbflute.erflute.editor.controller.editpart.element.node.IResizable;
import org.dbflute.erflute.editor.controller.editpart.element.node.WalkerNoteEditPart;
import org.dbflute.erflute.editor.model.diagram_contents.element.node.DiagramWalker;
import org.dbflute.erflute.editor.view.action.AbstractBaseSelectionAction;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.GraphicalViewer;
import org.eclipse.gef.commands.Command;
import org.eclipse.swt.widgets.Event;
public class ResizeModelAction extends AbstractBaseSelectionAction {
public static final String ID = ResizeModelAction.class.getName();
public ResizeModelAction(MainDiagramEditor editor) {
super(ID, DisplayMessages.getMessage("action.title.auto.resize"), editor);
setImageDescriptor(Activator.getImageDescriptor(ImageKey.RESIZE));
}
@Override
protected List<Command> getCommand(EditPart editPart, Event event) {
final List<Command> commandList = new ArrayList<>();
if (editPart instanceof IResizable) {
final DiagramWalker nodeElement = (DiagramWalker) editPart.getModel();
final MoveElementCommand command =
new MoveElementCommand(getDiagram(), ((DiagramWalkerEditPart) editPart).getFigure().getBounds(),
nodeElement.getX(), nodeElement.getY(), -1, -1, nodeElement);
commandList.add(command);
}
return commandList;
}
@Override
protected boolean calculateEnabled() {
final GraphicalViewer viewer = getGraphicalViewer();
for (final Object object : viewer.getSelectedEditParts()) {
if (object instanceof DiagramWalkerEditPart) {
final DiagramWalkerEditPart nodeElementEditPart = (DiagramWalkerEditPart) object;
if (nodeElementEditPart instanceof ERTableEditPart || nodeElementEditPart instanceof WalkerNoteEditPart) {
return true;
}
}
}
return false;
}
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_2084.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_2084 {
}
| apache-2.0 |
fnl/txtfnnl | txtfnnl-utils/src/test/java/txtfnnl/utils/TestConcurrentPatriciaTree.java | 1468 | package txtfnnl.utils;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.googlecode.concurrenttrees.common.KeyValuePair;
public class TestConcurrentPatriciaTree {
PatriciaTree<String> trie;
int hits;
@Before
public void setUp() {
trie = new ConcurrentPatriciaTree<String>();
trie.put("key", "value1");
trie.put("keykey", "value2");
trie.put("other", "value2");
hits = 0;
}
@Test
public final void testScanForKeyValuePairsAtStartOf() {
for (KeyValuePair<String> kvp : trie.scanForKeyValuePairsAtStartOf("keykeyother")) {
if (kvp.getKey().equals("key")) assertEquals("value1", kvp.getValue());
else if (kvp.getKey().equals("keykey")) assertEquals("value2", kvp.getValue());
else fail("unexpected key " + kvp.getKey());
hits++;
}
assertEquals(2, hits);
}
@Test
public final void testScanForKeysAtStartOf() {
for (CharSequence key : trie.scanForKeysAtStartOf("keykeyother")) {
if (key.equals("key")) hits++;
else if (key.equals("keykey")) hits++;
else fail("unexpected key " + key);
}
assertEquals(2, hits);
}
@Test
public final void testScanForValuesAtStartOf() {
for (String value : trie.scanForValuesAtStartOf("keykeyother")) {
if (value.equals("value1")) hits++;
else if (value.equals("value2")) hits++;
else fail("unexpected value " + value);
}
assertEquals(2, hits);
}
}
| apache-2.0 |
qdiankun/firstcode | firstcode/aidlclient/src/androidTest/java/com/me/diankun/aidlserver/ApplicationTest.java | 368 | package com.me.diankun.aidlserver;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | apache-2.0 |
google-code-export/google-api-dfp-java | src/com/google/api/ads/dfp/v201311/ReconciliationReportRowServiceInterface.java | 4948 | /**
* ReconciliationReportRowServiceInterface.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.v201311;
public interface ReconciliationReportRowServiceInterface extends java.rmi.Remote {
/**
* Gets a {@link ReconciliationReportRowPage} of {@link ReconciliationReportRow}
* objects that
* satisfy the given {@link Statement#query}. The following fields
* are supported for filtering:
*
* <table>
* <tr>
* <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
* </tr>
* <tr>
* <td>{@code reconciliationReportId}</td>
* <td>{@link ReconciliationReportRow#reconciliationReportId}</td>
* </tr>
* <tr>
* <td>{@code advertiserId}</td>
* <td>{@link ReconciliationReportRow#advertiserId}</td>
* </tr>
* <tr>
* <td>{@code orderId}</td>
* <td>{@link ReconciliationReportRow#orderId}</td>
* </tr>
* <tr>
* <td>{@code lineItemId}</td>
* <td>{@link ReconciliationReportRow#lineItemId}</td>
* </tr>
* <tr>
* <td>{@code creativeId}</td>
* <td>{@link ReconciliationReportRow#creativeId}</td>
* </tr>
* <tr>
* <td>{@code lineItemCostType}</td>
* <td>{@link ReconciliationReportRow#lineItemCostType}</td>
* </tr>
* <tr>
* <td>{@code dfpClicks}</td>
* <td>{@link ReconciliationReportRow#dfpClicks}</td>
* </tr>
* <tr>
* <td>{@code dfpImpressions}</td>
* <td>{@link ReconciliationReportRow#dfpImpressions}</td>
* </tr>
* <tr>
* <td>{@code dfpLineItemDays}</td>
* <td>{@link ReconciliationReportRow#dfpLineItemDays}</td>
* </tr>
* <tr>
* <td>{@code thirdPartyClicks}</td>
* <td>{@link ReconciliationReportRow#thirdPartyClicks}</td>
* </tr>
* <tr>
* <td>{@code thirdPartyImpressions}</td>
* <td>{@link ReconciliationReportRow#thirdPartyImpressions}</td>
* </tr>
* <tr>
* <td>{@code thirdPartyLineItemDays}</td>
* <td>{@link ReconciliationReportRow#thirdPartyLineItemDays}</td>
* </tr>
* <tr>
* <td>{@code manualClicks}</td>
* <td>{@link ReconciliationReportRow#manualClicks}</td>
* </tr>
* <tr>
* <td>{@code manualImpressions}</td>
* <td>{@link ReconciliationReportRow#manualImpressions}</td>
* </tr>
* <tr>
* <td>{@code manualLineItemDays}</td>
* <td>{@link ReconciliationReportRow#manualLineItemDays}</td>
* </tr>
* <tr>
* <td>{@code reconciledClicks}</td>
* <td>{@link ReconciliationReportRow#reconciledClicks}</td>
* </tr>
* <tr>
* <td>{@code reconciledImpressions}</td>
* <td>{@link ReconciliationReportRow#reconciledImpressions}</td>
* </tr>
* <tr>
* <td>{@code reconciledLineItemDays}</td>
* <td>{@link ReconciliationReportRow#reconciledLineItemDays}</td>
* </tr>
* </table>
*
* The {@code reconciliationReportId} field is required and can
* only be combined with an
* {@code AND} to other conditions. Furthermore, the results
* may only belong to
* one {@link ReconciliationReport}.
*
*
* @param filterStatement a Publisher Query Language statement used to
* filter a set of reconciliation report rows
*
* @return the reconciliation report rows that match the given filter
*/
public com.google.api.ads.dfp.v201311.ReconciliationReportRowPage getReconciliationReportRowsByStatement(com.google.api.ads.dfp.v201311.Statement filterStatement) throws java.rmi.RemoteException, com.google.api.ads.dfp.v201311.ApiException;
/**
* Updates a list of {@link ReconciliationReportRow} which belong
* to same
* {@link ReconciliationReport}.
*
*
* @param reconciliationReportRows a list of reconciliation report rows
* to update
*
* @return the updated reconciliation report rows
*/
public com.google.api.ads.dfp.v201311.ReconciliationReportRow[] updateReconciliationReportRows(com.google.api.ads.dfp.v201311.ReconciliationReportRow[] reconciliationReportRows) throws java.rmi.RemoteException, com.google.api.ads.dfp.v201311.ApiException;
}
| apache-2.0 |
blstream/StudyBox_Android | app/src/main/java/com/blstream/studybox/exam/question_view/QuestionViewState.java | 5063 | package com.blstream.studybox.exam.question_view;
import com.hannesdorfmann.mosby.mvp.viewstate.ViewState;
public class QuestionViewState<V extends QuestionView> implements ViewState<V> {
protected final static int STATE_SHOW_QUESTION_TEXT = 0;
protected final static int STATE_SHOW_QUESTION_IMAGE = 1;
protected final static int STATE_SHOW_PROMPT_TEXT = 2;
protected final static int STATE_SHOW_PROMPT_IMAGE = 3;
protected final static int STATE_ENABLE_PROMPT = 4;
protected final static int STATE_DISABLE_PROMPT = 5;
protected final static int STATE_SHOW_QUESTION = 6;
protected final static int STATE_SHOW_PROMPT = 7;
protected final static int STATE_SHOW_LEFT_PROMPT_ARROW = 8;
protected final static int STATE_HIDE_LEFT_PROMPT_ARROW = 9;
protected final static int STATE_SHOW_RIGHT_PROMPT_ARROW = 10;
protected final static int STATE_HIDE_RIGHT_PROMPT_ARROW = 11;
protected String question;
protected String prompt;
protected int promptPosition;
protected int viewSwitcherState = STATE_SHOW_QUESTION;
protected int questionState = STATE_SHOW_QUESTION_TEXT;
protected int promptState = STATE_DISABLE_PROMPT;
protected int leftPromptArrowState = STATE_HIDE_LEFT_PROMPT_ARROW;
protected int rightPromptArrowState = STATE_HIDE_RIGHT_PROMPT_ARROW;
public void setStateShowQuestion() {
viewSwitcherState = STATE_SHOW_QUESTION;
}
public void setStateShowPrompt() {
viewSwitcherState = STATE_SHOW_PROMPT;
}
public void setStateShowQuestionText(String question) {
this.question = question;
questionState = STATE_SHOW_QUESTION_TEXT;
}
public void setStateShowQuestionImage(String question) {
this.question = question;
questionState = STATE_SHOW_QUESTION_IMAGE;
}
public void setStateShowPromptText(String prompt, int promptPosition) {
this.prompt = prompt;
this.promptPosition = promptPosition;
promptState = STATE_SHOW_PROMPT_TEXT;
}
public void setStateShowPromptImage(String prompt, int promptPosition) {
this.prompt = prompt;
this.promptPosition = promptPosition;
promptState = STATE_SHOW_PROMPT_IMAGE;
}
public void setStateShowLeftPromptArrow() {
leftPromptArrowState = STATE_SHOW_LEFT_PROMPT_ARROW;
}
public void setStateHideLeftPromptArrow() {
leftPromptArrowState = STATE_HIDE_LEFT_PROMPT_ARROW;
}
public void setStateShowRightPromptArrow() {
rightPromptArrowState = STATE_SHOW_RIGHT_PROMPT_ARROW;
}
public void setStateHideRightPromptArrow() {
rightPromptArrowState = STATE_HIDE_RIGHT_PROMPT_ARROW;
}
public void setStateEnablePrompt() {
promptState = STATE_ENABLE_PROMPT;
}
public void setStateDisablePrompt() {
promptState = STATE_DISABLE_PROMPT;
}
@Override
public void apply(V view, boolean retained) {
switch (viewSwitcherState) {
case STATE_SHOW_QUESTION:
view.showPromptsAfterOrientationChanged(false);
break;
case STATE_SHOW_PROMPT:
view.showPromptsAfterOrientationChanged(true);
break;
}
switch (questionState) {
case STATE_SHOW_QUESTION_TEXT:
view.showTextQuestion(question);
break;
case STATE_SHOW_QUESTION_IMAGE:
view.showImageQuestion(question);
break;
}
switch (promptState) {
case STATE_SHOW_PROMPT_TEXT:
view.enablePrompt();
view.showTextPrompt(prompt);
view.setPromptPosition(promptPosition);
checkLeftPromptArrowState(view);
checkRightPromptArrowState(view);
break;
case STATE_SHOW_PROMPT_IMAGE:
view.enablePrompt();
view.showImagePrompt(prompt);
view.setPromptPosition(promptPosition);
checkLeftPromptArrowState(view);
checkRightPromptArrowState(view);
break;
case STATE_ENABLE_PROMPT:
view.enablePrompt();
break;
case STATE_DISABLE_PROMPT:
view.disablePrompt();
break;
}
}
private void checkLeftPromptArrowState(V view) {
switch (leftPromptArrowState) {
case STATE_SHOW_LEFT_PROMPT_ARROW:
view.showLeftPromptArrow();
break;
case STATE_HIDE_LEFT_PROMPT_ARROW:
view.hideLeftPromptArrow();
break;
}
}
private void checkRightPromptArrowState(V view) {
switch (rightPromptArrowState) {
case STATE_SHOW_RIGHT_PROMPT_ARROW:
view.showRightPromptArrow();
break;
case STATE_HIDE_RIGHT_PROMPT_ARROW:
view.hideRightPromptArrow();
break;
}
}
}
| apache-2.0 |
code-distillery/httpclient-configuration-support | src/test/java/net/distilledcode/httpclient/impl/HttpClientConfigurationIT.java | 12220 | package net.distilledcode.httpclient.impl;
import net.distilledcode.testing.osgi.ServiceUtils.Action;
import net.distilledcode.testing.osgi.ServiceUtils.ServiceAction;
import net.distilledcode.testing.osgi.ServiceUtils.ServicePropertiesAction;
import org.apache.http.client.HttpClient;
import org.apache.http.osgi.services.HttpClientBuilderFactory;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;
import static net.distilledcode.httpclient.impl.HttpClientConfiguration.HTTP_CLIENT_CONFIG_NAME;
import static net.distilledcode.testing.osgi.PaxUtils.debug;
import static net.distilledcode.testing.osgi.PaxUtils.failOnUnresolvedBundle;
import static net.distilledcode.testing.osgi.PaxUtils.findProjectBundle;
import static net.distilledcode.testing.osgi.PaxUtils.logback;
import static net.distilledcode.testing.osgi.PaxUtils.webconsole;
import static net.distilledcode.testing.osgi.PaxUtils.workingDirectory;
import static net.distilledcode.testing.osgi.ServiceUtils.EVENT_TYPE_ANY;
import static net.distilledcode.testing.osgi.ServiceUtils.awaitServiceEvent;
import static net.distilledcode.testing.osgi.ServiceUtils.properties;
import static net.distilledcode.testing.osgi.ServiceUtils.withEachService;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.ops4j.pax.exam.CoreOptions.bootClasspathLibrary;
import static org.ops4j.pax.exam.CoreOptions.bundle;
import static org.ops4j.pax.exam.CoreOptions.cleanCaches;
import static org.ops4j.pax.exam.CoreOptions.junitBundles;
import static org.ops4j.pax.exam.CoreOptions.linkBundle;
import static org.ops4j.pax.exam.CoreOptions.options;
import static org.osgi.framework.Constants.SERVICE_RANKING;
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerClass.class)
public class HttpClientConfigurationIT {
private static final Logger LOG = LoggerFactory.getLogger(HttpClientConfigurationIT.class);
private static final String SOCKET_TIMEOUT = "request.config.socket.timeout";
@Inject
private BundleContext bundleContext;
@Inject
private HttpClient defaultHttpClient;
@Inject
private ConfigurationAdmin configurationAdmin;
@org.ops4j.pax.exam.Configuration
public Option[] config() throws IOException, URISyntaxException {
final File projectJarFile = findProjectBundle("httpclient-configuration-support-*.jar");
return options(
bootClasspathLibrary(toPath(org.ops4j.pax.url.link.Handler.class)), // support for link: protocol
bootClasspathLibrary(toPath(org.ops4j.pax.url.classpath.Handler.class)), // support for classpath: protocol
failOnUnresolvedBundle(),
workingDirectory(getClass()),
logback(),
bundle(projectJarFile.toURI().toString()),
linkBundle("org.apache.felix.configadmin"),
linkBundle("org.apache.felix.eventadmin"),
linkBundle("org.apache.felix.metatype"),
linkBundle("org.apache.felix.scr"),
linkBundle("org.apache.httpcomponents.httpclient"),
linkBundle("org.apache.httpcomponents.httpcore"),
linkBundle("org.apache.commons.lang"),
// only required for the test setup
junitBundles(),
linkBundle("org.apache.commons.io"),
cleanCaches(),
debug(Integer.getInteger("debug.port", 0))
.useOptions(webconsole(Integer.getInteger("http.port", 8080)))
);
}
private String toPath(final Class<?> clazz) throws URISyntaxException {
return clazz.getProtectionDomain().getCodeSource().getLocation().toURI().toString();
}
@Test
public void defaultClientRegistration() throws Exception {
assertThat(bundleContext, notNullValue());
assertThat("Expected a HttpClient instance", defaultHttpClient, notNullValue());
}
@Test
public void defaultClientRegistrationWithConfiguration() throws Exception {
assertDefaultRegistration(HttpClient.class);
assertDefaultRegistration(HttpClientBuilderFactory.class);
}
private <T> void assertDefaultRegistration(final Class<T> type) throws org.osgi.framework.InvalidSyntaxException, IOException {
final String name = type.getSimpleName();
String filter = "(!(service.pid=org.apache.http.httpclientfactory))";
withEachService(bundleContext, type, filter, new ServicePropertiesAction() {
@Override
public void perform(final Map<String, Object> properties) {
assertThat("Expected properties of a " + name + " instance", properties, notNullValue());
assertThat(properties, not(hasKey(HTTP_CLIENT_CONFIG_NAME)));
assertThat(properties, hasEntry(SERVICE_RANKING, (Object)100));
}
});
final Configuration configuration = configFor(DefaultHttpClientConfiguration.DEFAULT_HTTP_CLIENT_CONFIG_PID);
assertThat(configuration.getProperties(), nullValue());
awaitServiceEvent(bundleContext, objectClassFilter(type), ServiceEvent.REGISTERED, new Action() {
@Override
public void perform() throws IOException {
LOG.trace("Updating config {}", configuration);
configuration.update(properties(SOCKET_TIMEOUT, 2000));
}
});
withEachService(bundleContext, type, filter, new ServicePropertiesAction() {
@Override
public void perform(final Map<String, Object> properties) {
assertThat("Expected properties of a " + name + " instance", properties, notNullValue());
assertThat(properties, not(hasKey(HTTP_CLIENT_CONFIG_NAME)));
assertThat(properties, hasEntry(SERVICE_RANKING, (Object)100));
assertThat(properties, hasEntry(SOCKET_TIMEOUT, (Object)2000));
}
});
awaitServiceEvent(bundleContext, objectClassFilter(HttpClient.class), ServiceEvent.REGISTERED, new Action() {
@Override
public void perform() throws IOException {
try {
awaitServiceEvent(bundleContext, objectClassFilter(HttpClientBuilderFactory.class), ServiceEvent.REGISTERED, new Action() {
@Override
public void perform() throws IOException {
configuration.delete();
}
});
} catch (InvalidSyntaxException e) {
throw new RuntimeException(e);
}
}
});
withEachService(bundleContext, type, filter, new ServiceAction<T>() {
@Override
public void perform(final T service) {
assertThat("Default " + name + " should not require configuration", service, notNullValue());
}
});
}
@Test
public void clientRegistrationWithFactoryConfiguration() throws Exception {
assertFactoryConfigRegistration(HttpClient.class);
assertFactoryConfigRegistration(HttpClientBuilderFactory.class);
}
private <T> void assertFactoryConfigRegistration(final Class<T> type) throws org.osgi.framework.InvalidSyntaxException, IOException {
final String name = type.getSimpleName();
withEachService(bundleContext, type, "(" + HTTP_CLIENT_CONFIG_NAME + "=test-client)", new ServiceAction<T>() {
@Override
public void perform(final T service) {
assertThat(name + "(" + HTTP_CLIENT_CONFIG_NAME + "=test-client) should require configuration",
service, nullValue());
}
});
final Configuration configuration = configurationAdmin.createFactoryConfiguration(HttpClientConfiguration.HTTP_CLIENT_CONFIG_FACTORY_PID, null);
awaitServiceEvent(bundleContext, objectClassFilter(type), EVENT_TYPE_ANY, new Action() {
@Override
public void perform() throws IOException {
LOG.trace("Updating config {}", configuration);
configuration.update(properties(
HTTP_CLIENT_CONFIG_NAME, "test-client",
SOCKET_TIMEOUT, 5000
));
}
});
withEachService(bundleContext, type, "(" + HTTP_CLIENT_CONFIG_NAME + "=test-client)", new ServicePropertiesAction() {
@Override
public void perform(final Map<String, Object> properties) {
assertThat("Expected properties of a " + name + " instance", properties, notNullValue());
assertThat(properties, hasEntry(HTTP_CLIENT_CONFIG_NAME, (Object)"test-client"));
assertThat(properties, not(hasKey(SERVICE_RANKING)));
assertThat(properties, hasEntry(SOCKET_TIMEOUT, (Object)5000));
}
});
awaitServiceEvent(bundleContext, objectClassFilter(HttpClient.class), ServiceEvent.UNREGISTERING, new Action() {
@Override
public void perform() throws IOException {
try {
awaitServiceEvent(bundleContext, objectClassFilter(HttpClientBuilderFactory.class), ServiceEvent.UNREGISTERING, new Action() {
@Override
public void perform() throws IOException {
configuration.delete();
}
});
} catch (InvalidSyntaxException e) {
throw new RuntimeException(e);
}
}
});
withEachService(bundleContext, type, "(" + HTTP_CLIENT_CONFIG_NAME + "=test-client)", new ServiceAction<T>() {
@Override
public void perform(final T service) {
assertThat(name + "(" + HTTP_CLIENT_CONFIG_NAME + "=test-client) should require configuration",
service, nullValue());
}
});
}
private Configuration configFor(final String name) throws IOException {
return configurationAdmin.getConfiguration(name, null);
}
private static String objectClassFilter(final Class<?> clazz) {
return "(objectClass=" + clazz.getName() + ")";
}
private static <K, V> Matcher<? super Map<K, V>> hasEntry(final K key, final V value) {
return new TypeSafeMatcher<Map<K,V>>() {
@Override
public void describeTo(final Description description) {
description.appendText("has entry ");
description.appendValue(key + "=" + value);
}
@Override
protected boolean matchesSafely(final Map<K, V> map) {
return map.containsKey(key) && map.get(key).equals(value);
}
};
}
private static <K, V> Matcher<? super Map<K, V>> hasKey(final K key) {
return new TypeSafeMatcher<Map<K,V>>() {
@Override
public void describeTo(final Description description) {
description.appendText("has key ");
description.appendValue(key);
}
@Override
protected boolean matchesSafely(final Map<K, V> map) {
return map.containsKey(key);
}
};
}
}
| apache-2.0 |
mckunkel/DCDataBaseWithSpark | FaultFinder/src/main/java/testingPackage/JTableRowSelectProgramatically.java | 4809 | /* +__^_________,_________,_____,________^-.-------------------,
* | ||||||||| `--------' | | O
* `+-------------USMC----------^----------|___________________|
* `\_,---------,---------,--------------'
* / X MK X /'| /'
* / X MK X / `\ /'
* / X MK X /`-------'
* / X MK X /
* / X MK X /
* (________( @author m.c.kunkel
* `------'
*/
package testingPackage;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
public class JTableRowSelectProgramatically extends JPanel {
public JTableRowSelectProgramatically() {
initializePanel();
}
private void initializePanel() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(475, 150));
final JTable table = new JTable(new MyTableModel());
table.setFillsViewportHeight(true);
JScrollPane pane = new JScrollPane(table);
JLabel label1 = new JLabel("From row: ");
final JTextField field1 = new JTextField(3);
JLabel label2 = new JLabel("To row: ");
final JTextField field2 = new JTextField(3);
JButton select = new JButton("Select");
JButton clear = new JButton("Clear");
JButton add = new JButton("Add another one");
//
// Enables row selection mode and disable column selection
// mode.
//
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(false);
//
// Select rows based on the input.
//
select.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
int index1 = 0;
int index2 = 0;
try {
index1 = Integer.valueOf(field1.getText());
index2 = Integer.valueOf(field2.getText());
} catch (NumberFormatException e) {
e.printStackTrace();
}
if (index1 < 0 || index2 < 0 || index1 >= table.getRowCount() || index2 >= table.getRowCount()) {
JOptionPane.showMessageDialog(table, "Selection out of range!");
} else {
table.setRowSelectionInterval(index1, index2);
}
}
});
//
// Clears row selection
//
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
table.removeRowSelectionInterval(0, table.getRowCount() - 1);
field1.setText("");
field2.setText("");
}
});
//
// Add one more row after the last selected row.
//
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
int index2 = 0;
try {
index2 = Integer.valueOf(field2.getText());
} catch (NumberFormatException e) {
e.printStackTrace();
}
index2 = index2 + 1;
table.addRowSelectionInterval(index2, index2);
field2.setText(String.valueOf(index2));
}
});
JPanel command = new JPanel(new FlowLayout());
command.add(label1);
command.add(field1);
command.add(label2);
command.add(field2);
command.add(select);
command.add(clear);
command.add(add);
add(pane, BorderLayout.CENTER);
add(command, BorderLayout.SOUTH);
}
public static void showFrame() {
JPanel panel = new JTableRowSelectProgramatically();
panel.setOpaque(true);
JFrame frame = new JFrame("JTable Row Selection");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JTableRowSelectProgramatically.showFrame();
}
});
}
public class MyTableModel extends AbstractTableModel {
private String[] columns = { "ID", "NAME", "AGE", "A STUDENT?" };
private Object[][] data = { { 1, "Alice", 20, Boolean.FALSE }, { 2, "Bob", 10, Boolean.TRUE },
{ 3, "Carol", 15, Boolean.TRUE }, { 4, "Mallory", 25, Boolean.FALSE } };
public int getRowCount() {
return data.length;
}
public int getColumnCount() {
return columns.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
@Override
public String getColumnName(int column) {
return columns[column];
}
//
// This method is used by the JTable to define the default
// renderer or editor for each cell. For example if you have
// a boolean data it will be rendered as a check box. A
// number value is right aligned.
//
@Override
public Class getColumnClass(int columnIndex) {
return data[0][columnIndex].getClass();
}
}
} | apache-2.0 |
scaug10/NETESP | src/main/java/com/g10/ssm/mapper/UserNoticeQueryMapper.java | 371 | package com.g10.ssm.mapper;
import java.util.List;
import com.g10.ssm.po.UserNoticeKey;
import com.g10.ssm.po.UserNoticeVo;
public interface UserNoticeQueryMapper {
/**
* 给指定用户发布公告
*/
int sendNoticeToManyUser(UserNoticeVo userNoticeVo);
List<UserNoticeKey> selectAllUserNotice();
List<UserNoticeKey> selectAllNotice(String userName);
}
| apache-2.0 |
kamransaleem/waltz | waltz-data/src/main/java/com/khartec/waltz/data/physical_flow/PhysicalFlowIdSelectorFactory.java | 6973 | /*
* Waltz - Enterprise Architecture
* Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project
* See README.md for more information
*
* 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
*
*/
package com.khartec.waltz.data.physical_flow;
import com.khartec.waltz.data.IdSelectorFactory;
import com.khartec.waltz.data.logical_flow.LogicalFlowIdSelectorFactory;
import com.khartec.waltz.model.EntityKind;
import com.khartec.waltz.model.EntityLifecycleStatus;
import com.khartec.waltz.model.IdSelectionOptions;
import com.khartec.waltz.schema.tables.PhysicalFlow;
import org.jooq.Condition;
import org.jooq.Record1;
import org.jooq.Select;
import org.jooq.impl.DSL;
import static com.khartec.waltz.common.Checks.checkNotNull;
import static com.khartec.waltz.data.SelectorUtilities.ensureScopeIsExact;
import static com.khartec.waltz.schema.Tables.*;
import static com.khartec.waltz.schema.tables.FlowDiagramEntity.FLOW_DIAGRAM_ENTITY;
import static com.khartec.waltz.schema.tables.PhysicalFlow.PHYSICAL_FLOW;
import static com.khartec.waltz.schema.tables.PhysicalFlowParticipant.PHYSICAL_FLOW_PARTICIPANT;
public class PhysicalFlowIdSelectorFactory implements IdSelectorFactory {
private static final Condition PHYSICAL_FLOW_NOT_REMOVED = PhysicalFlow.PHYSICAL_FLOW.IS_REMOVED.isFalse()
.and(PhysicalFlow.PHYSICAL_FLOW.ENTITY_LIFECYCLE_STATUS.ne(EntityLifecycleStatus.REMOVED.name()));
@Override
public Select<Record1<Long>> apply(IdSelectionOptions options) {
checkNotNull(options, "options cannot be null");
switch(options.entityReference().kind()) {
case PHYSICAL_SPECIFICATION:
return mkForPhysicalSpecification(options);
case LOGICAL_DATA_FLOW:
return mkForLogicalFlow(options);
case FLOW_DIAGRAM:
return mkForFlowDiagram(options);
case SERVER:
return mkForServer(options);
case CHANGE_SET:
return mkForChangeSet(options);
case TAG:
return mkForTag(options);
case APP_GROUP:
case CHANGE_INITIATIVE:
case DATA_TYPE:
case MEASURABLE:
case ORG_UNIT:
case PERSON:
case SCENARIO:
return mkViaLogicalFlowSelector(options);
default:
throw new UnsupportedOperationException("Cannot create physical flow selector from options: "+options);
}
}
private Select<Record1<Long>> mkViaLogicalFlowSelector(IdSelectionOptions options) {
Select<Record1<Long>> logicalFlowSelector = new LogicalFlowIdSelectorFactory().apply(options);
return DSL
.select(PHYSICAL_FLOW.ID)
.from(PHYSICAL_FLOW)
.where(PHYSICAL_FLOW.LOGICAL_FLOW_ID.in(logicalFlowSelector));
}
private Select<Record1<Long>> mkForTag(IdSelectionOptions options) {
ensureScopeIsExact(options);
long tagId = options.entityReference().id();
return DSL
.select(TAG_USAGE.ENTITY_ID)
.from(TAG_USAGE)
.join(PhysicalFlow.PHYSICAL_FLOW)
.on(PhysicalFlow.PHYSICAL_FLOW.ID.eq(TAG_USAGE.ENTITY_ID)
.and(TAG_USAGE.ENTITY_KIND.eq(EntityKind.PHYSICAL_FLOW.name())))
.where(TAG_USAGE.TAG_ID.eq(tagId))
.and(getLifecycleCondition(options));
}
private Select<Record1<Long>> mkForServer(IdSelectionOptions options) {
ensureScopeIsExact(options);
long serverId = options.entityReference().id();
return DSL
.select(PHYSICAL_FLOW_PARTICIPANT.PHYSICAL_FLOW_ID)
.from(PHYSICAL_FLOW_PARTICIPANT)
.innerJoin(PhysicalFlow.PHYSICAL_FLOW)
.on(PhysicalFlow.PHYSICAL_FLOW.ID.eq(PHYSICAL_FLOW_PARTICIPANT.PHYSICAL_FLOW_ID))
.where(PHYSICAL_FLOW_PARTICIPANT.PARTICIPANT_ENTITY_KIND.eq(EntityKind.SERVER.name()))
.and(PHYSICAL_FLOW_PARTICIPANT.PARTICIPANT_ENTITY_ID.eq(serverId))
.and(getLifecycleCondition(options));
}
private Select<Record1<Long>> mkForFlowDiagram(IdSelectionOptions options) {
ensureScopeIsExact(options);
long diagramId = options.entityReference().id();
return DSL
.select(PhysicalFlow.PHYSICAL_FLOW.ID)
.from(PhysicalFlow.PHYSICAL_FLOW)
.innerJoin(FLOW_DIAGRAM_ENTITY)
.on(PhysicalFlow.PHYSICAL_FLOW.ID.eq(FLOW_DIAGRAM_ENTITY.ENTITY_ID))
.where(FLOW_DIAGRAM_ENTITY.DIAGRAM_ID.eq(diagramId))
.and(FLOW_DIAGRAM_ENTITY.ENTITY_KIND.eq(EntityKind.PHYSICAL_FLOW.name()))
.and(getLifecycleCondition(options));
}
private Select<Record1<Long>> mkForLogicalFlow(IdSelectionOptions options) {
ensureScopeIsExact(options);
long logicalFlowId = options.entityReference().id();
return DSL
.select(PhysicalFlow.PHYSICAL_FLOW.ID)
.from(PhysicalFlow.PHYSICAL_FLOW)
.where(PhysicalFlow.PHYSICAL_FLOW.LOGICAL_FLOW_ID.eq(logicalFlowId))
.and(getLifecycleCondition(options));
}
private Select<Record1<Long>> mkForChangeSet(IdSelectionOptions options) {
ensureScopeIsExact(options);
return DSL
.select(PhysicalFlow.PHYSICAL_FLOW.ID)
.from(PhysicalFlow.PHYSICAL_FLOW)
.innerJoin(CHANGE_UNIT).on(PhysicalFlow.PHYSICAL_FLOW.ID.eq(CHANGE_UNIT.SUBJECT_ENTITY_ID)
.and(CHANGE_UNIT.SUBJECT_ENTITY_KIND.eq(EntityKind.PHYSICAL_FLOW.name())))
.where(CHANGE_UNIT.CHANGE_SET_ID.eq(options.entityReference().id()))
.and(getLifecycleCondition(options));
}
private Select<Record1<Long>> mkForPhysicalSpecification(IdSelectionOptions options) {
ensureScopeIsExact(options);
long specificationId = options.entityReference().id();
return DSL
.select(PhysicalFlow.PHYSICAL_FLOW.ID)
.from(PhysicalFlow.PHYSICAL_FLOW)
.where(PhysicalFlow.PHYSICAL_FLOW.SPECIFICATION_ID.eq(specificationId));
}
public Condition getLifecycleCondition(IdSelectionOptions options) {
return options.entityLifecycleStatuses().contains(EntityLifecycleStatus.REMOVED)
? DSL.trueCondition()
: PHYSICAL_FLOW_NOT_REMOVED;
}
}
| apache-2.0 |
klarna/HiveRunner | src/main/java/com/klarna/hiverunner/HiveRunnerExtension.java | 4038 | /**
* Copyright (C) 2013-2021 Klarna AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.klarna.hiverunner;
import static org.reflections.ReflectionUtils.withAnnotation;
import static org.reflections.ReflectionUtils.withType;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestInstancePostProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.klarna.hiverunner.annotations.HiveRunnerSetup;
import com.klarna.hiverunner.annotations.HiveSQL;
import com.klarna.hiverunner.builder.Script;
import com.klarna.hiverunner.config.HiveRunnerConfig;
import com.klarna.reflection.ReflectionUtils;
public class HiveRunnerExtension implements AfterEachCallback, TestInstancePostProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(HiveRunnerExtension.class);
private final HiveRunnerCore core;
private final HiveRunnerConfig config = new HiveRunnerConfig();
private Path basedir;
private HiveShellContainer container;
protected List<Script> scriptsUnderTest = new ArrayList<Script>();
public HiveRunnerExtension() {
core = new HiveRunnerCore();
}
protected List<Path> getScriptPaths(HiveSQL annotation) throws URISyntaxException {
return core.getScriptPaths(annotation);
}
@Override
public void postProcessTestInstance(Object target, ExtensionContext extensionContext) {
setupConfig(target);
try {
basedir = Files.createTempDirectory("hiverunner_test");
container = createHiveServerContainer(scriptsUnderTest, target, basedir);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
scriptsUnderTest = container.getScriptsUnderTest();
}
private void setupConfig(Object target) {
Set<Field> fields = ReflectionUtils.getAllFields(target.getClass(),
Predicates.and(
withAnnotation(HiveRunnerSetup.class),
withType(HiveRunnerConfig.class)));
Preconditions.checkState(fields.size() <= 1,
"Only one field of type HiveRunnerConfig should be annotated with @HiveRunnerSetup");
if (!fields.isEmpty()) {
config.override(ReflectionUtils
.getFieldValue(target, fields.iterator().next().getName(), HiveRunnerConfig.class));
}
}
private void tearDown(Object target) {
if (container != null) {
LOGGER.info("Tearing down {}", target.getClass());
container.tearDown();
}
deleteTempFolder(basedir);
}
private void deleteTempFolder(Path directory) {
try {
FileUtils.deleteDirectory(directory.toFile());
} catch (IOException e) {
LOGGER.debug("Temporary folder was not deleted successfully: " + directory);
}
}
private HiveShellContainer createHiveServerContainer(List<? extends Script> scripts, Object testCase, Path basedir)
throws IOException {
return core.createHiveServerContainer(scripts, testCase, basedir, config);
}
@Override
public void afterEach(ExtensionContext extensionContext) {
tearDown(extensionContext.getRequiredTestInstance());
}
}
| apache-2.0 |
steveloughran/hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/Constants.java | 4193 | /**
* 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.hadoop.fs.viewfs;
import org.apache.hadoop.fs.permission.FsPermission;
/**
* Config variable prefixes for ViewFs -
* see {@link org.apache.hadoop.fs.viewfs.ViewFs} for examples.
* The mount table is specified in the config using these prefixes.
* See {@link org.apache.hadoop.fs.viewfs.ConfigUtil} for convenience lib.
*/
public interface Constants {
/**
* Prefix for the config variable prefix for the ViewFs mount-table
*/
public static final String CONFIG_VIEWFS_PREFIX = "fs.viewfs.mounttable";
/**
* Prefix for the config variable for the ViewFs mount-table path.
*/
String CONFIG_VIEWFS_MOUNTTABLE_PATH = CONFIG_VIEWFS_PREFIX + ".path";
/**
* Prefix for the home dir for the mount table - if not specified
* then the hadoop default value (/user) is used.
*/
public static final String CONFIG_VIEWFS_HOMEDIR = "homedir";
/**
* Config key to specify the name of the default mount table.
*/
String CONFIG_VIEWFS_DEFAULT_MOUNT_TABLE_NAME_KEY =
"fs.viewfs.mounttable.default.name.key";
/**
* Config variable name for the default mount table.
*/
public static final String CONFIG_VIEWFS_DEFAULT_MOUNT_TABLE = "default";
/**
* Config variable full prefix for the default mount table.
*/
public static final String CONFIG_VIEWFS_PREFIX_DEFAULT_MOUNT_TABLE =
CONFIG_VIEWFS_PREFIX + "." + CONFIG_VIEWFS_DEFAULT_MOUNT_TABLE;
/**
* Config variable for specifying a simple link
*/
String CONFIG_VIEWFS_LINK = "link";
/**
* Config variable for specifying a fallback for link mount points.
*/
String CONFIG_VIEWFS_LINK_FALLBACK = "linkFallback";
/**
* Config variable for specifying a merge link
*/
String CONFIG_VIEWFS_LINK_MERGE = "linkMerge";
/**
* Config variable for specifying an nfly link. Nfly writes to multiple
* locations, and allows reads from the closest one.
*/
String CONFIG_VIEWFS_LINK_NFLY = "linkNfly";
/**
* Config variable for specifying a merge of the root of the mount-table
* with the root of another file system.
*/
String CONFIG_VIEWFS_LINK_MERGE_SLASH = "linkMergeSlash";
FsPermission PERMISSION_555 = new FsPermission((short) 0555);
String CONFIG_VIEWFS_RENAME_STRATEGY = "fs.viewfs.rename.strategy";
/**
* Enable ViewFileSystem to cache all children filesystems in inner cache.
*/
String CONFIG_VIEWFS_ENABLE_INNER_CACHE = "fs.viewfs.enable.inner.cache";
boolean CONFIG_VIEWFS_ENABLE_INNER_CACHE_DEFAULT = true;
/**
* Enable ViewFileSystem to show mountlinks as symlinks.
*/
String CONFIG_VIEWFS_MOUNT_LINKS_AS_SYMLINKS =
"fs.viewfs.mount.links.as.symlinks";
boolean CONFIG_VIEWFS_MOUNT_LINKS_AS_SYMLINKS_DEFAULT = true;
/**
* When initializing the viewfs, authority will be used as the mount table
* name to find the mount link configurations. To make the mount table name
* unique, we may want to ignore port if initialized uri authority contains
* port number. By default, we will consider port number also in
* ViewFileSystem(This default value false, because to support existing
* deployments continue with the current behavior).
*/
String CONFIG_VIEWFS_IGNORE_PORT_IN_MOUNT_TABLE_NAME =
"fs.viewfs.ignore.port.in.mount.table.name";
boolean CONFIG_VIEWFS_IGNORE_PORT_IN_MOUNT_TABLE_NAME_DEFAULT = false;
}
| apache-2.0 |
hujiaweibujidao/textfairy | app/src/main/java/imagepicker/ui/ImagesThumbnailAdapter.java | 5595 | package imagepicker.ui;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.renard.ocr.R;
import de.greenrobot.event.EventBus;
import imagepicker.model.AlbumEntry;
import imagepicker.model.ImageEntry;
import imagepicker.util.Events;
import imagepicker.util.Picker;
import imagepicker.util.Util;
/**
* 图片adapter
*
* update
* 1.修改图片选中后的显示样式
*
*/
public class ImagesThumbnailAdapter extends RecyclerView.Adapter<ImagesThumbnailAdapter.ImageViewHolder> implements Util.OnClickImage {
protected final AlbumEntry mAlbum;
protected final RecyclerView mRecyclerView;
protected final Drawable mCheckIcon;
protected final Fragment mFragment;
protected final Picker mPickOptions;
public ImagesThumbnailAdapter(final Fragment fragment, final AlbumEntry album, final RecyclerView recyclerView, Picker pickOptions) {
mFragment = fragment;
mAlbum = album;
mRecyclerView = recyclerView;
mPickOptions = pickOptions;
mCheckIcon = createCheckIcon();
}
private Drawable createCheckIcon() {
Drawable checkIcon = ContextCompat.getDrawable(mRecyclerView.getContext(), R.drawable.ic_action_done_white);
checkIcon = DrawableCompat.wrap(checkIcon);
DrawableCompat.setTint(checkIcon, mPickOptions.checkIconTintColor);
return checkIcon;
}
@Override
public int getItemCount() {
return mAlbum.imageList.size();
}
@Override
public ImageViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
final View imageLayout = LayoutInflater.from(mRecyclerView.getContext()).inflate(R.layout.element_image, viewGroup, false);
return new ImageViewHolder(imageLayout, this);
}
@Override
public void onBindViewHolder(ImageViewHolder imageViewHolder, int position) {
final ImageEntry imageEntry = mAlbum.imageList.get(position);
setHeight(imageViewHolder.itemView);
displayThumbnail(imageViewHolder, imageEntry);
drawGrid(imageViewHolder, imageEntry);
}
@Override
public void onClickImage(View layout, ImageView thumbnail, ImageView check) {
final int position = Util.getPositionOfChild(layout, R.id.image_layout, mRecyclerView);
final ImageViewHolder holder = (ImageViewHolder) mRecyclerView.getChildViewHolder(layout);
pickImage(holder, mAlbum.imageList.get(position));
}
public void setHeight(final View convertView) {
final int height = mRecyclerView.getMeasuredWidth() / mRecyclerView.getResources().getInteger(R.integer.num_columns_images);
convertView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height));
}
public void displayThumbnail(final ImageViewHolder holder, final ImageEntry photo) {
Glide.with(mFragment).load(photo.path).asBitmap().centerCrop().into(holder.thumbnail);
}
public void drawGrid(final ImageViewHolder holder, final ImageEntry imageEntry) {
holder.check.setImageDrawable(mCheckIcon);
if (imageEntry.isPicked) {
holder.check.setBackgroundColor(mPickOptions.imageBackgroundColorWhenChecked);
holder.itemView.setBackgroundColor(mPickOptions.imageBackgroundColorWhenChecked);
holder.thumbnail.setColorFilter(mPickOptions.checkedImageOverlayColor);
//final int padding = mRecyclerView.getContext().getResources().getDimensionPixelSize(R.dimen.image_checked_padding);
//holder.itemView.setPadding(padding, padding, padding, padding);
holder.itemView.setPadding(0, 0, 0, 0);//hujiawei 去掉此处的padding
} else {
holder.check.setBackgroundColor(mPickOptions.imageCheckColor);
holder.itemView.setBackgroundColor(mPickOptions.imageBackgroundColor);
holder.thumbnail.setColorFilter(Color.TRANSPARENT);
holder.itemView.setPadding(0, 0, 0, 0);
}
if (mPickOptions.pickMode == Picker.PickMode.SINGLE_IMAGE) {
holder.check.setVisibility(View.GONE);
}
}
public void pickImage(final ImageViewHolder holder, final ImageEntry imageEntry) {
if (imageEntry.isPicked) {
EventBus.getDefault().post(new Events.OnUnpickImageEvent(imageEntry));//Unpick
} else {
EventBus.getDefault().postSticky(new Events.OnPickImageEvent(imageEntry));//pick
}
drawGrid(holder, imageEntry);
}
//ViewHolder
public static class ImageViewHolder extends RecyclerView.ViewHolder {
private final ImageView thumbnail;
private final ImageView check;
public ImageViewHolder(final View itemView, final Util.OnClickImage listener) {
super(itemView);
thumbnail = (ImageView) itemView.findViewById(R.id.image_thumbnail);
check = (ImageView) itemView.findViewById(R.id.image_check);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onClickImage(itemView, thumbnail, check);
}
});
}
}
}
| apache-2.0 |
x19990416/macrossx-spring-contribute | src/wechat/java/com/github/x19990416/macrossx/spring/wechat/server/WechatTextRequest.java | 1096 | /**
* Copyright (C) 2016 X-Forever.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.x19990416.macrossx.spring.wechat.server;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@Data
@EqualsAndHashCode(callSuper=false)
@ToString(callSuper=true)
@XmlRootElement(name="xml")
public class WechatTextRequest extends WechatHttpEntity{
@XmlElement(name = "Content")
private String Content;
@XmlElement(name = "MsgId")
private String MsgId;
}
| apache-2.0 |
FangStarNet/symphonyx | src/main/java/org/b3log/symphony/processor/advice/stopwatch/StopwatchStartAdvice.java | 1524 | /*
* Copyright (c) 2012-2016, b3log.org & hacpai.com & fangstar.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.symphony.processor.advice.stopwatch;
import java.util.Map;
import org.b3log.latke.service.annotation.Service;
import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.advice.BeforeRequestProcessAdvice;
import org.b3log.latke.servlet.advice.RequestProcessAdviceException;
import org.b3log.latke.util.Stopwatchs;
/**
* Stopwatch start advice for request processors.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.0.0, Oct 17, 2012
* @since 0.2.0
*/
@Service
public class StopwatchStartAdvice extends BeforeRequestProcessAdvice {
@Override
public void doAdvice(final HTTPRequestContext context, final Map<String, Object> args) throws RequestProcessAdviceException {
final String requestURI = context.getRequest().getRequestURI();
Stopwatchs.start("Request URI [" + requestURI + ']');
}
}
| apache-2.0 |
joshuasachtleben/ZombieBird | ZombieBird-html/src/com/kilobolt/ZombieBird/client/GwtLauncher.java | 548 | package com.kilobolt.ZombieBird.client;
import com.kilobolt.ZombieBird.ZBGame;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
public class GwtLauncher extends GwtApplication {
@Override
public GwtApplicationConfiguration getConfig () {
GwtApplicationConfiguration cfg = new GwtApplicationConfiguration(480, 320);
return cfg;
}
@Override
public ApplicationListener getApplicationListener () {
return new ZBGame();
}
} | apache-2.0 |
tetrapods/raft | src/io/tetrapod/raft/storage/StorageItem.java | 3036 | package io.tetrapod.raft.storage;
import java.io.*;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A wrapper for a document in the Storage database
*/
public class StorageItem {
public static final Logger logger = LoggerFactory.getLogger(StorageItem.class);
public final String key;
private int version;
private byte[] data;
private LockInfo lock;
public StorageItem(String key) {
this.key = key;
}
public StorageItem(String key, byte[] data) {
this.key = key;
this.data = data;
}
public StorageItem(StorageItem copy) {
this.key = copy.key;
this.version = copy.version;
if (copy.data != null) {
this.data = Arrays.copyOf(copy.data, copy.data.length);
}
if (copy.lock != null) {
this.lock = copy.lock.copy();
}
}
public StorageItem(DataInputStream in, int fileVersion) throws IOException {
this.key = in.readUTF();
this.data = new byte[in.readInt()];
in.readFully(this.data);
this.version = in.readInt();
if (in.readBoolean()) {
this.lock = new LockInfo(in.readLong(), in.readUTF());
}
}
public void write(DataOutputStream out) throws IOException {
out.writeUTF(key);
out.writeInt(data == null ? 0 : data.length);
if (data != null) {
out.write(data);
}
out.writeInt(version);
out.writeBoolean(lock != null);
if (lock != null) {
out.writeLong(lock.lockExpiry);
out.writeUTF(lock.lockOwner != null ? lock.lockOwner : "");
}
}
public void setData(byte[] data) {
this.data = data;
}
public byte[] getData() {
return this.data;
}
public String getDataAsString() {
if (data != null) {
try {
return new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {}
}
return null;
}
public int getVersion() {
return version;
}
public void modify(byte[] data) {
this.data = data;
this.version++;
}
public boolean lock(long leaseForMillis, long curTime, String lockOwner) {
if (lock != null && lock.lockExpiry > curTime) {
logger.debug("Lock is held by {} for another {} ms", lock.lockOwner, lock.lockExpiry - curTime);
return false;
}
this.version++;
this.lock = new LockInfo(curTime + leaseForMillis, lockOwner);
return true;
}
public void unlock() {
this.version++;
this.lock = null;
}
public boolean isOwned(String lockOwner) {
return lock != null && lockOwner.equals(lock.lockOwner);
}
public static class LockInfo {
private long lockExpiry;
private String lockOwner;
public LockInfo(long lockExpiry, String lockOwner) {
this.lockExpiry = lockExpiry;
this.lockOwner = lockOwner;
}
public LockInfo copy() {
return new LockInfo(lockExpiry, lockOwner);
}
}
}
| apache-2.0 |
imotSpot/imotSpot | src/main/java/com/imotspot/model/imot/Imot.java | 985 | package com.imotspot.model.imot;
import com.imotspot.model.imot.enumerations.Condition;
import com.imotspot.model.imot.enumerations.ImotType;
import com.imotspot.model.User;
import com.imotspot.model.imot.interfaces.Media;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Data
//@Accessors(fluent = true)
public class Imot implements Serializable {
private static final long serialVersionUID = 1L;
private User owner;
private float price;
private ImotType type;
private String year;
private String description;
private Date published;
private Location location;
private Condition condition;
private Picture frontImage;
private List<Media> media = new ArrayList<>();
private List<Feature> features = new ArrayList<>();
private List<Appliance> appliances = new ArrayList<>();
public Imot(Location location) {
this.location = location;
}
}
| apache-2.0 |
schorndorfer/uima-components | annotator-parent/type-system/src/main/java/org/apache/ctakes/typesystem/type/textsem/MeasurementAnnotation.java | 1778 |
/* First created by JCasGen Fri Jan 03 13:40:16 CST 2014 */
package org.apache.ctakes.typesystem.type.textsem;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.JCasRegistry;
import org.apache.uima.jcas.cas.TOP_Type;
/** Equivalent to cTAKES:
edu.mayo.bmi.uima.cdt.type.MeasurementAnnotation
* Updated by JCasGen Fri Jan 03 13:40:16 CST 2014
* XML source: C:/WKT/git/schorndorfer/uima-components/annotator-parent/type-system/src/main/resources/org/apache/ctakes/typesystem/types/TypeSystem.xml
* @generated */
public class MeasurementAnnotation extends IdentifiedAnnotation {
/** @generated
* @ordered
*/
@SuppressWarnings ("hiding")
public final static int typeIndexID = JCasRegistry.register(MeasurementAnnotation.class);
/** @generated
* @ordered
*/
@SuppressWarnings ("hiding")
public final static int type = typeIndexID;
/** @generated */
@Override
public int getTypeIndexID() {return typeIndexID;}
/** Never called. Disable default constructor
* @generated */
protected MeasurementAnnotation() {/* intentionally empty block */}
/** Internal - constructor used by generator
* @generated */
public MeasurementAnnotation(int addr, TOP_Type type) {
super(addr, type);
readObject();
}
/** @generated */
public MeasurementAnnotation(JCas jcas) {
super(jcas);
readObject();
}
/** @generated */
public MeasurementAnnotation(JCas jcas, int begin, int end) {
super(jcas);
setBegin(begin);
setEnd(end);
readObject();
}
/** <!-- begin-user-doc -->
* Write your own initialization here
* <!-- end-user-doc -->
@generated modifiable */
private void readObject() {/*default - does nothing empty block */}
}
| apache-2.0 |
android-art-intel/Nougat | art-extension/opttests/src/OptimizationTests/ShortMethodsInliningNonVirtualInvokes/InvokeDirectRangeAWideThrowNullSet_001/Main.java | 1774 | /*
* Copyright (C) 2016 Intel Corporation
*
* 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 OptimizationTests.ShortMethodsInliningNonVirtualInvokes.InvokeDirectRangeAWideThrowNullSet_001;
// The test checks that stack after NullPointerException occurs is correct despite inlining
class Main {
final static int iterations = 10;
// public static int getThingies(int i) {
// return thingiesArray[i];
// }
// |[000194] Main.getThingies:(I)I
// |0000: sget-object v0, LMain;.thingiesArray:[I // field@0001
// |0002: aget v0, v0, v1
// |0004: return v0
public static void main(String[] args) {
Test test = new Test(iterations);
double nextThingy = -10.0;
double sumArrElements = 0.0;
double d1 = 1.0;
double d2 = 2.0;
double d3 = 3.0;
double d4 = 4.0;
double d5 = 5.0;
double d6 = 6.0;
for(int i = 0; i < iterations; i++) {
sumArrElements = sumArrElements + test.thingiesArray[i];
}
for(int i = 0; i < iterations; i++) {
nextThingy = test.gimme(test.thingiesArray, i, d1, d2, d3, d4, d5, d6) - i*1.0;
test.hereyouare(test.thingiesArray, nextThingy, i, d1, d2, d3, d4, d5, d6);
}
}
}
| apache-2.0 |
projectbuendia/client | app/src/main/java/org/projectbuendia/client/providers/PatientCountsDelegate.java | 2926 | // Copyright 2015 The Project Buendia Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distrib-
// uted 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
// specific language governing permissions and limitations under the License.
package org.projectbuendia.client.providers;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import org.projectbuendia.client.sync.Database;
import org.projectbuendia.client.sync.QueryBuilder;
import org.projectbuendia.client.providers.Contracts.Table;
/** A {@link ProviderDelegate} that provides query access to the count of patients in each location. */
public class PatientCountsDelegate implements ProviderDelegate<Database> {
@Override public String getType() {
return Contracts.PatientCounts.GROUP_TYPE;
}
@Override public Cursor query(
Database dbHelper, ContentResolver contentResolver, Uri uri, String[] projection,
String selection, String[] selectionArgs, String sortOrder) {
return new QueryBuilder(Table.PATIENTS)
.where(selection, selectionArgs)
.where(Contracts.Patients.LOCATION_UUID + " is not null")
.groupBy(Contracts.Patients.LOCATION_UUID)
.orderBy(sortOrder)
.select(dbHelper.getReadableDatabase(),
Contracts.Patients.ID,
Contracts.Patients.LOCATION_UUID,
"count(*) as " + Contracts.PatientCounts.PATIENT_COUNT);
}
@Override public Uri insert(
Database dbHelper, ContentResolver contentResolver, Uri uri,
ContentValues values) {
throw new UnsupportedOperationException("Insert is not supported for URI '" + uri + "'.");
}
@Override public int bulkInsert(
Database dbHelper, ContentResolver contentResolver, Uri uri,
ContentValues[] values) {
throw new UnsupportedOperationException(
"Bulk insert is not supported for URI '" + uri + "'.");
}
@Override public int delete(
Database dbHelper, ContentResolver contentResolver, Uri uri, String selection,
String[] selectionArgs) {
throw new UnsupportedOperationException("Delete is not supported for URI '" + uri + "'.");
}
@Override public int update(
Database dbHelper, ContentResolver contentResolver, Uri uri,
ContentValues values, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException("Update is not supported for URI '" + uri + "'.");
}
}
| apache-2.0 |
ThiagoGarciaAlves/intellij-community | java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaModuleImpl.java | 5549 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.source;
import com.intellij.lang.ASTNode;
import com.intellij.navigation.ItemPresentation;
import com.intellij.navigation.ItemPresentationProviders;
import com.intellij.psi.*;
import com.intellij.psi.impl.JavaPsiImplementationHelper;
import com.intellij.psi.impl.java.stubs.JavaStubElementTypes;
import com.intellij.psi.impl.java.stubs.PsiJavaModuleStub;
import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.search.ProjectScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.util.PsiModificationTracker;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.JBIterable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static com.intellij.psi.SyntaxTraverser.psiTraverser;
public class PsiJavaModuleImpl extends JavaStubPsiElement<PsiJavaModuleStub> implements PsiJavaModule {
public PsiJavaModuleImpl(@NotNull PsiJavaModuleStub stub) {
super(stub, JavaStubElementTypes.MODULE);
}
public PsiJavaModuleImpl(@NotNull ASTNode node) {
super(node);
}
@NotNull
@Override
public Iterable<PsiRequiresStatement> getRequires() {
PsiJavaModuleStub stub = getGreenStub();
if (stub != null) {
return JBIterable.of(stub.getChildrenByType(JavaElementType.REQUIRES_STATEMENT, PsiRequiresStatement.EMPTY_ARRAY));
}
else {
return psiTraverser().children(this).filter(PsiRequiresStatement.class);
}
}
@NotNull
@Override
public Iterable<PsiPackageAccessibilityStatement> getExports() {
PsiJavaModuleStub stub = getGreenStub();
if (stub != null) {
return JBIterable.of(stub.getChildrenByType(JavaElementType.EXPORTS_STATEMENT, PsiPackageAccessibilityStatement.EMPTY_ARRAY));
}
else {
return psiTraverser().children(this)
.filter(PsiPackageAccessibilityStatement.class)
.filter(statement -> statement.getRole() == PsiPackageAccessibilityStatement.Role.EXPORTS);
}
}
@NotNull
@Override
public Iterable<PsiPackageAccessibilityStatement> getOpens() {
PsiJavaModuleStub stub = getGreenStub();
if (stub != null) {
return JBIterable.of(stub.getChildrenByType(JavaElementType.OPENS_STATEMENT, PsiPackageAccessibilityStatement.EMPTY_ARRAY));
}
else {
return psiTraverser().children(this)
.filter(PsiPackageAccessibilityStatement.class)
.filter(statement -> statement.getRole() == PsiPackageAccessibilityStatement.Role.OPENS);
}
}
@NotNull
@Override
public Iterable<PsiUsesStatement> getUses() {
return psiTraverser().children(this).filter(PsiUsesStatement.class);
}
@NotNull
@Override
public Iterable<PsiProvidesStatement> getProvides() {
return psiTraverser().children(this).filter(PsiProvidesStatement.class);
}
@NotNull
@Override
public PsiJavaModuleReferenceElement getNameIdentifier() {
return PsiTreeUtil.getRequiredChildOfType(this, PsiJavaModuleReferenceElement.class);
}
@NotNull
@Override
public String getName() {
PsiJavaModuleStub stub = getGreenStub();
if (stub != null) {
return stub.getName();
}
else {
return getNameIdentifier().getReferenceText();
}
}
@Override
public PsiElement setName(@NotNull String name) throws IncorrectOperationException {
PsiJavaModuleReferenceElement newName = PsiElementFactory.SERVICE.getInstance(getProject()).createModuleReferenceFromText(name);
getNameIdentifier().replace(newName);
return this;
}
@Override
public PsiModifierList getModifierList() {
return getStubOrPsiChild(JavaStubElementTypes.MODIFIER_LIST);
}
@Override
public boolean hasModifierProperty(@NotNull String name) {
PsiModifierList modifierList = getModifierList();
return modifierList != null && modifierList.hasModifierProperty(name);
}
@Nullable
@Override
public PsiDocComment getDocComment() {
return PsiTreeUtil.getChildOfType(this, PsiDocComment.class);
}
@Override
public ItemPresentation getPresentation() {
return ItemPresentationProviders.getItemPresentation(this);
}
@Override
public int getTextOffset() {
return getNameIdentifier().getTextOffset();
}
@NotNull
@Override
public PsiElement getNavigationElement() {
return getNameIdentifier();
}
@Override
public PsiElement getOriginalElement() {
return CachedValuesManager.getCachedValue(this, () -> {
JavaPsiImplementationHelper helper = JavaPsiImplementationHelper.getInstance(getProject());
PsiJavaModule result = helper != null ? helper.getOriginalModule(this) : this;
return CachedValueProvider.Result.create(result, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
});
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof JavaElementVisitor) {
((JavaElementVisitor)visitor).visitModule(this);
}
else {
visitor.visitElement(this);
}
}
@NotNull
@Override
public SearchScope getUseScope() {
return ProjectScope.getProjectScope(getProject());
}
@Override
public String toString() {
return "PsiJavaModule:" + getName();
}
} | apache-2.0 |
gstevey/gradle | subprojects/core-api/src/main/java/org/gradle/api/initialization/IncludedBuild.java | 1228 | /*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.initialization;
import org.gradle.api.Incubating;
import org.gradle.api.tasks.TaskReference;
import org.gradle.internal.HasInternalProtocol;
import java.io.File;
/**
* A build that is included in the composite.
*
* @since 3.1
*/
@Incubating
@HasInternalProtocol
public interface IncludedBuild {
/**
* The name of the included build.
*/
String getName();
/**
* The root directory of the included build.
*/
File getProjectDir();
/**
* Produces a reference to a task in the included build.
*/
TaskReference task(String path);
}
| apache-2.0 |
PkayJava/pluggable | framework/src/main/java/com/googlecode/wickedcharts/highcharts/options/HorizontalAlignment.java | 1030 | /**
* Copyright 2012-2013 Wicked Charts (http://wicked-charts.googlecode.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.wickedcharts.highcharts.options;
import com.googlecode.wickedcharts.highcharts.json.LowercaseEnum;
/**
* Enumeration of possible horizontal alignments.
*
* @author Tom Hombergs (tom.hombergs@gmail.com)
*
*/
public enum HorizontalAlignment implements LowercaseEnum {
LEFT,
CENTER,
RIGHT,
HIGH;
}
| apache-2.0 |
guogu82/garytool | app/src/main/java/com/gary/garytool/business/volley/GsonRequest.java | 3759 | package com.gary.garytool.business.volley;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Gary on 2015/9/19.
*/
public class GsonRequest<T> extends Request<T> {
private static Map<String, String> mHeader = new HashMap<String, String>();
/**
* 设置访问服务器时必须传递的参数,密钥等
*/
static
{
mHeader.put("apikey", "3fa06fc0f9c91551e068779fb3872e10");
}
private final Response.Listener<T> mListener;
private Gson mGson;
private Class<T> mClass;
public GsonRequest(String url,Class<T> clazz,Response.Listener<T> listener, Response.ErrorListener errorListener) {
this(Method.GET,url,clazz,listener,errorListener);
}
public GsonRequest(int method, String url,Class<T> clazz,Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
mListener = listener;
mGson=new Gson();
mClass=clazz;
setRetryPolicy(getMyDefaultRetryPolicy());
}
public GsonRequest(int method, String url,Class<T> clazz,Map<String, String> appendHeader,Response.Listener<T> listener, Response.ErrorListener errorListener) {
this(method,url,clazz,listener,errorListener);
mHeader=appendHeader;
}
private RetryPolicy getMyDefaultRetryPolicy() {
RetryPolicy retryPolicy=new DefaultRetryPolicy(5000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
return retryPolicy;
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString=new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(mGson.fromJson(jsonString,mClass),HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
//列表 array 数据
//String str="[{'id': '1','code': 'bj','name': '北京','map': '39.90403, 116.40752599999996'}, {'id': '2','code': 'sz','name': '深圳','map': '22.543099, 114.05786799999998'}, {'id': '9','code': 'sh','name': '上海','map': '31.230393,121.473704'}, {'id': '10','code': 'gz','name': '广州','map': '23.129163,113.26443500000005'}]";
//List<City> rs=new ArrayList<City>();
//Type type = new TypeToken<ArrayList<City>>() {}.getType();
//rs=gson.fromJson(str, type);
//map数据
//String jsonStr="{'1': {'id': '1','code': 'bj','name': '北京','map': '39.90403, 116.40752599999996'},'2': {'id': '2','code': 'sz','name': '深圳','map': '22.543099, 114.05786799999998'},'9': {'id': '9','code': 'sh','name': '上海','map': '31.230393,121.473704'},'10': {'id': '10','code': 'gz','name': '广州','map': '23.129163,113.26443500000005'}}";
//Map<String, City> citys = gson.fromJson(jsonStr, new TypeToken<Map<String, City>>() {}.getType());
//System.out.println(citys.get("1").name+"----------"+citys.get("2").code);
@Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError
{
return mHeader;
}
}
| apache-2.0 |
masonmei/java-agent | profiler/src/main/java/com/baidu/oped/apm/profiler/plugin/xml/transformer/ConditionalClassFileTransformerBuilder.java | 791 | /**
* Copyright 2014 NAVER Corp.
* 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.baidu.oped.apm.profiler.plugin.xml.transformer;
/**
* @author Jongho Moon
*
*/
public interface ConditionalClassFileTransformerBuilder extends BaseClassFileTransformerBuilder {
}
| apache-2.0 |
greghogan/flink | flink-mesos/src/main/java/org/apache/flink/mesos/util/MesosArtifactServer.java | 1762 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.mesos.util;
import org.apache.flink.core.fs.Path;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* A generic Mesos artifact server, designed specifically for use by the Mesos Fetcher.
*
* <p>More information:
* http://mesos.apache.org/documentation/latest/fetcher/
* http://mesos.apache.org/documentation/latest/fetcher-cache-internals/
*/
public interface MesosArtifactServer extends MesosArtifactResolver {
/**
* Adds a path to the artifact server.
* @param path the qualified FS path to serve (local, hdfs, etc).
* @param remoteFile the remote path with which to locate the file.
* @return the fully-qualified remote path to the file.
* @throws MalformedURLException if the remote path is invalid.
*/
URL addPath(Path path, Path remoteFile) throws IOException;
/**
* Stops the artifact server.
* @throws Exception
*/
void stop() throws Exception;
}
| apache-2.0 |
C-isCoder/isCoderWeather | src/com/iscoderweather/app/model/County.java | 671 | package com.iscoderweather.app.model;
/**
* ±íCounty¶ÔÓ¦µÄʵÌåÀà
*/
public class County {
private int id;
private String countyName;
private String countyCode;
private int cityId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountyName() {
return countyName;
}
public void setCountyName(String countyName) {
this.countyName = countyName;
}
public String getCountyCode() {
return countyCode;
}
public void setCountyCode(String countyCode) {
this.countyCode = countyCode;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
}
| apache-2.0 |
torrances/swtk-commons | commons-dict-wiktionary/src/main/java/org/swtk/commons/dict/wiktionary/generated/h/o/e/WiktionaryHOE000.java | 989 | package org.swtk.commons.dict.wiktionary.generated.h.o.e; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.swtk.common.dict.dto.wiktionary.Entry; import com.trimc.blogger.commons.utils.GsonUtils; public class WiktionaryHOE000 { private static Map<String, Entry> map = new HashMap<String, Entry>(); static { add("hoelite", "{\"term\":\"hoelite\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"\u0027-ite\u0027\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"A monoclinic-prismatic mineral containing carbon, hydrogen, and oxygen\", \"priority\":1}]}, \"synonyms\":{}}");
} private static void add(String term, String json) { map.put(term, GsonUtils.toObject(json, Entry.class)); } public static Entry get(String term) { return map.get(term); } public static boolean has(String term) { return null != get(term); } public static Collection<String> terms() { return map.keySet(); } } | apache-2.0 |
if-zz/coolweather | app/src/main/java/com/coolweather/app/service/AutoUpdateService.java | 2162 | package com.coolweather.app.service;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import com.coolweather.app.receiver.AutoUpdateReceiver;
import com.coolweather.app.util.HttpCallbackListener;
import com.coolweather.app.util.HttpUtil;
import com.coolweather.app.util.Utility;
/**
* Created by Administrator on 2015/11/7.
*/
public class AutoUpdateService extends Service{
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
updateWeather();
}
}).start();
AlarmManager manager=(AlarmManager)getSystemService(ALARM_SERVICE);
int anHour=8*60*60*1000;// 这是8小时的毫秒数
long triggerAtTime= SystemClock.elapsedRealtime()+anHour;
Intent i=new Intent(this,AutoUpdateReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(this,0,i,0);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);
return super.onStartCommand(intent,flags,startId);
}
/**
* 更新天气信息
*/
private void updateWeather(){
SharedPreferences preferences= PreferenceManager.getDefaultSharedPreferences(this);
String weatherCode=preferences.getString("weather_code", "");
String address="http://www.weather.com.cn/data/cityinfo/"+weatherCode+".html";
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
Utility.handleWeatherResponse(AutoUpdateService.this,response);
}
@Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
}
| apache-2.0 |
campbe13/JavaSourceSamples360 | fromslides/S08-loops-while/while1Intro/CountDown.java | 628 | import java.util.Scanner;
/**
* This class illustrates exercises from the slide deck for the course
* 360-420-DW Intro to Java
*
* while loops & methods
*
* @author PMCampbell
* @version today
**/
public class CountDown
{
public static void main(String[] args)
{
int start;
Scanner kb = new Scanner(System.in);
// initialize the border condition variable
System.out.print("Count down from: ");
start = kb.nextInt();
while (start >= 0) {
System.out.println(start);
start--;
}
System.out.println("Blastoff!");
} // main()
} // CountDown | apache-2.0 |
daniellemayne/dasein-cloud-vcloud_old | src/main/java/org/dasein/cloud/vcloud/compute/TemplateCapabilities.java | 4386 | /**
* Copyright (C) 2009-2014 Dell, Inc
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.dasein.cloud.vcloud.compute;
import org.dasein.cloud.*;
import org.dasein.cloud.compute.ImageCapabilities;
import org.dasein.cloud.compute.ImageClass;
import org.dasein.cloud.compute.MachineImageFormat;
import org.dasein.cloud.compute.MachineImageType;
import org.dasein.cloud.compute.VmState;
import org.dasein.cloud.vcloud.vCloud;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.Locale;
/**
* Describes the capabilities of Dasein Cloud template support for vCloud.
* <p>Created by George Reese: 3/5/14 10:20 PM</p>
* @author George Reese
* @version 2014.03
* @since 2014.03
*/
public class TemplateCapabilities extends AbstractCapabilities<vCloud> implements ImageCapabilities {
public TemplateCapabilities(vCloud provider) { super(provider); }
@Override
public boolean canBundle(@Nonnull VmState fromState) throws CloudException, InternalException {
return false;
}
@Override
public boolean canImage(@Nonnull VmState fromState) throws CloudException, InternalException {
return (fromState.equals(VmState.STOPPED) || fromState.equals(VmState.PAUSED) || fromState.equals(VmState.SUSPENDED));
}
@Override
public @Nonnull String getProviderTermForImage(@Nonnull Locale locale, @Nonnull ImageClass imageClass) {
return "template";
}
@Override
public @Nonnull String getProviderTermForCustomImage(@Nonnull Locale locale, @Nonnull ImageClass imageClass) {
return "template";
}
@Override
public @Nullable VisibleScope getImageVisibleScope() {
return null;
}
@Override
public @Nonnull Requirement identifyLocalBundlingRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Iterable<MachineImageFormat> listSupportedFormats() throws CloudException, InternalException {
return Collections.singletonList(MachineImageFormat.VMDK);
}
@Override
public @Nonnull Iterable<MachineImageFormat> listSupportedFormatsForBundling() throws CloudException, InternalException {
return Collections.emptyList();
}
@Override
public @Nonnull Iterable<ImageClass> listSupportedImageClasses() throws CloudException, InternalException {
return Collections.singletonList(ImageClass.MACHINE);
}
@Override
public @Nonnull Iterable<MachineImageType> listSupportedImageTypes() throws CloudException, InternalException {
return Collections.singletonList(MachineImageType.VOLUME);
}
@Override
public boolean supportsDirectImageUpload() throws CloudException, InternalException {
return false;
}
@Override
public boolean supportsImageCapture(@Nonnull MachineImageType type) throws CloudException, InternalException {
return type.equals(MachineImageType.VOLUME);
}
@Override
public boolean supportsImageCopy() throws CloudException, InternalException {
return false;
}
@Override
public boolean supportsImageSharing() throws CloudException, InternalException {
return false;
}
@Override
public boolean supportsImageSharingWithPublic() throws CloudException, InternalException {
return false;
}
@Override
public boolean supportsListingAllRegions() throws CloudException, InternalException {
return false;
}
@Override
public boolean supportsPublicLibrary(@Nonnull ImageClass imageClass) throws CloudException, InternalException {
return imageClass.equals(ImageClass.MACHINE);
}
}
| apache-2.0 |
jessefugitt/nuklei | protocol/amqp-1.0/src/main/java/org/kaazing/nuklei/amqp_1_0/connection/ConnectionStateMachine.java | 10423 | /*
* Copyright 2014 Kaazing Corporation, All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.nuklei.amqp_1_0.connection;
import static java.util.EnumSet.allOf;
import org.kaazing.nuklei.amqp_1_0.codec.transport.Close;
import org.kaazing.nuklei.amqp_1_0.codec.transport.Frame;
import org.kaazing.nuklei.amqp_1_0.codec.transport.Header;
import org.kaazing.nuklei.amqp_1_0.codec.transport.Open;
/*
* See AMQP 1.0 specification, section 2.4.7 "Connection State Diagram"
*/
public class ConnectionStateMachine<C, S, L>
{
private final ConnectionHooks<C, S, L> connectionHooks;
public ConnectionStateMachine(ConnectionHooks<C, S, L> connectionHooks)
{
this.connectionHooks = connectionHooks;
}
public void start(Connection<C, S, L> connection)
{
connection.state = ConnectionState.START;
connectionHooks.whenInitialized.accept(connection);
}
public void received(Connection<C, S, L> connection, Header header)
{
connection.headerReceived = header.buffer().getLong(header.offset());
switch (connection.state)
{
case START:
transition(connection, ConnectionTransition.RECEIVED_HEADER);
connectionHooks.whenHeaderReceived.accept(connection, header);
break;
case HEADER_SENT:
case OPEN_PIPE:
case OPEN_CLOSE_PIPE:
if (connection.headerReceived == connection.headerSent)
{
transition(connection, ConnectionTransition.RECEIVED_HEADER);
connectionHooks.whenHeaderReceived.accept(connection, header);
}
else
{
transition(connection, ConnectionTransition.RECEIVED_HEADER_NOT_EQUAL_SENT);
connectionHooks.whenHeaderReceivedNotEqualSent.accept(connection, header);
}
break;
default:
transition(connection, ConnectionTransition.RECEIVED_HEADER);
connectionHooks.whenError.accept(connection);
break;
}
}
public void sent(Connection<C, S, L> connection, Header header)
{
connection.headerSent = header.buffer().getLong(header.offset());
switch (connection.state)
{
case START:
transition(connection, ConnectionTransition.SENT_HEADER);
connectionHooks.whenHeaderSent.accept(connection, header);
break;
case HEADER_RECEIVED:
if (connection.headerReceived == connection.headerSent)
{
transition(connection, ConnectionTransition.SENT_HEADER);
connectionHooks.whenHeaderSent.accept(connection, header);
}
else
{
transition(connection, ConnectionTransition.SENT_HEADER_NOT_EQUAL_RECEIVED);
connectionHooks.whenHeaderSentNotEqualReceived.accept(connection, header);
}
break;
default:
transition(connection, ConnectionTransition.SENT_HEADER);
connectionHooks.whenError.accept(connection);
break;
}
}
public void received(Connection<C, S, L> connection, Frame frame, Open open)
{
switch (connection.state)
{
case DISCARDING:
transition(connection, ConnectionTransition.RECEIVED_OPEN);
break;
case HEADER_EXCHANGED:
case OPEN_SENT:
case CLOSE_PIPE:
transition(connection, ConnectionTransition.RECEIVED_OPEN);
connectionHooks.whenOpenReceived.accept(connection, frame, open);
break;
default:
transition(connection, ConnectionTransition.RECEIVED_OPEN);
connectionHooks.whenError.accept(connection);
break;
}
}
public void sent(Connection<C, S, L> connection, Frame frame, Open open)
{
switch (connection.state)
{
case HEADER_SENT:
case HEADER_EXCHANGED:
case OPEN_RECEIVED:
transition(connection, ConnectionTransition.SENT_OPEN);
connectionHooks.whenOpenSent.accept(connection, frame, open);
break;
default:
transition(connection, ConnectionTransition.SENT_OPEN);
connectionHooks.whenError.accept(connection);
break;
}
}
public void received(Connection<C, S, L> connection, Frame frame, Close close)
{
switch (connection.state)
{
case DISCARDING:
case OPENED:
case CLOSE_SENT:
transition(connection, ConnectionTransition.RECEIVED_CLOSE);
connectionHooks.whenCloseReceived.accept(connection, frame, close);
break;
default:
transition(connection, ConnectionTransition.RECEIVED_CLOSE);
connectionHooks.whenError.accept(connection);
break;
}
}
public void sent(Connection<C, S, L> connection, Frame frame, Close close)
{
switch (connection.state)
{
case OPEN_SENT:
case OPEN_PIPE:
case OPENED:
case CLOSE_RECEIVED:
transition(connection, ConnectionTransition.SENT_CLOSE);
connectionHooks.whenCloseSent.accept(connection, frame, close);
break;
default:
transition(connection, ConnectionTransition.SENT_CLOSE);
connectionHooks.whenError.accept(connection);
break;
}
}
public void error(Connection<C, S, L> connection)
{
switch (connection.state)
{
case DISCARDING:
transition(connection, ConnectionTransition.ERROR);
break;
default:
transition(connection, ConnectionTransition.ERROR);
connectionHooks.whenError.accept(connection);
break;
}
}
private static void transition(Connection<?, ?, ?> connection, ConnectionTransition transition)
{
connection.state = STATE_MACHINE[connection.state.ordinal()][transition.ordinal()];
}
private static final ConnectionState[][] STATE_MACHINE;
static
{
int stateCount = ConnectionState.values().length;
int transitionCount = ConnectionTransition.values().length;
ConnectionState[][] stateMachine = new ConnectionState[stateCount][transitionCount];
for (ConnectionState state : allOf(ConnectionState.class))
{
// default transition to "end" state
for (ConnectionTransition transition : allOf(ConnectionTransition.class))
{
stateMachine[state.ordinal()][transition.ordinal()] = ConnectionState.END;
}
// default "error" transition to "discarding" state
stateMachine[state.ordinal()][ConnectionTransition.ERROR.ordinal()] = ConnectionState.DISCARDING;
}
stateMachine[ConnectionState.START.ordinal()][ConnectionTransition.RECEIVED_HEADER.ordinal()] =
ConnectionState.HEADER_RECEIVED;
stateMachine[ConnectionState.START.ordinal()][ConnectionTransition.SENT_HEADER.ordinal()] = ConnectionState.HEADER_SENT;
stateMachine[ConnectionState.HEADER_RECEIVED.ordinal()][ConnectionTransition.SENT_HEADER.ordinal()] =
ConnectionState.HEADER_EXCHANGED;
stateMachine[ConnectionState.HEADER_SENT.ordinal()][ConnectionTransition.RECEIVED_HEADER.ordinal()] =
ConnectionState.HEADER_EXCHANGED;
stateMachine[ConnectionState.HEADER_SENT.ordinal()][ConnectionTransition.SENT_OPEN.ordinal()] = ConnectionState.OPEN_PIPE;
stateMachine[ConnectionState.HEADER_EXCHANGED.ordinal()][ConnectionTransition.RECEIVED_OPEN.ordinal()] =
ConnectionState.OPEN_RECEIVED;
stateMachine[ConnectionState.HEADER_EXCHANGED.ordinal()][ConnectionTransition.SENT_OPEN.ordinal()] =
ConnectionState.OPEN_SENT;
stateMachine[ConnectionState.OPEN_PIPE.ordinal()][ConnectionTransition.RECEIVED_HEADER.ordinal()] =
ConnectionState.OPEN_SENT;
stateMachine[ConnectionState.OPEN_PIPE.ordinal()][ConnectionTransition.SENT_CLOSE.ordinal()] =
ConnectionState.OPEN_CLOSE_PIPE;
stateMachine[ConnectionState.OPEN_CLOSE_PIPE.ordinal()][ConnectionTransition.RECEIVED_HEADER.ordinal()] =
ConnectionState.CLOSE_PIPE;
stateMachine[ConnectionState.OPEN_RECEIVED.ordinal()][ConnectionTransition.SENT_OPEN.ordinal()] = ConnectionState.OPENED;
stateMachine[ConnectionState.OPEN_SENT.ordinal()][ConnectionTransition.RECEIVED_OPEN.ordinal()] = ConnectionState.OPENED;
stateMachine[ConnectionState.OPEN_SENT.ordinal()][ConnectionTransition.SENT_CLOSE.ordinal()] =
ConnectionState.CLOSE_PIPE;
stateMachine[ConnectionState.CLOSE_PIPE.ordinal()][ConnectionTransition.RECEIVED_OPEN.ordinal()] =
ConnectionState.CLOSE_SENT;
stateMachine[ConnectionState.OPENED.ordinal()][ConnectionTransition.RECEIVED_CLOSE.ordinal()] =
ConnectionState.CLOSE_RECEIVED;
stateMachine[ConnectionState.OPENED.ordinal()][ConnectionTransition.SENT_CLOSE.ordinal()] =
ConnectionState.CLOSE_SENT;
stateMachine[ConnectionState.CLOSE_RECEIVED.ordinal()][ConnectionTransition.SENT_CLOSE.ordinal()] =
ConnectionState.END;
stateMachine[ConnectionState.CLOSE_SENT.ordinal()][ConnectionTransition.RECEIVED_CLOSE.ordinal()] =
ConnectionState.END;
stateMachine[ConnectionState.DISCARDING.ordinal()][ConnectionTransition.RECEIVED_OPEN.ordinal()] =
ConnectionState.DISCARDING;
stateMachine[ConnectionState.DISCARDING.ordinal()][ConnectionTransition.RECEIVED_CLOSE.ordinal()] = ConnectionState.END;
STATE_MACHINE = stateMachine;
}
} | apache-2.0 |
jivesoftware/jive-utils | shell-utils/src/main/java/com/jivesoftware/os/jive/utils/shell/utils/Unzip.java | 2199 | /*
* Copyright 2013 Jive Software, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.jivesoftware.os.jive.utils.shell.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import org.apache.commons.io.FileUtils;
/**
*
*/
public class Unzip {
public static File unGzip(boolean verbose,
File outputDir,
String outName,
File inputFile,
boolean deleteOriginal) throws FileNotFoundException, IOException {
String inFilePath = inputFile.getAbsolutePath();
if (verbose) {
System.out.println("unzipping " + inFilePath);
}
GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(inFilePath));
File outFile = new File(outputDir, outName);
outFile.getParentFile().mkdirs();
String outFilePath = outFile.getAbsolutePath();
OutputStream out = new FileOutputStream(outFilePath);
byte[] buf = new byte[1024];
int len;
while ((len = gzipInputStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
gzipInputStream.close();
out.close();
if (deleteOriginal) {
FileUtils.forceDelete(inputFile);
if (verbose) {
System.out.println(String.format("deleted original file %s.", inputFile.getAbsolutePath()));
}
}
if (verbose) {
System.out.println("unzipped " + inFilePath);
}
return new File(outFilePath);
}
} | apache-2.0 |
LIST-LUXEMBOURG/eagle-dashboard | eu.fp7.eagle.portal.ui.dashboard.design/src/main/java/eu/fp7/eagle/portal/ui/dashboard/design/ActivitiesDesign.java | 883 | /**
* Copyright (c) 2016-2017 Luxembourg Institute of Science and Technology (LIST).
*
* This software is 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.
*
* for more information about the software, please contact info@list.lu
*/
package eu.fp7.eagle.portal.ui.dashboard.design;
import com.vaadin.ui.Component;
public interface ActivitiesDesign extends Component {
}
| apache-2.0 |
paulcwarren/spring-content | spring-content-fs/src/main/java/org/springframework/content/fs/config/FilesystemStoreConverter.java | 187 | package org.springframework.content.fs.config;
import org.springframework.core.convert.converter.Converter;
public interface FilesystemStoreConverter<S, T> extends Converter<S, T> {
}
| apache-2.0 |
jessyZu/jsongood | jsongood-core/src/main/java/com/github/jessyZu/jsongood/core/RpcResultCodeEnum.java | 1256 | /**
*
*/
package com.github.jessyZu.jsongood.core;
public enum RpcResultCodeEnum {
SUCCESS(1000, "success"),
SYSTEM_ERROR(-1000, "system error"),
DECODE_ERROR(-1001, "decoded rpc request error"),
METHOD_ENDPOINT_ERROR(-1002, "methodEndPoint format error,splitMethodEndPoint length must be 2 or 3"),
CLASS_NOT_FOUND_ERROR(-1003, "can't find a service class with the classname"),
SERVICE_BEAN_NOT_FOUND_ERROR(-1004, "can't find a service bean with the classname"),
METHOD_NOT_FOUND_ERROR(-1005, "can't find a mehotd with the service bean"),
METHOD_INVOKE_ERROR(-1006, "invoke method occurs error"),
ENCODE_ERROR(-1007, "encoded rpc result error"),
PARAMETER_ERROR(-1008, " rpc request parameter error"),
VALIDATION_ERROR(-1009, "method validation error");
private int code;
private String message;
private RpcResultCodeEnum(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| apache-2.0 |
namdo/spring-cloud-samples | spring-cloud-hystrix-example/spring-cloud-hystrix-consumer/src/main/java/com/dohongnam/samples/service/ReviewService.java | 190 | package com.dohongnam.samples.service;
import java.util.List;
import com.dohongnam.samples.domain.Review;
public interface ReviewService {
List<Review> getReviews(String productId);
}
| apache-2.0 |
billzbh/XML2Java | iMateInterface/src/com/hxsmart/imateinterface/pinpad/Pinpad.java | 9572 | package com.hxsmart.imateinterface.pinpad;
public class Pinpad {
public final static int KMY_MODEL = 0;
public final static int XYD_MODEL = 1;
public final static int ALGO_ENCRYPT = 1;
public final static int ALGO_DECRYPT = 2;
public final static int DECRYPT_KEY_MODE = 0x00;
public final static int ENCRYPT_KEY_MODE = 0x01;
public final static int PIN_KEY_MODE = 0x02;
public final static int COMM_NONE = 0;
public final static int COMM_EVEN = 1;
public final static int COMM_ODD = 2;
private KmyPinpad kmyPinpad;
private XydPinpad xydPinpad;
private int pinpadModel = KMY_MODEL;
/*
* 设置Pinpad型号
* @param pinpadModel Pinpad.KMY_MODEL :凯明扬密码键盘
* Pinpad.XYD_MODEL : 信雅达密码键盘
*/
public void setPinpadModel(int pinpadModel)
{
if (pinpadModel != KMY_MODEL && pinpadModel != XYD_MODEL)
return;
this.pinpadModel = pinpadModel;
kmyPinpad = null;
xydPinpad = null;
if (pinpadModel == KMY_MODEL) {
kmyPinpad = new KmyPinpad();
}else {
xydPinpad = new XydPinpad();
}
}
/**
* 设置算法类型, 用于下载masterkey或workingkey之前调用
* @param mode 主密钥类型包括 :
* Pinpad.DECRYPT_KEY_MODE, Pinpad.ENCRYPT_KEY_MODE, Pinpad.PIN_KEY_MODE
*/
public void setKeyMode(int mode)
{
if (xydPinpad != null)
xydPinpad.setKeyMode(mode);
}
/**
* Pinpad上电 (缺省波特率连接,9600bps,Pinpad.COMM_NONE)
* @throws Exception
*/
public void powerOn() throws Exception
{
kmyPinpad = null;
xydPinpad = null;
if (pinpadModel == KMY_MODEL && kmyPinpad == null) {
kmyPinpad = new KmyPinpad();
}
if (pinpadModel == XYD_MODEL && xydPinpad == null) {
xydPinpad = new XydPinpad();
}
try {
if (kmyPinpad != null)
kmyPinpad.powerOn();
if (xydPinpad != null)
xydPinpad.powerOn();
}catch (Exception e) {
throw e;
}
}
/**
* Pinpad下电
* @throws Exception
* iMate通讯超时
*/
public void powerOff() throws Exception
{
try {
if (kmyPinpad != null)
kmyPinpad.powerOff();
if (xydPinpad != null)
xydPinpad.powerOff();
}catch (Exception e) {
throw e;
}
kmyPinpad = null;
xydPinpad = null;
}
/**
* 设置密码键盘参数, KMY密码键盘不支持
* key : 参数名称
* "AuthCode" : 认证密钥, 16字节长度, 缺省值为16个0x00
* "UID" : Pinpad UID, 缺省值为{'1','2','3','4','5','6','7','8','9','0','1','2','3','4','5'}
* "WorkDirNum : 子目录编号, 缺省值为1;
*/
public void pinpadSetup(String key, byte[] value)
{
if (pinpadModel == XYD_MODEL && xydPinpad != null)
xydPinpad.pinpadSetup(key, value);
}
/**
* 取消密码输入操作
*/
public void cancel()
{
if (kmyPinpad != null)
kmyPinpad.cancel();
if (xydPinpad != null)
xydPinpad.cancel();
}
/**
* 获取Pinpad的终端序列号信息
* @return 成功将返回Pinpad的序列号信息(8或16个字节)
* @throws Exception
*/
public byte[] getSerialNo() throws Exception
{
if (kmyPinpad != null)
return kmyPinpad.getSerialNo();
if (xydPinpad != null)
return xydPinpad.getSerialNo();
return null;
}
/**
* Pinpad复位自检
* @param initFlag true清除Pinpad中的密钥,false不清除密钥
* @throws Exception
*/
public void reset(boolean initFlag) throws Exception
{
if (kmyPinpad == null && xydPinpad == null)
throw new Exception("Pinpad对象为null");
try {
if (kmyPinpad != null)
kmyPinpad.reset(initFlag);
else
xydPinpad.reset(initFlag);
}catch (Exception e) {
throw e;
}
}
/**
* 获取Pinpad的版本号信息
* @return 成功将返回Pinpad的版本号信息,详细格式请参考厂家文档。
* @throws Exception
*/
public byte[] getVersion() throws Exception
{
if (kmyPinpad == null && xydPinpad == null)
throw new Exception("Pinpad对象为null");
try {
if (kmyPinpad != null)
return kmyPinpad.getVersion();
else
return xydPinpad.getVersion();
}catch (Exception e) {
throw e;
}
}
/**
* Pinpad下装主密钥
* @param is3des 是否采用3DES算法,false表示使用DES算法
* @param index 主密钥索引
* @param mastKey 主密钥
* @param keyLength 主密钥长度
* @throws Exception
*/
public void downloadMasterKey(boolean is3des, int index, byte[] masterKey, int keyLength) throws Exception
{
if (kmyPinpad == null && xydPinpad == null)
throw new Exception("Pinpad对象为null");
try {
if (kmyPinpad != null)
kmyPinpad.downloadMasterKey(is3des, index, masterKey, keyLength);
else
xydPinpad.downloadMasterKey(is3des, index, masterKey, keyLength);
}catch (Exception e) {
throw e;
}
}
/**
* Pinpad下装工作密钥(主密钥加密)
* @param is3des 是否采用3DES算法,false表示使用DES算法
* @param masterIndex 主密钥索引
* @param workingIndex 工作密钥索引
* @param workingKey 工作密钥
* @param keyLength 工作密钥长度
* @throws Exception
*/
public void downloadWorkingKey(boolean is3des, int masterIndex, int workingIndex, byte[] workingKey, int keyLength)
throws Exception
{
if (kmyPinpad == null && xydPinpad == null)
throw new Exception("Pinpad对象为null");
try {
if (kmyPinpad != null)
kmyPinpad.downloadWorkingKey(is3des, masterIndex, workingIndex, workingKey, keyLength);
if (xydPinpad != null)
xydPinpad.downloadWorkingKey(is3des, masterIndex, workingIndex, workingKey, keyLength);
}catch (Exception e) {
throw e;
}
}
/**
* Pinpad输入密码(PinBlock)
* @param is3des 是否采用3DES算法,false表示使用DES算法
* @param isAutoReturn 输入到约定长度时是否自动返回(不需要按Enter)
* @param masterIndex 主密钥索引
* @param workingIndex 工作密钥索引
* @param cardNo 卡号/帐号(最少12位数字)
* @param pinLength 需要输入PIN的长度
* @param timeout 输入密码等待超时时间 <= 255 秒
* @return 成功返回输入的Pinblock
* @throws Exception
*/
public byte[] inputPinblock(boolean is3des, boolean isAutoReturn, int masterIndex, int workingIndex, String cardNo, int pinLength, int timeout)
throws Exception
{
if (kmyPinpad == null && xydPinpad == null)
throw new Exception("Pinpad对象为null");
try {
if (kmyPinpad != null)
return kmyPinpad.inputPinblock(is3des, isAutoReturn, masterIndex, workingIndex, cardNo, pinLength, timeout);
else
return xydPinpad.inputPinblock(is3des, isAutoReturn, masterIndex, workingIndex, cardNo, pinLength, timeout);
}catch (Exception e) {
throw e;
}
}
/**
* Pinpad加解密数据
* @param is3des 是否采用3DES算法,false表示使用DES算法
* @param algo 算法,取值: Pinpad.ALGO_ENCRYPT, Pinpad.ALGO_DECRYPT, 以ECB方式进行加解密运算
* @param masterIndex 主密钥索引
* @param workingIndex 工作密钥索引,如果工作密钥索引取值-1,使用主密钥索引指定的主密钥进行加解密
* @param data 加解密数据
* @param dataLength 加解密数据的长度,要求8的倍数并小于或等于248字节长度
* @return 成功返回加解密的结果数据
* @throws Exception
*/
public byte[] encrypt(boolean is3des, int algo, int masterIndex,
int workingIndex, byte[] data, int dataLength) throws Exception
{
if (kmyPinpad == null && xydPinpad == null)
throw new Exception("Pinpad对象为null");
try {
if (kmyPinpad != null)
return kmyPinpad.encrypt(is3des, algo, masterIndex, workingIndex, data, dataLength);
else
return xydPinpad.encrypt(is3des, algo, masterIndex, workingIndex, data, dataLength);
}catch (Exception e) {
throw e;
}
}
/**
* Pinpad数据MAC运算(ANSIX9.9)
* @param is3des 是否采用3DES算法,false表示使用DES算法
* @param masterIndex 主密钥索引
* @param workingIndex 工作密钥索引,如果工作密钥索引取值-1,使用主密钥索引指定的主密钥进行加解密
* @param data 计算Mac原数据
* @param dataLength Mac原数据的长度,要求8的倍数并小于或等于246字节长度
* @return 成功返回8字节Mac数据
* @throws Exception
*/
public byte[] mac(boolean is3des, int masterIndex,
int workingIndex, byte[] data, int dataLength) throws Exception
{
if (kmyPinpad == null && xydPinpad == null)
throw new Exception("Pinpad对象为null");
try {
if (kmyPinpad != null)
return kmyPinpad.mac(is3des, masterIndex, workingIndex, data, dataLength);
else
return xydPinpad.mac(is3des, masterIndex, workingIndex, data, dataLength);
}catch (Exception e) {
throw e;
}
}
private int toupper(int in) {
if (in >= 'a' && in <= 'z')
return in+32;
return in;
}
public void twoOne(byte[] in, int offset, int length, byte[] out)
{
int tmp;
for (int i=0; i<length; i+=2)
{
tmp = in[i+offset];
if (tmp > '9')
tmp = toupper(tmp) - 'A' + 0x0a;
else
tmp &= 0x0f;
out[i/2] = (byte)(tmp << 4);
tmp = in[i+1+offset];
if (tmp > '9')
tmp = toupper(tmp) - 'A' + 0x0a;
else
tmp &= 0x0f;
out[i/2] += tmp;
} // for(i=0; i<uiLength; i+=2) {
}
public String oneTwo(byte[] in, int offset, int length)
{
String twoString = "";
for (int m=0; m<length; m++) {
twoString += Integer.toHexString((in[m + offset]&0x000000ff)|0xffffff00).substring(6);
}
return twoString;
}
}
| apache-2.0 |
akarnokd/Reactive4JavaFlow | src/test/java/hu/akarnokd/reactive4javaflow/impl/operators/EsetlegOnErrorResumeNextTest.java | 3051 | /*
* Copyright 2017 David Karnok
*
* 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 hu.akarnokd.reactive4javaflow.impl.operators;
import hu.akarnokd.reactive4javaflow.*;
import hu.akarnokd.reactive4javaflow.errors.CompositeThrowable;
import org.junit.Test;
import java.io.IOException;
public class EsetlegOnErrorResumeNextTest {
@Test
public void standard() {
TestHelper.assertResult(
Esetleg.just(1)
.onErrorReturn(6),
1
);
}
@Test
public void standardError() {
TestHelper.assertResult(
Esetleg.error(new IOException())
.onErrorReturn(6),
6
);
}
@Test
public void standardHidden() {
TestHelper.assertResult(
Esetleg.just(1).hide()
.onErrorReturn(6),
1
);
}
@Test
public void bothError() {
Esetleg.error(new IOException("First"))
.onErrorResumeNext(v -> Esetleg.error(new IOException("Second")))
.test()
.assertFailureAndMessage(IOException.class, "Second");
}
@Test
public void bothErrorConditional() {
Esetleg.error(new IOException("First"))
.onErrorResumeNext(v -> Esetleg.error(new IOException("Second")))
.filter(v -> true)
.test()
.assertFailureAndMessage(IOException.class, "Second");
}
@Test
public void handlerCrash() {
Esetleg.error(new IOException("First"))
.onErrorResumeNext(v -> { throw new IOException("Second"); })
.test()
.assertFailure(CompositeThrowable.class)
.assertInnerErrors(errors -> {
TestHelper.assertError(errors, 0, IOException.class, "First");
TestHelper.assertError(errors, 1, IOException.class, "Second");
});
}
@Test
public void handlerCrashConditional() {
Esetleg.error(new IOException("First"))
.onErrorResumeNext(v -> { throw new IOException("Second"); })
.filter(v -> true)
.test()
.assertFailure(CompositeThrowable.class)
.assertInnerErrors(errors -> {
TestHelper.assertError(errors, 0, IOException.class, "First");
TestHelper.assertError(errors, 1, IOException.class, "Second");
});
}
}
| apache-2.0 |
nikelin/Redshape-AS | utils/utils-core/src/main/java/com/redshape/utils/system/scripts/bash/BashScriptExecutor.java | 8328 | /*
* Copyright 2012 Cyril A. Karpenko
*
* 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.redshape.utils.system.scripts.bash;
import com.redshape.utils.ILambda;
import com.redshape.utils.InvocationException;
import com.redshape.utils.system.processes.ISystemProcess;
import com.redshape.utils.system.processes.SystemProcess;
import com.redshape.utils.system.scripts.IScriptExecutionHandler;
import com.redshape.utils.system.scripts.IScriptExecutor;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
public class BashScriptExecutor implements IScriptExecutor {
private static final Logger log = Logger.getLogger( BashScriptExecutor.class );
private String command;
private Map<String, Object> parameters = new LinkedHashMap<String, Object>();
private List<Object> unnamedParameters = new ArrayList<Object>();
private Object inputSource;
private Object outputSource;
private boolean finished;
private boolean successful;
private String output;
private String errors;
private ISystemProcess process;
private IScriptExecutionHandler handler;
protected BashScriptExecutor() {
this(null);
}
public BashScriptExecutor( String command ) {
this.command = command;
}
protected void markFinished( boolean value ) {
this.finished = value;
}
protected void markSuccessful( boolean value ) {
this.successful= value;
}
protected String prepareSource( Object source ) {
if ( source instanceof String ) {
return (String) source;
} else if ( source instanceof IScriptExecutor ) {
return ( (IScriptExecutor) source ).getExecCommand();
} else {
throw new IllegalArgumentException("Invalid I/O source object passed to executor");
}
}
@Override
public ISystemProcess spawn() throws IOException {
return this.spawn(null);
}
@Override
public ISystemProcess spawn( ExecutorService service ) throws IOException {
return this.spawn(service, null);
}
@Override
public ISystemProcess spawn( ExecutorService service, final ILambda<?> callback ) throws IOException {
this.process = new SystemProcess(
Runtime.getRuntime().exec( this.getExecCommand().toString() )
);
try {
if ( service == null ) {
int exitCode = this.process.waitFor();
if ( callback != null ) {
try {
callback.invoke(exitCode, this.process);
} catch ( InvocationException e ) {
throw new IllegalStateException( e.getMessage(), e );
}
}
} else {
service.execute(new Runnable() {
@Override
public void run() {
try {
int exitCode = process.waitFor();
if ( callback != null ) {
try {
callback.invoke(exitCode, process);
} catch ( InvocationException e ) {
throw new IllegalStateException( e.getMessage(), e );
}
}
} catch ( InterruptedException e ) {
throw new IllegalStateException( e.getMessage(), e );
}
}
});
}
} catch (InterruptedException e) {
log.error( e.getMessage(), e );
}
return this.process;
}
@Override
public synchronized String execute(ISystemProcess process) throws IOException {
this.proceedResult(process);
return this.getExecutionResult();
}
protected void proceedResult( ISystemProcess process ) throws IOException {
String processStdInput = process.readStdInput();
String processStdErr = process.readStdError();
boolean successful = processStdErr.isEmpty();
if ( this.handler != null ) {
if ( processStdErr.isEmpty() ) {
successful = this.handler.onExit( processStdInput );
} else {
this.handler.onError( processStdErr );
}
}
this.finished = true;
this.successful = successful;
this.errors = processStdErr;
this.output = processStdInput;
}
@Override
public synchronized String execute() throws IOException {
this.process = this.spawn();
this.proceedResult(this.process);
return this.getExecutionResult();
}
public Integer getProgress() throws IOException {
if ( null == this.handler ) {
return 0;
}
return this.handler.onProgressRequested( this.process );
}
@Override
public String getExecCommand() {
StringBuilder builder = new StringBuilder();
boolean bothIO = false;
if ( this.hasDeclaredInputSource() && this.hasDeclaredOutputSource() ) {
bothIO = true;
}
if ( bothIO ) {
builder.append("(");
}
builder.append( this.command )
.append( " " );
for ( String parameter : this.parameters.keySet() ) {
builder.append( parameter )
.append("=")
.append( String.valueOf( this.parameters.get(parameter) ) )
.append(" ");
}
for ( Object parameter : this.unnamedParameters ) {
builder.append( String.valueOf( parameter ) )
.append( " " );
}
if ( this.hasDeclaredInputSource() ) {
builder.append(" ")
.append("<")
.append(" ");
// @author nikelin
// TODO: refactor with generification of inputsource from Object
// to IScriptExecutorSource which will be return destination on *.toString()
// invokation.
builder.append( this.prepareSource( this.inputSource ) );
}
if ( bothIO ) {
builder.append(")");
}
if ( this.hasDeclaredOutputSource() ) {
builder.append(" ")
.append(">")
.append(" ")
.append( this.prepareSource( this.inputSource ) );
}
return builder.toString();
}
@Override
public void kill() {
if ( this.process != null ) {
log.info("Script " + this.getExecCommand() + " has been killed...");
this.process.destroy();
}
}
@Override
public boolean isFinished() {
return this.finished;
}
@Override
public IScriptExecutor addUnnamedParameter( Object value ) {
this.unnamedParameters.add(value);
return this;
}
@Override
public IScriptExecutor setParameter(String name, Object value) {
this.parameters.put(name, value);
return this;
}
@Override
public IScriptExecutor declareInputSource( IScriptExecutor executor ) {
this.inputSource = executor;
return this;
}
@Override
public IScriptExecutor declareInputSource(String source) {
this.inputSource = source;
return this;
}
@Override
public IScriptExecutor declareOutputSource( IScriptExecutor executor ) {
this.outputSource = executor;
return this;
}
@Override
public IScriptExecutor declareOutputSource(String source) {
this.outputSource = source;
return this;
}
@Override
public IScriptExecutor setHandler(IScriptExecutionHandler handler) {
this.handler = handler;
return this;
}
@Override
public String getExecutionResult() {
return this.output;
}
@Override
public String getExecutionErrors() {
return this.errors;
}
@Override
public boolean hasDeclaredInputSource() {
return this.inputSource != null;
}
@Override
public boolean hasDeclaredOutputSource() {
return this.outputSource != null;
}
@Override
public boolean isSuccess() {
if ( !this.isFinished() ) {
throw new IllegalAccessError("Method is only invokable after execute() has been processed");
}
return this.successful;
}
@Override
public String toString() {
return this.getExecCommand();
}
}
| apache-2.0 |
MikeFot/android-crossy-score | app/src/main/java/com/michaelfotiadis/crossyscore/ui/core/intent/NavLog.java | 871 | package com.michaelfotiadis.crossyscore.ui.core.intent;
import com.michaelfotiadis.crossyscore.utils.AppLog;
/**
*
*/
public final class NavLog {
private static final String PREFIX = "NAV:";
private NavLog() {
}
public static void d(final String message) {
AppLog.d(formatMessage(message));
}
public static void e(final String message, final Exception e) {
AppLog.e(formatMessage(message), e);
}
public static void e(final String message) {
AppLog.e(formatMessage(message));
}
private static String formatMessage(final String message) {
return PREFIX + message;
}
public static void w(final String message) {
AppLog.w(formatMessage(message));
}
public static void w(final String message, final Exception e) {
AppLog.w(formatMessage(message), e);
}
}
| apache-2.0 |
CSCSI/Triana | triana-gui/src/main/java/org/trianacode/gui/extensions/ExtensionManager.java | 5355 | /*
* The University of Wales, Cardiff Triana Project Software License (Based
* on the Apache Software License Version 1.1)
*
* Copyright (c) 2007 University of Wales, Cardiff. All rights reserved.
*
* Redistribution and use of the software in source and binary forms, with
* or without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if any,
* must include the following acknowledgment: "This product includes
* software developed by the University of Wales, Cardiff for the Triana
* Project (http://www.trianacode.org)." Alternately, this
* acknowledgment may appear in the software itself, if and wherever
* such third-party acknowledgments normally appear.
*
* 4. The names "Triana" and "University of Wales, Cardiff" must not be
* used to endorse or promote products derived from this software
* without prior written permission. For written permission, please
* contact triana@trianacode.org.
*
* 5. Products derived from this software may not be called "Triana," nor
* may Triana appear in their name, without prior written permission of
* the University of Wales, Cardiff.
*
* 6. This software may not be sold, used or incorporated into any product
* for sale to third parties.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 UNIVERSITY OF WALES, CARDIFF OR ITS 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.
*
* ------------------------------------------------------------------------
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Triana Project. For more information on the
* Triana Project, please see. http://www.trianacode.org.
*
* This license is based on the BSD license as adopted by the Apache
* Foundation and is governed by the laws of England and Wales.
*
*/
package org.trianacode.gui.extensions;
import org.trianacode.taskgraph.Task;
import org.trianacode.taskgraph.tool.Tool;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Iterator;
/**
* The manager responsible for handling extension classes.
*
* @author Ian Wang
* @version $Revision: 4048 $
*/
public class ExtensionManager {
/**
* a list of the extension instances
*/
private static final ArrayList extlist = new ArrayList();
/**
* Register an extension
*/
public static void registerExtension(Extension extension) {
if (!extlist.contains(extension)) {
extlist.add(extension);
}
}
/**
* Unregister an extension
*/
public static void unregisterExtension(Extension extension) {
extlist.remove(extension);
}
/**
* @return an array of the workspace extension actions for the specified tool
*/
public static Action[] getWorkspaceExtensions(Task tool) {
ArrayList exts = new ArrayList();
Action action;
for (Iterator it = extlist.iterator(); it.hasNext(); ) {
action = ((Extension) it.next()).getWorkspaceAction(tool);
if (action != null) {
exts.add(action);
}
}
return (Action[]) exts.toArray(new Action[exts.size()]);
}
/**
* @return an array of the tool tree extension actions for the specified tool
*/
public static Action[] getTreeExtensions(Tool tool) {
ArrayList exts = new ArrayList();
Action action;
for (Iterator it = extlist.iterator(); it.hasNext(); ) {
action = ((Extension) it.next()).getTreeAction(tool);
if (action != null) {
exts.add(action);
}
}
return (Action[]) exts.toArray(new Action[exts.size()]);
}
/**
* @return an array of the workfloe actions of the specified type (Extension.TOOL_TYPE or Extension.SERVICE_TYPE)
*/
public static Action[] getWorkflowExtensions(int type) {
ArrayList exts = new ArrayList();
Action action;
for (Iterator it = extlist.iterator(); it.hasNext(); ) {
action = ((Extension) it.next()).getWorkflowAction(type);
if (action != null) {
exts.add(action);
}
}
return (Action[]) exts.toArray(new Action[exts.size()]);
}
}
| apache-2.0 |
edouardhue/prospero | src/main/java/prospero/commons/mediawiki/Continue.java | 906 | package prospero.commons.mediawiki;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Objects;
public final class Continue {
@JsonProperty("continue")
private String queryContinue;
private String gcmcontinue;
public Continue() {
this.queryContinue = "";
this.gcmcontinue = "";
}
public String getGcmcontinue() {
return gcmcontinue;
}
public void setGcmcontinue(String gcmcontinue) {
this.gcmcontinue = gcmcontinue;
}
public String getQueryContinue() {
return queryContinue;
}
public void setQueryContinue(String queryContinue) {
this.queryContinue = queryContinue;
}
@Override
public String toString() {
return Objects.toStringHelper(this).add("continue", queryContinue).add("gcmcontinue", gcmcontinue).toString();
}
}
| apache-2.0 |
berinle/jawr-core | src/main/java/net/jawr/web/resource/bundle/locale/message/GrailsMessageBundleScriptCreator.java | 7306 | /**
* Copyright 2008-2010 Jordi Hernández Sellés, Ibrahim Chaehoi
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package net.jawr.web.resource.bundle.locale.message;
import java.io.IOException;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import net.jawr.web.JawrConstant;
import net.jawr.web.exception.BundlingProcessException;
import net.jawr.web.resource.bundle.generator.GeneratorContext;
import org.apache.log4j.Logger;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.context.support.ServletContextResourceLoader;
/**
* This is a specialized subclass of MessageBundleScriptCreator that takes in account the
* special scheme used by grails to manage message bundles. Said speciality comes from the
* fact that the applications get deployed differently in development mode and production
* mode (run-app vs run-war), and message properties go to different places each time.
* Besides, a regular ResourceBundle cannot be used since the encoding is 'fixed' by grails
* to avoid users the pain of encoding special characters in the properties files. Therefore
* Spring's MessageSource implementations are used to actually access the messages.
*
* @author Jordi Hernández Sellés
* @author ibrahim Chaehoi
*/
public class GrailsMessageBundleScriptCreator extends MessageBundleScriptCreator{
private static final Logger LOGGER = Logger.getLogger(GrailsMessageBundleScriptCreator.class);
private static final String PROPERTIES_DIR = "/WEB-INF/grails-app/i18n/";
private static final String PROPERTIES_EXT =".properties";
private static final String CHARSET_ISO_8859_1 = "ISO-8859-1";
public GrailsMessageBundleScriptCreator(GeneratorContext context) {
super(context);
if(LOGGER.isDebugEnabled())
LOGGER.debug("Using Grails i18n messages generator.");
}
/* (non-Javadoc)
* @see net.jawr.web.resource.bundle.locale.message.MessageBundleScriptCreator#createScript(java.nio.charset.Charset)
*/
public Reader createScript(Charset charset) {
// Determine wether this is run-app or run-war style of runtime.
boolean warDeployed = ((Boolean)this.servletContext.getAttribute(JawrConstant.GRAILS_WAR_DEPLOYED)).booleanValue();
// Spring message bundle object, the same used by grails.
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setFallbackToSystemLocale(false);
Set<String> allPropertyNames = null;
// Read the properties files to find out the available message keys. It is done differently
// for run-app or run-war style of runtimes.
if(warDeployed){
allPropertyNames = getPropertyNamesFromWar();
if(LOGGER.isDebugEnabled())
LOGGER.debug("found a total of " + allPropertyNames.size() + " distinct message keys.");
messageSource.setResourceLoader(new ServletContextResourceLoader(this.servletContext));
messageSource.setBasename(PROPERTIES_DIR + configParam.substring(configParam.lastIndexOf('.')+1));
}
else
{
ResourceBundle bundle;
if(null != locale)
bundle = ResourceBundle.getBundle(configParam,locale);
else bundle = ResourceBundle.getBundle(configParam);
allPropertyNames = new HashSet<String>();
Enumeration<String> keys = bundle.getKeys();
while(keys.hasMoreElements())
allPropertyNames.add(keys.nextElement());
String basename = "file:./" + configParam.replaceAll("\\.", "/");
messageSource.setBasename(basename);
}
// Pass all messages to a properties file.
Properties props = new Properties();
for(Iterator<String> it = allPropertyNames.iterator();it.hasNext();) {
String key = it.next();
if(matchesFilter(key)){
try {
// Use the property encoding of the file
String msg = new String(messageSource.getMessage(key, new Object[0], locale).getBytes(
CHARSET_ISO_8859_1), charset.displayName());
props.put(key, msg);
} catch (NoSuchMessageException e) {
// This is expected, so it's OK to have an empty catch block.
if(LOGGER.isDebugEnabled())
LOGGER.debug("Message key [" + key + "] not found.");
} catch (UnsupportedEncodingException e) {
LOGGER.warn("Unable to convert value of message bundle associated to key '"
+ key + "' because the charset is unknown");
}
}
}
return doCreateScript(props);
}
/**
* Reads the property names of the resourcebundle for the current locale from the war file.
* @return
*/
@SuppressWarnings("unchecked")
private Set<String> getPropertyNamesFromWar() {
Set<String> filenames = this.servletContext.getResourcePaths(PROPERTIES_DIR);
Set<String> allPropertyNames = new HashSet<String>();
for(Iterator<String> it = filenames.iterator();it.hasNext();){
String name = it.next();
if(matchesConfigParam(name)) {
try {
Properties props = new Properties();
props.load(servletContext.getResourceAsStream(name));
if(LOGGER.isDebugEnabled()){
LOGGER.debug("Found " + props.keySet().size() + " message keys at " + name + ".");
}
for (Object key : props.keySet()) {
allPropertyNames.add((String) key);
}
} catch (IOException e) {
throw new BundlingProcessException("Unexpected error retrieving i18n grails properties file", e);
}
}
}
return allPropertyNames;
}
/**
* Determines if a file found at the locale directory matches the locale for the bundle.
*
* @param fileName
* @return
*/
private boolean matchesConfigParam(String fileName){
String configValue = configParam.substring(configParam.lastIndexOf('.')+1);
String fileNameWOPath = fileName.substring(fileName.lastIndexOf('/') + 1 );
// List all the names of files which might have values used by the current locale
List<String> allowedNames = new ArrayList<String>(4);
allowedNames.add(configValue + PROPERTIES_EXT);
if(null != locale) {
allowedNames.add(configValue + "_" + locale.getLanguage() + PROPERTIES_EXT);
allowedNames.add(configValue + "_" + locale.getLanguage()+ "_" + locale.getCountry() + PROPERTIES_EXT);
allowedNames.add(configValue + "_" + locale.getLanguage()+ "_" + locale.getCountry()+ "_" + locale.getVariant() + PROPERTIES_EXT);
}
return allowedNames.contains(fileNameWOPath);
}
}
| apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/GetMaintenanceWindowExecutionRequestProtocolMarshaller.java | 2899 | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.simplesystemsmanagement.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* GetMaintenanceWindowExecutionRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class GetMaintenanceWindowExecutionRequestProtocolMarshaller implements
Marshaller<Request<GetMaintenanceWindowExecutionRequest>, GetMaintenanceWindowExecutionRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("AmazonSSM.GetMaintenanceWindowExecution").serviceName("AWSSimpleSystemsManagement").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public GetMaintenanceWindowExecutionRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<GetMaintenanceWindowExecutionRequest> marshall(GetMaintenanceWindowExecutionRequest getMaintenanceWindowExecutionRequest) {
if (getMaintenanceWindowExecutionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<GetMaintenanceWindowExecutionRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(
SDK_OPERATION_BINDING, getMaintenanceWindowExecutionRequest);
protocolMarshaller.startMarshalling();
GetMaintenanceWindowExecutionRequestMarshaller.getInstance().marshall(getMaintenanceWindowExecutionRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
stserp/erp1 | source/src/com/baosight/sts/st/xt/domain/STXT0201.java | 67631 | /**
* Generate time : 2009-05-13 9:26:15
* Version : 1.0.1.V20070717
*/
package com.baosight.sts.st.xt.domain;
import com.baosight.iplat4j.util.NumberUtils;
import java.util.Date;
import com.baosight.iplat4j.util.DateUtils;
import com.baosight.iplat4j.core.ei.EiColumn;
import com.baosight.iplat4j.ep.DaoEPBase;
import java.util.HashMap;
import java.util.Map;
import com.baosight.iplat4j.util.StringUtils;
/**
* STXT0102
*
*/
public class STXT0201 extends DaoEPBase {
private String customerId = " "; // 客户代码
private String custName = " "; // 客户名称
private String segNo = " "; // 对应业务单元代码
private String custEngName = " "; // 客户名称(英文)
private String custShortName = " "; // 客户简称
private String status = " "; // 客户状态
private String custType = " "; // 客户分类
private String custInvesterType = " "; // 客户投资类别
private String custAssetType = " "; // 客户资产类别(国企外资)
private String custStyle = " "; // 客户性质
private String vocationCode = " "; // 行业编码
private String privinceId = " "; // 省份代码
private String townId = " "; // 地级市代码
private String areaCode = " "; // 地区代码(区域)
private String groupFlag = " "; // 集团客户标识
private String groupCustId = " "; // 对应集团客户代码
private String creditClass = " "; // 信用等级
private String taxNum = " "; // 税号
private String regCurrencyId = " "; // 注册资金币种
private Double regFund = new Double(0); // 注册资金
private String regAddr = " "; // 注册地址
private Date validEndDate; // 有效终止日期(营业执照终止日期)
private Date validStartDate; // 有效起始日期(营业执照起始日期)
private String bankAcctNum = " "; // 银行开户行帐号
private String bankName = " "; // 开户行名称
private String ivoiceAddr = " "; // 发票地址
private String invoiceTele = " "; // 发票电话
private String invoiceZip = " "; // 发票邮编
private String invoiceAcctNum = " "; // 发票结算户帐号
private String invoiceBank = " "; // 发票结算户开户行
private String invoicePostType = " "; // 发票领取方式
private String invoiceBuildType = " "; // 发票要求
private String settleAcctNum = " "; // 结算户帐号
private String settleBank = " "; // 结算户开户行
private String artPerson = " "; // 法人
private String artPersonPre = " "; // 法人代表
private String boss = " "; // 公司负责人
private String contactPerson = " "; // 公司联系人
private String contactAddr = " "; // 公司联系地址
private String contactTele = " "; // 公司联系电话
private String faxNum = " "; // 公司联系传真
private String postCode = " "; // 公司联系邮编
private String email = " "; // 公司电子邮箱
private String web = " "; // 公司网站地址
private String tradeRemark = " "; // 公司业务说明
private String remark = " "; // 备注
private Date modiDate; // 更新日期
private String modiPerson = " "; // 更新人
private String salesPersNo = " "; // 营销员
private String printFreight = " "; // 是否打印运费(1是 0否)
private String gljyCode = " "; // 股份关联交易对应代码
private String ifFeeAll = " "; // 运费全额预收标记
private String currencyId = " "; // 记账币种
private String jgCenterFlag = " "; // 加工中心标记
private String invoicePrintType = " "; // 发票打印类型
private String insuranceCompany = " "; // 保险公司
private String insuranceType = " "; // 保险类型(a包到价;b半包到价,c代收代付)
private String insuranceFlag = " "; // 保险标志("1"入成本,即价内加价保险;"0"代收代付)
private String gfCompanyCode = " "; // 股份公司组织码
private String generalTaxpayerFlag = " "; // 一般纳税人
private Date createDate; // 客户开户日期
private String qaFlag = " "; // 是否需要质保书
private String p_customerId = " "; // 一体化客户代码
private String emsContactPerson = " "; // EMS发票联系人
private String ssCustomerId = " "; // 现货客户代码
private String ssPassword = " "; // 初始密码
private String contractCustomerId = " "; // 对应合同客户
private String disPlusFlag = " "; // 正数折扣单独结算
private String organizationCode = " "; // 组织机构证件号
private String ifMach = " "; // 加工中心标记//FOR YTH(J或空)
private String figContractFlag = " "; // 数字合同标记
private String companyScale = " "; // 公司规模
private String custInnerType = " "; // 客户内部分类10贸易20配送30贸易及配送
private String gzFlag = " "; // 行业跟踪标记
private String reportCount = " "; // 报告数
private String ifFreeDiscount = " "; // 是否自由款给付利息
private String innerSegNo = " "; // 内部往来交易对应的业务单元代码
private Date taxpayerEndDate; // 纳税人终止日期
private Date taxpayerStartDate; // 纳税人起始日期
private String ifShow = " ";
private String mnemonic_code = " ";
private String payType = " ";
private String deliveryAddr = " ";
//private String userId=" ";
private String processRequire=" ";
private String signUserId="";
private Double accountPeriod = new Double(0);
/**
* initialize the metadata
*/
public void initMetaData() {
EiColumn eiColumn;
eiColumn = new EiColumn("customerId");
eiColumn.setPrimaryKey(true);
eiColumn.setFieldLength(10);
eiColumn.setDescName("客户代码");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("custName");
eiColumn.setPrimaryKey(true);
eiColumn.setFieldLength(100);
eiColumn.setDescName("客户名称");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("segNo");
eiColumn.setPrimaryKey(true);
eiColumn.setFieldLength(20);
eiColumn.setDescName("对应业务单元代码");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("custEngName");
eiColumn.setFieldLength(100);
eiColumn.setDescName("客户名称(英文)");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("custShortName");
eiColumn.setFieldLength(60);
eiColumn.setDescName("客户简称");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("status");
eiColumn.setFieldLength(2);
eiColumn.setDescName("客户状态");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("custType");
eiColumn.setFieldLength(10);
eiColumn.setDescName("客户分类");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("custInvesterType");
eiColumn.setFieldLength(10);
eiColumn.setDescName("客户投资类别");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("custAssetType");
eiColumn.setFieldLength(10);
eiColumn.setDescName("客户资产类别(国企外资)");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("custStyle");
eiColumn.setFieldLength(10);
eiColumn.setDescName("客户性质");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("vocationCode");
eiColumn.setFieldLength(12);
eiColumn.setDescName("行业编码");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("privinceId");
eiColumn.setFieldLength(10);
eiColumn.setDescName("省份代码");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("townId");
eiColumn.setFieldLength(10);
eiColumn.setDescName("地级市代码");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("areaCode");
eiColumn.setFieldLength(10);
eiColumn.setDescName("地区代码(区域)");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("groupFlag");
eiColumn.setFieldLength(1);
eiColumn.setDescName("集团客户标识");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("groupCustId");
eiColumn.setFieldLength(10);
eiColumn.setDescName("对应集团客户代码");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("creditClass");
eiColumn.setFieldLength(10);
eiColumn.setDescName("信用等级");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("taxNum");
eiColumn.setFieldLength(15);
eiColumn.setDescName("税号");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("regCurrencyId");
eiColumn.setFieldLength(2);
eiColumn.setDescName("注册资金币种");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("regFund");
eiColumn.setType("N");
eiColumn.setScaleLength(2);
eiColumn.setFieldLength(14);
eiColumn.setDescName("注册资金");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("regAddr");
eiColumn.setFieldLength(100);
eiColumn.setDescName("注册地址");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("validEndDate");
eiColumn.setDescName("有效终止日期(营业执照终止日期)");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("validStartDate");
eiColumn.setDescName("有效起始日期(营业执照起始日期)");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("bankAcctNum");
eiColumn.setFieldLength(50);
eiColumn.setDescName("银行开户行帐号");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("bankName");
eiColumn.setFieldLength(60);
eiColumn.setDescName("开户行名称");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("ivoiceAddr");
eiColumn.setFieldLength(100);
eiColumn.setDescName("发票地址");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("invoiceTele");
eiColumn.setFieldLength(40);
eiColumn.setDescName("发票电话");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("invoiceZip");
eiColumn.setFieldLength(20);
eiColumn.setDescName("发票邮编");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("invoiceAcctNum");
eiColumn.setFieldLength(50);
eiColumn.setDescName("发票结算户帐号");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("invoiceBank");
eiColumn.setFieldLength(60);
eiColumn.setDescName("发票结算户开户行");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("invoicePostType");
eiColumn.setFieldLength(10);
eiColumn.setDescName("发票领取方式");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("invoiceBuildType");
eiColumn.setFieldLength(10);
eiColumn.setDescName("发票要求");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("settleAcctNum");
eiColumn.setFieldLength(50);
eiColumn.setDescName("结算户帐号");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("settleBank");
eiColumn.setFieldLength(60);
eiColumn.setDescName("结算户开户行");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("artPerson");
eiColumn.setFieldLength(50);
eiColumn.setDescName("法人");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("artPersonPre");
eiColumn.setFieldLength(50);
eiColumn.setDescName("法人代表");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("boss");
eiColumn.setFieldLength(20);
eiColumn.setDescName("公司负责人");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("contactPerson");
eiColumn.setFieldLength(30);
eiColumn.setDescName("公司联系人");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("contactAddr");
eiColumn.setFieldLength(100);
eiColumn.setDescName("公司联系地址");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("contactTele");
eiColumn.setFieldLength(40);
eiColumn.setDescName("公司联系电话");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("faxNum");
eiColumn.setFieldLength(30);
eiColumn.setDescName("公司联系传真");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("postCode");
eiColumn.setFieldLength(20);
eiColumn.setDescName("公司联系邮编");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("email");
eiColumn.setFieldLength(40);
eiColumn.setDescName("公司电子邮箱");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("web");
eiColumn.setFieldLength(60);
eiColumn.setDescName("公司网站地址");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("tradeRemark");
eiColumn.setFieldLength(300);
eiColumn.setDescName("公司业务说明");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("remark");
eiColumn.setFieldLength(1000);
eiColumn.setDescName("备注");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("modiDate");
eiColumn.setDescName("更新日期");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("modiPerson");
eiColumn.setFieldLength(30);
eiColumn.setDescName("更新人");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("salesPersNo");
eiColumn.setFieldLength(10);
eiColumn.setDescName("营销员");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("printFreight");
eiColumn.setFieldLength(1);
eiColumn.setDescName("是否打印运费(1是 0否)");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("gljyCode");
eiColumn.setFieldLength(20);
eiColumn.setDescName("股份关联交易对应代码");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("ifFeeAll");
eiColumn.setFieldLength(1);
eiColumn.setDescName("运费全额预收标记");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("currencyId");
eiColumn.setFieldLength(2);
eiColumn.setDescName("记账币种");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("jgCenterFlag");
eiColumn.setFieldLength(1);
eiColumn.setDescName("加工中心标记");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("invoicePrintType");
eiColumn.setFieldLength(2);
eiColumn.setDescName("发票打印类型");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("insuranceCompany");
eiColumn.setFieldLength(100);
eiColumn.setDescName("保险公司");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("insuranceType");
eiColumn.setFieldLength(2);
eiColumn.setDescName("保险类型(a包到价;b半包到价,c代收代付)");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("insuranceFlag");
eiColumn.setFieldLength(2);
eiColumn.setDescName("保险标志('1'入成本,即价内加价保险;'0'代收代付)");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("gfCompanyCode");
eiColumn.setFieldLength(100);
eiColumn.setDescName("股份公司组织码");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("generalTaxpayerFlag");
eiColumn.setFieldLength(1);
eiColumn.setDescName("一般纳税人");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("createDate");
eiColumn.setDescName("客户开户日期");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("qaFlag");
eiColumn.setFieldLength(1);
eiColumn.setDescName("是否需要质保书");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("p_customerId");
eiColumn.setFieldLength(20);
eiColumn.setDescName("一体化客户代码");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("emsContactPerson");
eiColumn.setFieldLength(30);
eiColumn.setDescName("EMS发票联系人");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("ssCustomerId");
eiColumn.setFieldLength(10);
eiColumn.setDescName("现货客户代码");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("ssPassword");
eiColumn.setFieldLength(100);
eiColumn.setDescName("初始密码");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("contractCustomerId");
eiColumn.setFieldLength(10);
eiColumn.setDescName("对应合同客户");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("disPlusFlag");
eiColumn.setFieldLength(1);
eiColumn.setDescName("正数折扣单独结算");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("organizationCode");
eiColumn.setFieldLength(20);
eiColumn.setDescName("组织机构证件号");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("ifMach");
eiColumn.setFieldLength(10);
eiColumn.setDescName("加工中心标记//FOR YTH(J或空)");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("figContractFlag");
eiColumn.setFieldLength(2);
eiColumn.setDescName("数字合同标记");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("companyScale");
eiColumn.setFieldLength(2);
eiColumn.setDescName("公司规模");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("custInnerType");
eiColumn.setFieldLength(2);
eiColumn.setDescName("客户内部分类10贸易20配送30贸易及配送");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("gzFlag");
eiColumn.setFieldLength(2);
eiColumn.setDescName("行业跟踪标记");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("reportCount");
eiColumn.setFieldLength(2);
eiColumn.setDescName("报告数");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("ifFreeDiscount");
eiColumn.setFieldLength(2);
eiColumn.setDescName("是否自由款给付利息");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("innerSegNo");
eiColumn.setFieldLength(20);
eiColumn.setDescName("内部往来交易对应的业务单元代码");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("taxpayerEndDate");
eiColumn.setDescName("纳税人终止日期");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("taxpayerStartDate");
eiColumn.setDescName("纳税人起始日期");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("ifShow");
eiColumn.setPrimaryKey(true);
eiColumn.setFieldLength(1);
eiColumn.setDescName("是否显示");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("mnemonic_code");
eiColumn.setFieldLength(100);
eiColumn.setDescName("助记码");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("payType");
eiColumn.setFieldLength(100);
eiColumn.setDescName("支付方式");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("deliveryAddr");
eiColumn.setFieldLength(100);
eiColumn.setDescName("送货地址");
eiMetadata.addMeta(eiColumn);
// eiColumn = new EiColumn("userId");
// eiColumn.setFieldLength(100);
// eiColumn.setDescName("签约人");
// eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("signUserId");
eiColumn.setFieldLength(100);
eiColumn.setDescName("签约人");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("processRequire");
eiColumn.setFieldLength(100);
eiColumn.setDescName("加工要求");
eiMetadata.addMeta(eiColumn);
eiColumn = new EiColumn("accountPeriod");
eiColumn.setType("N");
eiColumn.setScaleLength(2);
eiColumn.setFieldLength(14);
eiColumn.setDescName("账期");
eiMetadata.addMeta(eiColumn);
}
/**
* the constructor
*/
public STXT0201() {
initMetaData();
}
/**
* get the customerId - 客户代码
* @return the customerId
*/
public String getCustomerId() {
return this.customerId;
}
/**
* set the customerId - 客户代码
*/
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
/**
* get the custName - 客户名称
* @return the custName
*/
public String getCustName() {
return this.custName;
}
/**
* set the custName - 客户名称
*/
public void setCustName(String custName) {
this.custName = custName;
}
/**
* get the segNo - 对应业务单元代码
* @return the segNo
*/
public String getSegNo() {
return this.segNo;
}
/**
* set the segNo - 对应业务单元代码
*/
public void setSegNo(String segNo) {
this.segNo = segNo;
}
/**
* get the custEngName - 客户名称(英文)
* @return the custEngName
*/
public String getCustEngName() {
return this.custEngName;
}
/**
* set the custEngName - 客户名称(英文)
*/
public void setCustEngName(String custEngName) {
this.custEngName = custEngName;
}
/**
* get the custShortName - 客户简称
* @return the custShortName
*/
public String getCustShortName() {
return this.custShortName;
}
/**
* set the custShortName - 客户简称
*/
public void setCustShortName(String custShortName) {
this.custShortName = custShortName;
}
/**
* get the status - 客户状态
* @return the status
*/
public String getStatus() {
return this.status;
}
/**
* set the status - 客户状态
*/
public void setStatus(String status) {
this.status = status;
}
/**
* get the custType - 客户分类
* @return the custType
*/
public String getCustType() {
return this.custType;
}
/**
* set the custType - 客户分类
*/
public void setCustType(String custType) {
this.custType = custType;
}
/**
* get the custInvesterType - 客户投资类别
* @return the custInvesterType
*/
public String getCustInvesterType() {
return this.custInvesterType;
}
/**
* set the custInvesterType - 客户投资类别
*/
public void setCustInvesterType(String custInvesterType) {
this.custInvesterType = custInvesterType;
}
/**
* get the custAssetType - 客户资产类别(国企外资)
* @return the custAssetType
*/
public String getCustAssetType() {
return this.custAssetType;
}
/**
* set the custAssetType - 客户资产类别(国企外资)
*/
public void setCustAssetType(String custAssetType) {
this.custAssetType = custAssetType;
}
/**
* get the custStyle - 客户性质
* @return the custStyle
*/
public String getCustStyle() {
return this.custStyle;
}
/**
* set the custStyle - 客户性质
*/
public void setCustStyle(String custStyle) {
this.custStyle = custStyle;
}
/**
* get the vocationCode - 行业编码
* @return the vocationCode
*/
public String getVocationCode() {
return this.vocationCode;
}
/**
* set the vocationCode - 行业编码
*/
public void setVocationCode(String vocationCode) {
this.vocationCode = vocationCode;
}
/**
* get the privinceId - 省份代码
* @return the privinceId
*/
public String getPrivinceId() {
return this.privinceId;
}
/**
* set the privinceId - 省份代码
*/
public void setPrivinceId(String privinceId) {
this.privinceId = privinceId;
}
/**
* get the townId - 地级市代码
* @return the townId
*/
public String getTownId() {
return this.townId;
}
/**
* set the townId - 地级市代码
*/
public void setTownId(String townId) {
this.townId = townId;
}
/**
* get the areaCode - 地区代码(区域)
* @return the areaCode
*/
public String getAreaCode() {
return this.areaCode;
}
/**
* set the areaCode - 地区代码(区域)
*/
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
/**
* get the groupFlag - 集团客户标识
* @return the groupFlag
*/
public String getGroupFlag() {
return this.groupFlag;
}
/**
* set the groupFlag - 集团客户标识
*/
public void setGroupFlag(String groupFlag) {
this.groupFlag = groupFlag;
}
/**
* get the groupCustId - 对应集团客户代码
* @return the groupCustId
*/
public String getGroupCustId() {
return this.groupCustId;
}
/**
* set the groupCustId - 对应集团客户代码
*/
public void setGroupCustId(String groupCustId) {
this.groupCustId = groupCustId;
}
/**
* get the creditClass - 信用等级
* @return the creditClass
*/
public String getCreditClass() {
return this.creditClass;
}
/**
* set the creditClass - 信用等级
*/
public void setCreditClass(String creditClass) {
this.creditClass = creditClass;
}
/**
* get the taxNum - 税号
* @return the taxNum
*/
public String getTaxNum() {
return this.taxNum;
}
/**
* set the taxNum - 税号
*/
public void setTaxNum(String taxNum) {
this.taxNum = taxNum;
}
/**
* get the regCurrencyId - 注册资金币种
* @return the regCurrencyId
*/
public String getRegCurrencyId() {
return this.regCurrencyId;
}
/**
* set the regCurrencyId - 注册资金币种
*/
public void setRegCurrencyId(String regCurrencyId) {
this.regCurrencyId = regCurrencyId;
}
/**
* get the regFund - 注册资金
* @return the regFund
*/
public Double getRegFund() {
return this.regFund;
}
/**
* set the regFund - 注册资金
*/
public void setRegFund(Double regFund) {
this.regFund = regFund;
}
/**
* get the regAddr - 注册地址
* @return the regAddr
*/
public String getRegAddr() {
return this.regAddr;
}
/**
* set the regAddr - 注册地址
*/
public void setRegAddr(String regAddr) {
this.regAddr = regAddr;
}
/**
* get the validEndDate - 有效终止日期(营业执照终止日期)
* @return the validEndDate
*/
public Date getValidEndDate() {
return this.validEndDate;
}
/**
* set the validEndDate - 有效终止日期(营业执照终止日期)
*/
public void setValidEndDate(Date validEndDate) {
this.validEndDate = validEndDate;
}
/**
* get the validStartDate - 有效起始日期(营业执照起始日期)
* @return the validStartDate
*/
public Date getValidStartDate() {
return this.validStartDate;
}
/**
* set the validStartDate - 有效起始日期(营业执照起始日期)
*/
public void setValidStartDate(Date validStartDate) {
this.validStartDate = validStartDate;
}
/**
* get the bankAcctNum - 银行开户行帐号
* @return the bankAcctNum
*/
public String getBankAcctNum() {
return this.bankAcctNum;
}
/**
* set the bankAcctNum - 银行开户行帐号
*/
public void setBankAcctNum(String bankAcctNum) {
this.bankAcctNum = bankAcctNum;
}
/**
* get the bankName - 开户行名称
* @return the bankName
*/
public String getBankName() {
return this.bankName;
}
/**
* set the bankName - 开户行名称
*/
public void setBankName(String bankName) {
this.bankName = bankName;
}
/**
* get the ivoiceAddr - 发票地址
* @return the ivoiceAddr
*/
public String getIvoiceAddr() {
return this.ivoiceAddr;
}
/**
* set the ivoiceAddr - 发票地址
*/
public void setIvoiceAddr(String ivoiceAddr) {
this.ivoiceAddr = ivoiceAddr;
}
/**
* get the invoiceTele - 发票电话
* @return the invoiceTele
*/
public String getInvoiceTele() {
return this.invoiceTele;
}
/**
* set the invoiceTele - 发票电话
*/
public void setInvoiceTele(String invoiceTele) {
this.invoiceTele = invoiceTele;
}
/**
* get the invoiceZip - 发票邮编
* @return the invoiceZip
*/
public String getInvoiceZip() {
return this.invoiceZip;
}
/**
* set the invoiceZip - 发票邮编
*/
public void setInvoiceZip(String invoiceZip) {
this.invoiceZip = invoiceZip;
}
/**
* get the invoiceAcctNum - 发票结算户帐号
* @return the invoiceAcctNum
*/
public String getInvoiceAcctNum() {
return this.invoiceAcctNum;
}
/**
* set the invoiceAcctNum - 发票结算户帐号
*/
public void setInvoiceAcctNum(String invoiceAcctNum) {
this.invoiceAcctNum = invoiceAcctNum;
}
/**
* get the invoiceBank - 发票结算户开户行
* @return the invoiceBank
*/
public String getInvoiceBank() {
return this.invoiceBank;
}
/**
* set the invoiceBank - 发票结算户开户行
*/
public void setInvoiceBank(String invoiceBank) {
this.invoiceBank = invoiceBank;
}
/**
* get the invoicePostType - 发票领取方式
* @return the invoicePostType
*/
public String getInvoicePostType() {
return this.invoicePostType;
}
/**
* set the invoicePostType - 发票领取方式
*/
public void setInvoicePostType(String invoicePostType) {
this.invoicePostType = invoicePostType;
}
/**
* get the invoiceBuildType - 发票要求
* @return the invoiceBuildType
*/
public String getInvoiceBuildType() {
return this.invoiceBuildType;
}
/**
* set the invoiceBuildType - 发票要求
*/
public void setInvoiceBuildType(String invoiceBuildType) {
this.invoiceBuildType = invoiceBuildType;
}
/**
* get the settleAcctNum - 结算户帐号
* @return the settleAcctNum
*/
public String getSettleAcctNum() {
return this.settleAcctNum;
}
/**
* set the settleAcctNum - 结算户帐号
*/
public void setSettleAcctNum(String settleAcctNum) {
this.settleAcctNum = settleAcctNum;
}
/**
* get the settleBank - 结算户开户行
* @return the settleBank
*/
public String getSettleBank() {
return this.settleBank;
}
/**
* set the settleBank - 结算户开户行
*/
public void setSettleBank(String settleBank) {
this.settleBank = settleBank;
}
/**
* get the artPerson - 法人
* @return the artPerson
*/
public String getArtPerson() {
return this.artPerson;
}
/**
* set the artPerson - 法人
*/
public void setArtPerson(String artPerson) {
this.artPerson = artPerson;
}
/**
* get the artPersonPre - 法人代表
* @return the artPersonPre
*/
public String getArtPersonPre() {
return this.artPersonPre;
}
/**
* set the artPersonPre - 法人代表
*/
public void setArtPersonPre(String artPersonPre) {
this.artPersonPre = artPersonPre;
}
/**
* get the boss - 公司负责人
* @return the boss
*/
public String getBoss() {
return this.boss;
}
/**
* set the boss - 公司负责人
*/
public void setBoss(String boss) {
this.boss = boss;
}
/**
* get the contactPerson - 公司联系人
* @return the contactPerson
*/
public String getContactPerson() {
return this.contactPerson;
}
/**
* set the contactPerson - 公司联系人
*/
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
/**
* get the contactAddr - 公司联系地址
* @return the contactAddr
*/
public String getContactAddr() {
return this.contactAddr;
}
/**
* set the contactAddr - 公司联系地址
*/
public void setContactAddr(String contactAddr) {
this.contactAddr = contactAddr;
}
/**
* get the contactTele - 公司联系电话
* @return the contactTele
*/
public String getContactTele() {
return this.contactTele;
}
/**
* set the contactTele - 公司联系电话
*/
public void setContactTele(String contactTele) {
this.contactTele = contactTele;
}
/**
* get the faxNum - 公司联系传真
* @return the faxNum
*/
public String getFaxNum() {
return this.faxNum;
}
/**
* set the faxNum - 公司联系传真
*/
public void setFaxNum(String faxNum) {
this.faxNum = faxNum;
}
/**
* get the postCode - 公司联系邮编
* @return the postCode
*/
public String getPostCode() {
return this.postCode;
}
/**
* set the postCode - 公司联系邮编
*/
public void setPostCode(String postCode) {
this.postCode = postCode;
}
/**
* get the email - 公司电子邮箱
* @return the email
*/
public String getEmail() {
return this.email;
}
/**
* set the email - 公司电子邮箱
*/
public void setEmail(String email) {
this.email = email;
}
/**
* get the web - 公司网站地址
* @return the web
*/
public String getWeb() {
return this.web;
}
/**
* set the web - 公司网站地址
*/
public void setWeb(String web) {
this.web = web;
}
/**
* get the tradeRemark - 公司业务说明
* @return the tradeRemark
*/
public String getTradeRemark() {
return this.tradeRemark;
}
/**
* set the tradeRemark - 公司业务说明
*/
public void setTradeRemark(String tradeRemark) {
this.tradeRemark = tradeRemark;
}
/**
* get the remark - 备注
* @return the remark
*/
public String getRemark() {
return this.remark;
}
/**
* set the remark - 备注
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* get the modiDate - 更新日期
* @return the modiDate
*/
public Date getModiDate() {
return this.modiDate;
}
/**
* set the modiDate - 更新日期
*/
public void setModiDate(Date modiDate) {
this.modiDate = modiDate;
}
/**
* get the modiPerson - 更新人
* @return the modiPerson
*/
public String getModiPerson() {
return this.modiPerson;
}
/**
* set the modiPerson - 更新人
*/
public void setModiPerson(String modiPerson) {
this.modiPerson = modiPerson;
}
/**
* get the salesPersNo - 营销员
* @return the salesPersNo
*/
public String getSalesPersNo() {
return this.salesPersNo;
}
/**
* set the salesPersNo - 营销员
*/
public void setSalesPersNo(String salesPersNo) {
this.salesPersNo = salesPersNo;
}
/**
* get the printFreight - 是否打印运费(1是 0否)
* @return the printFreight
*/
public String getPrintFreight() {
return this.printFreight;
}
/**
* set the printFreight - 是否打印运费(1是 0否)
*/
public void setPrintFreight(String printFreight) {
this.printFreight = printFreight;
}
/**
* get the gljyCode - 股份关联交易对应代码
* @return the gljyCode
*/
public String getGljyCode() {
return this.gljyCode;
}
/**
* set the gljyCode - 股份关联交易对应代码
*/
public void setGljyCode(String gljyCode) {
this.gljyCode = gljyCode;
}
/**
* get the ifFeeAll - 运费全额预收标记
* @return the ifFeeAll
*/
public String getIfFeeAll() {
return this.ifFeeAll;
}
/**
* set the ifFeeAll - 运费全额预收标记
*/
public void setIfFeeAll(String ifFeeAll) {
this.ifFeeAll = ifFeeAll;
}
/**
* get the currencyId - 记账币种
* @return the currencyId
*/
public String getCurrencyId() {
return this.currencyId;
}
/**
* set the currencyId - 记账币种
*/
public void setCurrencyId(String currencyId) {
this.currencyId = currencyId;
}
/**
* get the jgCenterFlag - 加工中心标记
* @return the jgCenterFlag
*/
public String getJgCenterFlag() {
return this.jgCenterFlag;
}
/**
* set the jgCenterFlag - 加工中心标记
*/
public void setJgCenterFlag(String jgCenterFlag) {
this.jgCenterFlag = jgCenterFlag;
}
/**
* get the invoicePrintType - 发票打印类型
* @return the invoicePrintType
*/
public String getInvoicePrintType() {
return this.invoicePrintType;
}
/**
* set the invoicePrintType - 发票打印类型
*/
public void setInvoicePrintType(String invoicePrintType) {
this.invoicePrintType = invoicePrintType;
}
/**
* get the insuranceCompany - 保险公司
* @return the insuranceCompany
*/
public String getInsuranceCompany() {
return this.insuranceCompany;
}
/**
* set the insuranceCompany - 保险公司
*/
public void setInsuranceCompany(String insuranceCompany) {
this.insuranceCompany = insuranceCompany;
}
/**
* get the insuranceType - 保险类型(a包到价;b半包到价,c代收代付)
* @return the insuranceType
*/
public String getInsuranceType() {
return this.insuranceType;
}
/**
* set the insuranceType - 保险类型(a包到价;b半包到价,c代收代付)
*/
public void setInsuranceType(String insuranceType) {
this.insuranceType = insuranceType;
}
/**
* get the insuranceFlag - 保险标志("1"入成本,即价内加价保险;"0"代收代付)
* @return the insuranceFlag
*/
public String getInsuranceFlag() {
return this.insuranceFlag;
}
/**
* set the insuranceFlag - 保险标志("1"入成本,即价内加价保险;"0"代收代付)
*/
public void setInsuranceFlag(String insuranceFlag) {
this.insuranceFlag = insuranceFlag;
}
/**
* get the gfCompanyCode - 股份公司组织码
* @return the gfCompanyCode
*/
public String getGfCompanyCode() {
return this.gfCompanyCode;
}
/**
* set the gfCompanyCode - 股份公司组织码
*/
public void setGfCompanyCode(String gfCompanyCode) {
this.gfCompanyCode = gfCompanyCode;
}
/**
* get the generalTaxpayerFlag - 一般纳税人
* @return the generalTaxpayerFlag
*/
public String getGeneralTaxpayerFlag() {
return this.generalTaxpayerFlag;
}
/**
* set the generalTaxpayerFlag - 一般纳税人
*/
public void setGeneralTaxpayerFlag(String generalTaxpayerFlag) {
this.generalTaxpayerFlag = generalTaxpayerFlag;
}
/**
* get the createDate - 客户开户日期
* @return the createDate
*/
public Date getCreateDate() {
return this.createDate;
}
/**
* set the createDate - 客户开户日期
*/
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
/**
* get the qaFlag - 是否需要质保书
* @return the qaFlag
*/
public String getQaFlag() {
return this.qaFlag;
}
/**
* set the qaFlag - 是否需要质保书
*/
public void setQaFlag(String qaFlag) {
this.qaFlag = qaFlag;
}
/**
* get the p_customerId - 一体化客户代码
* @return the p_customerId
*/
public String getP_customerId() {
return this.p_customerId;
}
/**
* set the p_customerId - 一体化客户代码
*/
public void setP_customerId(String p_customerId) {
this.p_customerId = p_customerId;
}
/**
* get the emsContactPerson - EMS发票联系人
* @return the emsContactPerson
*/
public String getEmsContactPerson() {
return this.emsContactPerson;
}
/**
* set the emsContactPerson - EMS发票联系人
*/
public void setEmsContactPerson(String emsContactPerson) {
this.emsContactPerson = emsContactPerson;
}
/**
* get the ssCustomerId - 现货客户代码
* @return the ssCustomerId
*/
public String getSsCustomerId() {
return this.ssCustomerId;
}
/**
* set the ssCustomerId - 现货客户代码
*/
public void setSsCustomerId(String ssCustomerId) {
this.ssCustomerId = ssCustomerId;
}
/**
* get the ssPassword - 初始密码
* @return the ssPassword
*/
public String getSsPassword() {
return this.ssPassword;
}
/**
* set the ssPassword - 初始密码
*/
public void setSsPassword(String ssPassword) {
this.ssPassword = ssPassword;
}
/**
* get the contractCustomerId - 对应合同客户
* @return the contractCustomerId
*/
public String getContractCustomerId() {
return this.contractCustomerId;
}
/**
* set the contractCustomerId - 对应合同客户
*/
public void setContractCustomerId(String contractCustomerId) {
this.contractCustomerId = contractCustomerId;
}
/**
* get the disPlusFlag - 正数折扣单独结算
* @return the disPlusFlag
*/
public String getDisPlusFlag() {
return this.disPlusFlag;
}
/**
* set the disPlusFlag - 正数折扣单独结算
*/
public void setDisPlusFlag(String disPlusFlag) {
this.disPlusFlag = disPlusFlag;
}
/**
* get the organizationCode - 组织机构证件号
* @return the organizationCode
*/
public String getOrganizationCode() {
return this.organizationCode;
}
/**
* set the organizationCode - 组织机构证件号
*/
public void setOrganizationCode(String organizationCode) {
this.organizationCode = organizationCode;
}
/**
* get the ifMach - 加工中心标记//FOR YTH(J或空)
* @return the ifMach
*/
public String getIfMach() {
return this.ifMach;
}
/**
* set the ifMach - 加工中心标记//FOR YTH(J或空)
*/
public void setIfMach(String ifMach) {
this.ifMach = ifMach;
}
/**
* get the figContractFlag - 数字合同标记
* @return the figContractFlag
*/
public String getFigContractFlag() {
return this.figContractFlag;
}
/**
* set the figContractFlag - 数字合同标记
*/
public void setFigContractFlag(String figContractFlag) {
this.figContractFlag = figContractFlag;
}
/**
* get the companyScale - 公司规模
* @return the companyScale
*/
public String getCompanyScale() {
return this.companyScale;
}
/**
* set the companyScale - 公司规模
*/
public void setCompanyScale(String companyScale) {
this.companyScale = companyScale;
}
/**
* get the custInnerType - 客户内部分类10贸易20配送30贸易及配送
* @return the custInnerType
*/
public String getCustInnerType() {
return this.custInnerType;
}
/**
* set the custInnerType - 客户内部分类10贸易20配送30贸易及配送
*/
public void setCustInnerType(String custInnerType) {
this.custInnerType = custInnerType;
}
/**
* get the gzFlag - 行业跟踪标记
* @return the gzFlag
*/
public String getGzFlag() {
return this.gzFlag;
}
/**
* set the gzFlag - 行业跟踪标记
*/
public void setGzFlag(String gzFlag) {
this.gzFlag = gzFlag;
}
/**
* get the reportCount - 报告数
* @return the reportCount
*/
public String getReportCount() {
return this.reportCount;
}
/**
* set the reportCount - 报告数
*/
public void setReportCount(String reportCount) {
this.reportCount = reportCount;
}
/**
* get the ifFreeDiscount - 是否自由款给付利息
* @return the ifFreeDiscount
*/
public String getIfFreeDiscount() {
return this.ifFreeDiscount;
}
/**
* set the ifFreeDiscount - 是否自由款给付利息
*/
public void setIfFreeDiscount(String ifFreeDiscount) {
this.ifFreeDiscount = ifFreeDiscount;
}
/**
* get the innerSegNo - 内部往来交易对应的业务单元代码
* @return the innerSegNo
*/
public String getInnerSegNo() {
return this.innerSegNo;
}
/**
* set the innerSegNo - 内部往来交易对应的业务单元代码
*/
public void setInnerSegNo(String innerSegNo) {
this.innerSegNo = innerSegNo;
}
/**
* get the taxpayerEndDate - 纳税人终止日期
* @return the taxpayerEndDate
*/
public Date getTaxpayerEndDate() {
return this.taxpayerEndDate;
}
/**
* set the taxpayerEndDate - 纳税人终止日期
*/
public void setTaxpayerEndDate(Date taxpayerEndDate) {
this.taxpayerEndDate = taxpayerEndDate;
}
/**
* get the taxpayerStartDate - 纳税人起始日期
* @return the taxpayerStartDate
*/
public Date getTaxpayerStartDate() {
return this.taxpayerStartDate;
}
/**
* set the taxpayerStartDate - 纳税人起始日期
*/
public void setTaxpayerStartDate(Date taxpayerStartDate) {
this.taxpayerStartDate = taxpayerStartDate;
}
/**
* get the ifShow
* @return the ifShow
*/
public String getIfShow() {
return this.ifShow;
}
/**
* set the ifShow
*/
public void setIfShow(String ifShow) {
this.ifShow = ifShow;
}
public String getDeliveryAddr() {
return deliveryAddr;
}
public void setDeliveryAddr(String deliveryAddr) {
this.deliveryAddr = deliveryAddr;
}
public String getPayType() {
return payType;
}
public void setPayType(String payType) {
this.payType = payType;
}
public Double getAccountPeriod() {
return accountPeriod;
}
public void setAccountPeriod(Double accountPeriod) {
this.accountPeriod = accountPeriod;
}
public String getSignUserId() {
return signUserId;
}
public void setSignUserId(String signUserId) {
this.signUserId = signUserId;
}
// public String getUserId() {
// return userId;
// }
// public void setUserId(String userId) {
// this.userId = userId;
// }
public String getProcessRequire() {
return processRequire;
}
public void setProcessRequire(String processRequire) {
this.processRequire = processRequire;
}
/**
* get the value from Map
*/
public void fromMap(Map map) {
setCustomerId(StringUtils.defaultIfEmpty(((String)map.get("customerId")), customerId));
setCustName(StringUtils.defaultIfEmpty(((String)map.get("custName")), custName));
setSegNo(StringUtils.defaultIfEmpty(((String)map.get("segNo")), segNo));
setCustEngName(StringUtils.defaultIfEmpty(((String)map.get("custEngName")), custEngName));
setCustShortName(StringUtils.defaultIfEmpty(((String)map.get("custShortName")), custShortName));
setStatus(StringUtils.defaultIfEmpty(((String)map.get("status")), status));
setCustType(StringUtils.defaultIfEmpty(((String)map.get("custType")), custType));
setCustInvesterType(StringUtils.defaultIfEmpty(((String)map.get("custInvesterType")), custInvesterType));
setCustAssetType(StringUtils.defaultIfEmpty(((String)map.get("custAssetType")), custAssetType));
setCustStyle(StringUtils.defaultIfEmpty(((String)map.get("custStyle")), custStyle));
setVocationCode(StringUtils.defaultIfEmpty(((String)map.get("vocationCode")), vocationCode));
setPrivinceId(StringUtils.defaultIfEmpty(((String)map.get("privinceId")), privinceId));
setTownId(StringUtils.defaultIfEmpty(((String)map.get("townId")), townId));
setAreaCode(StringUtils.defaultIfEmpty(((String)map.get("areaCode")), areaCode));
setGroupFlag(StringUtils.defaultIfEmpty(((String)map.get("groupFlag")), groupFlag));
setGroupCustId(StringUtils.defaultIfEmpty(((String)map.get("groupCustId")), groupCustId));
setCreditClass(StringUtils.defaultIfEmpty(((String)map.get("creditClass")), creditClass));
setTaxNum(StringUtils.defaultIfEmpty(((String)map.get("taxNum")), taxNum));
setRegCurrencyId(StringUtils.defaultIfEmpty(((String)map.get("regCurrencyId")), regCurrencyId));
setRegFund(NumberUtils.toDouble(((String)map.get("regFund")), regFund));
setRegAddr(StringUtils.defaultIfEmpty(((String)map.get("regAddr")), regAddr));
setValidEndDate(DateUtils.toDate((String)map.get("validEndDate")));
setValidStartDate(DateUtils.toDate((String)map.get("validStartDate")));
setBankAcctNum(StringUtils.defaultIfEmpty(((String)map.get("bankAcctNum")), bankAcctNum));
setBankName(StringUtils.defaultIfEmpty(((String)map.get("bankName")), bankName));
setIvoiceAddr(StringUtils.defaultIfEmpty(((String)map.get("ivoiceAddr")), ivoiceAddr));
setInvoiceTele(StringUtils.defaultIfEmpty(((String)map.get("invoiceTele")), invoiceTele));
setInvoiceZip(StringUtils.defaultIfEmpty(((String)map.get("invoiceZip")), invoiceZip));
setInvoiceAcctNum(StringUtils.defaultIfEmpty(((String)map.get("invoiceAcctNum")), invoiceAcctNum));
setInvoiceBank(StringUtils.defaultIfEmpty(((String)map.get("invoiceBank")), invoiceBank));
setInvoicePostType(StringUtils.defaultIfEmpty(((String)map.get("invoicePostType")), invoicePostType));
setInvoiceBuildType(StringUtils.defaultIfEmpty(((String)map.get("invoiceBuildType")), invoiceBuildType));
setSettleAcctNum(StringUtils.defaultIfEmpty(((String)map.get("settleAcctNum")), settleAcctNum));
setSettleBank(StringUtils.defaultIfEmpty(((String)map.get("settleBank")), settleBank));
setArtPerson(StringUtils.defaultIfEmpty(((String)map.get("artPerson")), artPerson));
setArtPersonPre(StringUtils.defaultIfEmpty(((String)map.get("artPersonPre")), artPersonPre));
setBoss(StringUtils.defaultIfEmpty(((String)map.get("boss")), boss));
setContactPerson(StringUtils.defaultIfEmpty(((String)map.get("contactPerson")), contactPerson));
setContactAddr(StringUtils.defaultIfEmpty(((String)map.get("contactAddr")), contactAddr));
setContactTele(StringUtils.defaultIfEmpty(((String)map.get("contactTele")), contactTele));
setFaxNum(StringUtils.defaultIfEmpty(((String)map.get("faxNum")), faxNum));
setPostCode(StringUtils.defaultIfEmpty(((String)map.get("postCode")), postCode));
setEmail(StringUtils.defaultIfEmpty(((String)map.get("email")), email));
setWeb(StringUtils.defaultIfEmpty(((String)map.get("web")), web));
setTradeRemark(StringUtils.defaultIfEmpty(((String)map.get("tradeRemark")), tradeRemark));
setRemark(StringUtils.defaultIfEmpty(((String)map.get("remark")), remark));
setModiDate(DateUtils.toDate((String)map.get("modiDate")));
setModiPerson(StringUtils.defaultIfEmpty(((String)map.get("modiPerson")), modiPerson));
setSalesPersNo(StringUtils.defaultIfEmpty(((String)map.get("salesPersNo")), salesPersNo));
setPrintFreight(StringUtils.defaultIfEmpty(((String)map.get("printFreight")), printFreight));
setGljyCode(StringUtils.defaultIfEmpty(((String)map.get("gljyCode")), gljyCode));
setIfFeeAll(StringUtils.defaultIfEmpty(((String)map.get("ifFeeAll")), ifFeeAll));
setCurrencyId(StringUtils.defaultIfEmpty(((String)map.get("currencyId")), currencyId));
setJgCenterFlag(StringUtils.defaultIfEmpty(((String)map.get("jgCenterFlag")), jgCenterFlag));
setInvoicePrintType(StringUtils.defaultIfEmpty(((String)map.get("invoicePrintType")), invoicePrintType));
setInsuranceCompany(StringUtils.defaultIfEmpty(((String)map.get("insuranceCompany")), insuranceCompany));
setInsuranceType(StringUtils.defaultIfEmpty(((String)map.get("insuranceType")), insuranceType));
setInsuranceFlag(StringUtils.defaultIfEmpty(((String)map.get("insuranceFlag")), insuranceFlag));
setGfCompanyCode(StringUtils.defaultIfEmpty(((String)map.get("gfCompanyCode")), gfCompanyCode));
setGeneralTaxpayerFlag(StringUtils.defaultIfEmpty(((String)map.get("generalTaxpayerFlag")), generalTaxpayerFlag));
setCreateDate(DateUtils.toDate((String)map.get("createDate")));
setQaFlag(StringUtils.defaultIfEmpty(((String)map.get("qaFlag")), qaFlag));
setP_customerId(StringUtils.defaultIfEmpty(((String)map.get("p_customerId")), p_customerId));
setEmsContactPerson(StringUtils.defaultIfEmpty(((String)map.get("emsContactPerson")), emsContactPerson));
setSsCustomerId(StringUtils.defaultIfEmpty(((String)map.get("ssCustomerId")), ssCustomerId));
setSsPassword(StringUtils.defaultIfEmpty(((String)map.get("ssPassword")), ssPassword));
setContractCustomerId(StringUtils.defaultIfEmpty(((String)map.get("contractCustomerId")), contractCustomerId));
setDisPlusFlag(StringUtils.defaultIfEmpty(((String)map.get("disPlusFlag")), disPlusFlag));
setOrganizationCode(StringUtils.defaultIfEmpty(((String)map.get("organizationCode")), organizationCode));
setIfMach(StringUtils.defaultIfEmpty(((String)map.get("ifMach")), ifMach));
setFigContractFlag(StringUtils.defaultIfEmpty(((String)map.get("figContractFlag")), figContractFlag));
setCompanyScale(StringUtils.defaultIfEmpty(((String)map.get("companyScale")), companyScale));
setCustInnerType(StringUtils.defaultIfEmpty(((String)map.get("custInnerType")), custInnerType));
setGzFlag(StringUtils.defaultIfEmpty(((String)map.get("gzFlag")), gzFlag));
setReportCount(StringUtils.defaultIfEmpty(((String)map.get("reportCount")), reportCount));
setIfFreeDiscount(StringUtils.defaultIfEmpty(((String)map.get("ifFreeDiscount")), ifFreeDiscount));
setInnerSegNo(StringUtils.defaultIfEmpty(((String)map.get("innerSegNo")), innerSegNo));
setTaxpayerEndDate(DateUtils.toDate((String)map.get("taxpayerEndDate")));
setTaxpayerStartDate(DateUtils.toDate((String)map.get("taxpayerStartDate")));
setIfShow(StringUtils.defaultIfEmpty(((String)map.get("ifShow")), ifShow));
setMnemonic_code(StringUtils.defaultIfEmpty(((String)map.get("mnemonic_code")), mnemonic_code));
setPayType(StringUtils.defaultIfEmpty(((String)map.get("payType")), payType));
setDeliveryAddr(StringUtils.defaultIfEmpty(((String)map.get("deliveryAddr")), deliveryAddr));
// setUserId(StringUtils.defaultIfEmpty(((String)map.get("userId")), userId));
setProcessRequire(StringUtils.defaultIfEmpty(((String)map.get("processRequire")), processRequire));
setAccountPeriod(NumberUtils.toDouble(((String)map.get("accountPeriod")), accountPeriod));
setSignUserId(StringUtils.defaultIfEmpty(((String)map.get("signUserId")), signUserId));
}
/**
* set the value to Map
*/
public Map toMap() {
Map map = new HashMap();
map.put("customerId",StringUtils.toString(customerId, eiMetadata.getMeta("customerId").getFieldLength(), eiMetadata.getMeta("customerId").getScaleLength()));
map.put("custName",StringUtils.toString(custName, eiMetadata.getMeta("custName").getFieldLength(), eiMetadata.getMeta("custName").getScaleLength()));
map.put("segNo",StringUtils.toString(segNo, eiMetadata.getMeta("segNo").getFieldLength(), eiMetadata.getMeta("segNo").getScaleLength()));
map.put("custEngName",StringUtils.toString(custEngName, eiMetadata.getMeta("custEngName").getFieldLength(), eiMetadata.getMeta("custEngName").getScaleLength()));
map.put("custShortName",StringUtils.toString(custShortName, eiMetadata.getMeta("custShortName").getFieldLength(), eiMetadata.getMeta("custShortName").getScaleLength()));
map.put("status",StringUtils.toString(status, eiMetadata.getMeta("status").getFieldLength(), eiMetadata.getMeta("status").getScaleLength()));
map.put("custType",StringUtils.toString(custType, eiMetadata.getMeta("custType").getFieldLength(), eiMetadata.getMeta("custType").getScaleLength()));
map.put("custInvesterType",StringUtils.toString(custInvesterType, eiMetadata.getMeta("custInvesterType").getFieldLength(), eiMetadata.getMeta("custInvesterType").getScaleLength()));
map.put("custAssetType",StringUtils.toString(custAssetType, eiMetadata.getMeta("custAssetType").getFieldLength(), eiMetadata.getMeta("custAssetType").getScaleLength()));
map.put("custStyle",StringUtils.toString(custStyle, eiMetadata.getMeta("custStyle").getFieldLength(), eiMetadata.getMeta("custStyle").getScaleLength()));
map.put("vocationCode",StringUtils.toString(vocationCode, eiMetadata.getMeta("vocationCode").getFieldLength(), eiMetadata.getMeta("vocationCode").getScaleLength()));
map.put("privinceId",StringUtils.toString(privinceId, eiMetadata.getMeta("privinceId").getFieldLength(), eiMetadata.getMeta("privinceId").getScaleLength()));
map.put("townId",StringUtils.toString(townId, eiMetadata.getMeta("townId").getFieldLength(), eiMetadata.getMeta("townId").getScaleLength()));
map.put("areaCode",StringUtils.toString(areaCode, eiMetadata.getMeta("areaCode").getFieldLength(), eiMetadata.getMeta("areaCode").getScaleLength()));
map.put("groupFlag",StringUtils.toString(groupFlag, eiMetadata.getMeta("groupFlag").getFieldLength(), eiMetadata.getMeta("groupFlag").getScaleLength()));
map.put("groupCustId",StringUtils.toString(groupCustId, eiMetadata.getMeta("groupCustId").getFieldLength(), eiMetadata.getMeta("groupCustId").getScaleLength()));
map.put("creditClass",StringUtils.toString(creditClass, eiMetadata.getMeta("creditClass").getFieldLength(), eiMetadata.getMeta("creditClass").getScaleLength()));
map.put("taxNum",StringUtils.toString(taxNum, eiMetadata.getMeta("taxNum").getFieldLength(), eiMetadata.getMeta("taxNum").getScaleLength()));
map.put("regCurrencyId",StringUtils.toString(regCurrencyId, eiMetadata.getMeta("regCurrencyId").getFieldLength(), eiMetadata.getMeta("regCurrencyId").getScaleLength()));
map.put("regFund",StringUtils.toString(regFund, eiMetadata.getMeta("regFund").getFieldLength(), eiMetadata.getMeta("regFund").getScaleLength()));
map.put("regAddr",StringUtils.toString(regAddr, eiMetadata.getMeta("regAddr").getFieldLength(), eiMetadata.getMeta("regAddr").getScaleLength()));
map.put("validEndDate",StringUtils.toString(validEndDate, eiMetadata.getMeta("validEndDate").getFieldLength(), eiMetadata.getMeta("validEndDate").getScaleLength()));
map.put("validStartDate",StringUtils.toString(validStartDate, eiMetadata.getMeta("validStartDate").getFieldLength(), eiMetadata.getMeta("validStartDate").getScaleLength()));
map.put("bankAcctNum",StringUtils.toString(bankAcctNum, eiMetadata.getMeta("bankAcctNum").getFieldLength(), eiMetadata.getMeta("bankAcctNum").getScaleLength()));
map.put("bankName",StringUtils.toString(bankName, eiMetadata.getMeta("bankName").getFieldLength(), eiMetadata.getMeta("bankName").getScaleLength()));
map.put("ivoiceAddr",StringUtils.toString(ivoiceAddr, eiMetadata.getMeta("ivoiceAddr").getFieldLength(), eiMetadata.getMeta("ivoiceAddr").getScaleLength()));
map.put("invoiceTele",StringUtils.toString(invoiceTele, eiMetadata.getMeta("invoiceTele").getFieldLength(), eiMetadata.getMeta("invoiceTele").getScaleLength()));
map.put("invoiceZip",StringUtils.toString(invoiceZip, eiMetadata.getMeta("invoiceZip").getFieldLength(), eiMetadata.getMeta("invoiceZip").getScaleLength()));
map.put("invoiceAcctNum",StringUtils.toString(invoiceAcctNum, eiMetadata.getMeta("invoiceAcctNum").getFieldLength(), eiMetadata.getMeta("invoiceAcctNum").getScaleLength()));
map.put("invoiceBank",StringUtils.toString(invoiceBank, eiMetadata.getMeta("invoiceBank").getFieldLength(), eiMetadata.getMeta("invoiceBank").getScaleLength()));
map.put("invoicePostType",StringUtils.toString(invoicePostType, eiMetadata.getMeta("invoicePostType").getFieldLength(), eiMetadata.getMeta("invoicePostType").getScaleLength()));
map.put("invoiceBuildType",StringUtils.toString(invoiceBuildType, eiMetadata.getMeta("invoiceBuildType").getFieldLength(), eiMetadata.getMeta("invoiceBuildType").getScaleLength()));
map.put("settleAcctNum",StringUtils.toString(settleAcctNum, eiMetadata.getMeta("settleAcctNum").getFieldLength(), eiMetadata.getMeta("settleAcctNum").getScaleLength()));
map.put("settleBank",StringUtils.toString(settleBank, eiMetadata.getMeta("settleBank").getFieldLength(), eiMetadata.getMeta("settleBank").getScaleLength()));
map.put("artPerson",StringUtils.toString(artPerson, eiMetadata.getMeta("artPerson").getFieldLength(), eiMetadata.getMeta("artPerson").getScaleLength()));
map.put("artPersonPre",StringUtils.toString(artPersonPre, eiMetadata.getMeta("artPersonPre").getFieldLength(), eiMetadata.getMeta("artPersonPre").getScaleLength()));
map.put("boss",StringUtils.toString(boss, eiMetadata.getMeta("boss").getFieldLength(), eiMetadata.getMeta("boss").getScaleLength()));
map.put("contactPerson",StringUtils.toString(contactPerson, eiMetadata.getMeta("contactPerson").getFieldLength(), eiMetadata.getMeta("contactPerson").getScaleLength()));
map.put("contactAddr",StringUtils.toString(contactAddr, eiMetadata.getMeta("contactAddr").getFieldLength(), eiMetadata.getMeta("contactAddr").getScaleLength()));
map.put("contactTele",StringUtils.toString(contactTele, eiMetadata.getMeta("contactTele").getFieldLength(), eiMetadata.getMeta("contactTele").getScaleLength()));
map.put("faxNum",StringUtils.toString(faxNum, eiMetadata.getMeta("faxNum").getFieldLength(), eiMetadata.getMeta("faxNum").getScaleLength()));
map.put("postCode",StringUtils.toString(postCode, eiMetadata.getMeta("postCode").getFieldLength(), eiMetadata.getMeta("postCode").getScaleLength()));
map.put("email",StringUtils.toString(email, eiMetadata.getMeta("email").getFieldLength(), eiMetadata.getMeta("email").getScaleLength()));
map.put("web",StringUtils.toString(web, eiMetadata.getMeta("web").getFieldLength(), eiMetadata.getMeta("web").getScaleLength()));
map.put("tradeRemark",StringUtils.toString(tradeRemark, eiMetadata.getMeta("tradeRemark").getFieldLength(), eiMetadata.getMeta("tradeRemark").getScaleLength()));
map.put("remark",StringUtils.toString(remark, eiMetadata.getMeta("remark").getFieldLength(), eiMetadata.getMeta("remark").getScaleLength()));
map.put("modiDate",StringUtils.toString(modiDate, eiMetadata.getMeta("modiDate").getFieldLength(), eiMetadata.getMeta("modiDate").getScaleLength()));
map.put("modiPerson",StringUtils.toString(modiPerson, eiMetadata.getMeta("modiPerson").getFieldLength(), eiMetadata.getMeta("modiPerson").getScaleLength()));
map.put("salesPersNo",StringUtils.toString(salesPersNo, eiMetadata.getMeta("salesPersNo").getFieldLength(), eiMetadata.getMeta("salesPersNo").getScaleLength()));
map.put("printFreight",StringUtils.toString(printFreight, eiMetadata.getMeta("printFreight").getFieldLength(), eiMetadata.getMeta("printFreight").getScaleLength()));
map.put("gljyCode",StringUtils.toString(gljyCode, eiMetadata.getMeta("gljyCode").getFieldLength(), eiMetadata.getMeta("gljyCode").getScaleLength()));
map.put("ifFeeAll",StringUtils.toString(ifFeeAll, eiMetadata.getMeta("ifFeeAll").getFieldLength(), eiMetadata.getMeta("ifFeeAll").getScaleLength()));
map.put("currencyId",StringUtils.toString(currencyId, eiMetadata.getMeta("currencyId").getFieldLength(), eiMetadata.getMeta("currencyId").getScaleLength()));
map.put("jgCenterFlag",StringUtils.toString(jgCenterFlag, eiMetadata.getMeta("jgCenterFlag").getFieldLength(), eiMetadata.getMeta("jgCenterFlag").getScaleLength()));
map.put("invoicePrintType",StringUtils.toString(invoicePrintType, eiMetadata.getMeta("invoicePrintType").getFieldLength(), eiMetadata.getMeta("invoicePrintType").getScaleLength()));
map.put("insuranceCompany",StringUtils.toString(insuranceCompany, eiMetadata.getMeta("insuranceCompany").getFieldLength(), eiMetadata.getMeta("insuranceCompany").getScaleLength()));
map.put("insuranceType",StringUtils.toString(insuranceType, eiMetadata.getMeta("insuranceType").getFieldLength(), eiMetadata.getMeta("insuranceType").getScaleLength()));
map.put("insuranceFlag",StringUtils.toString(insuranceFlag, eiMetadata.getMeta("insuranceFlag").getFieldLength(), eiMetadata.getMeta("insuranceFlag").getScaleLength()));
map.put("gfCompanyCode",StringUtils.toString(gfCompanyCode, eiMetadata.getMeta("gfCompanyCode").getFieldLength(), eiMetadata.getMeta("gfCompanyCode").getScaleLength()));
map.put("generalTaxpayerFlag",StringUtils.toString(generalTaxpayerFlag, eiMetadata.getMeta("generalTaxpayerFlag").getFieldLength(), eiMetadata.getMeta("generalTaxpayerFlag").getScaleLength()));
map.put("createDate",StringUtils.toString(createDate, eiMetadata.getMeta("createDate").getFieldLength(), eiMetadata.getMeta("createDate").getScaleLength()));
map.put("qaFlag",StringUtils.toString(qaFlag, eiMetadata.getMeta("qaFlag").getFieldLength(), eiMetadata.getMeta("qaFlag").getScaleLength()));
map.put("p_customerId",StringUtils.toString(p_customerId, eiMetadata.getMeta("p_customerId").getFieldLength(), eiMetadata.getMeta("p_customerId").getScaleLength()));
map.put("emsContactPerson",StringUtils.toString(emsContactPerson, eiMetadata.getMeta("emsContactPerson").getFieldLength(), eiMetadata.getMeta("emsContactPerson").getScaleLength()));
map.put("ssCustomerId",StringUtils.toString(ssCustomerId, eiMetadata.getMeta("ssCustomerId").getFieldLength(), eiMetadata.getMeta("ssCustomerId").getScaleLength()));
map.put("ssPassword",StringUtils.toString(ssPassword, eiMetadata.getMeta("ssPassword").getFieldLength(), eiMetadata.getMeta("ssPassword").getScaleLength()));
map.put("contractCustomerId",StringUtils.toString(contractCustomerId, eiMetadata.getMeta("contractCustomerId").getFieldLength(), eiMetadata.getMeta("contractCustomerId").getScaleLength()));
map.put("disPlusFlag",StringUtils.toString(disPlusFlag, eiMetadata.getMeta("disPlusFlag").getFieldLength(), eiMetadata.getMeta("disPlusFlag").getScaleLength()));
map.put("organizationCode",StringUtils.toString(organizationCode, eiMetadata.getMeta("organizationCode").getFieldLength(), eiMetadata.getMeta("organizationCode").getScaleLength()));
map.put("ifMach",StringUtils.toString(ifMach, eiMetadata.getMeta("ifMach").getFieldLength(), eiMetadata.getMeta("ifMach").getScaleLength()));
map.put("figContractFlag",StringUtils.toString(figContractFlag, eiMetadata.getMeta("figContractFlag").getFieldLength(), eiMetadata.getMeta("figContractFlag").getScaleLength()));
map.put("companyScale",StringUtils.toString(companyScale, eiMetadata.getMeta("companyScale").getFieldLength(), eiMetadata.getMeta("companyScale").getScaleLength()));
map.put("custInnerType",StringUtils.toString(custInnerType, eiMetadata.getMeta("custInnerType").getFieldLength(), eiMetadata.getMeta("custInnerType").getScaleLength()));
map.put("gzFlag",StringUtils.toString(gzFlag, eiMetadata.getMeta("gzFlag").getFieldLength(), eiMetadata.getMeta("gzFlag").getScaleLength()));
map.put("reportCount",StringUtils.toString(reportCount, eiMetadata.getMeta("reportCount").getFieldLength(), eiMetadata.getMeta("reportCount").getScaleLength()));
map.put("ifFreeDiscount",StringUtils.toString(ifFreeDiscount, eiMetadata.getMeta("ifFreeDiscount").getFieldLength(), eiMetadata.getMeta("ifFreeDiscount").getScaleLength()));
map.put("innerSegNo",StringUtils.toString(innerSegNo, eiMetadata.getMeta("innerSegNo").getFieldLength(), eiMetadata.getMeta("innerSegNo").getScaleLength()));
map.put("taxpayerEndDate",StringUtils.toString(taxpayerEndDate, eiMetadata.getMeta("taxpayerEndDate").getFieldLength(), eiMetadata.getMeta("taxpayerEndDate").getScaleLength()));
map.put("taxpayerStartDate",StringUtils.toString(taxpayerStartDate, eiMetadata.getMeta("taxpayerStartDate").getFieldLength(), eiMetadata.getMeta("taxpayerStartDate").getScaleLength()));
map.put("ifShow",StringUtils.toString(ifShow, eiMetadata.getMeta("ifShow").getFieldLength(), eiMetadata.getMeta("ifShow").getScaleLength()));
map.put("mnemonic_code",StringUtils.toString(mnemonic_code, eiMetadata.getMeta("mnemonic_code").getFieldLength(), eiMetadata.getMeta("mnemonic_code").getScaleLength()));
map.put("payType",StringUtils.toString(payType, eiMetadata.getMeta("payType").getFieldLength(), eiMetadata.getMeta("payType").getScaleLength()));
map.put("deliveryAddr",StringUtils.toString(deliveryAddr, eiMetadata.getMeta("deliveryAddr").getFieldLength(), eiMetadata.getMeta("deliveryAddr").getScaleLength()));
//map.put("userId",StringUtils.toString(userId, eiMetadata.getMeta("userId").getFieldLength(), eiMetadata.getMeta("userId").getScaleLength()));
map.put("processRequire",StringUtils.toString(processRequire, eiMetadata.getMeta("processRequire").getFieldLength(), eiMetadata.getMeta("processRequire").getScaleLength()));
map.put("accountPeriod",StringUtils.toString(accountPeriod, eiMetadata.getMeta("accountPeriod").getFieldLength(), eiMetadata.getMeta("accountPeriod").getScaleLength()));
map.put("signUserId",StringUtils.toString(signUserId, eiMetadata.getMeta("signUserId").getFieldLength(), eiMetadata.getMeta("signUserId").getScaleLength()));
return map;
}
/**
* @return the mnemonic_code
*/
public String getMnemonic_code() {
return mnemonic_code;
}
/**
* @param mnemonic_code the mnemonic_code to set
*/
public void setMnemonic_code(String mnemonic_code) {
this.mnemonic_code = mnemonic_code;
}
} | apache-2.0 |
Stephen-Cameron-Data-Services/isis-chats | dom/src/main/java/au/com/scds/chats/dom/dex/reference/AbstractDexReferenceItem.java | 1641 | package au.com.scds.chats.dom.dex.reference;
import javax.jdo.annotations.Column;
import javax.jdo.annotations.Discriminator;
import javax.jdo.annotations.DiscriminatorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.Inheritance;
import javax.jdo.annotations.InheritanceStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;
import org.apache.isis.applib.annotation.MemberOrder;
import org.apache.isis.applib.annotation.Property;
import org.apache.isis.applib.annotation.Where;
@PersistenceCapable(identityType = IdentityType.APPLICATION, table = "DEXReferenceItem")
@Inheritance(strategy = InheritanceStrategy.NEW_TABLE)
@Discriminator(strategy = DiscriminatorStrategy.VALUE_MAP, column = "class", value = "AbstractItem")
public abstract class AbstractDexReferenceItem {
protected String name;
protected String description;
protected int orderNumber;
public String title(){
return getDescription();
}
@Property()
@MemberOrder(sequence = "1")
@Column(allowsNull = "false")
@PrimaryKey()
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Property()
@MemberOrder(sequence = "2")
@Column(allowsNull = "true")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Property(hidden = Where.EVERYWHERE)
@MemberOrder(sequence = "3")
@Column(allowsNull = "false")
public int getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(int order) {
this.orderNumber = order;
}
}
| apache-2.0 |
halfapple/InfiniteVerticalViewPager | demo/src/com/example/demo/Fragment1.java | 1380 | package com.example.demo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
* Created by Administrator on 14-10-30.
*
*/
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
initView(rootView);
return rootView;
}
private void initView(View rootView) {
LinearLayout linear = (LinearLayout)rootView.findViewById(R.id.linear1);
linear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity().getApplicationContext(), "child linear1 clicked", Toast.LENGTH_SHORT).show();
}
});
Button btn = (Button)rootView.findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity().getApplicationContext(), "button1 clicked", Toast.LENGTH_SHORT).show();
}
});
}
}
| apache-2.0 |
AlanCheen/Climb | app/src/main/java/me/yifeiyuan/climb/ui/widget/DividerItemDecoration.java | 3863 | package me.yifeiyuan.climb.ui.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by 程序亦非猿 on 16/1/20.
*
*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{
android.R.attr.listDivider
};
public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
private Drawable mDivider;
private int mOrientation;
public DividerItemDecoration(Context context, int orientation) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
setOrientation(orientation);
}
public void setOrientation(int orientation) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw new IllegalArgumentException("invalid orientation");
}
mOrientation = orientation;
}
@Override
public void onDraw(Canvas c, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}
}
public void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
public void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int left = child.getRight() + params.rightMargin;
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
}
} | apache-2.0 |
Stratio/Explorer | cassandra/src/main/java/com/stratio/explorer/cassandra/models/SHCQLOperation.java | 1584 | /**
* Copyright (C) 2015 Stratio (http://stratio.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stratio.explorer.cassandra.models;
/**
* bean with values of describe operation
*/
public class SHCQLOperation {
private String [] describe;
/**
* Constructor of shCQL command .
* @param shCQLcommand
*/
public SHCQLOperation(String shCQLcommand){
describe = shCQLcommand.split(" +");;
}
/**
* name of shCql operation .
* @return name of shCql operation
*/
public String nameOperation(){
return describe[0];
}
/**
* identifier of Describe (table,Tables,KeySpace,KeySpaces) .
* @return identifier of Describe
*/
public String identifier(){
return describe[1].replaceAll(";","").trim();
}
/**
* Recovery optional value of Describe
* @return optional Value
*/
public String optionalValue(){
String result ="";
if (describe.length>2)
result = describe[2];
return result;
}
}
| apache-2.0 |
InMobi/hadoop | src/usage/src/com/inmobi/grid/lib/MultiFileTextInputFormat.java | 3181 | package com.inmobi.grid.lib;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MultiFileTextInputFormat
extends MultiFileInputFormat<LongWritable, Text> {
@Override
public RecordReader<LongWritable,Text> getRecordReader(InputSplit split
, JobConf job, Reporter reporter) throws IOException {
return new MultiFileLineRecordReader(job, (MultiFileSplit)split);
}
/**
* RecordReader is responsible from extracting records from the InputSplit.
* This record reader accepts a {@link MultiFileSplit}, which encapsulates several
* files, and no file is divided.
*/
public static class MultiFileLineRecordReader
implements RecordReader<LongWritable, Text> {
private MultiFileSplit split;
private long offset; //total offset read so far;
private long totLength;
private FileSystem fs;
private int count = 0;
private Path[] paths;
private FSDataInputStream currentStream;
private BufferedReader currentReader;
public MultiFileLineRecordReader(Configuration conf, MultiFileSplit split)
throws IOException {
this.split = split;
fs = FileSystem.get(conf);
this.paths = split.getPaths();
this.totLength = split.getLength();
this.offset = 0;
//open the first file
Path file = paths[count];
currentStream = fs.open(file);
currentReader = new BufferedReader(new InputStreamReader(currentStream));
}
public void close() throws IOException { }
public long getPos() throws IOException {
long currentOffset = currentStream == null ? 0 : currentStream.getPos();
return offset + currentOffset;
}
public float getProgress() throws IOException {
return ((float)getPos()) / totLength;
}
public boolean next(LongWritable key, Text value) throws IOException {
if(count >= split.getNumPaths())
return false;
/* Read from file, fill in key and value, if we reach the end of file,
* then open the next file and continue from there until all files are
* consumed.
*/
String line;
do {
line = currentReader.readLine();
if(line == null) {
//close the file
currentReader.close();
offset += split.getLength(count);
if(++count >= split.getNumPaths()) //if we are done
return false;
//open a new file
Path file = paths[count];
currentStream = fs.open(file);
currentReader=new BufferedReader(new InputStreamReader(currentStream));
}
} while(line == null);
//update the key and value
key.set(0);
value.set(line);
return true;
}
public LongWritable createKey() {
return new LongWritable();
}
public Text createValue() {
return new Text();
}
}
} | apache-2.0 |
jjvargas/You2b | app/src/main/java/com/chilliwifi/you2b/searchyou2b/playlists/PlaylistItemsComponent.java | 587 | package com.chilliwifi.you2b.searchyou2b.playlists;
import com.chilliwifi.you2b.SampleModule;
import com.chilliwifi.you2b.repos.ReposAdapter;
import com.chilliwifi.you2b.searchyou2b.model.YouTubeApi;
import com.chilliwifi.you2b.videourl.VideoUrlApi;
import javax.inject.Singleton;
import dagger.Component;
@Singleton @Component(
modules = SampleModule.class)
public interface PlaylistItemsComponent {
public void inject(PlaylistItemsFragment fragment);
public PlaylistItemsRxPresenter presenter();
public PlaylistAdapter adapter();
public YouTubeApi youTubeApi();
}
| apache-2.0 |
kevelbreh/steamchat | steamchat/src/main/java/com/kevelbreh/steamchat/steam/proto/SteamMessagesBaseProto.java | 231501 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: steammessages_base.proto
package com.kevelbreh.steamchat.steam.proto;
public final class SteamMessagesBaseProto {
private SteamMessagesBaseProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registry.add(com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.msgpoolSoftLimit);
registry.add(com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.msgpoolHardLimit);
}
public interface CMsgProtoBufHeaderOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// optional fixed64 steamid = 1;
/**
* <code>optional fixed64 steamid = 1;</code>
*/
boolean hasSteamid();
/**
* <code>optional fixed64 steamid = 1;</code>
*/
long getSteamid();
// optional int32 client_sessionid = 2;
/**
* <code>optional int32 client_sessionid = 2;</code>
*/
boolean hasClientSessionid();
/**
* <code>optional int32 client_sessionid = 2;</code>
*/
int getClientSessionid();
// optional uint32 routing_appid = 3;
/**
* <code>optional uint32 routing_appid = 3;</code>
*/
boolean hasRoutingAppid();
/**
* <code>optional uint32 routing_appid = 3;</code>
*/
int getRoutingAppid();
// optional fixed64 jobid_source = 10 [default = 18446744073709551615];
/**
* <code>optional fixed64 jobid_source = 10 [default = 18446744073709551615];</code>
*/
boolean hasJobidSource();
/**
* <code>optional fixed64 jobid_source = 10 [default = 18446744073709551615];</code>
*/
long getJobidSource();
// optional fixed64 jobid_target = 11 [default = 18446744073709551615];
/**
* <code>optional fixed64 jobid_target = 11 [default = 18446744073709551615];</code>
*/
boolean hasJobidTarget();
/**
* <code>optional fixed64 jobid_target = 11 [default = 18446744073709551615];</code>
*/
long getJobidTarget();
// optional string target_job_name = 12;
/**
* <code>optional string target_job_name = 12;</code>
*/
boolean hasTargetJobName();
/**
* <code>optional string target_job_name = 12;</code>
*/
java.lang.String getTargetJobName();
/**
* <code>optional string target_job_name = 12;</code>
*/
com.google.protobuf.ByteString
getTargetJobNameBytes();
// optional int32 seq_num = 24;
/**
* <code>optional int32 seq_num = 24;</code>
*/
boolean hasSeqNum();
/**
* <code>optional int32 seq_num = 24;</code>
*/
int getSeqNum();
// optional int32 eresult = 13 [default = 2];
/**
* <code>optional int32 eresult = 13 [default = 2];</code>
*/
boolean hasEresult();
/**
* <code>optional int32 eresult = 13 [default = 2];</code>
*/
int getEresult();
// optional string error_message = 14;
/**
* <code>optional string error_message = 14;</code>
*/
boolean hasErrorMessage();
/**
* <code>optional string error_message = 14;</code>
*/
java.lang.String getErrorMessage();
/**
* <code>optional string error_message = 14;</code>
*/
com.google.protobuf.ByteString
getErrorMessageBytes();
// optional uint32 ip = 15;
/**
* <code>optional uint32 ip = 15;</code>
*/
boolean hasIp();
/**
* <code>optional uint32 ip = 15;</code>
*/
int getIp();
// optional uint32 auth_account_flags = 16;
/**
* <code>optional uint32 auth_account_flags = 16;</code>
*/
boolean hasAuthAccountFlags();
/**
* <code>optional uint32 auth_account_flags = 16;</code>
*/
int getAuthAccountFlags();
// optional uint32 token_source = 22;
/**
* <code>optional uint32 token_source = 22;</code>
*/
boolean hasTokenSource();
/**
* <code>optional uint32 token_source = 22;</code>
*/
int getTokenSource();
// optional bool admin_spoofing_user = 23;
/**
* <code>optional bool admin_spoofing_user = 23;</code>
*/
boolean hasAdminSpoofingUser();
/**
* <code>optional bool admin_spoofing_user = 23;</code>
*/
boolean getAdminSpoofingUser();
// optional int32 transport_error = 17 [default = 1];
/**
* <code>optional int32 transport_error = 17 [default = 1];</code>
*/
boolean hasTransportError();
/**
* <code>optional int32 transport_error = 17 [default = 1];</code>
*/
int getTransportError();
// optional uint64 messageid = 18 [default = 18446744073709551615];
/**
* <code>optional uint64 messageid = 18 [default = 18446744073709551615];</code>
*/
boolean hasMessageid();
/**
* <code>optional uint64 messageid = 18 [default = 18446744073709551615];</code>
*/
long getMessageid();
// optional uint32 publisher_group_id = 19;
/**
* <code>optional uint32 publisher_group_id = 19;</code>
*/
boolean hasPublisherGroupId();
/**
* <code>optional uint32 publisher_group_id = 19;</code>
*/
int getPublisherGroupId();
// optional uint32 sysid = 20;
/**
* <code>optional uint32 sysid = 20;</code>
*/
boolean hasSysid();
/**
* <code>optional uint32 sysid = 20;</code>
*/
int getSysid();
// optional uint64 trace_tag = 21;
/**
* <code>optional uint64 trace_tag = 21;</code>
*/
boolean hasTraceTag();
/**
* <code>optional uint64 trace_tag = 21;</code>
*/
long getTraceTag();
}
/**
* Protobuf type {@code CMsgProtoBufHeader}
*/
public static final class CMsgProtoBufHeader extends
com.google.protobuf.GeneratedMessage
implements CMsgProtoBufHeaderOrBuilder {
// Use CMsgProtoBufHeader.newBuilder() to construct.
private CMsgProtoBufHeader(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private CMsgProtoBufHeader(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final CMsgProtoBufHeader defaultInstance;
public static CMsgProtoBufHeader getDefaultInstance() {
return defaultInstance;
}
public CMsgProtoBufHeader getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private CMsgProtoBufHeader(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 9: {
bitField0_ |= 0x00000001;
steamid_ = input.readFixed64();
break;
}
case 16: {
bitField0_ |= 0x00000002;
clientSessionid_ = input.readInt32();
break;
}
case 24: {
bitField0_ |= 0x00000004;
routingAppid_ = input.readUInt32();
break;
}
case 81: {
bitField0_ |= 0x00000008;
jobidSource_ = input.readFixed64();
break;
}
case 89: {
bitField0_ |= 0x00000010;
jobidTarget_ = input.readFixed64();
break;
}
case 98: {
bitField0_ |= 0x00000020;
targetJobName_ = input.readBytes();
break;
}
case 104: {
bitField0_ |= 0x00000080;
eresult_ = input.readInt32();
break;
}
case 114: {
bitField0_ |= 0x00000100;
errorMessage_ = input.readBytes();
break;
}
case 120: {
bitField0_ |= 0x00000200;
ip_ = input.readUInt32();
break;
}
case 128: {
bitField0_ |= 0x00000400;
authAccountFlags_ = input.readUInt32();
break;
}
case 136: {
bitField0_ |= 0x00002000;
transportError_ = input.readInt32();
break;
}
case 144: {
bitField0_ |= 0x00004000;
messageid_ = input.readUInt64();
break;
}
case 152: {
bitField0_ |= 0x00008000;
publisherGroupId_ = input.readUInt32();
break;
}
case 160: {
bitField0_ |= 0x00010000;
sysid_ = input.readUInt32();
break;
}
case 168: {
bitField0_ |= 0x00020000;
traceTag_ = input.readUInt64();
break;
}
case 176: {
bitField0_ |= 0x00000800;
tokenSource_ = input.readUInt32();
break;
}
case 184: {
bitField0_ |= 0x00001000;
adminSpoofingUser_ = input.readBool();
break;
}
case 192: {
bitField0_ |= 0x00000040;
seqNum_ = input.readInt32();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgProtoBufHeader_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgProtoBufHeader_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader.class, com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader.Builder.class);
}
public static com.google.protobuf.Parser<CMsgProtoBufHeader> PARSER =
new com.google.protobuf.AbstractParser<CMsgProtoBufHeader>() {
public CMsgProtoBufHeader parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new CMsgProtoBufHeader(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<CMsgProtoBufHeader> getParserForType() {
return PARSER;
}
private int bitField0_;
// optional fixed64 steamid = 1;
public static final int STEAMID_FIELD_NUMBER = 1;
private long steamid_;
/**
* <code>optional fixed64 steamid = 1;</code>
*/
public boolean hasSteamid() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional fixed64 steamid = 1;</code>
*/
public long getSteamid() {
return steamid_;
}
// optional int32 client_sessionid = 2;
public static final int CLIENT_SESSIONID_FIELD_NUMBER = 2;
private int clientSessionid_;
/**
* <code>optional int32 client_sessionid = 2;</code>
*/
public boolean hasClientSessionid() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional int32 client_sessionid = 2;</code>
*/
public int getClientSessionid() {
return clientSessionid_;
}
// optional uint32 routing_appid = 3;
public static final int ROUTING_APPID_FIELD_NUMBER = 3;
private int routingAppid_;
/**
* <code>optional uint32 routing_appid = 3;</code>
*/
public boolean hasRoutingAppid() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional uint32 routing_appid = 3;</code>
*/
public int getRoutingAppid() {
return routingAppid_;
}
// optional fixed64 jobid_source = 10 [default = 18446744073709551615];
public static final int JOBID_SOURCE_FIELD_NUMBER = 10;
private long jobidSource_;
/**
* <code>optional fixed64 jobid_source = 10 [default = 18446744073709551615];</code>
*/
public boolean hasJobidSource() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional fixed64 jobid_source = 10 [default = 18446744073709551615];</code>
*/
public long getJobidSource() {
return jobidSource_;
}
// optional fixed64 jobid_target = 11 [default = 18446744073709551615];
public static final int JOBID_TARGET_FIELD_NUMBER = 11;
private long jobidTarget_;
/**
* <code>optional fixed64 jobid_target = 11 [default = 18446744073709551615];</code>
*/
public boolean hasJobidTarget() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>optional fixed64 jobid_target = 11 [default = 18446744073709551615];</code>
*/
public long getJobidTarget() {
return jobidTarget_;
}
// optional string target_job_name = 12;
public static final int TARGET_JOB_NAME_FIELD_NUMBER = 12;
private java.lang.Object targetJobName_;
/**
* <code>optional string target_job_name = 12;</code>
*/
public boolean hasTargetJobName() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>optional string target_job_name = 12;</code>
*/
public java.lang.String getTargetJobName() {
java.lang.Object ref = targetJobName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
targetJobName_ = s;
}
return s;
}
}
/**
* <code>optional string target_job_name = 12;</code>
*/
public com.google.protobuf.ByteString
getTargetJobNameBytes() {
java.lang.Object ref = targetJobName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
targetJobName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// optional int32 seq_num = 24;
public static final int SEQ_NUM_FIELD_NUMBER = 24;
private int seqNum_;
/**
* <code>optional int32 seq_num = 24;</code>
*/
public boolean hasSeqNum() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>optional int32 seq_num = 24;</code>
*/
public int getSeqNum() {
return seqNum_;
}
// optional int32 eresult = 13 [default = 2];
public static final int ERESULT_FIELD_NUMBER = 13;
private int eresult_;
/**
* <code>optional int32 eresult = 13 [default = 2];</code>
*/
public boolean hasEresult() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
/**
* <code>optional int32 eresult = 13 [default = 2];</code>
*/
public int getEresult() {
return eresult_;
}
// optional string error_message = 14;
public static final int ERROR_MESSAGE_FIELD_NUMBER = 14;
private java.lang.Object errorMessage_;
/**
* <code>optional string error_message = 14;</code>
*/
public boolean hasErrorMessage() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
/**
* <code>optional string error_message = 14;</code>
*/
public java.lang.String getErrorMessage() {
java.lang.Object ref = errorMessage_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
errorMessage_ = s;
}
return s;
}
}
/**
* <code>optional string error_message = 14;</code>
*/
public com.google.protobuf.ByteString
getErrorMessageBytes() {
java.lang.Object ref = errorMessage_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
errorMessage_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// optional uint32 ip = 15;
public static final int IP_FIELD_NUMBER = 15;
private int ip_;
/**
* <code>optional uint32 ip = 15;</code>
*/
public boolean hasIp() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
/**
* <code>optional uint32 ip = 15;</code>
*/
public int getIp() {
return ip_;
}
// optional uint32 auth_account_flags = 16;
public static final int AUTH_ACCOUNT_FLAGS_FIELD_NUMBER = 16;
private int authAccountFlags_;
/**
* <code>optional uint32 auth_account_flags = 16;</code>
*/
public boolean hasAuthAccountFlags() {
return ((bitField0_ & 0x00000400) == 0x00000400);
}
/**
* <code>optional uint32 auth_account_flags = 16;</code>
*/
public int getAuthAccountFlags() {
return authAccountFlags_;
}
// optional uint32 token_source = 22;
public static final int TOKEN_SOURCE_FIELD_NUMBER = 22;
private int tokenSource_;
/**
* <code>optional uint32 token_source = 22;</code>
*/
public boolean hasTokenSource() {
return ((bitField0_ & 0x00000800) == 0x00000800);
}
/**
* <code>optional uint32 token_source = 22;</code>
*/
public int getTokenSource() {
return tokenSource_;
}
// optional bool admin_spoofing_user = 23;
public static final int ADMIN_SPOOFING_USER_FIELD_NUMBER = 23;
private boolean adminSpoofingUser_;
/**
* <code>optional bool admin_spoofing_user = 23;</code>
*/
public boolean hasAdminSpoofingUser() {
return ((bitField0_ & 0x00001000) == 0x00001000);
}
/**
* <code>optional bool admin_spoofing_user = 23;</code>
*/
public boolean getAdminSpoofingUser() {
return adminSpoofingUser_;
}
// optional int32 transport_error = 17 [default = 1];
public static final int TRANSPORT_ERROR_FIELD_NUMBER = 17;
private int transportError_;
/**
* <code>optional int32 transport_error = 17 [default = 1];</code>
*/
public boolean hasTransportError() {
return ((bitField0_ & 0x00002000) == 0x00002000);
}
/**
* <code>optional int32 transport_error = 17 [default = 1];</code>
*/
public int getTransportError() {
return transportError_;
}
// optional uint64 messageid = 18 [default = 18446744073709551615];
public static final int MESSAGEID_FIELD_NUMBER = 18;
private long messageid_;
/**
* <code>optional uint64 messageid = 18 [default = 18446744073709551615];</code>
*/
public boolean hasMessageid() {
return ((bitField0_ & 0x00004000) == 0x00004000);
}
/**
* <code>optional uint64 messageid = 18 [default = 18446744073709551615];</code>
*/
public long getMessageid() {
return messageid_;
}
// optional uint32 publisher_group_id = 19;
public static final int PUBLISHER_GROUP_ID_FIELD_NUMBER = 19;
private int publisherGroupId_;
/**
* <code>optional uint32 publisher_group_id = 19;</code>
*/
public boolean hasPublisherGroupId() {
return ((bitField0_ & 0x00008000) == 0x00008000);
}
/**
* <code>optional uint32 publisher_group_id = 19;</code>
*/
public int getPublisherGroupId() {
return publisherGroupId_;
}
// optional uint32 sysid = 20;
public static final int SYSID_FIELD_NUMBER = 20;
private int sysid_;
/**
* <code>optional uint32 sysid = 20;</code>
*/
public boolean hasSysid() {
return ((bitField0_ & 0x00010000) == 0x00010000);
}
/**
* <code>optional uint32 sysid = 20;</code>
*/
public int getSysid() {
return sysid_;
}
// optional uint64 trace_tag = 21;
public static final int TRACE_TAG_FIELD_NUMBER = 21;
private long traceTag_;
/**
* <code>optional uint64 trace_tag = 21;</code>
*/
public boolean hasTraceTag() {
return ((bitField0_ & 0x00020000) == 0x00020000);
}
/**
* <code>optional uint64 trace_tag = 21;</code>
*/
public long getTraceTag() {
return traceTag_;
}
private void initFields() {
steamid_ = 0L;
clientSessionid_ = 0;
routingAppid_ = 0;
jobidSource_ = -1L;
jobidTarget_ = -1L;
targetJobName_ = "";
seqNum_ = 0;
eresult_ = 2;
errorMessage_ = "";
ip_ = 0;
authAccountFlags_ = 0;
tokenSource_ = 0;
adminSpoofingUser_ = false;
transportError_ = 1;
messageid_ = -1L;
publisherGroupId_ = 0;
sysid_ = 0;
traceTag_ = 0L;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeFixed64(1, steamid_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeInt32(2, clientSessionid_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeUInt32(3, routingAppid_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeFixed64(10, jobidSource_);
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
output.writeFixed64(11, jobidTarget_);
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
output.writeBytes(12, getTargetJobNameBytes());
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
output.writeInt32(13, eresult_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
output.writeBytes(14, getErrorMessageBytes());
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
output.writeUInt32(15, ip_);
}
if (((bitField0_ & 0x00000400) == 0x00000400)) {
output.writeUInt32(16, authAccountFlags_);
}
if (((bitField0_ & 0x00002000) == 0x00002000)) {
output.writeInt32(17, transportError_);
}
if (((bitField0_ & 0x00004000) == 0x00004000)) {
output.writeUInt64(18, messageid_);
}
if (((bitField0_ & 0x00008000) == 0x00008000)) {
output.writeUInt32(19, publisherGroupId_);
}
if (((bitField0_ & 0x00010000) == 0x00010000)) {
output.writeUInt32(20, sysid_);
}
if (((bitField0_ & 0x00020000) == 0x00020000)) {
output.writeUInt64(21, traceTag_);
}
if (((bitField0_ & 0x00000800) == 0x00000800)) {
output.writeUInt32(22, tokenSource_);
}
if (((bitField0_ & 0x00001000) == 0x00001000)) {
output.writeBool(23, adminSpoofingUser_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
output.writeInt32(24, seqNum_);
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeFixed64Size(1, steamid_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(2, clientSessionid_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(3, routingAppid_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
size += com.google.protobuf.CodedOutputStream
.computeFixed64Size(10, jobidSource_);
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
size += com.google.protobuf.CodedOutputStream
.computeFixed64Size(11, jobidTarget_);
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(12, getTargetJobNameBytes());
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(13, eresult_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(14, getErrorMessageBytes());
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(15, ip_);
}
if (((bitField0_ & 0x00000400) == 0x00000400)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(16, authAccountFlags_);
}
if (((bitField0_ & 0x00002000) == 0x00002000)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(17, transportError_);
}
if (((bitField0_ & 0x00004000) == 0x00004000)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt64Size(18, messageid_);
}
if (((bitField0_ & 0x00008000) == 0x00008000)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(19, publisherGroupId_);
}
if (((bitField0_ & 0x00010000) == 0x00010000)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(20, sysid_);
}
if (((bitField0_ & 0x00020000) == 0x00020000)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt64Size(21, traceTag_);
}
if (((bitField0_ & 0x00000800) == 0x00000800)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(22, tokenSource_);
}
if (((bitField0_ & 0x00001000) == 0x00001000)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(23, adminSpoofingUser_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(24, seqNum_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code CMsgProtoBufHeader}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeaderOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgProtoBufHeader_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgProtoBufHeader_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader.class, com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader.Builder.class);
}
// Construct using com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
steamid_ = 0L;
bitField0_ = (bitField0_ & ~0x00000001);
clientSessionid_ = 0;
bitField0_ = (bitField0_ & ~0x00000002);
routingAppid_ = 0;
bitField0_ = (bitField0_ & ~0x00000004);
jobidSource_ = -1L;
bitField0_ = (bitField0_ & ~0x00000008);
jobidTarget_ = -1L;
bitField0_ = (bitField0_ & ~0x00000010);
targetJobName_ = "";
bitField0_ = (bitField0_ & ~0x00000020);
seqNum_ = 0;
bitField0_ = (bitField0_ & ~0x00000040);
eresult_ = 2;
bitField0_ = (bitField0_ & ~0x00000080);
errorMessage_ = "";
bitField0_ = (bitField0_ & ~0x00000100);
ip_ = 0;
bitField0_ = (bitField0_ & ~0x00000200);
authAccountFlags_ = 0;
bitField0_ = (bitField0_ & ~0x00000400);
tokenSource_ = 0;
bitField0_ = (bitField0_ & ~0x00000800);
adminSpoofingUser_ = false;
bitField0_ = (bitField0_ & ~0x00001000);
transportError_ = 1;
bitField0_ = (bitField0_ & ~0x00002000);
messageid_ = -1L;
bitField0_ = (bitField0_ & ~0x00004000);
publisherGroupId_ = 0;
bitField0_ = (bitField0_ & ~0x00008000);
sysid_ = 0;
bitField0_ = (bitField0_ & ~0x00010000);
traceTag_ = 0L;
bitField0_ = (bitField0_ & ~0x00020000);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgProtoBufHeader_descriptor;
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader getDefaultInstanceForType() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader.getDefaultInstance();
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader build() {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader buildPartial() {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader result = new com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.steamid_ = steamid_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.clientSessionid_ = clientSessionid_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.routingAppid_ = routingAppid_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
result.jobidSource_ = jobidSource_;
if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
to_bitField0_ |= 0x00000010;
}
result.jobidTarget_ = jobidTarget_;
if (((from_bitField0_ & 0x00000020) == 0x00000020)) {
to_bitField0_ |= 0x00000020;
}
result.targetJobName_ = targetJobName_;
if (((from_bitField0_ & 0x00000040) == 0x00000040)) {
to_bitField0_ |= 0x00000040;
}
result.seqNum_ = seqNum_;
if (((from_bitField0_ & 0x00000080) == 0x00000080)) {
to_bitField0_ |= 0x00000080;
}
result.eresult_ = eresult_;
if (((from_bitField0_ & 0x00000100) == 0x00000100)) {
to_bitField0_ |= 0x00000100;
}
result.errorMessage_ = errorMessage_;
if (((from_bitField0_ & 0x00000200) == 0x00000200)) {
to_bitField0_ |= 0x00000200;
}
result.ip_ = ip_;
if (((from_bitField0_ & 0x00000400) == 0x00000400)) {
to_bitField0_ |= 0x00000400;
}
result.authAccountFlags_ = authAccountFlags_;
if (((from_bitField0_ & 0x00000800) == 0x00000800)) {
to_bitField0_ |= 0x00000800;
}
result.tokenSource_ = tokenSource_;
if (((from_bitField0_ & 0x00001000) == 0x00001000)) {
to_bitField0_ |= 0x00001000;
}
result.adminSpoofingUser_ = adminSpoofingUser_;
if (((from_bitField0_ & 0x00002000) == 0x00002000)) {
to_bitField0_ |= 0x00002000;
}
result.transportError_ = transportError_;
if (((from_bitField0_ & 0x00004000) == 0x00004000)) {
to_bitField0_ |= 0x00004000;
}
result.messageid_ = messageid_;
if (((from_bitField0_ & 0x00008000) == 0x00008000)) {
to_bitField0_ |= 0x00008000;
}
result.publisherGroupId_ = publisherGroupId_;
if (((from_bitField0_ & 0x00010000) == 0x00010000)) {
to_bitField0_ |= 0x00010000;
}
result.sysid_ = sysid_;
if (((from_bitField0_ & 0x00020000) == 0x00020000)) {
to_bitField0_ |= 0x00020000;
}
result.traceTag_ = traceTag_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader) {
return mergeFrom((com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader other) {
if (other == com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader.getDefaultInstance()) return this;
if (other.hasSteamid()) {
setSteamid(other.getSteamid());
}
if (other.hasClientSessionid()) {
setClientSessionid(other.getClientSessionid());
}
if (other.hasRoutingAppid()) {
setRoutingAppid(other.getRoutingAppid());
}
if (other.hasJobidSource()) {
setJobidSource(other.getJobidSource());
}
if (other.hasJobidTarget()) {
setJobidTarget(other.getJobidTarget());
}
if (other.hasTargetJobName()) {
bitField0_ |= 0x00000020;
targetJobName_ = other.targetJobName_;
onChanged();
}
if (other.hasSeqNum()) {
setSeqNum(other.getSeqNum());
}
if (other.hasEresult()) {
setEresult(other.getEresult());
}
if (other.hasErrorMessage()) {
bitField0_ |= 0x00000100;
errorMessage_ = other.errorMessage_;
onChanged();
}
if (other.hasIp()) {
setIp(other.getIp());
}
if (other.hasAuthAccountFlags()) {
setAuthAccountFlags(other.getAuthAccountFlags());
}
if (other.hasTokenSource()) {
setTokenSource(other.getTokenSource());
}
if (other.hasAdminSpoofingUser()) {
setAdminSpoofingUser(other.getAdminSpoofingUser());
}
if (other.hasTransportError()) {
setTransportError(other.getTransportError());
}
if (other.hasMessageid()) {
setMessageid(other.getMessageid());
}
if (other.hasPublisherGroupId()) {
setPublisherGroupId(other.getPublisherGroupId());
}
if (other.hasSysid()) {
setSysid(other.getSysid());
}
if (other.hasTraceTag()) {
setTraceTag(other.getTraceTag());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtoBufHeader) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
// optional fixed64 steamid = 1;
private long steamid_ ;
/**
* <code>optional fixed64 steamid = 1;</code>
*/
public boolean hasSteamid() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional fixed64 steamid = 1;</code>
*/
public long getSteamid() {
return steamid_;
}
/**
* <code>optional fixed64 steamid = 1;</code>
*/
public Builder setSteamid(long value) {
bitField0_ |= 0x00000001;
steamid_ = value;
onChanged();
return this;
}
/**
* <code>optional fixed64 steamid = 1;</code>
*/
public Builder clearSteamid() {
bitField0_ = (bitField0_ & ~0x00000001);
steamid_ = 0L;
onChanged();
return this;
}
// optional int32 client_sessionid = 2;
private int clientSessionid_ ;
/**
* <code>optional int32 client_sessionid = 2;</code>
*/
public boolean hasClientSessionid() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional int32 client_sessionid = 2;</code>
*/
public int getClientSessionid() {
return clientSessionid_;
}
/**
* <code>optional int32 client_sessionid = 2;</code>
*/
public Builder setClientSessionid(int value) {
bitField0_ |= 0x00000002;
clientSessionid_ = value;
onChanged();
return this;
}
/**
* <code>optional int32 client_sessionid = 2;</code>
*/
public Builder clearClientSessionid() {
bitField0_ = (bitField0_ & ~0x00000002);
clientSessionid_ = 0;
onChanged();
return this;
}
// optional uint32 routing_appid = 3;
private int routingAppid_ ;
/**
* <code>optional uint32 routing_appid = 3;</code>
*/
public boolean hasRoutingAppid() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional uint32 routing_appid = 3;</code>
*/
public int getRoutingAppid() {
return routingAppid_;
}
/**
* <code>optional uint32 routing_appid = 3;</code>
*/
public Builder setRoutingAppid(int value) {
bitField0_ |= 0x00000004;
routingAppid_ = value;
onChanged();
return this;
}
/**
* <code>optional uint32 routing_appid = 3;</code>
*/
public Builder clearRoutingAppid() {
bitField0_ = (bitField0_ & ~0x00000004);
routingAppid_ = 0;
onChanged();
return this;
}
// optional fixed64 jobid_source = 10 [default = 18446744073709551615];
private long jobidSource_ = -1L;
/**
* <code>optional fixed64 jobid_source = 10 [default = 18446744073709551615];</code>
*/
public boolean hasJobidSource() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional fixed64 jobid_source = 10 [default = 18446744073709551615];</code>
*/
public long getJobidSource() {
return jobidSource_;
}
/**
* <code>optional fixed64 jobid_source = 10 [default = 18446744073709551615];</code>
*/
public Builder setJobidSource(long value) {
bitField0_ |= 0x00000008;
jobidSource_ = value;
onChanged();
return this;
}
/**
* <code>optional fixed64 jobid_source = 10 [default = 18446744073709551615];</code>
*/
public Builder clearJobidSource() {
bitField0_ = (bitField0_ & ~0x00000008);
jobidSource_ = -1L;
onChanged();
return this;
}
// optional fixed64 jobid_target = 11 [default = 18446744073709551615];
private long jobidTarget_ = -1L;
/**
* <code>optional fixed64 jobid_target = 11 [default = 18446744073709551615];</code>
*/
public boolean hasJobidTarget() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>optional fixed64 jobid_target = 11 [default = 18446744073709551615];</code>
*/
public long getJobidTarget() {
return jobidTarget_;
}
/**
* <code>optional fixed64 jobid_target = 11 [default = 18446744073709551615];</code>
*/
public Builder setJobidTarget(long value) {
bitField0_ |= 0x00000010;
jobidTarget_ = value;
onChanged();
return this;
}
/**
* <code>optional fixed64 jobid_target = 11 [default = 18446744073709551615];</code>
*/
public Builder clearJobidTarget() {
bitField0_ = (bitField0_ & ~0x00000010);
jobidTarget_ = -1L;
onChanged();
return this;
}
// optional string target_job_name = 12;
private java.lang.Object targetJobName_ = "";
/**
* <code>optional string target_job_name = 12;</code>
*/
public boolean hasTargetJobName() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>optional string target_job_name = 12;</code>
*/
public java.lang.String getTargetJobName() {
java.lang.Object ref = targetJobName_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref)
.toStringUtf8();
targetJobName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string target_job_name = 12;</code>
*/
public com.google.protobuf.ByteString
getTargetJobNameBytes() {
java.lang.Object ref = targetJobName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
targetJobName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string target_job_name = 12;</code>
*/
public Builder setTargetJobName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000020;
targetJobName_ = value;
onChanged();
return this;
}
/**
* <code>optional string target_job_name = 12;</code>
*/
public Builder clearTargetJobName() {
bitField0_ = (bitField0_ & ~0x00000020);
targetJobName_ = getDefaultInstance().getTargetJobName();
onChanged();
return this;
}
/**
* <code>optional string target_job_name = 12;</code>
*/
public Builder setTargetJobNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000020;
targetJobName_ = value;
onChanged();
return this;
}
// optional int32 seq_num = 24;
private int seqNum_ ;
/**
* <code>optional int32 seq_num = 24;</code>
*/
public boolean hasSeqNum() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>optional int32 seq_num = 24;</code>
*/
public int getSeqNum() {
return seqNum_;
}
/**
* <code>optional int32 seq_num = 24;</code>
*/
public Builder setSeqNum(int value) {
bitField0_ |= 0x00000040;
seqNum_ = value;
onChanged();
return this;
}
/**
* <code>optional int32 seq_num = 24;</code>
*/
public Builder clearSeqNum() {
bitField0_ = (bitField0_ & ~0x00000040);
seqNum_ = 0;
onChanged();
return this;
}
// optional int32 eresult = 13 [default = 2];
private int eresult_ = 2;
/**
* <code>optional int32 eresult = 13 [default = 2];</code>
*/
public boolean hasEresult() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
/**
* <code>optional int32 eresult = 13 [default = 2];</code>
*/
public int getEresult() {
return eresult_;
}
/**
* <code>optional int32 eresult = 13 [default = 2];</code>
*/
public Builder setEresult(int value) {
bitField0_ |= 0x00000080;
eresult_ = value;
onChanged();
return this;
}
/**
* <code>optional int32 eresult = 13 [default = 2];</code>
*/
public Builder clearEresult() {
bitField0_ = (bitField0_ & ~0x00000080);
eresult_ = 2;
onChanged();
return this;
}
// optional string error_message = 14;
private java.lang.Object errorMessage_ = "";
/**
* <code>optional string error_message = 14;</code>
*/
public boolean hasErrorMessage() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
/**
* <code>optional string error_message = 14;</code>
*/
public java.lang.String getErrorMessage() {
java.lang.Object ref = errorMessage_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref)
.toStringUtf8();
errorMessage_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string error_message = 14;</code>
*/
public com.google.protobuf.ByteString
getErrorMessageBytes() {
java.lang.Object ref = errorMessage_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
errorMessage_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string error_message = 14;</code>
*/
public Builder setErrorMessage(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000100;
errorMessage_ = value;
onChanged();
return this;
}
/**
* <code>optional string error_message = 14;</code>
*/
public Builder clearErrorMessage() {
bitField0_ = (bitField0_ & ~0x00000100);
errorMessage_ = getDefaultInstance().getErrorMessage();
onChanged();
return this;
}
/**
* <code>optional string error_message = 14;</code>
*/
public Builder setErrorMessageBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000100;
errorMessage_ = value;
onChanged();
return this;
}
// optional uint32 ip = 15;
private int ip_ ;
/**
* <code>optional uint32 ip = 15;</code>
*/
public boolean hasIp() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
/**
* <code>optional uint32 ip = 15;</code>
*/
public int getIp() {
return ip_;
}
/**
* <code>optional uint32 ip = 15;</code>
*/
public Builder setIp(int value) {
bitField0_ |= 0x00000200;
ip_ = value;
onChanged();
return this;
}
/**
* <code>optional uint32 ip = 15;</code>
*/
public Builder clearIp() {
bitField0_ = (bitField0_ & ~0x00000200);
ip_ = 0;
onChanged();
return this;
}
// optional uint32 auth_account_flags = 16;
private int authAccountFlags_ ;
/**
* <code>optional uint32 auth_account_flags = 16;</code>
*/
public boolean hasAuthAccountFlags() {
return ((bitField0_ & 0x00000400) == 0x00000400);
}
/**
* <code>optional uint32 auth_account_flags = 16;</code>
*/
public int getAuthAccountFlags() {
return authAccountFlags_;
}
/**
* <code>optional uint32 auth_account_flags = 16;</code>
*/
public Builder setAuthAccountFlags(int value) {
bitField0_ |= 0x00000400;
authAccountFlags_ = value;
onChanged();
return this;
}
/**
* <code>optional uint32 auth_account_flags = 16;</code>
*/
public Builder clearAuthAccountFlags() {
bitField0_ = (bitField0_ & ~0x00000400);
authAccountFlags_ = 0;
onChanged();
return this;
}
// optional uint32 token_source = 22;
private int tokenSource_ ;
/**
* <code>optional uint32 token_source = 22;</code>
*/
public boolean hasTokenSource() {
return ((bitField0_ & 0x00000800) == 0x00000800);
}
/**
* <code>optional uint32 token_source = 22;</code>
*/
public int getTokenSource() {
return tokenSource_;
}
/**
* <code>optional uint32 token_source = 22;</code>
*/
public Builder setTokenSource(int value) {
bitField0_ |= 0x00000800;
tokenSource_ = value;
onChanged();
return this;
}
/**
* <code>optional uint32 token_source = 22;</code>
*/
public Builder clearTokenSource() {
bitField0_ = (bitField0_ & ~0x00000800);
tokenSource_ = 0;
onChanged();
return this;
}
// optional bool admin_spoofing_user = 23;
private boolean adminSpoofingUser_ ;
/**
* <code>optional bool admin_spoofing_user = 23;</code>
*/
public boolean hasAdminSpoofingUser() {
return ((bitField0_ & 0x00001000) == 0x00001000);
}
/**
* <code>optional bool admin_spoofing_user = 23;</code>
*/
public boolean getAdminSpoofingUser() {
return adminSpoofingUser_;
}
/**
* <code>optional bool admin_spoofing_user = 23;</code>
*/
public Builder setAdminSpoofingUser(boolean value) {
bitField0_ |= 0x00001000;
adminSpoofingUser_ = value;
onChanged();
return this;
}
/**
* <code>optional bool admin_spoofing_user = 23;</code>
*/
public Builder clearAdminSpoofingUser() {
bitField0_ = (bitField0_ & ~0x00001000);
adminSpoofingUser_ = false;
onChanged();
return this;
}
// optional int32 transport_error = 17 [default = 1];
private int transportError_ = 1;
/**
* <code>optional int32 transport_error = 17 [default = 1];</code>
*/
public boolean hasTransportError() {
return ((bitField0_ & 0x00002000) == 0x00002000);
}
/**
* <code>optional int32 transport_error = 17 [default = 1];</code>
*/
public int getTransportError() {
return transportError_;
}
/**
* <code>optional int32 transport_error = 17 [default = 1];</code>
*/
public Builder setTransportError(int value) {
bitField0_ |= 0x00002000;
transportError_ = value;
onChanged();
return this;
}
/**
* <code>optional int32 transport_error = 17 [default = 1];</code>
*/
public Builder clearTransportError() {
bitField0_ = (bitField0_ & ~0x00002000);
transportError_ = 1;
onChanged();
return this;
}
// optional uint64 messageid = 18 [default = 18446744073709551615];
private long messageid_ = -1L;
/**
* <code>optional uint64 messageid = 18 [default = 18446744073709551615];</code>
*/
public boolean hasMessageid() {
return ((bitField0_ & 0x00004000) == 0x00004000);
}
/**
* <code>optional uint64 messageid = 18 [default = 18446744073709551615];</code>
*/
public long getMessageid() {
return messageid_;
}
/**
* <code>optional uint64 messageid = 18 [default = 18446744073709551615];</code>
*/
public Builder setMessageid(long value) {
bitField0_ |= 0x00004000;
messageid_ = value;
onChanged();
return this;
}
/**
* <code>optional uint64 messageid = 18 [default = 18446744073709551615];</code>
*/
public Builder clearMessageid() {
bitField0_ = (bitField0_ & ~0x00004000);
messageid_ = -1L;
onChanged();
return this;
}
// optional uint32 publisher_group_id = 19;
private int publisherGroupId_ ;
/**
* <code>optional uint32 publisher_group_id = 19;</code>
*/
public boolean hasPublisherGroupId() {
return ((bitField0_ & 0x00008000) == 0x00008000);
}
/**
* <code>optional uint32 publisher_group_id = 19;</code>
*/
public int getPublisherGroupId() {
return publisherGroupId_;
}
/**
* <code>optional uint32 publisher_group_id = 19;</code>
*/
public Builder setPublisherGroupId(int value) {
bitField0_ |= 0x00008000;
publisherGroupId_ = value;
onChanged();
return this;
}
/**
* <code>optional uint32 publisher_group_id = 19;</code>
*/
public Builder clearPublisherGroupId() {
bitField0_ = (bitField0_ & ~0x00008000);
publisherGroupId_ = 0;
onChanged();
return this;
}
// optional uint32 sysid = 20;
private int sysid_ ;
/**
* <code>optional uint32 sysid = 20;</code>
*/
public boolean hasSysid() {
return ((bitField0_ & 0x00010000) == 0x00010000);
}
/**
* <code>optional uint32 sysid = 20;</code>
*/
public int getSysid() {
return sysid_;
}
/**
* <code>optional uint32 sysid = 20;</code>
*/
public Builder setSysid(int value) {
bitField0_ |= 0x00010000;
sysid_ = value;
onChanged();
return this;
}
/**
* <code>optional uint32 sysid = 20;</code>
*/
public Builder clearSysid() {
bitField0_ = (bitField0_ & ~0x00010000);
sysid_ = 0;
onChanged();
return this;
}
// optional uint64 trace_tag = 21;
private long traceTag_ ;
/**
* <code>optional uint64 trace_tag = 21;</code>
*/
public boolean hasTraceTag() {
return ((bitField0_ & 0x00020000) == 0x00020000);
}
/**
* <code>optional uint64 trace_tag = 21;</code>
*/
public long getTraceTag() {
return traceTag_;
}
/**
* <code>optional uint64 trace_tag = 21;</code>
*/
public Builder setTraceTag(long value) {
bitField0_ |= 0x00020000;
traceTag_ = value;
onChanged();
return this;
}
/**
* <code>optional uint64 trace_tag = 21;</code>
*/
public Builder clearTraceTag() {
bitField0_ = (bitField0_ & ~0x00020000);
traceTag_ = 0L;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:CMsgProtoBufHeader)
}
static {
defaultInstance = new CMsgProtoBufHeader(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:CMsgProtoBufHeader)
}
public interface CMsgMultiOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// optional uint32 size_unzipped = 1;
/**
* <code>optional uint32 size_unzipped = 1;</code>
*/
boolean hasSizeUnzipped();
/**
* <code>optional uint32 size_unzipped = 1;</code>
*/
int getSizeUnzipped();
// optional bytes message_body = 2;
/**
* <code>optional bytes message_body = 2;</code>
*/
boolean hasMessageBody();
/**
* <code>optional bytes message_body = 2;</code>
*/
com.google.protobuf.ByteString getMessageBody();
}
/**
* Protobuf type {@code CMsgMulti}
*/
public static final class CMsgMulti extends
com.google.protobuf.GeneratedMessage
implements CMsgMultiOrBuilder {
// Use CMsgMulti.newBuilder() to construct.
private CMsgMulti(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private CMsgMulti(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final CMsgMulti defaultInstance;
public static CMsgMulti getDefaultInstance() {
return defaultInstance;
}
public CMsgMulti getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private CMsgMulti(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
bitField0_ |= 0x00000001;
sizeUnzipped_ = input.readUInt32();
break;
}
case 18: {
bitField0_ |= 0x00000002;
messageBody_ = input.readBytes();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgMulti_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgMulti_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti.class, com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti.Builder.class);
}
public static com.google.protobuf.Parser<CMsgMulti> PARSER =
new com.google.protobuf.AbstractParser<CMsgMulti>() {
public CMsgMulti parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new CMsgMulti(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<CMsgMulti> getParserForType() {
return PARSER;
}
private int bitField0_;
// optional uint32 size_unzipped = 1;
public static final int SIZE_UNZIPPED_FIELD_NUMBER = 1;
private int sizeUnzipped_;
/**
* <code>optional uint32 size_unzipped = 1;</code>
*/
public boolean hasSizeUnzipped() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional uint32 size_unzipped = 1;</code>
*/
public int getSizeUnzipped() {
return sizeUnzipped_;
}
// optional bytes message_body = 2;
public static final int MESSAGE_BODY_FIELD_NUMBER = 2;
private com.google.protobuf.ByteString messageBody_;
/**
* <code>optional bytes message_body = 2;</code>
*/
public boolean hasMessageBody() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional bytes message_body = 2;</code>
*/
public com.google.protobuf.ByteString getMessageBody() {
return messageBody_;
}
private void initFields() {
sizeUnzipped_ = 0;
messageBody_ = com.google.protobuf.ByteString.EMPTY;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeUInt32(1, sizeUnzipped_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, messageBody_);
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(1, sizeUnzipped_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, messageBody_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code CMsgMulti}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMultiOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgMulti_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgMulti_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti.class, com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti.Builder.class);
}
// Construct using com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
sizeUnzipped_ = 0;
bitField0_ = (bitField0_ & ~0x00000001);
messageBody_ = com.google.protobuf.ByteString.EMPTY;
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgMulti_descriptor;
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti getDefaultInstanceForType() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti.getDefaultInstance();
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti build() {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti buildPartial() {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti result = new com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.sizeUnzipped_ = sizeUnzipped_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.messageBody_ = messageBody_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti) {
return mergeFrom((com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti other) {
if (other == com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti.getDefaultInstance()) return this;
if (other.hasSizeUnzipped()) {
setSizeUnzipped(other.getSizeUnzipped());
}
if (other.hasMessageBody()) {
setMessageBody(other.getMessageBody());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgMulti) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
// optional uint32 size_unzipped = 1;
private int sizeUnzipped_ ;
/**
* <code>optional uint32 size_unzipped = 1;</code>
*/
public boolean hasSizeUnzipped() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional uint32 size_unzipped = 1;</code>
*/
public int getSizeUnzipped() {
return sizeUnzipped_;
}
/**
* <code>optional uint32 size_unzipped = 1;</code>
*/
public Builder setSizeUnzipped(int value) {
bitField0_ |= 0x00000001;
sizeUnzipped_ = value;
onChanged();
return this;
}
/**
* <code>optional uint32 size_unzipped = 1;</code>
*/
public Builder clearSizeUnzipped() {
bitField0_ = (bitField0_ & ~0x00000001);
sizeUnzipped_ = 0;
onChanged();
return this;
}
// optional bytes message_body = 2;
private com.google.protobuf.ByteString messageBody_ = com.google.protobuf.ByteString.EMPTY;
/**
* <code>optional bytes message_body = 2;</code>
*/
public boolean hasMessageBody() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional bytes message_body = 2;</code>
*/
public com.google.protobuf.ByteString getMessageBody() {
return messageBody_;
}
/**
* <code>optional bytes message_body = 2;</code>
*/
public Builder setMessageBody(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
messageBody_ = value;
onChanged();
return this;
}
/**
* <code>optional bytes message_body = 2;</code>
*/
public Builder clearMessageBody() {
bitField0_ = (bitField0_ & ~0x00000002);
messageBody_ = getDefaultInstance().getMessageBody();
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:CMsgMulti)
}
static {
defaultInstance = new CMsgMulti(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:CMsgMulti)
}
public interface CMsgProtobufWrappedOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// optional bytes message_body = 1;
/**
* <code>optional bytes message_body = 1;</code>
*/
boolean hasMessageBody();
/**
* <code>optional bytes message_body = 1;</code>
*/
com.google.protobuf.ByteString getMessageBody();
}
/**
* Protobuf type {@code CMsgProtobufWrapped}
*/
public static final class CMsgProtobufWrapped extends
com.google.protobuf.GeneratedMessage
implements CMsgProtobufWrappedOrBuilder {
// Use CMsgProtobufWrapped.newBuilder() to construct.
private CMsgProtobufWrapped(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private CMsgProtobufWrapped(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final CMsgProtobufWrapped defaultInstance;
public static CMsgProtobufWrapped getDefaultInstance() {
return defaultInstance;
}
public CMsgProtobufWrapped getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private CMsgProtobufWrapped(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
bitField0_ |= 0x00000001;
messageBody_ = input.readBytes();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgProtobufWrapped_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgProtobufWrapped_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped.class, com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped.Builder.class);
}
public static com.google.protobuf.Parser<CMsgProtobufWrapped> PARSER =
new com.google.protobuf.AbstractParser<CMsgProtobufWrapped>() {
public CMsgProtobufWrapped parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new CMsgProtobufWrapped(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<CMsgProtobufWrapped> getParserForType() {
return PARSER;
}
private int bitField0_;
// optional bytes message_body = 1;
public static final int MESSAGE_BODY_FIELD_NUMBER = 1;
private com.google.protobuf.ByteString messageBody_;
/**
* <code>optional bytes message_body = 1;</code>
*/
public boolean hasMessageBody() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional bytes message_body = 1;</code>
*/
public com.google.protobuf.ByteString getMessageBody() {
return messageBody_;
}
private void initFields() {
messageBody_ = com.google.protobuf.ByteString.EMPTY;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, messageBody_);
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(1, messageBody_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code CMsgProtobufWrapped}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrappedOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgProtobufWrapped_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgProtobufWrapped_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped.class, com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped.Builder.class);
}
// Construct using com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
messageBody_ = com.google.protobuf.ByteString.EMPTY;
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgProtobufWrapped_descriptor;
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped getDefaultInstanceForType() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped.getDefaultInstance();
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped build() {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped buildPartial() {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped result = new com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.messageBody_ = messageBody_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped) {
return mergeFrom((com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped other) {
if (other == com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped.getDefaultInstance()) return this;
if (other.hasMessageBody()) {
setMessageBody(other.getMessageBody());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgProtobufWrapped) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
// optional bytes message_body = 1;
private com.google.protobuf.ByteString messageBody_ = com.google.protobuf.ByteString.EMPTY;
/**
* <code>optional bytes message_body = 1;</code>
*/
public boolean hasMessageBody() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional bytes message_body = 1;</code>
*/
public com.google.protobuf.ByteString getMessageBody() {
return messageBody_;
}
/**
* <code>optional bytes message_body = 1;</code>
*/
public Builder setMessageBody(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
messageBody_ = value;
onChanged();
return this;
}
/**
* <code>optional bytes message_body = 1;</code>
*/
public Builder clearMessageBody() {
bitField0_ = (bitField0_ & ~0x00000001);
messageBody_ = getDefaultInstance().getMessageBody();
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:CMsgProtobufWrapped)
}
static {
defaultInstance = new CMsgProtobufWrapped(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:CMsgProtobufWrapped)
}
public interface CMsgAuthTicketOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// optional uint32 estate = 1;
/**
* <code>optional uint32 estate = 1;</code>
*/
boolean hasEstate();
/**
* <code>optional uint32 estate = 1;</code>
*/
int getEstate();
// optional uint32 eresult = 2 [default = 2];
/**
* <code>optional uint32 eresult = 2 [default = 2];</code>
*/
boolean hasEresult();
/**
* <code>optional uint32 eresult = 2 [default = 2];</code>
*/
int getEresult();
// optional fixed64 steamid = 3;
/**
* <code>optional fixed64 steamid = 3;</code>
*/
boolean hasSteamid();
/**
* <code>optional fixed64 steamid = 3;</code>
*/
long getSteamid();
// optional fixed64 gameid = 4;
/**
* <code>optional fixed64 gameid = 4;</code>
*/
boolean hasGameid();
/**
* <code>optional fixed64 gameid = 4;</code>
*/
long getGameid();
// optional uint32 h_steam_pipe = 5;
/**
* <code>optional uint32 h_steam_pipe = 5;</code>
*/
boolean hasHSteamPipe();
/**
* <code>optional uint32 h_steam_pipe = 5;</code>
*/
int getHSteamPipe();
// optional uint32 ticket_crc = 6;
/**
* <code>optional uint32 ticket_crc = 6;</code>
*/
boolean hasTicketCrc();
/**
* <code>optional uint32 ticket_crc = 6;</code>
*/
int getTicketCrc();
// optional bytes ticket = 7;
/**
* <code>optional bytes ticket = 7;</code>
*/
boolean hasTicket();
/**
* <code>optional bytes ticket = 7;</code>
*/
com.google.protobuf.ByteString getTicket();
}
/**
* Protobuf type {@code CMsgAuthTicket}
*/
public static final class CMsgAuthTicket extends
com.google.protobuf.GeneratedMessage
implements CMsgAuthTicketOrBuilder {
// Use CMsgAuthTicket.newBuilder() to construct.
private CMsgAuthTicket(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private CMsgAuthTicket(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final CMsgAuthTicket defaultInstance;
public static CMsgAuthTicket getDefaultInstance() {
return defaultInstance;
}
public CMsgAuthTicket getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private CMsgAuthTicket(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
bitField0_ |= 0x00000001;
estate_ = input.readUInt32();
break;
}
case 16: {
bitField0_ |= 0x00000002;
eresult_ = input.readUInt32();
break;
}
case 25: {
bitField0_ |= 0x00000004;
steamid_ = input.readFixed64();
break;
}
case 33: {
bitField0_ |= 0x00000008;
gameid_ = input.readFixed64();
break;
}
case 40: {
bitField0_ |= 0x00000010;
hSteamPipe_ = input.readUInt32();
break;
}
case 48: {
bitField0_ |= 0x00000020;
ticketCrc_ = input.readUInt32();
break;
}
case 58: {
bitField0_ |= 0x00000040;
ticket_ = input.readBytes();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgAuthTicket_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgAuthTicket_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket.class, com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket.Builder.class);
}
public static com.google.protobuf.Parser<CMsgAuthTicket> PARSER =
new com.google.protobuf.AbstractParser<CMsgAuthTicket>() {
public CMsgAuthTicket parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new CMsgAuthTicket(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<CMsgAuthTicket> getParserForType() {
return PARSER;
}
private int bitField0_;
// optional uint32 estate = 1;
public static final int ESTATE_FIELD_NUMBER = 1;
private int estate_;
/**
* <code>optional uint32 estate = 1;</code>
*/
public boolean hasEstate() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional uint32 estate = 1;</code>
*/
public int getEstate() {
return estate_;
}
// optional uint32 eresult = 2 [default = 2];
public static final int ERESULT_FIELD_NUMBER = 2;
private int eresult_;
/**
* <code>optional uint32 eresult = 2 [default = 2];</code>
*/
public boolean hasEresult() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional uint32 eresult = 2 [default = 2];</code>
*/
public int getEresult() {
return eresult_;
}
// optional fixed64 steamid = 3;
public static final int STEAMID_FIELD_NUMBER = 3;
private long steamid_;
/**
* <code>optional fixed64 steamid = 3;</code>
*/
public boolean hasSteamid() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional fixed64 steamid = 3;</code>
*/
public long getSteamid() {
return steamid_;
}
// optional fixed64 gameid = 4;
public static final int GAMEID_FIELD_NUMBER = 4;
private long gameid_;
/**
* <code>optional fixed64 gameid = 4;</code>
*/
public boolean hasGameid() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional fixed64 gameid = 4;</code>
*/
public long getGameid() {
return gameid_;
}
// optional uint32 h_steam_pipe = 5;
public static final int H_STEAM_PIPE_FIELD_NUMBER = 5;
private int hSteamPipe_;
/**
* <code>optional uint32 h_steam_pipe = 5;</code>
*/
public boolean hasHSteamPipe() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>optional uint32 h_steam_pipe = 5;</code>
*/
public int getHSteamPipe() {
return hSteamPipe_;
}
// optional uint32 ticket_crc = 6;
public static final int TICKET_CRC_FIELD_NUMBER = 6;
private int ticketCrc_;
/**
* <code>optional uint32 ticket_crc = 6;</code>
*/
public boolean hasTicketCrc() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>optional uint32 ticket_crc = 6;</code>
*/
public int getTicketCrc() {
return ticketCrc_;
}
// optional bytes ticket = 7;
public static final int TICKET_FIELD_NUMBER = 7;
private com.google.protobuf.ByteString ticket_;
/**
* <code>optional bytes ticket = 7;</code>
*/
public boolean hasTicket() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>optional bytes ticket = 7;</code>
*/
public com.google.protobuf.ByteString getTicket() {
return ticket_;
}
private void initFields() {
estate_ = 0;
eresult_ = 2;
steamid_ = 0L;
gameid_ = 0L;
hSteamPipe_ = 0;
ticketCrc_ = 0;
ticket_ = com.google.protobuf.ByteString.EMPTY;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeUInt32(1, estate_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeUInt32(2, eresult_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeFixed64(3, steamid_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeFixed64(4, gameid_);
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
output.writeUInt32(5, hSteamPipe_);
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
output.writeUInt32(6, ticketCrc_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
output.writeBytes(7, ticket_);
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(1, estate_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(2, eresult_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeFixed64Size(3, steamid_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
size += com.google.protobuf.CodedOutputStream
.computeFixed64Size(4, gameid_);
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(5, hSteamPipe_);
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(6, ticketCrc_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(7, ticket_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code CMsgAuthTicket}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicketOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgAuthTicket_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgAuthTicket_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket.class, com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket.Builder.class);
}
// Construct using com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
estate_ = 0;
bitField0_ = (bitField0_ & ~0x00000001);
eresult_ = 2;
bitField0_ = (bitField0_ & ~0x00000002);
steamid_ = 0L;
bitField0_ = (bitField0_ & ~0x00000004);
gameid_ = 0L;
bitField0_ = (bitField0_ & ~0x00000008);
hSteamPipe_ = 0;
bitField0_ = (bitField0_ & ~0x00000010);
ticketCrc_ = 0;
bitField0_ = (bitField0_ & ~0x00000020);
ticket_ = com.google.protobuf.ByteString.EMPTY;
bitField0_ = (bitField0_ & ~0x00000040);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgAuthTicket_descriptor;
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket getDefaultInstanceForType() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket.getDefaultInstance();
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket build() {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket buildPartial() {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket result = new com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.estate_ = estate_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.eresult_ = eresult_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.steamid_ = steamid_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
result.gameid_ = gameid_;
if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
to_bitField0_ |= 0x00000010;
}
result.hSteamPipe_ = hSteamPipe_;
if (((from_bitField0_ & 0x00000020) == 0x00000020)) {
to_bitField0_ |= 0x00000020;
}
result.ticketCrc_ = ticketCrc_;
if (((from_bitField0_ & 0x00000040) == 0x00000040)) {
to_bitField0_ |= 0x00000040;
}
result.ticket_ = ticket_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket) {
return mergeFrom((com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket other) {
if (other == com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket.getDefaultInstance()) return this;
if (other.hasEstate()) {
setEstate(other.getEstate());
}
if (other.hasEresult()) {
setEresult(other.getEresult());
}
if (other.hasSteamid()) {
setSteamid(other.getSteamid());
}
if (other.hasGameid()) {
setGameid(other.getGameid());
}
if (other.hasHSteamPipe()) {
setHSteamPipe(other.getHSteamPipe());
}
if (other.hasTicketCrc()) {
setTicketCrc(other.getTicketCrc());
}
if (other.hasTicket()) {
setTicket(other.getTicket());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAuthTicket) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
// optional uint32 estate = 1;
private int estate_ ;
/**
* <code>optional uint32 estate = 1;</code>
*/
public boolean hasEstate() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional uint32 estate = 1;</code>
*/
public int getEstate() {
return estate_;
}
/**
* <code>optional uint32 estate = 1;</code>
*/
public Builder setEstate(int value) {
bitField0_ |= 0x00000001;
estate_ = value;
onChanged();
return this;
}
/**
* <code>optional uint32 estate = 1;</code>
*/
public Builder clearEstate() {
bitField0_ = (bitField0_ & ~0x00000001);
estate_ = 0;
onChanged();
return this;
}
// optional uint32 eresult = 2 [default = 2];
private int eresult_ = 2;
/**
* <code>optional uint32 eresult = 2 [default = 2];</code>
*/
public boolean hasEresult() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional uint32 eresult = 2 [default = 2];</code>
*/
public int getEresult() {
return eresult_;
}
/**
* <code>optional uint32 eresult = 2 [default = 2];</code>
*/
public Builder setEresult(int value) {
bitField0_ |= 0x00000002;
eresult_ = value;
onChanged();
return this;
}
/**
* <code>optional uint32 eresult = 2 [default = 2];</code>
*/
public Builder clearEresult() {
bitField0_ = (bitField0_ & ~0x00000002);
eresult_ = 2;
onChanged();
return this;
}
// optional fixed64 steamid = 3;
private long steamid_ ;
/**
* <code>optional fixed64 steamid = 3;</code>
*/
public boolean hasSteamid() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional fixed64 steamid = 3;</code>
*/
public long getSteamid() {
return steamid_;
}
/**
* <code>optional fixed64 steamid = 3;</code>
*/
public Builder setSteamid(long value) {
bitField0_ |= 0x00000004;
steamid_ = value;
onChanged();
return this;
}
/**
* <code>optional fixed64 steamid = 3;</code>
*/
public Builder clearSteamid() {
bitField0_ = (bitField0_ & ~0x00000004);
steamid_ = 0L;
onChanged();
return this;
}
// optional fixed64 gameid = 4;
private long gameid_ ;
/**
* <code>optional fixed64 gameid = 4;</code>
*/
public boolean hasGameid() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional fixed64 gameid = 4;</code>
*/
public long getGameid() {
return gameid_;
}
/**
* <code>optional fixed64 gameid = 4;</code>
*/
public Builder setGameid(long value) {
bitField0_ |= 0x00000008;
gameid_ = value;
onChanged();
return this;
}
/**
* <code>optional fixed64 gameid = 4;</code>
*/
public Builder clearGameid() {
bitField0_ = (bitField0_ & ~0x00000008);
gameid_ = 0L;
onChanged();
return this;
}
// optional uint32 h_steam_pipe = 5;
private int hSteamPipe_ ;
/**
* <code>optional uint32 h_steam_pipe = 5;</code>
*/
public boolean hasHSteamPipe() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>optional uint32 h_steam_pipe = 5;</code>
*/
public int getHSteamPipe() {
return hSteamPipe_;
}
/**
* <code>optional uint32 h_steam_pipe = 5;</code>
*/
public Builder setHSteamPipe(int value) {
bitField0_ |= 0x00000010;
hSteamPipe_ = value;
onChanged();
return this;
}
/**
* <code>optional uint32 h_steam_pipe = 5;</code>
*/
public Builder clearHSteamPipe() {
bitField0_ = (bitField0_ & ~0x00000010);
hSteamPipe_ = 0;
onChanged();
return this;
}
// optional uint32 ticket_crc = 6;
private int ticketCrc_ ;
/**
* <code>optional uint32 ticket_crc = 6;</code>
*/
public boolean hasTicketCrc() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>optional uint32 ticket_crc = 6;</code>
*/
public int getTicketCrc() {
return ticketCrc_;
}
/**
* <code>optional uint32 ticket_crc = 6;</code>
*/
public Builder setTicketCrc(int value) {
bitField0_ |= 0x00000020;
ticketCrc_ = value;
onChanged();
return this;
}
/**
* <code>optional uint32 ticket_crc = 6;</code>
*/
public Builder clearTicketCrc() {
bitField0_ = (bitField0_ & ~0x00000020);
ticketCrc_ = 0;
onChanged();
return this;
}
// optional bytes ticket = 7;
private com.google.protobuf.ByteString ticket_ = com.google.protobuf.ByteString.EMPTY;
/**
* <code>optional bytes ticket = 7;</code>
*/
public boolean hasTicket() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>optional bytes ticket = 7;</code>
*/
public com.google.protobuf.ByteString getTicket() {
return ticket_;
}
/**
* <code>optional bytes ticket = 7;</code>
*/
public Builder setTicket(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000040;
ticket_ = value;
onChanged();
return this;
}
/**
* <code>optional bytes ticket = 7;</code>
*/
public Builder clearTicket() {
bitField0_ = (bitField0_ & ~0x00000040);
ticket_ = getDefaultInstance().getTicket();
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:CMsgAuthTicket)
}
static {
defaultInstance = new CMsgAuthTicket(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:CMsgAuthTicket)
}
public interface CCDDBAppDetailCommonOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// optional uint32 appid = 1;
/**
* <code>optional uint32 appid = 1;</code>
*/
boolean hasAppid();
/**
* <code>optional uint32 appid = 1;</code>
*/
int getAppid();
// optional string name = 2;
/**
* <code>optional string name = 2;</code>
*/
boolean hasName();
/**
* <code>optional string name = 2;</code>
*/
java.lang.String getName();
/**
* <code>optional string name = 2;</code>
*/
com.google.protobuf.ByteString
getNameBytes();
// optional string icon = 3;
/**
* <code>optional string icon = 3;</code>
*/
boolean hasIcon();
/**
* <code>optional string icon = 3;</code>
*/
java.lang.String getIcon();
/**
* <code>optional string icon = 3;</code>
*/
com.google.protobuf.ByteString
getIconBytes();
// optional string logo = 4;
/**
* <code>optional string logo = 4;</code>
*/
boolean hasLogo();
/**
* <code>optional string logo = 4;</code>
*/
java.lang.String getLogo();
/**
* <code>optional string logo = 4;</code>
*/
com.google.protobuf.ByteString
getLogoBytes();
// optional string logo_small = 5;
/**
* <code>optional string logo_small = 5;</code>
*/
boolean hasLogoSmall();
/**
* <code>optional string logo_small = 5;</code>
*/
java.lang.String getLogoSmall();
/**
* <code>optional string logo_small = 5;</code>
*/
com.google.protobuf.ByteString
getLogoSmallBytes();
// optional bool tool = 6;
/**
* <code>optional bool tool = 6;</code>
*/
boolean hasTool();
/**
* <code>optional bool tool = 6;</code>
*/
boolean getTool();
// optional bool demo = 7;
/**
* <code>optional bool demo = 7;</code>
*/
boolean hasDemo();
/**
* <code>optional bool demo = 7;</code>
*/
boolean getDemo();
// optional bool media = 8;
/**
* <code>optional bool media = 8;</code>
*/
boolean hasMedia();
/**
* <code>optional bool media = 8;</code>
*/
boolean getMedia();
// optional bool community_visible_stats = 9;
/**
* <code>optional bool community_visible_stats = 9;</code>
*/
boolean hasCommunityVisibleStats();
/**
* <code>optional bool community_visible_stats = 9;</code>
*/
boolean getCommunityVisibleStats();
// optional string friendly_name = 10;
/**
* <code>optional string friendly_name = 10;</code>
*/
boolean hasFriendlyName();
/**
* <code>optional string friendly_name = 10;</code>
*/
java.lang.String getFriendlyName();
/**
* <code>optional string friendly_name = 10;</code>
*/
com.google.protobuf.ByteString
getFriendlyNameBytes();
// optional string propagation = 11;
/**
* <code>optional string propagation = 11;</code>
*/
boolean hasPropagation();
/**
* <code>optional string propagation = 11;</code>
*/
java.lang.String getPropagation();
/**
* <code>optional string propagation = 11;</code>
*/
com.google.protobuf.ByteString
getPropagationBytes();
// optional bool has_adult_content = 12;
/**
* <code>optional bool has_adult_content = 12;</code>
*/
boolean hasHasAdultContent();
/**
* <code>optional bool has_adult_content = 12;</code>
*/
boolean getHasAdultContent();
}
/**
* Protobuf type {@code CCDDBAppDetailCommon}
*/
public static final class CCDDBAppDetailCommon extends
com.google.protobuf.GeneratedMessage
implements CCDDBAppDetailCommonOrBuilder {
// Use CCDDBAppDetailCommon.newBuilder() to construct.
private CCDDBAppDetailCommon(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private CCDDBAppDetailCommon(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final CCDDBAppDetailCommon defaultInstance;
public static CCDDBAppDetailCommon getDefaultInstance() {
return defaultInstance;
}
public CCDDBAppDetailCommon getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private CCDDBAppDetailCommon(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
bitField0_ |= 0x00000001;
appid_ = input.readUInt32();
break;
}
case 18: {
bitField0_ |= 0x00000002;
name_ = input.readBytes();
break;
}
case 26: {
bitField0_ |= 0x00000004;
icon_ = input.readBytes();
break;
}
case 34: {
bitField0_ |= 0x00000008;
logo_ = input.readBytes();
break;
}
case 42: {
bitField0_ |= 0x00000010;
logoSmall_ = input.readBytes();
break;
}
case 48: {
bitField0_ |= 0x00000020;
tool_ = input.readBool();
break;
}
case 56: {
bitField0_ |= 0x00000040;
demo_ = input.readBool();
break;
}
case 64: {
bitField0_ |= 0x00000080;
media_ = input.readBool();
break;
}
case 72: {
bitField0_ |= 0x00000100;
communityVisibleStats_ = input.readBool();
break;
}
case 82: {
bitField0_ |= 0x00000200;
friendlyName_ = input.readBytes();
break;
}
case 90: {
bitField0_ |= 0x00000400;
propagation_ = input.readBytes();
break;
}
case 96: {
bitField0_ |= 0x00000800;
hasAdultContent_ = input.readBool();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CCDDBAppDetailCommon_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CCDDBAppDetailCommon_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon.class, com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon.Builder.class);
}
public static com.google.protobuf.Parser<CCDDBAppDetailCommon> PARSER =
new com.google.protobuf.AbstractParser<CCDDBAppDetailCommon>() {
public CCDDBAppDetailCommon parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new CCDDBAppDetailCommon(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<CCDDBAppDetailCommon> getParserForType() {
return PARSER;
}
private int bitField0_;
// optional uint32 appid = 1;
public static final int APPID_FIELD_NUMBER = 1;
private int appid_;
/**
* <code>optional uint32 appid = 1;</code>
*/
public boolean hasAppid() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional uint32 appid = 1;</code>
*/
public int getAppid() {
return appid_;
}
// optional string name = 2;
public static final int NAME_FIELD_NUMBER = 2;
private java.lang.Object name_;
/**
* <code>optional string name = 2;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional string name = 2;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
}
}
/**
* <code>optional string name = 2;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// optional string icon = 3;
public static final int ICON_FIELD_NUMBER = 3;
private java.lang.Object icon_;
/**
* <code>optional string icon = 3;</code>
*/
public boolean hasIcon() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional string icon = 3;</code>
*/
public java.lang.String getIcon() {
java.lang.Object ref = icon_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
icon_ = s;
}
return s;
}
}
/**
* <code>optional string icon = 3;</code>
*/
public com.google.protobuf.ByteString
getIconBytes() {
java.lang.Object ref = icon_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
icon_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// optional string logo = 4;
public static final int LOGO_FIELD_NUMBER = 4;
private java.lang.Object logo_;
/**
* <code>optional string logo = 4;</code>
*/
public boolean hasLogo() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional string logo = 4;</code>
*/
public java.lang.String getLogo() {
java.lang.Object ref = logo_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
logo_ = s;
}
return s;
}
}
/**
* <code>optional string logo = 4;</code>
*/
public com.google.protobuf.ByteString
getLogoBytes() {
java.lang.Object ref = logo_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
logo_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// optional string logo_small = 5;
public static final int LOGO_SMALL_FIELD_NUMBER = 5;
private java.lang.Object logoSmall_;
/**
* <code>optional string logo_small = 5;</code>
*/
public boolean hasLogoSmall() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>optional string logo_small = 5;</code>
*/
public java.lang.String getLogoSmall() {
java.lang.Object ref = logoSmall_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
logoSmall_ = s;
}
return s;
}
}
/**
* <code>optional string logo_small = 5;</code>
*/
public com.google.protobuf.ByteString
getLogoSmallBytes() {
java.lang.Object ref = logoSmall_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
logoSmall_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// optional bool tool = 6;
public static final int TOOL_FIELD_NUMBER = 6;
private boolean tool_;
/**
* <code>optional bool tool = 6;</code>
*/
public boolean hasTool() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>optional bool tool = 6;</code>
*/
public boolean getTool() {
return tool_;
}
// optional bool demo = 7;
public static final int DEMO_FIELD_NUMBER = 7;
private boolean demo_;
/**
* <code>optional bool demo = 7;</code>
*/
public boolean hasDemo() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>optional bool demo = 7;</code>
*/
public boolean getDemo() {
return demo_;
}
// optional bool media = 8;
public static final int MEDIA_FIELD_NUMBER = 8;
private boolean media_;
/**
* <code>optional bool media = 8;</code>
*/
public boolean hasMedia() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
/**
* <code>optional bool media = 8;</code>
*/
public boolean getMedia() {
return media_;
}
// optional bool community_visible_stats = 9;
public static final int COMMUNITY_VISIBLE_STATS_FIELD_NUMBER = 9;
private boolean communityVisibleStats_;
/**
* <code>optional bool community_visible_stats = 9;</code>
*/
public boolean hasCommunityVisibleStats() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
/**
* <code>optional bool community_visible_stats = 9;</code>
*/
public boolean getCommunityVisibleStats() {
return communityVisibleStats_;
}
// optional string friendly_name = 10;
public static final int FRIENDLY_NAME_FIELD_NUMBER = 10;
private java.lang.Object friendlyName_;
/**
* <code>optional string friendly_name = 10;</code>
*/
public boolean hasFriendlyName() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
/**
* <code>optional string friendly_name = 10;</code>
*/
public java.lang.String getFriendlyName() {
java.lang.Object ref = friendlyName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
friendlyName_ = s;
}
return s;
}
}
/**
* <code>optional string friendly_name = 10;</code>
*/
public com.google.protobuf.ByteString
getFriendlyNameBytes() {
java.lang.Object ref = friendlyName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
friendlyName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// optional string propagation = 11;
public static final int PROPAGATION_FIELD_NUMBER = 11;
private java.lang.Object propagation_;
/**
* <code>optional string propagation = 11;</code>
*/
public boolean hasPropagation() {
return ((bitField0_ & 0x00000400) == 0x00000400);
}
/**
* <code>optional string propagation = 11;</code>
*/
public java.lang.String getPropagation() {
java.lang.Object ref = propagation_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
propagation_ = s;
}
return s;
}
}
/**
* <code>optional string propagation = 11;</code>
*/
public com.google.protobuf.ByteString
getPropagationBytes() {
java.lang.Object ref = propagation_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
propagation_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// optional bool has_adult_content = 12;
public static final int HAS_ADULT_CONTENT_FIELD_NUMBER = 12;
private boolean hasAdultContent_;
/**
* <code>optional bool has_adult_content = 12;</code>
*/
public boolean hasHasAdultContent() {
return ((bitField0_ & 0x00000800) == 0x00000800);
}
/**
* <code>optional bool has_adult_content = 12;</code>
*/
public boolean getHasAdultContent() {
return hasAdultContent_;
}
private void initFields() {
appid_ = 0;
name_ = "";
icon_ = "";
logo_ = "";
logoSmall_ = "";
tool_ = false;
demo_ = false;
media_ = false;
communityVisibleStats_ = false;
friendlyName_ = "";
propagation_ = "";
hasAdultContent_ = false;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeUInt32(1, appid_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getNameBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeBytes(3, getIconBytes());
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeBytes(4, getLogoBytes());
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
output.writeBytes(5, getLogoSmallBytes());
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
output.writeBool(6, tool_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
output.writeBool(7, demo_);
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
output.writeBool(8, media_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
output.writeBool(9, communityVisibleStats_);
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
output.writeBytes(10, getFriendlyNameBytes());
}
if (((bitField0_ & 0x00000400) == 0x00000400)) {
output.writeBytes(11, getPropagationBytes());
}
if (((bitField0_ & 0x00000800) == 0x00000800)) {
output.writeBool(12, hasAdultContent_);
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(1, appid_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getNameBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(3, getIconBytes());
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(4, getLogoBytes());
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(5, getLogoSmallBytes());
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(6, tool_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(7, demo_);
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(8, media_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(9, communityVisibleStats_);
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(10, getFriendlyNameBytes());
}
if (((bitField0_ & 0x00000400) == 0x00000400)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(11, getPropagationBytes());
}
if (((bitField0_ & 0x00000800) == 0x00000800)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(12, hasAdultContent_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code CCDDBAppDetailCommon}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommonOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CCDDBAppDetailCommon_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CCDDBAppDetailCommon_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon.class, com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon.Builder.class);
}
// Construct using com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
appid_ = 0;
bitField0_ = (bitField0_ & ~0x00000001);
name_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
icon_ = "";
bitField0_ = (bitField0_ & ~0x00000004);
logo_ = "";
bitField0_ = (bitField0_ & ~0x00000008);
logoSmall_ = "";
bitField0_ = (bitField0_ & ~0x00000010);
tool_ = false;
bitField0_ = (bitField0_ & ~0x00000020);
demo_ = false;
bitField0_ = (bitField0_ & ~0x00000040);
media_ = false;
bitField0_ = (bitField0_ & ~0x00000080);
communityVisibleStats_ = false;
bitField0_ = (bitField0_ & ~0x00000100);
friendlyName_ = "";
bitField0_ = (bitField0_ & ~0x00000200);
propagation_ = "";
bitField0_ = (bitField0_ & ~0x00000400);
hasAdultContent_ = false;
bitField0_ = (bitField0_ & ~0x00000800);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CCDDBAppDetailCommon_descriptor;
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon getDefaultInstanceForType() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon.getDefaultInstance();
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon build() {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon buildPartial() {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon result = new com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.appid_ = appid_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.name_ = name_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.icon_ = icon_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
result.logo_ = logo_;
if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
to_bitField0_ |= 0x00000010;
}
result.logoSmall_ = logoSmall_;
if (((from_bitField0_ & 0x00000020) == 0x00000020)) {
to_bitField0_ |= 0x00000020;
}
result.tool_ = tool_;
if (((from_bitField0_ & 0x00000040) == 0x00000040)) {
to_bitField0_ |= 0x00000040;
}
result.demo_ = demo_;
if (((from_bitField0_ & 0x00000080) == 0x00000080)) {
to_bitField0_ |= 0x00000080;
}
result.media_ = media_;
if (((from_bitField0_ & 0x00000100) == 0x00000100)) {
to_bitField0_ |= 0x00000100;
}
result.communityVisibleStats_ = communityVisibleStats_;
if (((from_bitField0_ & 0x00000200) == 0x00000200)) {
to_bitField0_ |= 0x00000200;
}
result.friendlyName_ = friendlyName_;
if (((from_bitField0_ & 0x00000400) == 0x00000400)) {
to_bitField0_ |= 0x00000400;
}
result.propagation_ = propagation_;
if (((from_bitField0_ & 0x00000800) == 0x00000800)) {
to_bitField0_ |= 0x00000800;
}
result.hasAdultContent_ = hasAdultContent_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon) {
return mergeFrom((com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon other) {
if (other == com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon.getDefaultInstance()) return this;
if (other.hasAppid()) {
setAppid(other.getAppid());
}
if (other.hasName()) {
bitField0_ |= 0x00000002;
name_ = other.name_;
onChanged();
}
if (other.hasIcon()) {
bitField0_ |= 0x00000004;
icon_ = other.icon_;
onChanged();
}
if (other.hasLogo()) {
bitField0_ |= 0x00000008;
logo_ = other.logo_;
onChanged();
}
if (other.hasLogoSmall()) {
bitField0_ |= 0x00000010;
logoSmall_ = other.logoSmall_;
onChanged();
}
if (other.hasTool()) {
setTool(other.getTool());
}
if (other.hasDemo()) {
setDemo(other.getDemo());
}
if (other.hasMedia()) {
setMedia(other.getMedia());
}
if (other.hasCommunityVisibleStats()) {
setCommunityVisibleStats(other.getCommunityVisibleStats());
}
if (other.hasFriendlyName()) {
bitField0_ |= 0x00000200;
friendlyName_ = other.friendlyName_;
onChanged();
}
if (other.hasPropagation()) {
bitField0_ |= 0x00000400;
propagation_ = other.propagation_;
onChanged();
}
if (other.hasHasAdultContent()) {
setHasAdultContent(other.getHasAdultContent());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CCDDBAppDetailCommon) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
// optional uint32 appid = 1;
private int appid_ ;
/**
* <code>optional uint32 appid = 1;</code>
*/
public boolean hasAppid() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional uint32 appid = 1;</code>
*/
public int getAppid() {
return appid_;
}
/**
* <code>optional uint32 appid = 1;</code>
*/
public Builder setAppid(int value) {
bitField0_ |= 0x00000001;
appid_ = value;
onChanged();
return this;
}
/**
* <code>optional uint32 appid = 1;</code>
*/
public Builder clearAppid() {
bitField0_ = (bitField0_ & ~0x00000001);
appid_ = 0;
onChanged();
return this;
}
// optional string name = 2;
private java.lang.Object name_ = "";
/**
* <code>optional string name = 2;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional string name = 2;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref)
.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string name = 2;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string name = 2;</code>
*/
public Builder setName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
name_ = value;
onChanged();
return this;
}
/**
* <code>optional string name = 2;</code>
*/
public Builder clearName() {
bitField0_ = (bitField0_ & ~0x00000002);
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <code>optional string name = 2;</code>
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
name_ = value;
onChanged();
return this;
}
// optional string icon = 3;
private java.lang.Object icon_ = "";
/**
* <code>optional string icon = 3;</code>
*/
public boolean hasIcon() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional string icon = 3;</code>
*/
public java.lang.String getIcon() {
java.lang.Object ref = icon_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref)
.toStringUtf8();
icon_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string icon = 3;</code>
*/
public com.google.protobuf.ByteString
getIconBytes() {
java.lang.Object ref = icon_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
icon_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string icon = 3;</code>
*/
public Builder setIcon(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
icon_ = value;
onChanged();
return this;
}
/**
* <code>optional string icon = 3;</code>
*/
public Builder clearIcon() {
bitField0_ = (bitField0_ & ~0x00000004);
icon_ = getDefaultInstance().getIcon();
onChanged();
return this;
}
/**
* <code>optional string icon = 3;</code>
*/
public Builder setIconBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
icon_ = value;
onChanged();
return this;
}
// optional string logo = 4;
private java.lang.Object logo_ = "";
/**
* <code>optional string logo = 4;</code>
*/
public boolean hasLogo() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional string logo = 4;</code>
*/
public java.lang.String getLogo() {
java.lang.Object ref = logo_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref)
.toStringUtf8();
logo_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string logo = 4;</code>
*/
public com.google.protobuf.ByteString
getLogoBytes() {
java.lang.Object ref = logo_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
logo_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string logo = 4;</code>
*/
public Builder setLogo(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
logo_ = value;
onChanged();
return this;
}
/**
* <code>optional string logo = 4;</code>
*/
public Builder clearLogo() {
bitField0_ = (bitField0_ & ~0x00000008);
logo_ = getDefaultInstance().getLogo();
onChanged();
return this;
}
/**
* <code>optional string logo = 4;</code>
*/
public Builder setLogoBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
logo_ = value;
onChanged();
return this;
}
// optional string logo_small = 5;
private java.lang.Object logoSmall_ = "";
/**
* <code>optional string logo_small = 5;</code>
*/
public boolean hasLogoSmall() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>optional string logo_small = 5;</code>
*/
public java.lang.String getLogoSmall() {
java.lang.Object ref = logoSmall_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref)
.toStringUtf8();
logoSmall_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string logo_small = 5;</code>
*/
public com.google.protobuf.ByteString
getLogoSmallBytes() {
java.lang.Object ref = logoSmall_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
logoSmall_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string logo_small = 5;</code>
*/
public Builder setLogoSmall(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000010;
logoSmall_ = value;
onChanged();
return this;
}
/**
* <code>optional string logo_small = 5;</code>
*/
public Builder clearLogoSmall() {
bitField0_ = (bitField0_ & ~0x00000010);
logoSmall_ = getDefaultInstance().getLogoSmall();
onChanged();
return this;
}
/**
* <code>optional string logo_small = 5;</code>
*/
public Builder setLogoSmallBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000010;
logoSmall_ = value;
onChanged();
return this;
}
// optional bool tool = 6;
private boolean tool_ ;
/**
* <code>optional bool tool = 6;</code>
*/
public boolean hasTool() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>optional bool tool = 6;</code>
*/
public boolean getTool() {
return tool_;
}
/**
* <code>optional bool tool = 6;</code>
*/
public Builder setTool(boolean value) {
bitField0_ |= 0x00000020;
tool_ = value;
onChanged();
return this;
}
/**
* <code>optional bool tool = 6;</code>
*/
public Builder clearTool() {
bitField0_ = (bitField0_ & ~0x00000020);
tool_ = false;
onChanged();
return this;
}
// optional bool demo = 7;
private boolean demo_ ;
/**
* <code>optional bool demo = 7;</code>
*/
public boolean hasDemo() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>optional bool demo = 7;</code>
*/
public boolean getDemo() {
return demo_;
}
/**
* <code>optional bool demo = 7;</code>
*/
public Builder setDemo(boolean value) {
bitField0_ |= 0x00000040;
demo_ = value;
onChanged();
return this;
}
/**
* <code>optional bool demo = 7;</code>
*/
public Builder clearDemo() {
bitField0_ = (bitField0_ & ~0x00000040);
demo_ = false;
onChanged();
return this;
}
// optional bool media = 8;
private boolean media_ ;
/**
* <code>optional bool media = 8;</code>
*/
public boolean hasMedia() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
/**
* <code>optional bool media = 8;</code>
*/
public boolean getMedia() {
return media_;
}
/**
* <code>optional bool media = 8;</code>
*/
public Builder setMedia(boolean value) {
bitField0_ |= 0x00000080;
media_ = value;
onChanged();
return this;
}
/**
* <code>optional bool media = 8;</code>
*/
public Builder clearMedia() {
bitField0_ = (bitField0_ & ~0x00000080);
media_ = false;
onChanged();
return this;
}
// optional bool community_visible_stats = 9;
private boolean communityVisibleStats_ ;
/**
* <code>optional bool community_visible_stats = 9;</code>
*/
public boolean hasCommunityVisibleStats() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
/**
* <code>optional bool community_visible_stats = 9;</code>
*/
public boolean getCommunityVisibleStats() {
return communityVisibleStats_;
}
/**
* <code>optional bool community_visible_stats = 9;</code>
*/
public Builder setCommunityVisibleStats(boolean value) {
bitField0_ |= 0x00000100;
communityVisibleStats_ = value;
onChanged();
return this;
}
/**
* <code>optional bool community_visible_stats = 9;</code>
*/
public Builder clearCommunityVisibleStats() {
bitField0_ = (bitField0_ & ~0x00000100);
communityVisibleStats_ = false;
onChanged();
return this;
}
// optional string friendly_name = 10;
private java.lang.Object friendlyName_ = "";
/**
* <code>optional string friendly_name = 10;</code>
*/
public boolean hasFriendlyName() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
/**
* <code>optional string friendly_name = 10;</code>
*/
public java.lang.String getFriendlyName() {
java.lang.Object ref = friendlyName_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref)
.toStringUtf8();
friendlyName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string friendly_name = 10;</code>
*/
public com.google.protobuf.ByteString
getFriendlyNameBytes() {
java.lang.Object ref = friendlyName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
friendlyName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string friendly_name = 10;</code>
*/
public Builder setFriendlyName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000200;
friendlyName_ = value;
onChanged();
return this;
}
/**
* <code>optional string friendly_name = 10;</code>
*/
public Builder clearFriendlyName() {
bitField0_ = (bitField0_ & ~0x00000200);
friendlyName_ = getDefaultInstance().getFriendlyName();
onChanged();
return this;
}
/**
* <code>optional string friendly_name = 10;</code>
*/
public Builder setFriendlyNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000200;
friendlyName_ = value;
onChanged();
return this;
}
// optional string propagation = 11;
private java.lang.Object propagation_ = "";
/**
* <code>optional string propagation = 11;</code>
*/
public boolean hasPropagation() {
return ((bitField0_ & 0x00000400) == 0x00000400);
}
/**
* <code>optional string propagation = 11;</code>
*/
public java.lang.String getPropagation() {
java.lang.Object ref = propagation_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref)
.toStringUtf8();
propagation_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string propagation = 11;</code>
*/
public com.google.protobuf.ByteString
getPropagationBytes() {
java.lang.Object ref = propagation_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
propagation_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string propagation = 11;</code>
*/
public Builder setPropagation(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000400;
propagation_ = value;
onChanged();
return this;
}
/**
* <code>optional string propagation = 11;</code>
*/
public Builder clearPropagation() {
bitField0_ = (bitField0_ & ~0x00000400);
propagation_ = getDefaultInstance().getPropagation();
onChanged();
return this;
}
/**
* <code>optional string propagation = 11;</code>
*/
public Builder setPropagationBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000400;
propagation_ = value;
onChanged();
return this;
}
// optional bool has_adult_content = 12;
private boolean hasAdultContent_ ;
/**
* <code>optional bool has_adult_content = 12;</code>
*/
public boolean hasHasAdultContent() {
return ((bitField0_ & 0x00000800) == 0x00000800);
}
/**
* <code>optional bool has_adult_content = 12;</code>
*/
public boolean getHasAdultContent() {
return hasAdultContent_;
}
/**
* <code>optional bool has_adult_content = 12;</code>
*/
public Builder setHasAdultContent(boolean value) {
bitField0_ |= 0x00000800;
hasAdultContent_ = value;
onChanged();
return this;
}
/**
* <code>optional bool has_adult_content = 12;</code>
*/
public Builder clearHasAdultContent() {
bitField0_ = (bitField0_ & ~0x00000800);
hasAdultContent_ = false;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:CCDDBAppDetailCommon)
}
static {
defaultInstance = new CCDDBAppDetailCommon(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:CCDDBAppDetailCommon)
}
public interface CMsgAppRightsOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// optional bool edit_info = 1;
/**
* <code>optional bool edit_info = 1;</code>
*/
boolean hasEditInfo();
/**
* <code>optional bool edit_info = 1;</code>
*/
boolean getEditInfo();
// optional bool publish = 2;
/**
* <code>optional bool publish = 2;</code>
*/
boolean hasPublish();
/**
* <code>optional bool publish = 2;</code>
*/
boolean getPublish();
// optional bool view_error_data = 3;
/**
* <code>optional bool view_error_data = 3;</code>
*/
boolean hasViewErrorData();
/**
* <code>optional bool view_error_data = 3;</code>
*/
boolean getViewErrorData();
// optional bool download = 4;
/**
* <code>optional bool download = 4;</code>
*/
boolean hasDownload();
/**
* <code>optional bool download = 4;</code>
*/
boolean getDownload();
// optional bool upload_cdkeys = 5;
/**
* <code>optional bool upload_cdkeys = 5;</code>
*/
boolean hasUploadCdkeys();
/**
* <code>optional bool upload_cdkeys = 5;</code>
*/
boolean getUploadCdkeys();
// optional bool generate_cdkeys = 6;
/**
* <code>optional bool generate_cdkeys = 6;</code>
*/
boolean hasGenerateCdkeys();
/**
* <code>optional bool generate_cdkeys = 6;</code>
*/
boolean getGenerateCdkeys();
// optional bool view_financials = 7;
/**
* <code>optional bool view_financials = 7;</code>
*/
boolean hasViewFinancials();
/**
* <code>optional bool view_financials = 7;</code>
*/
boolean getViewFinancials();
// optional bool manage_ceg = 8;
/**
* <code>optional bool manage_ceg = 8;</code>
*/
boolean hasManageCeg();
/**
* <code>optional bool manage_ceg = 8;</code>
*/
boolean getManageCeg();
// optional bool manage_signing = 9;
/**
* <code>optional bool manage_signing = 9;</code>
*/
boolean hasManageSigning();
/**
* <code>optional bool manage_signing = 9;</code>
*/
boolean getManageSigning();
// optional bool manage_cdkeys = 10;
/**
* <code>optional bool manage_cdkeys = 10;</code>
*/
boolean hasManageCdkeys();
/**
* <code>optional bool manage_cdkeys = 10;</code>
*/
boolean getManageCdkeys();
// optional bool edit_marketing = 11;
/**
* <code>optional bool edit_marketing = 11;</code>
*/
boolean hasEditMarketing();
/**
* <code>optional bool edit_marketing = 11;</code>
*/
boolean getEditMarketing();
// optional bool economy_support = 12;
/**
* <code>optional bool economy_support = 12;</code>
*/
boolean hasEconomySupport();
/**
* <code>optional bool economy_support = 12;</code>
*/
boolean getEconomySupport();
// optional bool economy_support_supervisor = 13;
/**
* <code>optional bool economy_support_supervisor = 13;</code>
*/
boolean hasEconomySupportSupervisor();
/**
* <code>optional bool economy_support_supervisor = 13;</code>
*/
boolean getEconomySupportSupervisor();
}
/**
* Protobuf type {@code CMsgAppRights}
*/
public static final class CMsgAppRights extends
com.google.protobuf.GeneratedMessage
implements CMsgAppRightsOrBuilder {
// Use CMsgAppRights.newBuilder() to construct.
private CMsgAppRights(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private CMsgAppRights(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final CMsgAppRights defaultInstance;
public static CMsgAppRights getDefaultInstance() {
return defaultInstance;
}
public CMsgAppRights getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private CMsgAppRights(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
bitField0_ |= 0x00000001;
editInfo_ = input.readBool();
break;
}
case 16: {
bitField0_ |= 0x00000002;
publish_ = input.readBool();
break;
}
case 24: {
bitField0_ |= 0x00000004;
viewErrorData_ = input.readBool();
break;
}
case 32: {
bitField0_ |= 0x00000008;
download_ = input.readBool();
break;
}
case 40: {
bitField0_ |= 0x00000010;
uploadCdkeys_ = input.readBool();
break;
}
case 48: {
bitField0_ |= 0x00000020;
generateCdkeys_ = input.readBool();
break;
}
case 56: {
bitField0_ |= 0x00000040;
viewFinancials_ = input.readBool();
break;
}
case 64: {
bitField0_ |= 0x00000080;
manageCeg_ = input.readBool();
break;
}
case 72: {
bitField0_ |= 0x00000100;
manageSigning_ = input.readBool();
break;
}
case 80: {
bitField0_ |= 0x00000200;
manageCdkeys_ = input.readBool();
break;
}
case 88: {
bitField0_ |= 0x00000400;
editMarketing_ = input.readBool();
break;
}
case 96: {
bitField0_ |= 0x00000800;
economySupport_ = input.readBool();
break;
}
case 104: {
bitField0_ |= 0x00001000;
economySupportSupervisor_ = input.readBool();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgAppRights_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgAppRights_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights.class, com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights.Builder.class);
}
public static com.google.protobuf.Parser<CMsgAppRights> PARSER =
new com.google.protobuf.AbstractParser<CMsgAppRights>() {
public CMsgAppRights parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new CMsgAppRights(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<CMsgAppRights> getParserForType() {
return PARSER;
}
private int bitField0_;
// optional bool edit_info = 1;
public static final int EDIT_INFO_FIELD_NUMBER = 1;
private boolean editInfo_;
/**
* <code>optional bool edit_info = 1;</code>
*/
public boolean hasEditInfo() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional bool edit_info = 1;</code>
*/
public boolean getEditInfo() {
return editInfo_;
}
// optional bool publish = 2;
public static final int PUBLISH_FIELD_NUMBER = 2;
private boolean publish_;
/**
* <code>optional bool publish = 2;</code>
*/
public boolean hasPublish() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional bool publish = 2;</code>
*/
public boolean getPublish() {
return publish_;
}
// optional bool view_error_data = 3;
public static final int VIEW_ERROR_DATA_FIELD_NUMBER = 3;
private boolean viewErrorData_;
/**
* <code>optional bool view_error_data = 3;</code>
*/
public boolean hasViewErrorData() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional bool view_error_data = 3;</code>
*/
public boolean getViewErrorData() {
return viewErrorData_;
}
// optional bool download = 4;
public static final int DOWNLOAD_FIELD_NUMBER = 4;
private boolean download_;
/**
* <code>optional bool download = 4;</code>
*/
public boolean hasDownload() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional bool download = 4;</code>
*/
public boolean getDownload() {
return download_;
}
// optional bool upload_cdkeys = 5;
public static final int UPLOAD_CDKEYS_FIELD_NUMBER = 5;
private boolean uploadCdkeys_;
/**
* <code>optional bool upload_cdkeys = 5;</code>
*/
public boolean hasUploadCdkeys() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>optional bool upload_cdkeys = 5;</code>
*/
public boolean getUploadCdkeys() {
return uploadCdkeys_;
}
// optional bool generate_cdkeys = 6;
public static final int GENERATE_CDKEYS_FIELD_NUMBER = 6;
private boolean generateCdkeys_;
/**
* <code>optional bool generate_cdkeys = 6;</code>
*/
public boolean hasGenerateCdkeys() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>optional bool generate_cdkeys = 6;</code>
*/
public boolean getGenerateCdkeys() {
return generateCdkeys_;
}
// optional bool view_financials = 7;
public static final int VIEW_FINANCIALS_FIELD_NUMBER = 7;
private boolean viewFinancials_;
/**
* <code>optional bool view_financials = 7;</code>
*/
public boolean hasViewFinancials() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>optional bool view_financials = 7;</code>
*/
public boolean getViewFinancials() {
return viewFinancials_;
}
// optional bool manage_ceg = 8;
public static final int MANAGE_CEG_FIELD_NUMBER = 8;
private boolean manageCeg_;
/**
* <code>optional bool manage_ceg = 8;</code>
*/
public boolean hasManageCeg() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
/**
* <code>optional bool manage_ceg = 8;</code>
*/
public boolean getManageCeg() {
return manageCeg_;
}
// optional bool manage_signing = 9;
public static final int MANAGE_SIGNING_FIELD_NUMBER = 9;
private boolean manageSigning_;
/**
* <code>optional bool manage_signing = 9;</code>
*/
public boolean hasManageSigning() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
/**
* <code>optional bool manage_signing = 9;</code>
*/
public boolean getManageSigning() {
return manageSigning_;
}
// optional bool manage_cdkeys = 10;
public static final int MANAGE_CDKEYS_FIELD_NUMBER = 10;
private boolean manageCdkeys_;
/**
* <code>optional bool manage_cdkeys = 10;</code>
*/
public boolean hasManageCdkeys() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
/**
* <code>optional bool manage_cdkeys = 10;</code>
*/
public boolean getManageCdkeys() {
return manageCdkeys_;
}
// optional bool edit_marketing = 11;
public static final int EDIT_MARKETING_FIELD_NUMBER = 11;
private boolean editMarketing_;
/**
* <code>optional bool edit_marketing = 11;</code>
*/
public boolean hasEditMarketing() {
return ((bitField0_ & 0x00000400) == 0x00000400);
}
/**
* <code>optional bool edit_marketing = 11;</code>
*/
public boolean getEditMarketing() {
return editMarketing_;
}
// optional bool economy_support = 12;
public static final int ECONOMY_SUPPORT_FIELD_NUMBER = 12;
private boolean economySupport_;
/**
* <code>optional bool economy_support = 12;</code>
*/
public boolean hasEconomySupport() {
return ((bitField0_ & 0x00000800) == 0x00000800);
}
/**
* <code>optional bool economy_support = 12;</code>
*/
public boolean getEconomySupport() {
return economySupport_;
}
// optional bool economy_support_supervisor = 13;
public static final int ECONOMY_SUPPORT_SUPERVISOR_FIELD_NUMBER = 13;
private boolean economySupportSupervisor_;
/**
* <code>optional bool economy_support_supervisor = 13;</code>
*/
public boolean hasEconomySupportSupervisor() {
return ((bitField0_ & 0x00001000) == 0x00001000);
}
/**
* <code>optional bool economy_support_supervisor = 13;</code>
*/
public boolean getEconomySupportSupervisor() {
return economySupportSupervisor_;
}
private void initFields() {
editInfo_ = false;
publish_ = false;
viewErrorData_ = false;
download_ = false;
uploadCdkeys_ = false;
generateCdkeys_ = false;
viewFinancials_ = false;
manageCeg_ = false;
manageSigning_ = false;
manageCdkeys_ = false;
editMarketing_ = false;
economySupport_ = false;
economySupportSupervisor_ = false;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBool(1, editInfo_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBool(2, publish_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeBool(3, viewErrorData_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeBool(4, download_);
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
output.writeBool(5, uploadCdkeys_);
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
output.writeBool(6, generateCdkeys_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
output.writeBool(7, viewFinancials_);
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
output.writeBool(8, manageCeg_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
output.writeBool(9, manageSigning_);
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
output.writeBool(10, manageCdkeys_);
}
if (((bitField0_ & 0x00000400) == 0x00000400)) {
output.writeBool(11, editMarketing_);
}
if (((bitField0_ & 0x00000800) == 0x00000800)) {
output.writeBool(12, economySupport_);
}
if (((bitField0_ & 0x00001000) == 0x00001000)) {
output.writeBool(13, economySupportSupervisor_);
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(1, editInfo_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(2, publish_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(3, viewErrorData_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(4, download_);
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(5, uploadCdkeys_);
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(6, generateCdkeys_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(7, viewFinancials_);
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(8, manageCeg_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(9, manageSigning_);
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(10, manageCdkeys_);
}
if (((bitField0_ & 0x00000400) == 0x00000400)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(11, editMarketing_);
}
if (((bitField0_ & 0x00000800) == 0x00000800)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(12, economySupport_);
}
if (((bitField0_ & 0x00001000) == 0x00001000)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(13, economySupportSupervisor_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code CMsgAppRights}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRightsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgAppRights_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgAppRights_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights.class, com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights.Builder.class);
}
// Construct using com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
editInfo_ = false;
bitField0_ = (bitField0_ & ~0x00000001);
publish_ = false;
bitField0_ = (bitField0_ & ~0x00000002);
viewErrorData_ = false;
bitField0_ = (bitField0_ & ~0x00000004);
download_ = false;
bitField0_ = (bitField0_ & ~0x00000008);
uploadCdkeys_ = false;
bitField0_ = (bitField0_ & ~0x00000010);
generateCdkeys_ = false;
bitField0_ = (bitField0_ & ~0x00000020);
viewFinancials_ = false;
bitField0_ = (bitField0_ & ~0x00000040);
manageCeg_ = false;
bitField0_ = (bitField0_ & ~0x00000080);
manageSigning_ = false;
bitField0_ = (bitField0_ & ~0x00000100);
manageCdkeys_ = false;
bitField0_ = (bitField0_ & ~0x00000200);
editMarketing_ = false;
bitField0_ = (bitField0_ & ~0x00000400);
economySupport_ = false;
bitField0_ = (bitField0_ & ~0x00000800);
economySupportSupervisor_ = false;
bitField0_ = (bitField0_ & ~0x00001000);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.internal_static_CMsgAppRights_descriptor;
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights getDefaultInstanceForType() {
return com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights.getDefaultInstance();
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights build() {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights buildPartial() {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights result = new com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.editInfo_ = editInfo_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.publish_ = publish_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.viewErrorData_ = viewErrorData_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
result.download_ = download_;
if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
to_bitField0_ |= 0x00000010;
}
result.uploadCdkeys_ = uploadCdkeys_;
if (((from_bitField0_ & 0x00000020) == 0x00000020)) {
to_bitField0_ |= 0x00000020;
}
result.generateCdkeys_ = generateCdkeys_;
if (((from_bitField0_ & 0x00000040) == 0x00000040)) {
to_bitField0_ |= 0x00000040;
}
result.viewFinancials_ = viewFinancials_;
if (((from_bitField0_ & 0x00000080) == 0x00000080)) {
to_bitField0_ |= 0x00000080;
}
result.manageCeg_ = manageCeg_;
if (((from_bitField0_ & 0x00000100) == 0x00000100)) {
to_bitField0_ |= 0x00000100;
}
result.manageSigning_ = manageSigning_;
if (((from_bitField0_ & 0x00000200) == 0x00000200)) {
to_bitField0_ |= 0x00000200;
}
result.manageCdkeys_ = manageCdkeys_;
if (((from_bitField0_ & 0x00000400) == 0x00000400)) {
to_bitField0_ |= 0x00000400;
}
result.editMarketing_ = editMarketing_;
if (((from_bitField0_ & 0x00000800) == 0x00000800)) {
to_bitField0_ |= 0x00000800;
}
result.economySupport_ = economySupport_;
if (((from_bitField0_ & 0x00001000) == 0x00001000)) {
to_bitField0_ |= 0x00001000;
}
result.economySupportSupervisor_ = economySupportSupervisor_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights) {
return mergeFrom((com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights other) {
if (other == com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights.getDefaultInstance()) return this;
if (other.hasEditInfo()) {
setEditInfo(other.getEditInfo());
}
if (other.hasPublish()) {
setPublish(other.getPublish());
}
if (other.hasViewErrorData()) {
setViewErrorData(other.getViewErrorData());
}
if (other.hasDownload()) {
setDownload(other.getDownload());
}
if (other.hasUploadCdkeys()) {
setUploadCdkeys(other.getUploadCdkeys());
}
if (other.hasGenerateCdkeys()) {
setGenerateCdkeys(other.getGenerateCdkeys());
}
if (other.hasViewFinancials()) {
setViewFinancials(other.getViewFinancials());
}
if (other.hasManageCeg()) {
setManageCeg(other.getManageCeg());
}
if (other.hasManageSigning()) {
setManageSigning(other.getManageSigning());
}
if (other.hasManageCdkeys()) {
setManageCdkeys(other.getManageCdkeys());
}
if (other.hasEditMarketing()) {
setEditMarketing(other.getEditMarketing());
}
if (other.hasEconomySupport()) {
setEconomySupport(other.getEconomySupport());
}
if (other.hasEconomySupportSupervisor()) {
setEconomySupportSupervisor(other.getEconomySupportSupervisor());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.kevelbreh.steamchat.steam.proto.SteamMessagesBaseProto.CMsgAppRights) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
// optional bool edit_info = 1;
private boolean editInfo_ ;
/**
* <code>optional bool edit_info = 1;</code>
*/
public boolean hasEditInfo() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional bool edit_info = 1;</code>
*/
public boolean getEditInfo() {
return editInfo_;
}
/**
* <code>optional bool edit_info = 1;</code>
*/
public Builder setEditInfo(boolean value) {
bitField0_ |= 0x00000001;
editInfo_ = value;
onChanged();
return this;
}
/**
* <code>optional bool edit_info = 1;</code>
*/
public Builder clearEditInfo() {
bitField0_ = (bitField0_ & ~0x00000001);
editInfo_ = false;
onChanged();
return this;
}
// optional bool publish = 2;
private boolean publish_ ;
/**
* <code>optional bool publish = 2;</code>
*/
public boolean hasPublish() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional bool publish = 2;</code>
*/
public boolean getPublish() {
return publish_;
}
/**
* <code>optional bool publish = 2;</code>
*/
public Builder setPublish(boolean value) {
bitField0_ |= 0x00000002;
publish_ = value;
onChanged();
return this;
}
/**
* <code>optional bool publish = 2;</code>
*/
public Builder clearPublish() {
bitField0_ = (bitField0_ & ~0x00000002);
publish_ = false;
onChanged();
return this;
}
// optional bool view_error_data = 3;
private boolean viewErrorData_ ;
/**
* <code>optional bool view_error_data = 3;</code>
*/
public boolean hasViewErrorData() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional bool view_error_data = 3;</code>
*/
public boolean getViewErrorData() {
return viewErrorData_;
}
/**
* <code>optional bool view_error_data = 3;</code>
*/
public Builder setViewErrorData(boolean value) {
bitField0_ |= 0x00000004;
viewErrorData_ = value;
onChanged();
return this;
}
/**
* <code>optional bool view_error_data = 3;</code>
*/
public Builder clearViewErrorData() {
bitField0_ = (bitField0_ & ~0x00000004);
viewErrorData_ = false;
onChanged();
return this;
}
// optional bool download = 4;
private boolean download_ ;
/**
* <code>optional bool download = 4;</code>
*/
public boolean hasDownload() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional bool download = 4;</code>
*/
public boolean getDownload() {
return download_;
}
/**
* <code>optional bool download = 4;</code>
*/
public Builder setDownload(boolean value) {
bitField0_ |= 0x00000008;
download_ = value;
onChanged();
return this;
}
/**
* <code>optional bool download = 4;</code>
*/
public Builder clearDownload() {
bitField0_ = (bitField0_ & ~0x00000008);
download_ = false;
onChanged();
return this;
}
// optional bool upload_cdkeys = 5;
private boolean uploadCdkeys_ ;
/**
* <code>optional bool upload_cdkeys = 5;</code>
*/
public boolean hasUploadCdkeys() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>optional bool upload_cdkeys = 5;</code>
*/
public boolean getUploadCdkeys() {
return uploadCdkeys_;
}
/**
* <code>optional bool upload_cdkeys = 5;</code>
*/
public Builder setUploadCdkeys(boolean value) {
bitField0_ |= 0x00000010;
uploadCdkeys_ = value;
onChanged();
return this;
}
/**
* <code>optional bool upload_cdkeys = 5;</code>
*/
public Builder clearUploadCdkeys() {
bitField0_ = (bitField0_ & ~0x00000010);
uploadCdkeys_ = false;
onChanged();
return this;
}
// optional bool generate_cdkeys = 6;
private boolean generateCdkeys_ ;
/**
* <code>optional bool generate_cdkeys = 6;</code>
*/
public boolean hasGenerateCdkeys() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>optional bool generate_cdkeys = 6;</code>
*/
public boolean getGenerateCdkeys() {
return generateCdkeys_;
}
/**
* <code>optional bool generate_cdkeys = 6;</code>
*/
public Builder setGenerateCdkeys(boolean value) {
bitField0_ |= 0x00000020;
generateCdkeys_ = value;
onChanged();
return this;
}
/**
* <code>optional bool generate_cdkeys = 6;</code>
*/
public Builder clearGenerateCdkeys() {
bitField0_ = (bitField0_ & ~0x00000020);
generateCdkeys_ = false;
onChanged();
return this;
}
// optional bool view_financials = 7;
private boolean viewFinancials_ ;
/**
* <code>optional bool view_financials = 7;</code>
*/
public boolean hasViewFinancials() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>optional bool view_financials = 7;</code>
*/
public boolean getViewFinancials() {
return viewFinancials_;
}
/**
* <code>optional bool view_financials = 7;</code>
*/
public Builder setViewFinancials(boolean value) {
bitField0_ |= 0x00000040;
viewFinancials_ = value;
onChanged();
return this;
}
/**
* <code>optional bool view_financials = 7;</code>
*/
public Builder clearViewFinancials() {
bitField0_ = (bitField0_ & ~0x00000040);
viewFinancials_ = false;
onChanged();
return this;
}
// optional bool manage_ceg = 8;
private boolean manageCeg_ ;
/**
* <code>optional bool manage_ceg = 8;</code>
*/
public boolean hasManageCeg() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
/**
* <code>optional bool manage_ceg = 8;</code>
*/
public boolean getManageCeg() {
return manageCeg_;
}
/**
* <code>optional bool manage_ceg = 8;</code>
*/
public Builder setManageCeg(boolean value) {
bitField0_ |= 0x00000080;
manageCeg_ = value;
onChanged();
return this;
}
/**
* <code>optional bool manage_ceg = 8;</code>
*/
public Builder clearManageCeg() {
bitField0_ = (bitField0_ & ~0x00000080);
manageCeg_ = false;
onChanged();
return this;
}
// optional bool manage_signing = 9;
private boolean manageSigning_ ;
/**
* <code>optional bool manage_signing = 9;</code>
*/
public boolean hasManageSigning() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
/**
* <code>optional bool manage_signing = 9;</code>
*/
public boolean getManageSigning() {
return manageSigning_;
}
/**
* <code>optional bool manage_signing = 9;</code>
*/
public Builder setManageSigning(boolean value) {
bitField0_ |= 0x00000100;
manageSigning_ = value;
onChanged();
return this;
}
/**
* <code>optional bool manage_signing = 9;</code>
*/
public Builder clearManageSigning() {
bitField0_ = (bitField0_ & ~0x00000100);
manageSigning_ = false;
onChanged();
return this;
}
// optional bool manage_cdkeys = 10;
private boolean manageCdkeys_ ;
/**
* <code>optional bool manage_cdkeys = 10;</code>
*/
public boolean hasManageCdkeys() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
/**
* <code>optional bool manage_cdkeys = 10;</code>
*/
public boolean getManageCdkeys() {
return manageCdkeys_;
}
/**
* <code>optional bool manage_cdkeys = 10;</code>
*/
public Builder setManageCdkeys(boolean value) {
bitField0_ |= 0x00000200;
manageCdkeys_ = value;
onChanged();
return this;
}
/**
* <code>optional bool manage_cdkeys = 10;</code>
*/
public Builder clearManageCdkeys() {
bitField0_ = (bitField0_ & ~0x00000200);
manageCdkeys_ = false;
onChanged();
return this;
}
// optional bool edit_marketing = 11;
private boolean editMarketing_ ;
/**
* <code>optional bool edit_marketing = 11;</code>
*/
public boolean hasEditMarketing() {
return ((bitField0_ & 0x00000400) == 0x00000400);
}
/**
* <code>optional bool edit_marketing = 11;</code>
*/
public boolean getEditMarketing() {
return editMarketing_;
}
/**
* <code>optional bool edit_marketing = 11;</code>
*/
public Builder setEditMarketing(boolean value) {
bitField0_ |= 0x00000400;
editMarketing_ = value;
onChanged();
return this;
}
/**
* <code>optional bool edit_marketing = 11;</code>
*/
public Builder clearEditMarketing() {
bitField0_ = (bitField0_ & ~0x00000400);
editMarketing_ = false;
onChanged();
return this;
}
// optional bool economy_support = 12;
private boolean economySupport_ ;
/**
* <code>optional bool economy_support = 12;</code>
*/
public boolean hasEconomySupport() {
return ((bitField0_ & 0x00000800) == 0x00000800);
}
/**
* <code>optional bool economy_support = 12;</code>
*/
public boolean getEconomySupport() {
return economySupport_;
}
/**
* <code>optional bool economy_support = 12;</code>
*/
public Builder setEconomySupport(boolean value) {
bitField0_ |= 0x00000800;
economySupport_ = value;
onChanged();
return this;
}
/**
* <code>optional bool economy_support = 12;</code>
*/
public Builder clearEconomySupport() {
bitField0_ = (bitField0_ & ~0x00000800);
economySupport_ = false;
onChanged();
return this;
}
// optional bool economy_support_supervisor = 13;
private boolean economySupportSupervisor_ ;
/**
* <code>optional bool economy_support_supervisor = 13;</code>
*/
public boolean hasEconomySupportSupervisor() {
return ((bitField0_ & 0x00001000) == 0x00001000);
}
/**
* <code>optional bool economy_support_supervisor = 13;</code>
*/
public boolean getEconomySupportSupervisor() {
return economySupportSupervisor_;
}
/**
* <code>optional bool economy_support_supervisor = 13;</code>
*/
public Builder setEconomySupportSupervisor(boolean value) {
bitField0_ |= 0x00001000;
economySupportSupervisor_ = value;
onChanged();
return this;
}
/**
* <code>optional bool economy_support_supervisor = 13;</code>
*/
public Builder clearEconomySupportSupervisor() {
bitField0_ = (bitField0_ & ~0x00001000);
economySupportSupervisor_ = false;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:CMsgAppRights)
}
static {
defaultInstance = new CMsgAppRights(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:CMsgAppRights)
}
public static final int MSGPOOL_SOFT_LIMIT_FIELD_NUMBER = 50000;
/**
* <code>extend .google.protobuf.MessageOptions { ... }</code>
*/
public static final
com.google.protobuf.GeneratedMessage.GeneratedExtension<
com.kevelbreh.steamchat.steam.proto.DescriptorsProto.MessageOptions,
java.lang.Integer> msgpoolSoftLimit = com.google.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int MSGPOOL_HARD_LIMIT_FIELD_NUMBER = 50001;
/**
* <code>extend .google.protobuf.MessageOptions { ... }</code>
*/
public static final
com.google.protobuf.GeneratedMessage.GeneratedExtension<
com.kevelbreh.steamchat.steam.proto.DescriptorsProto.MessageOptions,
java.lang.Integer> msgpoolHardLimit = com.google.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
private static com.google.protobuf.Descriptors.Descriptor
internal_static_CMsgProtoBufHeader_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_CMsgProtoBufHeader_fieldAccessorTable;
private static com.google.protobuf.Descriptors.Descriptor
internal_static_CMsgMulti_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_CMsgMulti_fieldAccessorTable;
private static com.google.protobuf.Descriptors.Descriptor
internal_static_CMsgProtobufWrapped_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_CMsgProtobufWrapped_fieldAccessorTable;
private static com.google.protobuf.Descriptors.Descriptor
internal_static_CMsgAuthTicket_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_CMsgAuthTicket_fieldAccessorTable;
private static com.google.protobuf.Descriptors.Descriptor
internal_static_CCDDBAppDetailCommon_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_CCDDBAppDetailCommon_fieldAccessorTable;
private static com.google.protobuf.Descriptors.Descriptor
internal_static_CMsgAppRights_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_CMsgAppRights_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\030steammessages_base.proto\032\020descriptor.p" +
"roto\"\341\003\n\022CMsgProtoBufHeader\022\017\n\007steamid\030\001" +
" \001(\006\022\030\n\020client_sessionid\030\002 \001(\005\022\025\n\rroutin" +
"g_appid\030\003 \001(\r\022*\n\014jobid_source\030\n \001(\006:\024184" +
"46744073709551615\022*\n\014jobid_target\030\013 \001(\006:" +
"\02418446744073709551615\022\027\n\017target_job_name" +
"\030\014 \001(\t\022\017\n\007seq_num\030\030 \001(\005\022\022\n\007eresult\030\r \001(\005" +
":\0012\022\025\n\rerror_message\030\016 \001(\t\022\n\n\002ip\030\017 \001(\r\022\032" +
"\n\022auth_account_flags\030\020 \001(\r\022\024\n\014token_sour" +
"ce\030\026 \001(\r\022\033\n\023admin_spoofing_user\030\027 \001(\010\022\032\n",
"\017transport_error\030\021 \001(\005:\0011\022\'\n\tmessageid\030\022" +
" \001(\004:\02418446744073709551615\022\032\n\022publisher_" +
"group_id\030\023 \001(\r\022\r\n\005sysid\030\024 \001(\r\022\021\n\ttrace_t" +
"ag\030\025 \001(\004\"8\n\tCMsgMulti\022\025\n\rsize_unzipped\030\001" +
" \001(\r\022\024\n\014message_body\030\002 \001(\014\"+\n\023CMsgProtob" +
"ufWrapped\022\024\n\014message_body\030\001 \001(\014\"\217\001\n\016CMsg" +
"AuthTicket\022\016\n\006estate\030\001 \001(\r\022\022\n\007eresult\030\002 " +
"\001(\r:\0012\022\017\n\007steamid\030\003 \001(\006\022\016\n\006gameid\030\004 \001(\006\022" +
"\024\n\014h_steam_pipe\030\005 \001(\r\022\022\n\nticket_crc\030\006 \001(" +
"\r\022\016\n\006ticket\030\007 \001(\014\"\366\001\n\024CCDDBAppDetailComm",
"on\022\r\n\005appid\030\001 \001(\r\022\014\n\004name\030\002 \001(\t\022\014\n\004icon\030" +
"\003 \001(\t\022\014\n\004logo\030\004 \001(\t\022\022\n\nlogo_small\030\005 \001(\t\022" +
"\014\n\004tool\030\006 \001(\010\022\014\n\004demo\030\007 \001(\010\022\r\n\005media\030\010 \001" +
"(\010\022\037\n\027community_visible_stats\030\t \001(\010\022\025\n\rf" +
"riendly_name\030\n \001(\t\022\023\n\013propagation\030\013 \001(\t\022" +
"\031\n\021has_adult_content\030\014 \001(\010\"\277\002\n\rCMsgAppRi" +
"ghts\022\021\n\tedit_info\030\001 \001(\010\022\017\n\007publish\030\002 \001(\010" +
"\022\027\n\017view_error_data\030\003 \001(\010\022\020\n\010download\030\004 " +
"\001(\010\022\025\n\rupload_cdkeys\030\005 \001(\010\022\027\n\017generate_c" +
"dkeys\030\006 \001(\010\022\027\n\017view_financials\030\007 \001(\010\022\022\n\n",
"manage_ceg\030\010 \001(\010\022\026\n\016manage_signing\030\t \001(\010" +
"\022\025\n\rmanage_cdkeys\030\n \001(\010\022\026\n\016edit_marketin" +
"g\030\013 \001(\010\022\027\n\017economy_support\030\014 \001(\010\022\"\n\032econ" +
"omy_support_supervisor\030\r \001(\010:A\n\022msgpool_" +
"soft_limit\022\037.google.protobuf.MessageOpti" +
"ons\030\320\206\003 \001(\005:\00232:B\n\022msgpool_hard_limit\022\037." +
"google.protobuf.MessageOptions\030\321\206\003 \001(\005:\003" +
"384B=\n#com.kevelbreh.steamchat.steam.pro" +
"toB\026SteamMessagesBaseProto"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
internal_static_CMsgProtoBufHeader_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_CMsgProtoBufHeader_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_CMsgProtoBufHeader_descriptor,
new java.lang.String[] { "Steamid", "ClientSessionid", "RoutingAppid", "JobidSource", "JobidTarget", "TargetJobName", "SeqNum", "Eresult", "ErrorMessage", "Ip", "AuthAccountFlags", "TokenSource", "AdminSpoofingUser", "TransportError", "Messageid", "PublisherGroupId", "Sysid", "TraceTag", });
internal_static_CMsgMulti_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_CMsgMulti_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_CMsgMulti_descriptor,
new java.lang.String[] { "SizeUnzipped", "MessageBody", });
internal_static_CMsgProtobufWrapped_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_CMsgProtobufWrapped_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_CMsgProtobufWrapped_descriptor,
new java.lang.String[] { "MessageBody", });
internal_static_CMsgAuthTicket_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_CMsgAuthTicket_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_CMsgAuthTicket_descriptor,
new java.lang.String[] { "Estate", "Eresult", "Steamid", "Gameid", "HSteamPipe", "TicketCrc", "Ticket", });
internal_static_CCDDBAppDetailCommon_descriptor =
getDescriptor().getMessageTypes().get(4);
internal_static_CCDDBAppDetailCommon_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_CCDDBAppDetailCommon_descriptor,
new java.lang.String[] { "Appid", "Name", "Icon", "Logo", "LogoSmall", "Tool", "Demo", "Media", "CommunityVisibleStats", "FriendlyName", "Propagation", "HasAdultContent", });
internal_static_CMsgAppRights_descriptor =
getDescriptor().getMessageTypes().get(5);
internal_static_CMsgAppRights_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_CMsgAppRights_descriptor,
new java.lang.String[] { "EditInfo", "Publish", "ViewErrorData", "Download", "UploadCdkeys", "GenerateCdkeys", "ViewFinancials", "ManageCeg", "ManageSigning", "ManageCdkeys", "EditMarketing", "EconomySupport", "EconomySupportSupervisor", });
msgpoolSoftLimit.internalInit(descriptor.getExtensions().get(0));
msgpoolHardLimit.internalInit(descriptor.getExtensions().get(1));
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.kevelbreh.steamchat.steam.proto.DescriptorsProto.getDescriptor(),
}, assigner);
}
// @@protoc_insertion_point(outer_class_scope)
}
| apache-2.0 |
zzsoszz/unicomweb | src/com/tdt/unicom/domains/BindResp.java | 1382 | package com.tdt.unicom.domains;
/**
* @project UNICOM
* @author sunnylocus
* @vresion 1.0 2009-8-4
* @description bindÃüÁî·µ»ØÌå
*/
public class BindResp extends SGIPCommand {
private byte result; //0±íʾִÐгɹ¦
private String reserve="";
public BindResp(byte[] unicomSN) {
this.header = new SGIPHeader(SGIPCommandDefine.SGIP_BIND_RESP);
this.header.setUnicomSN(unicomSN);
this.bodybytes = new byte[SGIPCommandDefine.LEN_SGIP_BIND_RESP];
//-------------------------------------------
byte[] reserveByte = new byte[8];
System.arraycopy(this.reserve.getBytes(), 0, reserveByte, 0, this.reserve.length());
System.arraycopy(reserveByte, 0, this.bodybytes,1, 8);
}
public BindResp(SGIPCommand command) {
this.header = command.header;
this.bodybytes = command.bodybytes;
//--------------------------------------------
result =command.bodybytes[0];
//--------------------------------------------
byte[] reserveBytes = new byte[8];
System.arraycopy(command.bodybytes, 1, reserveBytes, 0, 8);
reserve = new String(reserveBytes);
//--------------------------------------------
}
public int getResult() {
return result;
}
public String getReserve() {
return reserve;
}
public void setResult(byte result) {
this.result = result;
this.bodybytes[0] =result;
}
public void setReserve(String reserve) {
this.reserve = reserve;
}
}
| apache-2.0 |
lazycrafter/craft-route-android | app/src/main/java/org/lazycrafter/craftroute/app/ui/main/RibotsAdapter.java | 1960 | package org.lazycrafter.craftroute.app.ui.main;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import org.lazycrafter.craftroute.app.R;
import org.lazycrafter.craftroute.app.data.model.Ribot;
public class RibotsAdapter extends RecyclerView.Adapter<RibotsAdapter.RibotViewHolder> {
private List<Ribot> mRibots;
@Inject
public RibotsAdapter() {
mRibots = new ArrayList<>();
}
public void setRibots(List<Ribot> ribots) {
mRibots = ribots;
}
@Override
public RibotViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_ribot, parent, false);
return new RibotViewHolder(itemView);
}
@Override
public void onBindViewHolder(final RibotViewHolder holder, int position) {
Ribot ribot = mRibots.get(position);
holder.hexColorView.setBackgroundColor(Color.parseColor(ribot.profile().hexColor()));
holder.nameTextView.setText(String.format("%s %s",
ribot.profile().name().first(), ribot.profile().name().last()));
holder.emailTextView.setText(ribot.profile().email());
}
@Override
public int getItemCount() {
return mRibots.size();
}
class RibotViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.view_hex_color) View hexColorView;
@BindView(R.id.text_name) TextView nameTextView;
@BindView(R.id.text_email) TextView emailTextView;
public RibotViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
| apache-2.0 |
ringo/ringojs | src/org/ringojs/repository/WebappResource.java | 2194 | package org.ringojs.repository;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.Charset;
public class WebappResource extends AbstractResource {
final ServletContext context;
private int exists = -1;
protected WebappResource(ServletContext context, WebappRepository repository, String name) {
this.context = context;
this.repository = repository;
this.name = name;
this.path = repository.path + name;
setBaseNameFromName(name);
}
public long lastModified() {
try {
String realPath = context.getRealPath(path);
return realPath == null ? 0 : new File(realPath).lastModified();
} catch (Exception x) {
return 0;
}
}
public boolean exists() throws IOException{
if (exists < 0) {
try {
URL url = context.getResource(path);
if (url != null && url.getProtocol().equals("file")) {
String enc = Charset.defaultCharset().name();
String path = URLDecoder.decode(url.getPath(), enc);
exists = new File(path).isFile() ? 1 : 0;
} else {
exists = url != null ? 1 : 0;
}
} catch (MalformedURLException mux) {
exists = 0;
}
}
return exists == 1;
}
public long getLength() {
return 0;
}
public InputStream getInputStream() throws IOException {
return stripShebang(context.getResourceAsStream(path));
}
public URL getUrl() throws MalformedURLException {
return context.getResource(path);
}
@Override
public String toString() {
return "WebappResource[" + path + "]";
}
@Override
public int hashCode() {
return 37 + path.hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof WebappResource && path.equals(((WebappResource)obj).path);
}
}
| apache-2.0 |
diennea/herddb | herddb-core/src/main/java/herddb/core/DBManager.java | 71393 | /*
Licensed to Diennea S.r.l. under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Diennea S.r.l. 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 herddb.core;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.util.concurrent.MoreExecutors;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import herddb.client.ClientConfiguration;
import herddb.core.stats.ConnectionsInfoProvider;
import herddb.file.FileMetadataStorageManager;
import herddb.jmx.DBManagerStatsMXBean;
import herddb.jmx.JMXUtils;
import herddb.log.CommitLog;
import herddb.log.CommitLogManager;
import herddb.log.LogNotAvailableException;
import herddb.log.LogSequenceNumber;
import herddb.mem.MemoryMetadataStorageManager;
import herddb.metadata.MetadataChangeListener;
import herddb.metadata.MetadataStorageManager;
import herddb.metadata.MetadataStorageManagerException;
import herddb.model.DDLException;
import herddb.model.DDLStatement;
import herddb.model.DDLStatementExecutionResult;
import herddb.model.DMLStatement;
import herddb.model.DMLStatementExecutionResult;
import herddb.model.DataConsistencyStatementResult;
import herddb.model.DataScanner;
import herddb.model.DataScannerException;
import herddb.model.ExecutionPlan;
import herddb.model.GetResult;
import herddb.model.NodeMetadata;
import herddb.model.NotLeaderException;
import herddb.model.ScanResult;
import herddb.model.Statement;
import herddb.model.StatementEvaluationContext;
import herddb.model.StatementExecutionException;
import herddb.model.StatementExecutionResult;
import herddb.model.Table;
import herddb.model.TableSpace;
import herddb.model.TableSpaceDoesNotExistException;
import herddb.model.TableSpaceReplicaState;
import herddb.model.TransactionContext;
import herddb.model.commands.AlterTableSpaceStatement;
import herddb.model.commands.CreateTableSpaceStatement;
import herddb.model.commands.DropTableSpaceStatement;
import herddb.model.commands.GetStatement;
import herddb.model.commands.ScanStatement;
import herddb.model.commands.TableConsistencyCheckStatement;
import herddb.model.commands.TableSpaceConsistencyCheckStatement;
import herddb.network.Channel;
import herddb.network.ServerHostData;
import herddb.proto.Pdu;
import herddb.proto.PduCodec;
import herddb.server.ServerConfiguration;
import herddb.server.ServerSidePreparedStatementCache;
import herddb.sql.AbstractSQLPlanner;
import herddb.sql.CalcitePlanner;
import herddb.sql.JSQLParserPlanner;
import herddb.sql.NullSQLPlanner;
import herddb.sql.PlansCache;
import herddb.sql.TranslatedQuery;
import herddb.storage.DataStorageManager;
import herddb.storage.DataStorageManagerException;
import herddb.utils.DefaultJVMHalt;
import herddb.utils.Futures;
import io.netty.buffer.ByteBuf;
import io.netty.util.concurrent.FastThreadLocalThread;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.apache.bookkeeper.stats.NullStatsLogger;
import org.apache.bookkeeper.stats.StatsLogger;
/**
* General Manager of the local instance of HerdDB
*
* @author enrico.olivelli
*/
public class DBManager implements AutoCloseable, MetadataChangeListener {
private static final Logger LOGGER = Logger.getLogger(DBManager.class.getName());
private final Map<String, TableSpaceManager> tablesSpaces = new ConcurrentHashMap<>();
private final MetadataStorageManager metadataStorageManager;
private final DataStorageManager dataStorageManager;
private final CommitLogManager commitLogManager;
private final String nodeId;
private final String virtualTableSpaceId;
private final ReentrantReadWriteLock generalLock = new ReentrantReadWriteLock();
private final Thread activator;
private final Activator activatorJ;
private final AtomicBoolean stopped = new AtomicBoolean();
private final ExecutorService callbacksExecutor;
private final AbstractSQLPlanner planner;
private final ServerSidePreparedStatementCache preparedStatementsCache;
private final Path tmpDirectory;
private final RecordSetFactory recordSetFactory;
private MemoryManager memoryManager;
private final ServerHostData hostData;
private String serverToServerUsername = ClientConfiguration.PROPERTY_CLIENT_USERNAME_DEFAULT;
private String serverToServerPassword = ClientConfiguration.PROPERTY_CLIENT_PASSWORD_DEFAULT;
private boolean errorIfNotLeader = true;
private final ServerConfiguration serverConfiguration;
private final String mode;
private ConnectionsInfoProvider connectionsInfoProvider;
private long checkpointPeriod;
private long abandonedTransactionsTimeout;
private final StatsLogger mainStatsLogger;
private long maxMemoryReference = ServerConfiguration.PROPERTY_MEMORY_LIMIT_REFERENCE_DEFAULT;
private long maxLogicalPageSize = ServerConfiguration.PROPERTY_MAX_LOGICAL_PAGE_SIZE_DEFAULT;
private long maxDataUsedMemory = ServerConfiguration.PROPERTY_MAX_DATA_MEMORY_DEFAULT;
private long maxIndexUsedMemory = ServerConfiguration.PROPERTY_MAX_INDEX_MEMORY_DEFAULT;
private long maxPKUsedMemory = ServerConfiguration.PROPERTY_MAX_PK_MEMORY_DEFAULT;
private double maxDataUsedMemoryPercentage = ServerConfiguration.PROPERTY_MAX_DATA_MEMORY_PERCENTAGE_DEFAULT;
private double maxIndexUsedMemoryPercentage = ServerConfiguration.PROPERTY_MAX_INDEX_MEMORY_PERCENTAGE_DEFAULT;
private double maxPKUsedMemoryPercentage = ServerConfiguration.PROPERTY_MAX_PK_MEMORY_PERCENTAGE_DEFAULT;
private boolean clearAtBoot = false;
private boolean haltOnTableSpaceBootError = ServerConfiguration.PROPERTY_HALT_ON_TABLESPACE_BOOT_ERROR_DEAULT;
private Runnable haltProcedure = DefaultJVMHalt.INSTANCE;
private final AtomicLong lastCheckPointTs = new AtomicLong(System.currentTimeMillis());
private final RunningStatementsStats runningStatements;
private final ExecutorService followersThreadPool;
public DBManager(
String nodeId, MetadataStorageManager metadataStorageManager, DataStorageManager dataStorageManager,
CommitLogManager commitLogManager, Path tmpDirectory, herddb.network.ServerHostData hostData
) {
this(nodeId, metadataStorageManager, dataStorageManager, commitLogManager, tmpDirectory, hostData, new ServerConfiguration(),
null);
}
public DBManager(
String nodeId, MetadataStorageManager metadataStorageManager, DataStorageManager dataStorageManager,
CommitLogManager commitLogManager, Path tmpDirectory, herddb.network.ServerHostData hostData, ServerConfiguration configuration,
StatsLogger statsLogger
) {
this.serverConfiguration = configuration;
this.mode = serverConfiguration.getString(ServerConfiguration.PROPERTY_MODE, ServerConfiguration.PROPERTY_MODE_STANDALONE);
this.tmpDirectory = tmpDirectory;
int asyncWorkerThreads = configuration.getInt(ServerConfiguration.PROPERTY_ASYNC_WORKER_THREADS,
ServerConfiguration.PROPERTY_ASYNC_WORKER_THREADS_DEFAULT);
if (asyncWorkerThreads <= 0) {
// use this only for tests on in HerdDB Collections framework
// without a threadpool every statement will be executed
// on any system thread (Netty, BookKeeper...).
this.callbacksExecutor = MoreExecutors.newDirectExecutorService();
} else {
this.callbacksExecutor = Executors.newFixedThreadPool(asyncWorkerThreads, new ThreadFactory() {
private final AtomicLong count = new AtomicLong();
@Override
public Thread newThread(final Runnable r) {
final String marker = hostData == null ? "local" : hostData.getHost() + ":" + hostData.getPort();
return new FastThreadLocalThread(r, "db-dmlcall-" + marker + "-" + count.incrementAndGet());
}
});
}
// todo: make it configurable, cached have some pitfalls under load
this.followersThreadPool = Executors.newCachedThreadPool((Runnable r) -> new FastThreadLocalThread(
r, "herddb-worker-" + (hostData == null ? "local" : hostData.getHost() + ":" + hostData.getPort()) + "-" + r));
this.recordSetFactory = dataStorageManager.createRecordSetFactory();
this.metadataStorageManager = metadataStorageManager;
this.dataStorageManager = dataStorageManager;
this.commitLogManager = commitLogManager;
if (statsLogger == null) {
this.mainStatsLogger = NullStatsLogger.INSTANCE;
} else {
this.mainStatsLogger = statsLogger;
}
this.runningStatements = new RunningStatementsStats(this.mainStatsLogger);
this.nodeId = nodeId;
this.virtualTableSpaceId = makeVirtualTableSpaceManagerId(nodeId);
this.hostData = hostData != null ? hostData : new ServerHostData("localhost", 7000, "", false, new HashMap<>());
long planCacheMem = configuration.getLong(ServerConfiguration.PROPERTY_PLANSCACHE_MAXMEMORY,
ServerConfiguration.PROPERTY_PLANSCACHE_MAXMEMORY_DEFAULT);
long statementsMem = configuration.getLong(ServerConfiguration.PROPERTY_STATEMENTSCACHE_MAXMEMORY,
ServerConfiguration.PROPERTY_STATEMENTSCACHE_MAXMEMORY_DEFAULT);
preparedStatementsCache = new ServerSidePreparedStatementCache(statementsMem);
String plannerType = serverConfiguration.getString(ServerConfiguration.PROPERTY_PLANNER_TYPE,
ServerConfiguration.PROPERTY_PLANNER_TYPE_DEFAULT);
PlansCache plansCache = new PlansCache(planCacheMem);
switch (plannerType) {
case ServerConfiguration.PLANNER_TYPE_CALCITE:
planner = new CalcitePlanner(this, plansCache);
break;
case ServerConfiguration.PLANNER_TYPE_JSQLPARSER:
// no Calcite fallback, you can drop Calcite dependecy
planner = new JSQLParserPlanner(this, plansCache, null);
break;
case ServerConfiguration.PLANNER_TYPE_AUTO:
// try with jSQLParser, fallback to Calcite
planner = new JSQLParserPlanner(this, plansCache,
new CalcitePlanner(this, plansCache));
break;
case ServerConfiguration.PLANNER_TYPE_NONE:
planner = new NullSQLPlanner(this);
break;
default:
throw new IllegalArgumentException("invalid planner type " + plannerType);
}
this.activatorJ = new Activator();
this.activator = new Thread(activatorJ, "hdb-" + nodeId + "-activator");
this.activator.setDaemon(true);
this.maxMemoryReference = configuration.getLong(
ServerConfiguration.PROPERTY_MEMORY_LIMIT_REFERENCE,
ServerConfiguration.PROPERTY_MEMORY_LIMIT_REFERENCE_DEFAULT);
this.maxLogicalPageSize = configuration.getLong(
ServerConfiguration.PROPERTY_MAX_LOGICAL_PAGE_SIZE,
ServerConfiguration.PROPERTY_MAX_LOGICAL_PAGE_SIZE_DEFAULT);
this.maxDataUsedMemory = configuration.getLong(
ServerConfiguration.PROPERTY_MAX_DATA_MEMORY,
ServerConfiguration.PROPERTY_MAX_DATA_MEMORY_DEFAULT);
this.maxIndexUsedMemory = configuration.getLong(
ServerConfiguration.PROPERTY_MAX_INDEX_MEMORY,
ServerConfiguration.PROPERTY_MAX_INDEX_MEMORY_DEFAULT);
this.maxPKUsedMemory = configuration.getLong(
ServerConfiguration.PROPERTY_MAX_PK_MEMORY,
ServerConfiguration.PROPERTY_MAX_PK_MEMORY_DEFAULT);
this.maxDataUsedMemoryPercentage = configuration.getDouble(
ServerConfiguration.PROPERTY_MAX_DATA_MEMORY_PERCENTAGE,
ServerConfiguration.PROPERTY_MAX_DATA_MEMORY_PERCENTAGE_DEFAULT);
if (maxDataUsedMemoryPercentage <= 0.0D) {
maxDataUsedMemoryPercentage = ServerConfiguration.PROPERTY_MAX_DATA_MEMORY_PERCENTAGE_DEFAULT;
}
this.maxIndexUsedMemoryPercentage = configuration.getDouble(
ServerConfiguration.PROPERTY_MAX_INDEX_MEMORY_PERCENTAGE,
ServerConfiguration.PROPERTY_MAX_INDEX_MEMORY_PERCENTAGE_DEFAULT);
if (maxIndexUsedMemoryPercentage <= 0.0D) {
maxIndexUsedMemoryPercentage = ServerConfiguration.PROPERTY_MAX_DATA_MEMORY_PERCENTAGE_DEFAULT;
}
this.maxPKUsedMemoryPercentage = configuration.getDouble(
ServerConfiguration.PROPERTY_MAX_PK_MEMORY_PERCENTAGE,
ServerConfiguration.PROPERTY_MAX_PK_MEMORY_PERCENTAGE_DEFAULT);
if (maxPKUsedMemoryPercentage <= 0.0D) {
maxPKUsedMemoryPercentage = ServerConfiguration.PROPERTY_MAX_PK_MEMORY_PERCENTAGE_DEFAULT;
}
}
public boolean isHaltOnTableSpaceBootError() {
return haltOnTableSpaceBootError;
}
public void setHaltOnTableSpaceBootError(boolean haltOnTableSpaceBootError) {
this.haltOnTableSpaceBootError = haltOnTableSpaceBootError;
}
public Runnable getHaltProcedure() {
return haltProcedure;
}
public void setHaltProcedure(Runnable haltProcedure) {
this.haltProcedure = haltProcedure;
}
public boolean isErrorIfNotLeader() {
return errorIfNotLeader;
}
public void setErrorIfNotLeader(boolean errorIfNotLeader) {
this.errorIfNotLeader = errorIfNotLeader;
}
public MetadataStorageManager getMetadataStorageManager() {
return metadataStorageManager;
}
public DataStorageManager getDataStorageManager() {
return dataStorageManager;
}
public MemoryManager getMemoryManager() {
return memoryManager;
}
public String getServerToServerUsername() {
return serverToServerUsername;
}
public void setServerToServerUsername(String serverToServerUsername) {
this.serverToServerUsername = serverToServerUsername;
}
public String getServerToServerPassword() {
return serverToServerPassword;
}
public void setServerToServerPassword(String serverToServerPassword) {
this.serverToServerPassword = serverToServerPassword;
}
public ServerConfiguration getServerConfiguration() {
return serverConfiguration;
}
public ConnectionsInfoProvider getConnectionsInfoProvider() {
return connectionsInfoProvider;
}
public void setConnectionsInfoProvider(ConnectionsInfoProvider connectionsInfoProvider) {
this.connectionsInfoProvider = connectionsInfoProvider;
}
public AbstractSQLPlanner getPlanner() {
return planner;
}
public long getMaxMemoryReference() {
return maxMemoryReference;
}
public void setMaxMemoryReference(long maxMemoryReference) {
this.maxMemoryReference = maxMemoryReference;
}
public long getMaxLogicalPageSize() {
return maxLogicalPageSize;
}
public void setMaxLogicalPageSize(long maxLogicalPageSize) {
this.maxLogicalPageSize = maxLogicalPageSize;
}
public long getMaxDataUsedMemory() {
return maxDataUsedMemory;
}
public void setMaxDataUsedMemory(long maxDataUsedMemory) {
this.maxDataUsedMemory = maxDataUsedMemory;
}
public long getMaxIndexUsedMemory() {
return maxIndexUsedMemory;
}
public void setMaxIndexUsedMemory(long maxIndexUsedMemory) {
this.maxIndexUsedMemory = maxIndexUsedMemory;
}
public long getMaxPKUsedMemory() {
return maxPKUsedMemory;
}
public void setMaxPKUsedMemory(long maxPKUsedMemory) {
this.maxPKUsedMemory = maxPKUsedMemory;
}
private final DBManagerStatsMXBean stats = new DBManagerStatsMXBean() {
@Override
public long getCachedPlans() {
return planner.getCacheSize();
}
@Override
public long getCachePlansHits() {
return planner.getCacheHits();
}
@Override
public long getCachePlansMisses() {
return planner.getCacheMisses();
}
};
/**
* Initial boot of the system
*
* @throws herddb.storage.DataStorageManagerException
* @throws herddb.log.LogNotAvailableException
* @throws herddb.metadata.MetadataStorageManagerException
*/
public void start() throws DataStorageManagerException, LogNotAvailableException, MetadataStorageManagerException {
LOGGER.log(Level.FINE, "Starting DBManager at {0}", nodeId);
if (serverConfiguration.getBoolean(ServerConfiguration.PROPERTY_JMX_ENABLE, ServerConfiguration.PROPERTY_JMX_ENABLE_DEFAULT)) {
JMXUtils.registerDBManagerStatsMXBean(stats);
}
final long maxHeap = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax();
/* If max memory isn't configured or is too high default it to maximum heap */
if (maxMemoryReference == 0 || maxMemoryReference > maxHeap) {
maxMemoryReference = maxHeap;
}
LOGGER.log(Level.INFO, ServerConfiguration.PROPERTY_MEMORY_LIMIT_REFERENCE + "= {0} bytes", Long.toString(maxMemoryReference));
/* If max data memory for pages isn't configured or is too high default it to a maxMemoryReference percentage */
if (maxDataUsedMemory == 0 || maxDataUsedMemory > maxMemoryReference) {
maxDataUsedMemory = (long) (maxDataUsedMemoryPercentage * maxMemoryReference);
}
/* If max index memory for pages isn't configured or is too high default it to a maxMemoryReference percentage */
if (maxIndexUsedMemory == 0 || maxIndexUsedMemory > maxMemoryReference) {
maxIndexUsedMemory = (long) (maxIndexUsedMemoryPercentage * maxMemoryReference);
}
/* If max index memory for pages isn't configured or is too high default it to a maxMemoryReference percentage */
if (maxPKUsedMemory == 0 || maxPKUsedMemory > maxMemoryReference) {
maxPKUsedMemory = (long) (maxPKUsedMemoryPercentage * maxMemoryReference);
}
/* If max used memory is too high lower index and data accordingly */
if (maxDataUsedMemory + maxIndexUsedMemory + maxPKUsedMemory > maxMemoryReference) {
long data = (int) ((double) maxDataUsedMemory
/ ((double) (maxDataUsedMemory + maxIndexUsedMemory + maxPKUsedMemory)) * maxMemoryReference);
long index = (int) ((double) maxIndexUsedMemory
/ ((double) (maxDataUsedMemory + maxIndexUsedMemory + maxPKUsedMemory)) * maxMemoryReference);
long pk = (int) ((double) maxPKUsedMemory
/ ((double) (maxDataUsedMemory + maxIndexUsedMemory + maxPKUsedMemory)) * maxMemoryReference);
maxDataUsedMemory = data;
maxIndexUsedMemory = data;
maxPKUsedMemory = pk;
}
memoryManager = new MemoryManager(maxDataUsedMemory, maxIndexUsedMemory, maxPKUsedMemory, maxLogicalPageSize);
metadataStorageManager.start();
if (clearAtBoot) {
metadataStorageManager.clear();
}
metadataStorageManager.setMetadataChangeListener(this);
NodeMetadata nodeMetadata = NodeMetadata
.builder()
.host(hostData.getHost())
.port(hostData.getPort())
.ssl(hostData.isSsl())
.nodeId(nodeId)
.build();
if (!mode.equals(ServerConfiguration.PROPERTY_MODE_LOCAL)) {
LOGGER.log(Level.INFO, "Registering on metadata storage manager my data: {0}", nodeMetadata);
}
metadataStorageManager.registerNode(nodeMetadata);
try {
TableSpaceManager local_node_virtual_tables_manager = new TableSpaceManager(nodeId, virtualTableSpaceId,
virtualTableSpaceId, 1 /* expectedreplicacount*/,
metadataStorageManager, dataStorageManager, null, this, true);
tablesSpaces.put(virtualTableSpaceId, local_node_virtual_tables_manager);
local_node_virtual_tables_manager.start();
} catch (DDLException | DataStorageManagerException | LogNotAvailableException | MetadataStorageManagerException error) {
throw new IllegalStateException("cannot boot local virtual tablespace manager");
}
String initialDefaultTableSpaceLeader = nodeId;
String initialDefaultTableSpaceReplicaNode = initialDefaultTableSpaceLeader;
long initialDefaultTableSpaceMaxLeaderInactivityTime = 0; // disabled
int expectedreplicacount = 1;
// try to be more fault tolerant in case of DISKLESSCLUSTER
// setting replica = * and maxLeaderInactivityTime = 1 minutes means
// that if you lose the node with the server you will have at most 1 minute of unavailability (no leader)
if (ServerConfiguration.PROPERTY_MODE_DISKLESSCLUSTER.equals(mode)) {
initialDefaultTableSpaceReplicaNode = TableSpace.ANY_NODE;
initialDefaultTableSpaceMaxLeaderInactivityTime = 60_000; // 1 minute
expectedreplicacount = serverConfiguration.getInt(ServerConfiguration.PROPERTY_DEFAULT_REPLICA_COUNT, ServerConfiguration.PROPERTY_DEFAULT_REPLICA_COUNT_DEFAULT);
} else if (ServerConfiguration.PROPERTY_MODE_CLUSTER.equals(mode)) {
expectedreplicacount = serverConfiguration.getInt(ServerConfiguration.PROPERTY_DEFAULT_REPLICA_COUNT, ServerConfiguration.PROPERTY_DEFAULT_REPLICA_COUNT_DEFAULT);
}
boolean created = metadataStorageManager.ensureDefaultTableSpace(initialDefaultTableSpaceLeader, initialDefaultTableSpaceReplicaNode,
initialDefaultTableSpaceMaxLeaderInactivityTime, expectedreplicacount);
if (created && !ServerConfiguration.PROPERTY_MODE_LOCAL.equals(mode)) {
LOGGER.log(Level.INFO, "Created default tablespace " + TableSpace.DEFAULT
+ " with expectedreplicacount={0}, leader={1}, replica={2}, maxleaderinactivitytime={3}",
new Object[]{expectedreplicacount, initialDefaultTableSpaceLeader,
initialDefaultTableSpaceReplicaNode,
initialDefaultTableSpaceMaxLeaderInactivityTime});
}
commitLogManager.start();
generalLock.writeLock().lock();
try {
dataStorageManager.start();
} finally {
generalLock.writeLock().unlock();
}
activator.start();
triggerActivator(ActivatorRunRequest.FULL);
}
public boolean waitForTablespace(String tableSpace, int millis) throws InterruptedException {
return waitForTablespace(tableSpace, millis, true);
}
public boolean waitForBootOfLocalTablespaces(int millis) throws InterruptedException, MetadataStorageManagerException {
List<String> tableSpacesToWaitFor = new ArrayList<>();
Collection<String> allTableSpaces = metadataStorageManager.listTableSpaces();
for (String tableSpaceName : allTableSpaces) {
TableSpace tableSpace = metadataStorageManager.describeTableSpace(tableSpaceName);
if (tableSpace.leaderId.equals(nodeId)) {
tableSpacesToWaitFor.add(tableSpaceName);
}
}
LOGGER.log(Level.INFO, "Waiting (max " + millis + " ms) for boot of local tablespaces: " + tableSpacesToWaitFor);
for (String tableSpace : tableSpacesToWaitFor) {
boolean ok = waitForTablespace(tableSpace, millis, true);
if (!ok) {
return false;
}
}
return true;
}
public boolean waitForTablespace(String tableSpace, int millis, boolean checkLeader) throws InterruptedException {
long now = System.currentTimeMillis();
while (System.currentTimeMillis() - now <= millis) {
TableSpaceManager manager = tablesSpaces.get(tableSpace);
if (manager != null) {
if (checkLeader && manager.isLeader()) {
return true;
}
if (!checkLeader) {
return true;
}
}
Thread.sleep(100);
}
return false;
}
public boolean waitForTable(String tableSpace, String table, int millis, boolean checkLeader) throws InterruptedException {
long now = System.currentTimeMillis();
while (System.currentTimeMillis() - now <= millis) {
TableSpaceManager manager = tablesSpaces.get(tableSpace);
if (manager != null) {
if (checkLeader && manager.isLeader()) {
if (manager.getTableManager(table) != null) {
return true;
}
}
if (!checkLeader) {
AbstractTableManager tableManager = manager.getTableManager(table);
if (tableManager != null && tableManager.isStarted()) {
return true;
}
}
}
Thread.sleep(100);
}
return false;
}
private void handleTableSpace(TableSpace tableSpace) throws DataStorageManagerException, LogNotAvailableException, MetadataStorageManagerException, DDLException {
String tableSpaceName = tableSpace.name;
TableSpaceManager actual_manager = tablesSpaces.get(tableSpaceName);
if (actual_manager != null && actual_manager.isFailed()) {
LOGGER.log(Level.INFO, "Tablespace {0} is in 'Failed' status", new Object[]{tableSpaceName, nodeId});
return;
}
if (actual_manager != null && actual_manager.isLeader() && !tableSpace.leaderId.equals(nodeId)) {
LOGGER.log(Level.INFO, "Tablespace {0} leader is no more {1}, it changed to {2}", new Object[]{tableSpaceName, nodeId, tableSpace.leaderId});
stopTableSpace(tableSpaceName, tableSpace.uuid);
return;
}
if (actual_manager != null && !actual_manager.isLeader() && tableSpace.leaderId.equals(nodeId)) {
LOGGER.log(Level.INFO, "Tablespace {0} need to switch to leadership on node {1}", new Object[]{tableSpaceName, nodeId});
stopTableSpace(tableSpaceName, tableSpace.uuid);
return;
}
if (tableSpace.isNodeAssignedToTableSpace(nodeId) && !tablesSpaces.containsKey(tableSpaceName)) {
LOGGER.log(Level.INFO, "Booting tablespace {0} on {1}, uuid {2}", new Object[]{tableSpaceName, nodeId, tableSpace.uuid});
long _start = System.currentTimeMillis();
CommitLog commitLog = commitLogManager.createCommitLog(tableSpace.uuid, tableSpace.name, nodeId);
TableSpaceManager manager = new TableSpaceManager(nodeId, tableSpaceName, tableSpace.uuid, tableSpace.expectedReplicaCount, metadataStorageManager, dataStorageManager, commitLog, this, false);
try {
manager.start();
LOGGER.log(Level.INFO, "Boot success tablespace {0} on {1}, uuid {2}, time {3} ms leader:{4}", new Object[]{tableSpaceName, nodeId, tableSpace.uuid, (System.currentTimeMillis() - _start) + "", manager.isLeader()});
tablesSpaces.put(tableSpaceName, manager);
if (serverConfiguration.getBoolean(ServerConfiguration.PROPERTY_JMX_ENABLE, ServerConfiguration.PROPERTY_JMX_ENABLE_DEFAULT)) {
JMXUtils.registerTableSpaceManagerStatsMXBean(tableSpaceName, manager.getStats());
}
} catch (DataStorageManagerException | LogNotAvailableException | MetadataStorageManagerException | DDLException t) {
LOGGER.log(Level.SEVERE, "Error Booting tablespace {0} on {1}", new Object[]{tableSpaceName, nodeId});
LOGGER.log(Level.SEVERE, "Error", t);
tablesSpaces.remove(tableSpaceName);
try {
manager.close();
} catch (Throwable t2) {
LOGGER.log(Level.SEVERE, "Other Error", t2);
t.addSuppressed(t2);
}
throw t;
}
return;
}
if (tablesSpaces.containsKey(tableSpaceName) && !tableSpace.isNodeAssignedToTableSpace(nodeId)) {
LOGGER.log(Level.INFO, "Tablespace {0} on {1} is not more in replica list {3}, uuid {2}", new Object[]{tableSpaceName, nodeId, tableSpace.uuid, tableSpace.replicas + ""});
stopTableSpace(tableSpaceName, tableSpace.uuid);
return;
}
if (!tableSpace.isNodeAssignedToTableSpace("*")
&& tableSpace.replicas.size() < tableSpace.expectedReplicaCount) {
List<NodeMetadata> nodes = metadataStorageManager.listNodes();
LOGGER.log(Level.WARNING, "Tablespace {0} is underreplicated expectedReplicaCount={1}, replicas={2}, nodes={3}", new Object[]{tableSpaceName, tableSpace.expectedReplicaCount, tableSpace.replicas, nodes});
List<String> availableOtherNodes = nodes.stream().map(n -> {
return n.nodeId;
}).filter(n -> {
return !tableSpace.replicas.contains(n);
}).collect(Collectors.toList());
Collections.shuffle(availableOtherNodes);
int countMissing = tableSpace.expectedReplicaCount - tableSpace.replicas.size();
LOGGER.log(Level.WARNING, "Tablespace {0} is underreplicated expectedReplicaCount={1}, replicas={2}, missing {3}, availableOtherNodes={4}", new Object[]{tableSpaceName, tableSpace.expectedReplicaCount, tableSpace.replicas, countMissing, availableOtherNodes});
if (!availableOtherNodes.isEmpty()) {
TableSpace.Builder newTableSpaceBuilder =
TableSpace
.builder()
.cloning(tableSpace);
while (!availableOtherNodes.isEmpty() && countMissing-- > 0) {
String node = availableOtherNodes.remove(0);
LOGGER.log(Level.WARNING, "Tablespace {0} adding {1} node as replica", new Object[]{tableSpaceName, node});
newTableSpaceBuilder.replica(node);
}
TableSpace newTableSpace = newTableSpaceBuilder.build();
boolean ok = metadataStorageManager.updateTableSpace(newTableSpace, tableSpace);
if (!ok) {
LOGGER.log(Level.SEVERE, "updating tableSpace {0} metadata failed, someone else altered metadata", tableSpaceName);
}
}
}
if (actual_manager != null && !actual_manager.isFailed() && actual_manager.isLeader()) {
actual_manager.metadataUpdated(tableSpace);
}
}
public StatementExecutionResult executeStatement(Statement statement, StatementEvaluationContext context, TransactionContext transactionContext) throws StatementExecutionException {
CompletableFuture<StatementExecutionResult> res = executeStatementAsync(statement, context, transactionContext);
try {
return res.get();
} catch (InterruptedException err) {
Thread.currentThread().interrupt();
throw new StatementExecutionException(err);
} catch (ExecutionException err) {
Throwable cause = err.getCause();
if (cause instanceof StatementExecutionException) {
throw (StatementExecutionException) cause;
} else {
throw new StatementExecutionException(cause);
}
} catch (Throwable t) {
throw new StatementExecutionException(t);
}
}
public CompletableFuture<StatementExecutionResult> executeStatementAsync(Statement statement, StatementEvaluationContext context, TransactionContext transactionContext) {
context.setDefaultTablespace(statement.getTableSpace());
context.setManager(this);
context.setTransactionContext(transactionContext);
// LOGGER.log(Level.SEVERE, "executeStatement {0}", new Object[]{statement});
String tableSpace = statement.getTableSpace();
if (tableSpace == null) {
return Futures.exception(new StatementExecutionException("invalid null tableSpace"));
}
if (statement instanceof CreateTableSpaceStatement) {
if (transactionContext.transactionId > 0) {
return Futures.exception(new StatementExecutionException("CREATE TABLESPACE cannot be issued inside a transaction"));
}
return CompletableFuture.completedFuture(createTableSpace((CreateTableSpaceStatement) statement));
}
if (statement instanceof AlterTableSpaceStatement) {
if (transactionContext.transactionId > 0) {
return Futures.exception(new StatementExecutionException("ALTER TABLESPACE cannot be issued inside a transaction"));
}
return CompletableFuture.completedFuture(alterTableSpace((AlterTableSpaceStatement) statement));
}
if (statement instanceof DropTableSpaceStatement) {
if (transactionContext.transactionId > 0) {
return Futures.exception(new StatementExecutionException("DROP TABLESPACE cannot be issued inside a transaction"));
}
return CompletableFuture.completedFuture(dropTableSpace((DropTableSpaceStatement) statement));
}
if (statement instanceof TableSpaceConsistencyCheckStatement) {
if (transactionContext.transactionId > 0) {
return Futures.exception(new StatementExecutionException("TABLESPACECONSISTENCYCHECK cannot be issue inside a transaction"));
}
return CompletableFuture.completedFuture(createTableSpaceCheckSum((TableSpaceConsistencyCheckStatement) statement));
}
TableSpaceManager manager = tablesSpaces.get(tableSpace);
if (manager == null) {
return Futures.exception(new NotLeaderException("No such tableSpace " + tableSpace + " here (at " + nodeId + "). "
+ "Maybe the server is starting "));
}
if (errorIfNotLeader && !manager.isLeader()) {
return Futures.exception(new NotLeaderException("node " + nodeId + " is not leader for tableSpace " + tableSpace));
}
CompletableFuture<StatementExecutionResult> res = manager.executeStatementAsync(statement, context, transactionContext);
if (statement instanceof DDLStatement) {
res.whenComplete((s, err) -> {
planner.clearCache();
});
planner.clearCache();
}
// res.whenComplete((s, err) -> {
// LOGGER.log(Level.SEVERE, "completed " + statement + ": " + s, err);
// });
return res;
}
/**
* Executes a single lookup
*
* @param statement
* @param context
* @param transactionContext
* @return
* @throws StatementExecutionException
*/
public GetResult get(GetStatement statement, StatementEvaluationContext context, TransactionContext transactionContext) throws StatementExecutionException {
return (GetResult) executeStatement(statement, context, transactionContext);
}
public StatementExecutionResult executePlan(ExecutionPlan plan, StatementEvaluationContext context, TransactionContext transactionContext) throws StatementExecutionException {
CompletableFuture<StatementExecutionResult> res = executePlanAsync(plan, context, transactionContext);
try {
return res.get();
} catch (InterruptedException err) {
Thread.currentThread().interrupt();
throw new StatementExecutionException(err);
} catch (ExecutionException err) {
Throwable cause = err.getCause();
if (cause instanceof StatementExecutionException) {
throw (StatementExecutionException) cause;
} else {
throw new StatementExecutionException(cause);
}
} catch (Throwable t) {
throw new StatementExecutionException(t);
}
}
public CompletableFuture<StatementExecutionResult> executePlanAsync(ExecutionPlan plan, StatementEvaluationContext context, TransactionContext transactionContext) {
try {
context.setManager(this);
plan.validateContext(context);
if (plan.mainStatement instanceof ScanStatement) {
DataScanner result = scan((ScanStatement) plan.mainStatement, context, transactionContext);
// transction can be auto generated during the scan
transactionContext = new TransactionContext(result.getTransactionId());
return CompletableFuture
.completedFuture(new ScanResult(transactionContext.transactionId, result));
} else {
return executeStatementAsync(plan.mainStatement, context, transactionContext);
}
} catch (herddb.model.NotLeaderException err) {
LOGGER.log(Level.INFO, "not-leader", err);
return Futures.exception(err);
} catch (Throwable err) {
LOGGER.log(Level.SEVERE, "uncaught error", err);
return Futures.exception(err);
}
}
/**
* Internal method used to execute simple data accesses, like foreign key checks.
*/
public DataScanner executeSimpleQuery(String tableSpace, String query, List<Object> parameters,
int maxRows, boolean keepReadLocks, TransactionContext transactionContext, StatementEvaluationContext context) {
ScanResult scanResult = (ScanResult) executeSimpleStatement(tableSpace, query, parameters, maxRows, keepReadLocks, transactionContext, context);
return scanResult.dataScanner;
}
/**
* Internal method used to execute simple data accesses, like foreign key cascade actions.
*/
public StatementExecutionResult executeSimpleStatement(String tableSpace, String query, List<Object> parameters,
int maxRows, boolean keepReadLocks, TransactionContext transactionContext, StatementEvaluationContext context) {
TranslatedQuery translatedQuery = planner.translate(tableSpace,
query, parameters, true, true, false, maxRows);
translatedQuery.context.setForceRetainReadLock(keepReadLocks);
return executePlan(translatedQuery.plan, context != null ? context : translatedQuery.context, transactionContext);
}
public DataScanner scan(ScanStatement statement, StatementEvaluationContext context, TransactionContext transactionContext) throws StatementExecutionException {
context.setDefaultTablespace(statement.getTableSpace());
context.setManager(this);
context.setTransactionContext(transactionContext);
String tableSpace = statement.getTableSpace();
if (tableSpace == null) {
throw new StatementExecutionException("invalid null tableSpace");
}
TableSpaceManager manager = tablesSpaces.get(tableSpace);
if (manager == null) {
throw new NotLeaderException("No such tableSpace " + tableSpace + " here (at " + nodeId + "). "
+ "Maybe the server is starting ");
}
boolean allowExecutionFromFollower = statement.getAllowExecutionFromFollower();
if (errorIfNotLeader && !manager.isLeader() && !allowExecutionFromFollower) {
throw new NotLeaderException("node " + nodeId + " is not leader for tableSpace " + tableSpace);
}
return manager.scan(statement, context, transactionContext, false, false);
}
/**
* Utility method for DML/DDL statements
*
* @param statement
* @param context
* @param transactionContext
* @return
* @throws herddb.model.StatementExecutionException
*/
public DMLStatementExecutionResult executeUpdate(DMLStatement statement, StatementEvaluationContext context, TransactionContext transactionContext) throws StatementExecutionException {
return (DMLStatementExecutionResult) executeStatement(statement, context, transactionContext);
}
private StatementExecutionResult createTableSpace(CreateTableSpaceStatement createTableSpaceStatement) throws StatementExecutionException {
TableSpace tableSpace;
try {
tableSpace = TableSpace
.builder()
.leader(createTableSpaceStatement.getLeaderId())
.name(createTableSpaceStatement.getTableSpace())
.replicas(createTableSpaceStatement.getReplicas())
.expectedReplicaCount(createTableSpaceStatement.getExpectedReplicaCount())
.maxLeaderInactivityTime(createTableSpaceStatement.getMaxleaderinactivitytime())
.build();
} catch (IllegalArgumentException invalid) {
throw new StatementExecutionException("invalid CREATE TABLESPACE statement: " + invalid.getMessage(), invalid);
}
try {
metadataStorageManager.registerTableSpace(tableSpace);
triggerActivator(ActivatorRunRequest.FULL);
if (createTableSpaceStatement.getWaitForTableSpaceTimeout() > 0) {
boolean okWait = false;
int poolTime = 100;
if (metadataStorageManager instanceof MemoryMetadataStorageManager
|| metadataStorageManager instanceof FileMetadataStorageManager) {
poolTime = 5;
}
LOGGER.log(Level.INFO, "waiting for " + tableSpace.name + ", uuid " + tableSpace.uuid + ", to be up withint " + createTableSpaceStatement.getWaitForTableSpaceTimeout() + " ms");
final int timeout = createTableSpaceStatement.getWaitForTableSpaceTimeout();
for (int i = 0; i < timeout; i += poolTime) {
List<TableSpaceReplicaState> replicateStates = metadataStorageManager.getTableSpaceReplicaState(tableSpace.uuid);
for (TableSpaceReplicaState ts : replicateStates) {
LOGGER.log(Level.INFO, "waiting for " + tableSpace.name + ", uuid " + tableSpace.uuid + ", to be up, replica state node: " + ts.nodeId + ", state: " + TableSpaceReplicaState.modeToSQLString(ts.mode) + ", ts " + new java.sql.Timestamp(ts.timestamp));
if (ts.mode == TableSpaceReplicaState.MODE_LEADER) {
okWait = true;
break;
}
}
if (okWait) {
break;
}
Thread.sleep(poolTime);
}
if (!okWait) {
throw new StatementExecutionException("tablespace " + tableSpace.name + ", uuid " + tableSpace.uuid + " has been created but leader " + tableSpace.leaderId + " did not start within " + createTableSpaceStatement.getWaitForTableSpaceTimeout() + " ms");
}
}
return new DDLStatementExecutionResult(TransactionContext.NOTRANSACTION_ID);
} catch (StatementExecutionException err) {
throw err;
} catch (Exception err) {
throw new StatementExecutionException(err);
}
}
@Override
public void close() throws DataStorageManagerException {
stopped.set(true);
setActivatorPauseStatus(false);
triggerActivator(ActivatorRunRequest.NOOP);
try {
activator.join();
} catch (final InterruptedException ignore) {
ignore.printStackTrace();
}
followersThreadPool.shutdownNow();
if (serverConfiguration.getBoolean(ServerConfiguration.PROPERTY_JMX_ENABLE, ServerConfiguration.PROPERTY_JMX_ENABLE_DEFAULT)) {
JMXUtils.unregisterDBManagerStatsMXBean();
}
callbacksExecutor.shutdownNow();
// lastly give a chance to not "leak" even if not critical (ie not keep used instances after close())
try {
followersThreadPool.awaitTermination(1, SECONDS);
callbacksExecutor.awaitTermination(1, SECONDS); // give a chance to not "leak" even if not critical
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public void checkpoint() throws DataStorageManagerException, LogNotAvailableException {
for (TableSpaceManager man : tablesSpaces.values()) {
man.checkpoint(false, false, false);
}
}
public void triggerActivator(ActivatorRunRequest type) {
activatorJ.offer(type);
}
public String getNodeId() {
return nodeId;
}
public String getVirtualTableSpaceId() {
return virtualTableSpaceId;
}
public String getMode() {
return mode;
}
void submit(Runnable runnable) {
try {
followersThreadPool.submit(runnable);
} catch (RejectedExecutionException err) {
LOGGER.log(Level.SEVERE, "rejected " + runnable, err);
}
}
private StatementExecutionResult alterTableSpace(AlterTableSpaceStatement alterTableSpaceStatement) throws StatementExecutionException {
TableSpace tableSpace;
try {
TableSpace previous = metadataStorageManager.describeTableSpace(alterTableSpaceStatement.getTableSpace());
if (previous == null) {
throw new TableSpaceDoesNotExistException(alterTableSpaceStatement.getTableSpace());
}
try {
tableSpace = TableSpace.builder()
.cloning(previous)
.leader(alterTableSpaceStatement.getLeaderId())
.name(alterTableSpaceStatement.getTableSpace())
.replicas(alterTableSpaceStatement.getReplicas())
.expectedReplicaCount(alterTableSpaceStatement.getExpectedReplicaCount())
.maxLeaderInactivityTime(alterTableSpaceStatement.getMaxleaderinactivitytime())
.build();
} catch (IllegalArgumentException invalid) {
throw new StatementExecutionException("invalid ALTER TABLESPACE statement: " + invalid.getMessage(), invalid);
}
metadataStorageManager.updateTableSpace(tableSpace, previous);
triggerActivator(ActivatorRunRequest.FULL);
return new DDLStatementExecutionResult(TransactionContext.NOTRANSACTION_ID);
} catch (Exception err) {
throw new StatementExecutionException(err);
}
}
private StatementExecutionResult dropTableSpace(DropTableSpaceStatement dropTableSpaceStatement) throws StatementExecutionException {
try {
TableSpace previous = metadataStorageManager.describeTableSpace(dropTableSpaceStatement.getTableSpace());
if (previous == null) {
throw new TableSpaceDoesNotExistException(dropTableSpaceStatement.getTableSpace());
}
metadataStorageManager.dropTableSpace(dropTableSpaceStatement.getTableSpace(), previous);
triggerActivator(ActivatorRunRequest.TABLESPACEMANAGEMENT);
return new DDLStatementExecutionResult(TransactionContext.NOTRANSACTION_ID);
} catch (Exception err) {
throw new StatementExecutionException(err);
}
}
public void dumpTableSpace(String tableSpace, String dumpId, Pdu message, Channel channel, int fetchSize, boolean includeLog) {
TableSpaceManager manager = tablesSpaces.get(tableSpace);
ByteBuf resp;
if (manager == null) {
resp = PduCodec.ErrorResponse.write(message.messageId, "tableSpace " + tableSpace + " not booted here");
channel.sendReplyMessage(message.messageId, resp);
return;
} else {
resp = PduCodec.AckResponse.write(message.messageId);
channel.sendReplyMessage(message.messageId, resp);
}
try {
manager.dumpTableSpace(dumpId, channel, fetchSize, includeLog);
} catch (Exception error) {
LOGGER.log(Level.SEVERE, "error on dump", error);
}
}
public DataConsistencyStatementResult createTableCheckSum(TableConsistencyCheckStatement tableConsistencyCheckStatement, StatementEvaluationContext context) {
TableSpaceManager manager = tablesSpaces.get(tableConsistencyCheckStatement.getTableSpace());
String tableName = tableConsistencyCheckStatement.getTable();
String tableSpaceName = tableConsistencyCheckStatement.getTableSpace();
if (manager == null) {
return new DataConsistencyStatementResult(false, "No such tablespace " + tableSpaceName);
}
try {
manager.createAndWriteTableCheksum(manager, tableSpaceName, tableName, context);
} catch (IOException | DataScannerException ex) {
LOGGER.log(Level.SEVERE, "Error on check of tablespace " + tableSpaceName , ex);
return new DataConsistencyStatementResult(false, "Error on check of tablespace " + tableSpaceName + ":" + ex);
}
return new DataConsistencyStatementResult(true, "Check table consistency for " + tableName + "completed");
}
public DataConsistencyStatementResult createTableSpaceCheckSum(TableSpaceConsistencyCheckStatement tableSpaceConsistencyCheckStatement) {
TableSpaceManager manager = tablesSpaces.get(tableSpaceConsistencyCheckStatement.getTableSpace());
String tableSpace = tableSpaceConsistencyCheckStatement.getTableSpace();
List<Table> tables = manager.getAllCommittedTables();
long _start = System.currentTimeMillis();
for (Table table : tables) {
AbstractTableManager tableManager = manager.getTableManager(table.name);
if (!tableManager.isSystemTable()) {
try {
manager.createAndWriteTableCheksum(manager, tableSpace, tableManager.getTable().name, null);
} catch (IOException | DataScannerException ex) {
LOGGER.log(Level.SEVERE, "Error on check of tablespace " + tableSpace , ex);
return new DataConsistencyStatementResult(false, "Error on check of tablespace " + tableSpace + ":" + ex);
}
}
}
long _stop = System.currentTimeMillis();
long tableSpace_check_duration = (_stop - _start);
LOGGER.log(Level.INFO, "Check tablespace consistency for {0} Completed in {1} ms", new Object[]{tableSpace, tableSpace_check_duration});
return new DataConsistencyStatementResult(true, "Check tablespace consistency for " + tableSpace + "completed in " + tableSpace_check_duration);
}
private String makeVirtualTableSpaceManagerId(String nodeId) {
return nodeId.replace(":", "").replace(".", "").toLowerCase();
}
// visible for testing
public boolean isTableSpaceLocallyRecoverable(TableSpace tableSpace) {
LogSequenceNumber logSequenceNumber = dataStorageManager.getLastcheckpointSequenceNumber(tableSpace.uuid);
try (CommitLog tmpCommitLog = commitLogManager.createCommitLog(tableSpace.uuid, tableSpace.name, nodeId);) {
return tmpCommitLog.isRecoveryAvailable(logSequenceNumber);
}
}
private boolean tryBecomeLeaderFor(TableSpace tableSpace) throws DDLException, MetadataStorageManagerException {
if (!isTableSpaceLocallyRecoverable(tableSpace)) {
LOGGER.log(Level.INFO, "local node {0} cannot become leader of {1} (current is {2})."
+ "Cannot boot tablespace locally (not enough data, last checkpoint + log)",
new Object[]{nodeId, tableSpace.name, tableSpace.leaderId});
return false;
}
LOGGER.log(Level.INFO, "node {0}, try to become leader of {1} (prev was {2})", new Object[]{nodeId, tableSpace.name, tableSpace.leaderId});
TableSpace.Builder newTableSpaceBuilder =
TableSpace
.builder()
.cloning(tableSpace)
.leader(nodeId);
TableSpace newTableSpace = newTableSpaceBuilder.build();
boolean ok = metadataStorageManager.updateTableSpace(newTableSpace, tableSpace);
if (!ok) {
LOGGER.log(Level.SEVERE, "node {0} updating tableSpace {1} try to become leader failed", new Object[]{nodeId, tableSpace.name});
return false;
} else {
LOGGER.log(Level.SEVERE, "node {0} updating tableSpace {1} try to become leader succeeded", new Object[]{nodeId, tableSpace.name});
return true;
}
}
long handleLocalMemoryUsage() {
long result = 0;
for (TableSpaceManager tableSpaceManager : tablesSpaces.values()) {
result += tableSpaceManager.handleLocalMemoryUsage();
}
return result;
}
private class Activator implements Runnable {
private final Lock runLock = new ReentrantLock();
private final Condition resume = runLock.newCondition();
private final BlockingQueue<ActivatorRunRequest> activatorQueue = new ArrayBlockingQueue<>(1);
private volatile boolean activatorPaused = false;
@SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
public void offer(ActivatorRunRequest type) {
/*
* RV_RETURN_VALUE_IGNORED_BAD_PRACTICE: ignore return, activator queue can contain at max one
* element, every other request will be eventually handled from ActivatorRunRequest.FULL executed
* periodically from the activator itself when it doesn't have any other work to do
*/
activatorQueue.offer(type);
}
public void resume() {
runLock.lock();
try {
boolean wasPaused = activatorPaused;
if (!wasPaused) {
return;
} else {
activatorPaused = false;
}
resume.signalAll();
} finally {
runLock.unlock();
}
}
public void pause() {
runLock.lock();
try {
/*
* Must be update in lock to avoid racing conditions between pause check
* (activatorPaused == true) and resume signal check (resume.awaitUninterruptibly())
*/
activatorPaused = true;
} finally {
runLock.unlock();
}
}
@Override
public void run() {
try {
try {
while (!stopped.get()) {
runLock.lock();
try {
if (activatorPaused) {
LOGGER.log(Level.INFO, "{0} activator paused", nodeId);
resume.awaitUninterruptibly();
LOGGER.log(Level.INFO, "{0} activator resumed", nodeId);
continue;
}
} finally {
runLock.unlock();
}
ActivatorRunRequest type = activatorQueue.poll(1, TimeUnit.SECONDS);
if (type == null) {
type = ActivatorRunRequest.FULL;
}
activatorQueue.clear();
if (!stopped.get()) {
executeActivator(type);
}
}
} catch (InterruptedException ee) {
}
generalLock.writeLock().lock();
try {
for (Map.Entry<String, TableSpaceManager> manager : tablesSpaces.entrySet()) {
try {
manager.getValue().close();
} catch (Exception err) {
LOGGER.log(Level.SEVERE, "error during shutdown of manager of tablespace " + manager.getKey(), err);
}
}
} finally {
generalLock.writeLock().unlock();
}
try {
dataStorageManager.close();
} catch (Exception err) {
LOGGER.log(Level.SEVERE, "error during shutdown", err);
}
try {
metadataStorageManager.close();
} catch (Exception err) {
LOGGER.log(Level.SEVERE, "error during shutdown", err);
}
try {
commitLogManager.close();
} catch (Exception err) {
LOGGER.log(Level.SEVERE, "error during shutdown", err);
}
LOGGER.log(Level.FINE, "{0} activator stopped", nodeId);
} catch (RuntimeException err) {
LOGGER.log(Level.SEVERE, "fatal activator erro", err);
}
}
}
public void setActivatorPauseStatus(boolean pause) {
if (pause) {
activatorJ.pause();
} else {
activatorJ.resume();
}
}
public final boolean isStopped() {
return stopped.get();
}
private void executeActivator(ActivatorRunRequest type) {
try {
if (type.enableTableSpacesManagement()) {
if (manageTableSpaces()) {
return;
}
}
boolean checkpointDone = false;
if (type.enableGlobalCheckPoint()) {
long now = System.currentTimeMillis();
if (checkpointPeriod > 0 && now - lastCheckPointTs.get() > checkpointPeriod) {
lastCheckPointTs.set(now);
try {
checkpoint();
checkpointDone = true;
} catch (DataStorageManagerException | LogNotAvailableException error) {
LOGGER.log(Level.SEVERE, "checkpoint failed:" + error, error);
}
}
}
if (!checkpointDone && type.enableTableCheckPoints()) {
for (TableSpaceManager man : tablesSpaces.values()) {
man.runLocalTableCheckPoints();
}
}
if (!checkpointDone && type.enableAbandonedTransactionsMaintenaince()) {
for (TableSpaceManager man : tablesSpaces.values()) {
man.processAbandonedTransactions();
}
}
} catch (RuntimeException err) {
LOGGER.log(Level.SEVERE, "Fatal error during a system management task", err);
}
}
private boolean manageTableSpaces() {
Collection<String> actualTablesSpaces;
try {
// all lowercase names
actualTablesSpaces = metadataStorageManager.listTableSpaces();
} catch (MetadataStorageManagerException error) {
LOGGER.log(Level.SEVERE, "cannot access tablespaces metadata", error);
return true;
}
Map<String, TableSpace> currentTableSpaceMetadata = new HashMap<>();
generalLock.writeLock().lock();
try {
for (String tableSpace : actualTablesSpaces) {
TableSpace tableSpaceMetadata = metadataStorageManager.describeTableSpace(tableSpace);
if (tableSpaceMetadata == null) {
LOGGER.log(Level.INFO, "tablespace {0} does not exist", tableSpace);
continue;
}
currentTableSpaceMetadata.put(tableSpaceMetadata.uuid, tableSpaceMetadata);
try {
handleTableSpace(tableSpaceMetadata);
} catch (Exception err) {
LOGGER.log(Level.SEVERE, "cannot handle tablespace " + tableSpace, err);
if (haltOnTableSpaceBootError && haltProcedure != null) {
err.printStackTrace();
haltProcedure.run();
}
}
}
} catch (MetadataStorageManagerException error) {
LOGGER.log(Level.SEVERE, "cannot access tablespaces metadata", error);
return true;
} finally {
generalLock.writeLock().unlock();
}
List<TableSpaceManager> followingActiveTableSpaces = new ArrayList<>();
Set<String> failedTableSpaces = new HashSet<>();
for (Map.Entry<String, TableSpaceManager> entry : tablesSpaces.entrySet()) {
try {
String tableSpaceUuid = entry.getValue().getTableSpaceUUID();
if (entry.getValue().isFailed()) {
LOGGER.log(Level.SEVERE, "tablespace " + tableSpaceUuid + " failed");
failedTableSpaces.add(entry.getKey());
} else if (!entry.getKey().equals(virtualTableSpaceId) && !actualTablesSpaces.contains(entry.getKey().toLowerCase())) {
LOGGER.log(Level.SEVERE, "tablespace " + tableSpaceUuid + " should not run here");
failedTableSpaces.add(entry.getKey());
} else if (entry.getValue().isLeader()) {
metadataStorageManager.updateTableSpaceReplicaState(
TableSpaceReplicaState
.builder()
.mode(TableSpaceReplicaState.MODE_LEADER)
.nodeId(nodeId)
.uuid(tableSpaceUuid)
.timestamp(System.currentTimeMillis())
.build()
);
} else {
metadataStorageManager.updateTableSpaceReplicaState(
TableSpaceReplicaState
.builder()
.mode(TableSpaceReplicaState.MODE_FOLLOWER)
.nodeId(nodeId)
.uuid(tableSpaceUuid)
.timestamp(System.currentTimeMillis())
.build()
);
followingActiveTableSpaces.add(entry.getValue());
}
} catch (MetadataStorageManagerException error) {
LOGGER.log(Level.SEVERE, "cannot access tablespace " + entry.getKey() + " metadata", error);
return true;
}
}
if (!failedTableSpaces.isEmpty()) {
generalLock.writeLock().lock();
try {
for (String tableSpace : failedTableSpaces) {
stopTableSpace(tableSpace, null);
}
} catch (MetadataStorageManagerException error) {
LOGGER.log(Level.SEVERE, "cannot access tablespace metadata", error);
return true;
} finally {
generalLock.writeLock().unlock();
}
}
if (!followingActiveTableSpaces.isEmpty()) {
long now = System.currentTimeMillis();
try {
for (TableSpaceManager tableSpaceManager : followingActiveTableSpaces) {
String tableSpaceUuid = tableSpaceManager.getTableSpaceUUID();
TableSpace tableSpaceInfo = currentTableSpaceMetadata.get(tableSpaceUuid);
if (tableSpaceInfo != null
&& !tableSpaceInfo.leaderId.equals(nodeId)
&& tableSpaceInfo.maxLeaderInactivityTime > 0
&& !tableSpaceManager.isFailed()) {
List<TableSpaceReplicaState> allReplicas =
metadataStorageManager.getTableSpaceReplicaState(tableSpaceUuid);
TableSpaceReplicaState leaderState = allReplicas
.stream()
.filter(t -> t.nodeId.equals(tableSpaceInfo.leaderId))
.findAny()
.orElse(null);
if (leaderState == null) {
leaderState = new TableSpaceReplicaState(tableSpaceUuid, tableSpaceInfo.leaderId, tableSpaceInfo.metadataStorageCreationTime, TableSpaceReplicaState.MODE_STOPPED);
LOGGER.log(Level.INFO, "Leader for " + tableSpaceUuid + " should be " + tableSpaceInfo.leaderId + ", but it never sent pings or it disappeared,"
+ " considering last activity as tablespace creation time: " + new java.sql.Timestamp(tableSpaceInfo.metadataStorageCreationTime) + " to leave a minimal grace period");
}
long delta = now - leaderState.timestamp;
if (tableSpaceInfo.maxLeaderInactivityTime > delta) {
LOGGER.log(Level.FINE, "Leader for " + tableSpaceUuid + " is " + tableSpaceInfo.leaderId
+ ", last ping " + new java.sql.Timestamp(leaderState.timestamp) + ". leader is healty");
} else {
LOGGER.log(Level.SEVERE, "Leader for " + tableSpaceUuid + " is " + tableSpaceInfo.leaderId
+ ", last ping " + new java.sql.Timestamp(leaderState.timestamp) + ". leader is failed.");
if (tryBecomeLeaderFor(tableSpaceInfo)) {
// only one change at a time
break;
}
}
}
}
} catch (MetadataStorageManagerException | DDLException error) {
LOGGER.log(Level.SEVERE, "cannot access tablespace metadata", error);
return true;
}
}
return false;
}
private void stopTableSpace(String tableSpace, String uuid) throws MetadataStorageManagerException {
LOGGER.log(Level.INFO, "stopTableSpace " + tableSpace + " uuid " + uuid + ", on " + nodeId);
try {
tablesSpaces.get(tableSpace).close();
} catch (LogNotAvailableException err) {
LOGGER.log(Level.SEVERE, "node " + nodeId + " cannot close for reboot tablespace " + tableSpace, err);
}
tablesSpaces.remove(tableSpace);
if (uuid != null) {
metadataStorageManager.updateTableSpaceReplicaState(
TableSpaceReplicaState
.builder()
.mode(TableSpaceReplicaState.MODE_STOPPED)
.nodeId(nodeId)
.uuid(uuid)
.timestamp(System.currentTimeMillis())
.build()
);
}
}
public Collection<String> getLocalTableSpaces() {
return new ArrayList<>(tablesSpaces.keySet());
}
public TableSpaceManager getTableSpaceManager(String tableSpace) {
return tablesSpaces.get(tableSpace);
}
public Path getTmpDirectory() {
return tmpDirectory;
}
public RecordSetFactory getRecordSetFactory() {
return recordSetFactory;
}
public long getCheckpointPeriod() {
return checkpointPeriod;
}
public void setCheckpointPeriod(long checkpointPeriod) {
this.checkpointPeriod = checkpointPeriod;
}
public long getAbandonedTransactionsTimeout() {
return abandonedTransactionsTimeout;
}
public void setAbandonedTransactionsTimeout(long abandonedTransactionsTimeout) {
this.abandonedTransactionsTimeout = abandonedTransactionsTimeout;
}
public long getLastCheckPointTs() {
return lastCheckPointTs.get();
}
@Override
public void metadataChanged(String description) {
LOGGER.log(Level.INFO, "metadata changed: " + description);
triggerActivator(ActivatorRunRequest.TABLESPACEMANAGEMENT);
}
public boolean isClearAtBoot() {
return clearAtBoot;
}
public void setClearAtBoot(boolean clearAtBoot) {
this.clearAtBoot = clearAtBoot;
}
public RunningStatementsStats getRunningStatements() {
return runningStatements;
}
public ExecutorService getCallbacksExecutor() {
return callbacksExecutor;
}
public ServerSidePreparedStatementCache getPreparedStatementsCache() {
return preparedStatementsCache;
}
public StatsLogger getStatsLogger() {
return this.mainStatsLogger;
}
// visible
public boolean isFullSQLSupportEnabled() {
String plannerType = serverConfiguration.getString(ServerConfiguration.PROPERTY_PLANNER_TYPE,
ServerConfiguration.PROPERTY_PLANNER_TYPE_DEFAULT);
return plannerType.equals(ServerConfiguration.PLANNER_TYPE_CALCITE)
|| plannerType.equals(ServerConfiguration.PLANNER_TYPE_AUTO);
}
}
| apache-2.0 |
haohui/flink | flink-connectors/flink-connector-kafka-base/src/test/java/org/apache/flink/streaming/connectors/kafka/KafkaProducerTestBase.java | 19733 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.connectors.kafka;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.typeutils.TypeInfoParser;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.client.JobExecutionException;
import org.apache.flink.runtime.state.CheckpointListener;
import org.apache.flink.runtime.state.FunctionInitializationContext;
import org.apache.flink.runtime.state.FunctionSnapshotContext;
import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.operators.StreamSink;
import org.apache.flink.streaming.connectors.kafka.partitioner.FlinkKafkaPartitioner;
import org.apache.flink.streaming.connectors.kafka.testutils.FailingIdentityMapper;
import org.apache.flink.streaming.connectors.kafka.testutils.IntegerSource;
import org.apache.flink.streaming.util.serialization.KeyedSerializationSchema;
import org.apache.flink.streaming.util.serialization.KeyedSerializationSchemaWrapper;
import org.apache.flink.streaming.util.serialization.SerializationSchema;
import org.apache.flink.streaming.util.serialization.TypeInformationSerializationSchema;
import org.apache.flink.test.util.SuccessException;
import org.apache.flink.test.util.TestUtils;
import org.apache.flink.util.Preconditions;
import org.junit.Test;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import static org.apache.flink.test.util.TestUtils.tryExecute;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* Abstract test base for all Kafka producer tests.
*/
@SuppressWarnings("serial")
public abstract class KafkaProducerTestBase extends KafkaTestBase {
/**
* This tests verifies that custom partitioning works correctly, with a default topic
* and dynamic topic. The number of partitions for each topic is deliberately different.
*
* <p>Test topology:
*
* <pre>
* +------> (sink) --+--> [DEFAULT_TOPIC-1] --> (source) -> (map) -----+
* / | | | |
* | | | | ------+--> (sink)
* +------> (sink) --+--> [DEFAULT_TOPIC-2] --> (source) -> (map) -----+
* / |
* | |
* (source) ----------> (sink) --+--> [DYNAMIC_TOPIC-1] --> (source) -> (map) -----+
* | | | | |
* \ | | | |
* +------> (sink) --+--> [DYNAMIC_TOPIC-2] --> (source) -> (map) -----+--> (sink)
* | | | | |
* \ | | | |
* +------> (sink) --+--> [DYNAMIC_TOPIC-3] --> (source) -> (map) -----+
* </pre>
*
* <p>Each topic has an independent mapper that validates the values come consistently from
* the correct Kafka partition of the topic is is responsible of.
*
* <p>Each topic also has a final sink that validates that there are no duplicates and that all
* partitions are present.
*/
@Test
public void testCustomPartitioning() {
try {
LOG.info("Starting KafkaProducerITCase.testCustomPartitioning()");
final String defaultTopic = "defaultTopic";
final int defaultTopicPartitions = 2;
final String dynamicTopic = "dynamicTopic";
final int dynamicTopicPartitions = 3;
createTestTopic(defaultTopic, defaultTopicPartitions, 1);
createTestTopic(dynamicTopic, dynamicTopicPartitions, 1);
Map<String, Integer> expectedTopicsToNumPartitions = new HashMap<>(2);
expectedTopicsToNumPartitions.put(defaultTopic, defaultTopicPartitions);
expectedTopicsToNumPartitions.put(dynamicTopic, dynamicTopicPartitions);
TypeInformation<Tuple2<Long, String>> longStringInfo = TypeInfoParser.parse("Tuple2<Long, String>");
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRestartStrategy(RestartStrategies.noRestart());
env.getConfig().disableSysoutLogging();
TypeInformationSerializationSchema<Tuple2<Long, String>> serSchema =
new TypeInformationSerializationSchema<>(longStringInfo, env.getConfig());
TypeInformationSerializationSchema<Tuple2<Long, String>> deserSchema =
new TypeInformationSerializationSchema<>(longStringInfo, env.getConfig());
// ------ producing topology ---------
// source has DOP 1 to make sure it generates no duplicates
DataStream<Tuple2<Long, String>> stream = env.addSource(new SourceFunction<Tuple2<Long, String>>() {
private boolean running = true;
@Override
public void run(SourceContext<Tuple2<Long, String>> ctx) throws Exception {
long cnt = 0;
while (running) {
ctx.collect(new Tuple2<Long, String>(cnt, "kafka-" + cnt));
cnt++;
}
}
@Override
public void cancel() {
running = false;
}
}).setParallelism(1);
Properties props = new Properties();
props.putAll(FlinkKafkaProducerBase.getPropertiesFromBrokerList(brokerConnectionStrings));
props.putAll(secureProps);
// sink partitions into
kafkaServer.produceIntoKafka(
stream,
defaultTopic,
// this serialization schema will route between the default topic and dynamic topic
new CustomKeyedSerializationSchemaWrapper(serSchema, defaultTopic, dynamicTopic),
props,
new CustomPartitioner(expectedTopicsToNumPartitions))
.setParallelism(Math.max(defaultTopicPartitions, dynamicTopicPartitions));
// ------ consuming topology ---------
Properties consumerProps = new Properties();
consumerProps.putAll(standardProps);
consumerProps.putAll(secureProps);
FlinkKafkaConsumerBase<Tuple2<Long, String>> defaultTopicSource =
kafkaServer.getConsumer(defaultTopic, deserSchema, consumerProps);
FlinkKafkaConsumerBase<Tuple2<Long, String>> dynamicTopicSource =
kafkaServer.getConsumer(dynamicTopic, deserSchema, consumerProps);
env.addSource(defaultTopicSource).setParallelism(defaultTopicPartitions)
.map(new PartitionValidatingMapper(defaultTopicPartitions)).setParallelism(defaultTopicPartitions)
.addSink(new PartitionValidatingSink(defaultTopicPartitions)).setParallelism(1);
env.addSource(dynamicTopicSource).setParallelism(dynamicTopicPartitions)
.map(new PartitionValidatingMapper(dynamicTopicPartitions)).setParallelism(dynamicTopicPartitions)
.addSink(new PartitionValidatingSink(dynamicTopicPartitions)).setParallelism(1);
tryExecute(env, "custom partitioning test");
deleteTestTopic(defaultTopic);
deleteTestTopic(dynamicTopic);
LOG.info("Finished KafkaProducerITCase.testCustomPartitioning()");
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Tests the at-least-once semantic for the simple writes into Kafka.
*/
@Test
public void testOneToOneAtLeastOnceRegularSink() throws Exception {
testOneToOneAtLeastOnce(true);
}
/**
* Tests the at-least-once semantic for the simple writes into Kafka.
*/
@Test
public void testOneToOneAtLeastOnceCustomOperator() throws Exception {
testOneToOneAtLeastOnce(false);
}
/**
* This test sets KafkaProducer so that it will not automatically flush the data and
* simulate network failure between Flink and Kafka to check whether FlinkKafkaProducer
* flushed records manually on snapshotState.
*
* <p>Due to legacy reasons there are two different ways of instantiating a Kafka 0.10 sink. The
* parameter controls which method is used.
*/
protected void testOneToOneAtLeastOnce(boolean regularSink) throws Exception {
final String topic = regularSink ? "oneToOneTopicRegularSink" : "oneToOneTopicCustomOperator";
final int partition = 0;
final int numElements = 1000;
final int failAfterElements = 333;
createTestTopic(topic, 1, 1);
TypeInformationSerializationSchema<Integer> schema = new TypeInformationSerializationSchema<>(BasicTypeInfo.INT_TYPE_INFO, new ExecutionConfig());
KeyedSerializationSchema<Integer> keyedSerializationSchema = new KeyedSerializationSchemaWrapper(schema);
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(500);
env.setParallelism(1);
env.setRestartStrategy(RestartStrategies.noRestart());
env.getConfig().disableSysoutLogging();
Properties properties = new Properties();
properties.putAll(standardProps);
properties.putAll(secureProps);
// decrease timeout and block time from 60s down to 10s - this is how long KafkaProducer will try send pending (not flushed) data on close()
properties.setProperty("timeout.ms", "10000");
properties.setProperty("max.block.ms", "10000");
// increase batch.size and linger.ms - this tells KafkaProducer to batch produced events instead of flushing them immediately
properties.setProperty("batch.size", "10240000");
properties.setProperty("linger.ms", "10000");
BrokerRestartingMapper.resetState(kafkaServer::blockProxyTraffic);
// process exactly failAfterElements number of elements and then shutdown Kafka broker and fail application
DataStream<Integer> inputStream = env
.fromCollection(getIntegersSequence(numElements))
.map(new BrokerRestartingMapper<>(failAfterElements));
StreamSink<Integer> kafkaSink = kafkaServer.getProducerSink(topic, keyedSerializationSchema, properties, new FlinkKafkaPartitioner<Integer>() {
@Override
public int partition(Integer record, byte[] key, byte[] value, String targetTopic, int[] partitions) {
return partition;
}
});
if (regularSink) {
inputStream.addSink(kafkaSink.getUserFunction());
}
else {
kafkaServer.produceIntoKafka(inputStream, topic, keyedSerializationSchema, properties, new FlinkKafkaPartitioner<Integer>() {
@Override
public int partition(Integer record, byte[] key, byte[] value, String targetTopic, int[] partitions) {
return partition;
}
});
}
FailingIdentityMapper.failedBefore = false;
try {
env.execute("One-to-one at least once test");
fail("Job should fail!");
}
catch (JobExecutionException ex) {
// ignore error, it can be one of many errors so it would be hard to check the exception message/cause
}
kafkaServer.unblockProxyTraffic();
// assert that before failure we successfully snapshot/flushed all expected elements
assertAtLeastOnceForTopic(
properties,
topic,
partition,
Collections.unmodifiableSet(new HashSet<>(getIntegersSequence(BrokerRestartingMapper.numElementsBeforeSnapshot))),
30000L);
deleteTestTopic(topic);
}
/**
* Tests the exactly-once semantic for the simple writes into Kafka.
*/
@Test
public void testExactlyOnceRegularSink() throws Exception {
testExactlyOnce(true);
}
/**
* Tests the exactly-once semantic for the simple writes into Kafka.
*/
@Test
public void testExactlyOnceCustomOperator() throws Exception {
testExactlyOnce(false);
}
/**
* This test sets KafkaProducer so that it will automatically flush the data and
* and fails the broker to check whether flushed records since last checkpoint were not duplicated.
*/
protected void testExactlyOnce(boolean regularSink) throws Exception {
final String topic = regularSink ? "exactlyOnceTopicRegularSink" : "exactlyTopicCustomOperator";
final int partition = 0;
final int numElements = 1000;
final int failAfterElements = 333;
createTestTopic(topic, 1, 1);
TypeInformationSerializationSchema<Integer> schema = new TypeInformationSerializationSchema<>(BasicTypeInfo.INT_TYPE_INFO, new ExecutionConfig());
KeyedSerializationSchema<Integer> keyedSerializationSchema = new KeyedSerializationSchemaWrapper(schema);
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(500);
env.setParallelism(1);
env.setRestartStrategy(RestartStrategies.fixedDelayRestart(1, 0));
env.getConfig().disableSysoutLogging();
Properties properties = new Properties();
properties.putAll(standardProps);
properties.putAll(secureProps);
// process exactly failAfterElements number of elements and then shutdown Kafka broker and fail application
List<Integer> expectedElements = getIntegersSequence(numElements);
DataStream<Integer> inputStream = env
.addSource(new IntegerSource(numElements))
.map(new FailingIdentityMapper<Integer>(failAfterElements));
FlinkKafkaPartitioner<Integer> partitioner = new FlinkKafkaPartitioner<Integer>() {
@Override
public int partition(Integer record, byte[] key, byte[] value, String targetTopic, int[] partitions) {
return partition;
}
};
if (regularSink) {
StreamSink<Integer> kafkaSink = kafkaServer.getProducerSink(topic, keyedSerializationSchema, properties, partitioner);
inputStream.addSink(kafkaSink.getUserFunction());
}
else {
kafkaServer.produceIntoKafka(inputStream, topic, keyedSerializationSchema, properties, partitioner);
}
FailingIdentityMapper.failedBefore = false;
TestUtils.tryExecute(env, "Exactly once test");
// assert that before failure we successfully snapshot/flushed all expected elements
assertExactlyOnceForTopic(
properties,
topic,
partition,
expectedElements,
30000L);
deleteTestTopic(topic);
}
private List<Integer> getIntegersSequence(int size) {
List<Integer> result = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
result.add(i);
}
return result;
}
// ------------------------------------------------------------------------
private static class CustomPartitioner extends FlinkKafkaPartitioner<Tuple2<Long, String>> implements Serializable {
private final Map<String, Integer> expectedTopicsToNumPartitions;
public CustomPartitioner(Map<String, Integer> expectedTopicsToNumPartitions) {
this.expectedTopicsToNumPartitions = expectedTopicsToNumPartitions;
}
@Override
public int partition(Tuple2<Long, String> next, byte[] serializedKey, byte[] serializedValue, String topic, int[] partitions) {
assertEquals(expectedTopicsToNumPartitions.get(topic).intValue(), partitions.length);
return (int) (next.f0 % partitions.length);
}
}
/**
* A {@link KeyedSerializationSchemaWrapper} that supports routing serialized records to different target topics.
*/
public static class CustomKeyedSerializationSchemaWrapper extends KeyedSerializationSchemaWrapper<Tuple2<Long, String>> {
private final String defaultTopic;
private final String dynamicTopic;
public CustomKeyedSerializationSchemaWrapper(
SerializationSchema<Tuple2<Long, String>> serializationSchema,
String defaultTopic,
String dynamicTopic) {
super(serializationSchema);
this.defaultTopic = Preconditions.checkNotNull(defaultTopic);
this.dynamicTopic = Preconditions.checkNotNull(dynamicTopic);
}
@Override
public String getTargetTopic(Tuple2<Long, String> element) {
return (element.f0 % 2 == 0) ? defaultTopic : dynamicTopic;
}
}
/**
* Mapper that validates partitioning and maps to partition.
*/
public static class PartitionValidatingMapper extends RichMapFunction<Tuple2<Long, String>, Integer> {
private final int numPartitions;
private int ourPartition = -1;
public PartitionValidatingMapper(int numPartitions) {
this.numPartitions = numPartitions;
}
@Override
public Integer map(Tuple2<Long, String> value) throws Exception {
int partition = value.f0.intValue() % numPartitions;
if (ourPartition != -1) {
assertEquals("inconsistent partitioning", ourPartition, partition);
} else {
ourPartition = partition;
}
return partition;
}
}
/**
* Sink that validates records received from each partition and checks that there are no duplicates.
*/
public static class PartitionValidatingSink implements SinkFunction<Integer> {
private final int[] valuesPerPartition;
public PartitionValidatingSink(int numPartitions) {
this.valuesPerPartition = new int[numPartitions];
}
@Override
public void invoke(Integer value) throws Exception {
valuesPerPartition[value]++;
boolean missing = false;
for (int i : valuesPerPartition) {
if (i < 100) {
missing = true;
break;
}
}
if (!missing) {
throw new SuccessException();
}
}
}
private static class BrokerRestartingMapper<T> extends RichMapFunction<T, T>
implements CheckpointedFunction, CheckpointListener {
private static final long serialVersionUID = 6334389850158707313L;
public static volatile boolean restartedLeaderBefore;
public static volatile boolean hasBeenCheckpointedBeforeFailure;
public static volatile int numElementsBeforeSnapshot;
public static volatile Runnable shutdownAction;
private final int failCount;
private int numElementsTotal;
private boolean failer;
private boolean hasBeenCheckpointed;
public static void resetState(Runnable shutdownAction) {
restartedLeaderBefore = false;
hasBeenCheckpointedBeforeFailure = false;
numElementsBeforeSnapshot = 0;
BrokerRestartingMapper.shutdownAction = shutdownAction;
}
public BrokerRestartingMapper(int failCount) {
this.failCount = failCount;
}
@Override
public void open(Configuration parameters) {
failer = getRuntimeContext().getIndexOfThisSubtask() == 0;
}
@Override
public T map(T value) throws Exception {
numElementsTotal++;
if (!restartedLeaderBefore) {
Thread.sleep(10);
if (failer && numElementsTotal >= failCount) {
// shut down a Kafka broker
hasBeenCheckpointedBeforeFailure = hasBeenCheckpointed;
restartedLeaderBefore = true;
shutdownAction.run();
}
}
return value;
}
@Override
public void notifyCheckpointComplete(long checkpointId) {
hasBeenCheckpointed = true;
}
@Override
public void snapshotState(FunctionSnapshotContext context) throws Exception {
numElementsBeforeSnapshot = numElementsTotal;
}
@Override
public void initializeState(FunctionInitializationContext context) throws Exception {
}
}
}
| apache-2.0 |
javier-tarazaga/instasearch-app-android | presentation/src/androidTest/java/com/javiertarazaga/instasearch/test/exception/ErrorMessageFactoryTest.java | 2015 | /**
* Copyright (C) 2017 Javier Tarazaga Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.javiertarazaga.instasearch.test.exception;
import android.test.AndroidTestCase;
import com.javiertarazaga.instasearch.data.exception.NetworkConnectionException;
import com.javiertarazaga.instasearch.data.exception.UserNotFoundException;
import com.javiertarazaga.instasearch.presentation.exception.ErrorMessageFactory;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class ErrorMessageFactoryTest extends AndroidTestCase {
@Override protected void setUp() throws Exception {
super.setUp();
}
public void testNetworkConnectionErrorMessage() {
String expectedMessage = getContext().getString(com.javiertarazaga.instasearch.presentation.R.string.exception_message_no_connection);
String actualMessage = ErrorMessageFactory.create(getContext(),
new NetworkConnectionException());
assertThat(actualMessage, is(equalTo(expectedMessage)));
}
public void testUserNotFoundErrorMessage() {
String expectedMessage = getContext().getString(com.javiertarazaga.instasearch.presentation.R.string.exception_message_user_not_found);
String actualMessage = ErrorMessageFactory.create(getContext(), new UserNotFoundException());
assertThat(actualMessage, is(equalTo(expectedMessage)));
}
}
| apache-2.0 |
topcatv/tcshop | src/main/java/com/tcshop/mapper/WxMenuMapper.java | 157 | package com.tcshop.mapper;
import com.tcshop.entity.WxMenu;
import com.tcshop.util.BaseMapper;
public interface WxMenuMapper extends BaseMapper<WxMenu> {
} | apache-2.0 |
hotpads/datarouter | datarouter-storage/src/main/java/io/datarouter/storage/config/properties/DatarouterEnvironmentTypeSupplier.java | 1572 | /*
* Copyright © 2009 HotPads (admin@hotpads.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.datarouter.storage.config.properties;
import java.util.function.Supplier;
import javax.inject.Inject;
import javax.inject.Singleton;
import io.datarouter.storage.config.ComputedPropertiesFinder;
import io.datarouter.storage.config.environment.DatarouterEnvironmentType;
import io.datarouter.storage.config.environment.EnvironmentType;
@Singleton
public class DatarouterEnvironmentTypeSupplier implements Supplier<String>{
public static final String ENVIRONMENT_TYPE = "environmentType";
private final String environmentType;
@Inject
private DatarouterEnvironmentTypeSupplier(ComputedPropertiesFinder finder){
this.environmentType = finder.findProperty(ENVIRONMENT_TYPE,
() -> EnvironmentType.DEVELOPMENT.get().getPersistentString());
}
@Override
public String get(){
return environmentType;
}
public DatarouterEnvironmentType getDatarouterEnvironmentType(){
return new DatarouterEnvironmentType(environmentType);
}
}
| apache-2.0 |
TonyWang-UMU/TFG-TWang | opencds-parent/opencds-vmr-1_0/opencds-vmr-1_0-internal/src/main/java/org/opencds/vmr/v1_0/internal/concepts/VMRTemplateConcept.java | 1014 | /**
* Copyright 2011 OpenCDS.org
* 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.opencds.vmr.v1_0.internal.concepts;
public class VMRTemplateConcept extends VmrOpenCdsConcept {
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "VMRTemplateConcept [Id=" + Id + ", conceptTargetId="
+ conceptTargetId + ", openCdsConceptCode="
+ openCdsConceptCode + ", determinationMethodCode="
+ determinationMethodCode + "]";
}
} | apache-2.0 |
peeyushb/falcon | webapp/src/test/java/org/apache/falcon/resource/AbstractSchedulerManagerJerseyIT.java | 11613 | /**
* 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.falcon.resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.falcon.FalconException;
import org.apache.falcon.client.FalconCLIException;
import org.apache.falcon.entity.v0.EntityType;
import org.apache.falcon.hadoop.HadoopClientFactory;
import org.apache.falcon.state.AbstractSchedulerTestBase;
import org.apache.falcon.service.FalconJPAService;
import org.apache.falcon.unit.FalconUnitTestBase;
import org.apache.falcon.util.StartupProperties;
import org.apache.falcon.util.StateStoreProperties;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FsShell;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.fs.Path;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
/**
* Base class for tests using Native Scheduler.
*/
public class AbstractSchedulerManagerJerseyIT extends FalconUnitTestBase {
private static final String SLEEP_WORKFLOW = "sleepWorkflow.xml";
private static final String LOCAL_MODE = "local";
private static final String IT_RUN_MODE = "it.run.mode";
public static final String PROCESS_TEMPLATE = "/local-process-noinputs-template.xml";
public static final String PROCESS_TEMPLATE_NOLATE_DATA = "/process-nolatedata-template.xml";
public static final String PROCESS_NAME = "processName";
protected static final String START_INSTANCE = "2012-04-20T00:00Z";
private static FalconJPAService falconJPAService = FalconJPAService.get();
private static final String DB_BASE_DIR = "target/test-data/falcondb";
protected static String dbLocation = DB_BASE_DIR + File.separator + "data.db";
protected static String url = "jdbc:derby:"+ dbLocation +";create=true";
protected static final String DB_SQL_FILE = dbLocation + File.separator + "out.sql";
protected LocalFileSystem localFS = new LocalFileSystem();
@BeforeClass
public void setup() throws Exception {
Configuration localConf = new Configuration();
localFS.initialize(LocalFileSystem.getDefaultUri(localConf), localConf);
cleanupDB();
localFS.mkdirs(new Path(DB_BASE_DIR));
falconJPAService.init();
createDB();
super.setup();
}
protected void updateStartUpProps() {
StartupProperties.get().setProperty("workflow.engine.impl",
"org.apache.falcon.workflow.engine.FalconWorkflowEngine");
StartupProperties.get().setProperty("dag.engine.impl",
"org.apache.falcon.workflow.engine.OozieDAGEngine");
String[] listeners = StartupProperties.get().getProperty("configstore.listeners").split(",");
List<String> configListeners = new ArrayList<>(Arrays.asList(listeners));
configListeners.remove("org.apache.falcon.service.SharedLibraryHostingService");
configListeners.add("org.apache.falcon.state.store.jdbc.JDBCStateStore");
StartupProperties.get().setProperty("configstore.listeners", StringUtils.join(configListeners, ","));
StateStoreProperties.get().getProperty("falcon.state.store.impl",
"org.apache.falcon.state.store.jdbc.JDBCStateStore");
}
protected void submitProcess(Map<String, String> overlay) throws IOException, FalconCLIException {
String tmpFile = TestContext.overlayParametersOverTemplate(PROCESS_TEMPLATE, overlay);
APIResult result = submit(EntityType.PROCESS, tmpFile);
assertStatus(result);
}
protected void scheduleProcess(String processName, String cluster,
String startTime, int noOfInstances) throws FalconCLIException {
APIResult result = falconUnitClient.schedule(EntityType.PROCESS, processName, startTime, noOfInstances,
cluster, true, null);
assertStatus(result);
}
protected void setupProcessExecution(UnitTestContext context,
Map<String, String> overlay, int numInstances,
String processTemplate) throws Exception {
String colo = overlay.get(COLO);
String cluster = overlay.get(CLUSTER);
submitCluster(colo, cluster, null);
submitFeeds(overlay);
context.prepare();
submitProcess(processTemplate, overlay);
String processName = overlay.get(PROCESS_NAME);
scheduleProcess(processName, cluster, START_INSTANCE, numInstances);
}
private void createDB() throws Exception {
AbstractSchedulerTestBase abstractSchedulerTestBase = new AbstractSchedulerTestBase();
StateStoreProperties.get().setProperty(FalconJPAService.URL, url);
abstractSchedulerTestBase.createDB(DB_SQL_FILE);
}
@AfterClass
public void cleanup() throws Exception {
super.cleanup();
cleanupDB();
}
private void cleanupDB() throws IOException {
localFS.delete(new Path(DB_BASE_DIR), true);
}
protected void submitCluster(UnitTestContext context) throws IOException, FalconCLIException {
String mode = System.getProperty(IT_RUN_MODE);
if (StringUtils.isNotEmpty(mode) && mode.toLowerCase().equals(LOCAL_MODE)) {
submitCluster(context.colo, context.clusterName, null);
} else {
fs.mkdirs(new Path(STAGING_PATH), HadoopClientFactory.ALL_PERMISSION);
fs.mkdirs(new Path(WORKING_PATH), HadoopClientFactory.READ_EXECUTE_PERMISSION);
String tmpFile = TestContext.overlayParametersOverTemplate(TestContext.CLUSTER_TEMPLATE,
context.overlay);
submit(EntityType.CLUSTER, tmpFile);
}
}
protected APIResult submitFeed(String template, Map<String, String> overlay) throws IOException,
FalconCLIException {
String tmpFile = TestContext.overlayParametersOverTemplate(template, overlay);
APIResult result = falconUnitClient.submit(EntityType.FEED.name(), tmpFile, null);
return result;
}
protected void submitFeeds(Map<String, String> overlay) throws IOException, FalconCLIException {
String tmpFile = TestContext.overlayParametersOverTemplate(UnitTestContext.FEED_TEMPLATE1, overlay);
APIResult result = falconUnitClient.submit(EntityType.FEED.name(), tmpFile, null);
Assert.assertEquals(result.getStatus(), APIResult.Status.SUCCEEDED);
tmpFile = TestContext.overlayParametersOverTemplate(UnitTestContext.FEED_TEMPLATE2, overlay);
result = falconUnitClient.submit(EntityType.FEED.name(), tmpFile, null);
Assert.assertEquals(result.getStatus(), APIResult.Status.SUCCEEDED);
}
protected void submitProcess(String template, Map<String, String> overlay) throws Exception {
String tmpFile = TestContext.overlayParametersOverTemplate(template, overlay);
APIResult result = falconUnitClient.submit(EntityType.PROCESS.name(), tmpFile, null);
Assert.assertEquals(result.getStatus(), APIResult.Status.SUCCEEDED);
}
protected void scheduleProcess(UnitTestContext context) throws FalconCLIException, IOException, FalconException {
String scheduleTime = START_INSTANCE;
APIResult result = scheduleProcess(context.getProcessName(), scheduleTime, 1, context.getClusterName(),
getAbsolutePath(SLEEP_WORKFLOW), true, "");
Assert.assertEquals(result.getStatus(), APIResult.Status.SUCCEEDED);
}
protected void schedule(UnitTestContext context) throws Exception {
submitCluster(context);
context.prepare();
submitFeeds(context.overlay);
submitProcess(UnitTestContext.PROCESS_TEMPLATE, context.overlay);
scheduleProcess(context);
}
protected List<Path> createTestData() throws Exception {
List<Path> list = new ArrayList<Path>();
fs.mkdirs(new Path("/user/guest"));
fs.setOwner(new Path("/user/guest"), TestContext.REMOTE_USER, "users");
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd/HH/mm");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = new Date(System.currentTimeMillis() + 3 * 3600000);
Path path = new Path("/examples/input-data/rawLogs/" + formatter.format(date) + "/file");
fs.create(path).close();
date = new Date(date.getTime() - 3600000);
path = new Path("/examples/input-data/rawLogs/" + formatter.format(date) + "/file");
fs.create(path).close();
date = new Date(date.getTime() - 3600000);
path = new Path("/examples/input-data/rawLogs/" + formatter.format(date) + "/file");
fs.create(path).close();
date = new Date(date.getTime() - 3600000);
path = new Path("/examples/input-data/rawLogs/" + formatter.format(date) + "/file");
list.add(path);
fs.create(path).close();
date = new Date(date.getTime() - 3600000);
path = new Path("/examples/input-data/rawLogs/" + formatter.format(date) + "/file");
list.add(path);
fs.create(path).close();
date = new Date(date.getTime() - 3600000);
path = new Path("/examples/input-data/rawLogs/" + formatter.format(date) + "/file");
list.add(path);
fs.create(path).close();
date = new Date(date.getTime() - 3600000);
path = new Path("/examples/input-data/rawLogs/" + formatter.format(date) + "/file");
list.add(path);
fs.create(path).close();
date = new Date(date.getTime() - 3600000);
path = new Path("/examples/input-data/rawLogs/" + formatter.format(date) + "/file");
list.add(path);
fs.create(path).close();
date = new Date(date.getTime() - 3600000);
path = new Path("/examples/input-data/rawLogs/" + formatter.format(date) + "/file");
list.add(path);
fs.create(path).close();
date = new Date(date.getTime() - 3600000);
path = new Path("/examples/input-data/rawLogs/" + formatter.format(date) + "/file");
list.add(path);
fs.create(path).close();
new FsShell(new Configuration()).run(new String[] {
"-chown", "-R", "guest:users", "/examples/input-data/rawLogs", });
return list;
}
public void assertEntityStatus(APIResult apiResult) {
super.assertStatus(apiResult);
String message = apiResult.getMessage();
if (!message.contains(AbstractEntityManager.EntityStatus.SUBMITTED.name())) {
Assert.assertTrue(message.contains("native"));
}
}
}
| apache-2.0 |
RavishankarDuMCA10/java-html-sanitizer | src/main/java/org/owasp/html/CssTokens.java | 50554 | // Copyright (c) 2013, Mike Samuel
// 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 OWASP nor the names of its contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package org.owasp.html;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
import com.google.common.collect.ImmutableMap;
/**
* Given a string of CSS, produces a string of normalized CSS with certain
* useful properties detailed below.
* <ul>
* <li>All runs of white-space and comment tokens (including CDO and CDC)
* have been replaced with a single space character.</li>
* <li>All strings are quoted and escapes are escaped according to the
* following scheme:
* <table>
* <tr><td>NUL</td> <td><code>\0</code></tr>
* <tr><td>line feed</td> <td><code>\a</code></tr>
* <tr><td>vertical feed</td> <td><code>\c</code></tr>
* <tr><td>carriage return</td><td><code>\d</code></tr>
* <tr><td>double quote</td> <td><code>\22</code></tr>
* <tr><td>ampersand &</td><td><code>\26</code></tr>
* <tr><td>single quote</td> <td><code>\27</code></tr>
* <tr><td>left-angle <</td><td><code>\3c</code></tr>
* <tr><td>rt-angle ></td> <td><code>\3e</code></tr>
* <tr><td>back slash</td> <td><code>\\</code></tr>
* <tr><td>all others</td> <td>raw</td></tr>
* </table>
* </li>
* <li>All <code>url(…)</code> tokens are quoted.
* <li>All keywords, identifiers, and hex literals are lower-case and have
* embedded escape sequences decoded, except that .</li>
* <li>All brackets nest properly.</li>
* <li>Does not contain any case-insensitive variant of the sequences
* {@code <!--}, {@code -->}, {@code <![CDATA[}, {@code ]]>}, or
* {@code </style}.</li>
* <li>All delimiters that can start longer tokens are followed by a space.
* </ul>
*/
final class CssTokens implements Iterable<String> {
public final String normalizedCss;
public final Brackets brackets;
private final int[] tokenBreaks;
private final TokenType[] tokenTypes;
public TokenIterator start() {
return new TokenIterator(tokenTypes.length);
}
public TokenIterator iterator() { return start(); }
public static CssTokens lex(String css) {
Lexer lexer = new Lexer(css);
lexer.lex();
return lexer.build();
}
/** A cursor into a list of tokens. */
@SuppressWarnings("synthetic-access")
public final class TokenIterator implements Iterator<String> {
private int tokenIndex = 0;
private final int limit;
TokenIterator(int limit) {
this.limit = limit;
}
public boolean hasNext() {
return hasToken();
}
public String next() {
String token = token();
advance();
return token;
}
public @Nullable TokenIterator spliceToEnd() {
if (!hasNext()) { throw new NoSuchElementException(); }
int end = brackets.partner(tokenIndex);
if (end < 0) {
return null;
}
TokenIterator between = new TokenIterator(end);
between.tokenIndex = tokenIndex + 1;
tokenIndex = end + 1;
return between;
}
public int tokenIndex() {
return tokenIndex;
}
public int startOffset() {
return tokenBreaks[tokenIndex];
}
public int endOffset() {
return tokenBreaks[tokenIndex+1];
}
public String token() {
return normalizedCss.substring(startOffset(), endOffset());
}
public boolean hasToken() {
return tokenIndex < limit;
}
public boolean hasTokenAfterSpace() {
while (hasToken()) {
if (type() != TokenType.WHITESPACE) { return true; }
advance();
}
return false;
}
/** The type of the current token. */
public TokenType type() {
return tokenTypes[tokenIndex];
}
public void seek(int newTokenIndex) {
this.tokenIndex = newTokenIndex;
}
public void advance() {
if (!hasToken()) { throw new NoSuchElementException(); }
++tokenIndex;
}
public void backup() {
if (tokenIndex == 0) { throw new NoSuchElementException(); }
--tokenIndex;
}
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
}
private CssTokens(
String normalizedCss, Brackets brackets, int[] tokenBreaks,
TokenType[] tokenTypes) {
this.normalizedCss = normalizedCss;
this.brackets = brackets;
this.tokenBreaks = tokenBreaks;
this.tokenTypes = tokenTypes;
}
public enum TokenType {
/** An identifier. */
IDENT,
/** An identifier prefixed with a period. */
DOT_IDENT,
/** A function name and opening bracket. */
FUNCTION,
/** An {@code @<identifier>} directive token. */
AT,
/** A hash token that contains non-hex characters. */
HASH_ID,
/** A hash token that could be a color literal. */
HASH_UNRESTRICTED,
/** A quoted string. */
STRING,
/** A URL of the form <code>url("...")</code>. */
URL,
/** A single character. */
DELIM,
/** A scalar numeric value. */
NUMBER,
/** A percentage. */
PERCENTAGE,
/** A numeric value with a unit suffix. */
DIMENSION,
/** A numeric value with an unknown unit suffix. */
BAD_DIMENSION,
/** {@code U+<hex-or-qmark>} */
UNICODE_RANGE,
/**
* include-match, dash-match, prefix-match, suffix-match, substring-match
*/
MATCH,
/** {@code ||} */
COLUMN,
/** A run of white-space, comment, CDO, and CDC tokens. */
WHITESPACE,
/** {@code :} */
COLON,
/** {@code ;} */
SEMICOLON,
/** {@code ,} */
COMMA,
/** {@code [} */
LEFT_SQUARE,
/** {@code ]} */
RIGHT_SQUARE,
/** {@code (} */
LEFT_PAREN,
/** {@code )} */
RIGHT_PAREN,
/** <code>{</code> */
LEFT_CURLY,
/** <code>}</code> */
RIGHT_CURLY,
;
}
/**
* Maps tokens to their partners. A close bracket token like {@code (} may
* have a partner token like {@code )} if properly nested, and vice-versa.
*/
static final class Brackets {
/**
* For each token index, the index of the indexed token's partner or -1 if
* it has none.
*/
private final int[] brackets;
Brackets(int[] brackets) {
this.brackets = brackets;
}
/** The index of the partner token or -1 if none. */
int partner(int tokenIndex) {
int bracketIndex = bracketIndexForToken(tokenIndex);
if (bracketIndex < 0) { return -1; }
return brackets[(bracketIndex << 1) + 1];
}
int bracketIndexForToken(int target) {
// Binary search by leftmost element of pair.
int left = 0;
int right = brackets.length >> 1;
while (left < right) {
int mid = left + ((right - left) >> 1);
int value = brackets[mid << 1];
if (value == target) { return mid; }
if (value < target) {
left = mid + 1;
} else {
right = mid;
}
}
return -1;
}
}
private static final int[] ZERO_INTS = new int[0];
private static final TokenType[] ZERO_TYPES = new TokenType[0];
private static final Brackets EMPTY_BRACKETS = new Brackets(ZERO_INTS);
private static final CssTokens EMPTY = new CssTokens(
"", EMPTY_BRACKETS, ZERO_INTS, ZERO_TYPES);
/**
* Tokenizes according to section 4 of http://dev.w3.org/csswg/css-syntax/
*/
@SuppressWarnings("synthetic-access")
private static final class Lexer {
private final String css;
private final StringBuilder sb;
private int pos = 0;
private final int cssLimit;
private List<TokenType> tokenTypes = null;
private int[] tokenBreaks = new int[128];
private int tokenBreaksLimit = 0;
/**
* For each bracket, 2 ints: the token index of the bracket, and the token
* index of its partner.
* The array is sorted by the first int.
* The second int is -1 when the bracket has not yet been closed.
*/
private int[] brackets = ZERO_INTS;
/**
* The number of elements in {@link #brackets} that are valid.
* {@code brackets[bracketsLimit:]} is zeroed space that the list can grow
* into.
*/
private int bracketsLimit = 0;
/**
* For each bracket that has not been closed, 2 ints:
* its index in {@link #brackets} and the character of its close bracket
* as an int.
* This is a bracket stack so the array is sorted by the first int.
*/
private int[] open = ZERO_INTS;
/**
* The number of elements in {@link #open} that are valid.
* {@code open[openLimit:]} is garbage space that the stack can grow into.
*/
private int openLimit = 0;
Lexer(String css) {
this.css = css;
this.sb = new StringBuilder();
this.cssLimit = css.length();
}
TokenType openBracket(char bracketChar) {
char close;
TokenType type;
switch (bracketChar) {
case '(': close = ')'; type = TokenType.LEFT_PAREN; break;
case '[': close = ']'; type = TokenType.LEFT_SQUARE; break;
case '{': close = '}'; type = TokenType.LEFT_CURLY; break;
default:
throw new AssertionError("Invalid open bracket " + bracketChar);
}
brackets = expandIfNecessary(brackets, bracketsLimit, 2);
open = expandIfNecessary(open, openLimit, 2);
open[openLimit++] = bracketsLimit;
open[openLimit++] = close;
brackets[bracketsLimit++] = tokenBreaksLimit;
brackets[bracketsLimit++] = -1;
sb.append(bracketChar);
return type;
}
void closeBracket(char bracketChar) {
int openLimitAfterClose = openLimit;
do {
if (openLimitAfterClose == 0) {
// Drop an orphaned close bracket.
breakOutput();
return;
}
openLimitAfterClose -= 2;
} while (bracketChar != open[openLimitAfterClose + 1]);
closeBrackets(openLimitAfterClose);
}
private void closeBrackets(int openLimitAfterClose) {
// Make sure we've got space on brackets.
int spaceNeeded = openLimit - openLimitAfterClose;
brackets = expandIfNecessary(brackets, bracketsLimit, spaceNeeded);
int closeTokenIndex = tokenBreaksLimit;
while (openLimit > openLimitAfterClose) {
// Pop the stack.
int closeBracket = open[--openLimit];
int openBracketIndex = open[--openLimit];
int openTokenIndex = brackets[openBracketIndex];
// Update open bracket to point to its partner.
brackets[openBracketIndex + 1] = closeTokenIndex;
// Emit the close bracket.
brackets[bracketsLimit++] = closeTokenIndex;
brackets[bracketsLimit++] = openTokenIndex;
sb.appendCodePoint(closeBracket);
closeTokenIndex++;
}
}
CssTokens build() {
// Close any still open brackets.
{
int startOfCloseBrackets = sb.length();
closeBrackets(0);
emitMergedTokens(startOfCloseBrackets, sb.length());
}
if (tokenTypes == null) { return EMPTY; }
int[] bracketsTrunc = truncateOrShare(brackets, bracketsLimit);
// Strip any trailing space off, since it may have been inserted by a
// breakAfter call anyway.
int cssEnd = sb.length();
if (cssEnd > 0 && sb.charAt(cssEnd - 1) == ' ') {
--cssEnd;
tokenTypes.remove(--tokenBreaksLimit);
}
String normalizedCss = sb.substring(0, cssEnd);
// Store the last character on the tokenBreaksList to simplify finding the
// end of a token.
tokenBreaks = expandIfNecessary(tokenBreaks, tokenBreaksLimit, 1);
tokenBreaks[tokenBreaksLimit++] = normalizedCss.length();
int[] tokenBreaksTrunc = truncateOrShare(tokenBreaks, tokenBreaksLimit);
TokenType[] tokenTypesArr = tokenTypes.toArray(ZERO_TYPES);
return new CssTokens(
normalizedCss, new Brackets(bracketsTrunc),
tokenBreaksTrunc, tokenTypesArr);
}
void lex() {
// Fast-track no content.
consumeIgnorable();
sb.setLength(0);
if (pos == cssLimit) { return; }
tokenTypes = new ArrayList<TokenType>();
@SuppressWarnings("hiding") // final
String css = this.css;
@SuppressWarnings("hiding") // final
int cssLimit = this.cssLimit;
while (pos < cssLimit) {
assert this.tokenBreaksLimit == this.tokenTypes.size()
: "token and types out of sync at " + tokenBreaksLimit
+ " in `" + css + "`";
// SPEC: 4. Tokenization
// The output of the tokenization step is a stream of zero
// or more of the following tokens: <ident>, <function>,
// <at-keyword>, <hash>, <string>, <bad-string>, <url>,
// <bad-url>, <delim>, <number>, <percentage>,
// <dimension>, <unicode-range>, <include-match>,
// <dash-match>, <prefix-match>, <suffix-match>,
// <substring-match>, <column>, <whitespace>, <CDO>,
// <CDC>, <colon>, <semicolon>, <comma>, <[>, <]>,
// <(>, <)>, <{>, and <}>.
// IMPLEMENTS: 4.3 Consume a token
char ch = css.charAt(pos);
int startOfToken = pos;
int startOfOutputToken = sb.length();
final TokenType type;
switch (ch) {
case '\t': case '\n': case '\f': case '\r': case ' ': case '\ufeff':
consumeIgnorable();
type = TokenType.WHITESPACE;
break;
case '/': {
char lookahead = pos + 1 < cssLimit ? css.charAt(pos + 1) : 0;
if (lookahead == '/' || lookahead == '*') {
consumeIgnorable();
type = TokenType.WHITESPACE;
} else {
consumeDelim(ch);
type = TokenType.DELIM;
}
break;
}
case '<':
if (consumeIgnorable()) { // <!--
type = TokenType.WHITESPACE;
} else {
consumeDelim('<');
type = TokenType.DELIM;
}
break;
case '>':
breakOutput();
sb.append('>');
type = TokenType.DELIM;
++pos;
break;
case '@':
if (consumeAtKeyword()) {
type = TokenType.AT;
} else {
consumeDelim(ch);
type = TokenType.DELIM;
}
break;
case '#': {
sb.append('#');
TokenType hashType = consumeHash();
if (hashType != null) {
type = hashType;
} else {
++pos;
sb.append(' ');
type = TokenType.DELIM;
}
break;
}
case '"':
case '\'':
type = consumeString();
break;
case 'U': case 'u':
// SPEC handle URL under "ident like token".
if (consumeUnicodeRange()) {
type = TokenType.UNICODE_RANGE;
} else {
type = consumeIdentOrUrlOrFunction();
}
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
type = consumeNumberOrPercentageOrDimension();
break;
case '+': case '-': case '.': {
char lookahead = pos + 1 < cssLimit ? css.charAt(pos + 1) : 0;
if (isDecimal(lookahead)
|| (lookahead == '.' && pos + 2 < cssLimit
&& isDecimal(css.charAt(pos + 2)))) {
type = consumeNumberOrPercentageOrDimension();
} else if (ch == '+') {
consumeDelim(ch);
type = TokenType.DELIM;
} else if (ch == '-') {
if (consumeIgnorable()) { // -->
type = TokenType.WHITESPACE;
} else {
type = consumeIdentOrUrlOrFunction();
}
} else if (isIdentPart(lookahead)) {
// treat ".<IDENT>" as one token.
sb.append('.');
++pos;
consumeIdent(false);
if (pos != startOfToken + 1) {
type = TokenType.DOT_IDENT;
if (pos < cssLimit) {
char next = css.charAt(pos);
if ('(' == next) {
// A dotted identifier followed by a parenthesis is
// ambiguously a function.
sb.append(' ');
}
}
} else {
type = TokenType.DELIM;
sb.append(' ');
}
} else {
consumeDelim('.');
type = TokenType.DELIM;
}
break;
}
case ':': consumeDelim(ch); type = TokenType.COLON; break;
case ';': consumeDelim(ch); type = TokenType.SEMICOLON; break;
case ',': consumeDelim(ch); type = TokenType.COMMA; break;
case '[': case '(': case '{':
type = openBracket(ch);
++pos;
break;
case '}': case ')': case ']':
closeBracket(ch);
++pos;
// Use DELIM so that a later loop will split output into multiple
// tokens since we may have inserted missing close brackets for
// unclosed open brackets already on the stack.
type = TokenType.DELIM;
break;
case '~': case '|': case '^': case '$': case '*': {
char lookahead = pos + 1 < cssLimit ? css.charAt(pos + 1) : 0;
if (lookahead == '=') {
consumeMatch(ch);
type = TokenType.MATCH;
} else if (ch == '|' && lookahead == '|') {
consumeColumn();
type = TokenType.COLUMN;
} else {
consumeDelim(ch);
type = TokenType.DELIM;
}
break;
}
case '_':
type = consumeIdentOrUrlOrFunction();
break;
case '\\': {
// Optimistically parse as an ident.
TokenType identType = consumeIdentOrUrlOrFunction();
if (identType == null) {
++pos; // drop
breakOutput();
type = TokenType.WHITESPACE;
} else {
type = identType;
}
// TODO: handle case where "url" is encoded.
break;
}
default:
int chlower = ch | 32;
if ('a' <= chlower && chlower <= 'z' || ch >= 0x80) {
TokenType identType = consumeIdentOrUrlOrFunction();
if (identType != null) {
type = identType;
} else { // Occurs on undefined-codepoints.
++pos;
breakOutput();
type = TokenType.WHITESPACE;
}
} else if (ch > 0x20) {
consumeDelim(ch);
type = TokenType.DELIM;
} else { // Ignore.
consumeIgnorable();
type = TokenType.WHITESPACE;
}
}
assert pos > startOfToken
: "empty token at " + pos + ", ch0=" + css.charAt(startOfToken)
+ ":U+" + Integer.toHexString(css.charAt(startOfToken));
int endOfOutputToken = sb.length();
if (endOfOutputToken > startOfOutputToken) {
if (type == TokenType.DELIM) {
emitMergedTokens(startOfOutputToken, endOfOutputToken);
} else {
if (type != TokenType.WHITESPACE
&& sb.charAt(startOfOutputToken) == ' ') {
emitToken(TokenType.WHITESPACE, startOfOutputToken);
++startOfOutputToken;
assert startOfOutputToken != endOfOutputToken;
}
emitToken(type, startOfOutputToken);
// Token emitters can emit a space after a token to avoid possible
// merges with following tokens
if (type != TokenType.WHITESPACE) {
int sbLen = sb.length();
if (startOfOutputToken + 1 < sbLen
&& sb.charAt(sbLen - 1) == ' ') {
emitToken(TokenType.WHITESPACE, sbLen - 1);
}
}
}
}
}
}
private void emitMergedTokens(int start, int end) {
// Handle breakOutput and merging of output tokens.
for (int e = start; e < end; ++e) {
TokenType delimType;
switch (sb.charAt(e)) {
case ' ': delimType = TokenType.WHITESPACE; break;
case '}': delimType = TokenType.RIGHT_CURLY; break;
case ')': delimType = TokenType.RIGHT_PAREN; break;
case ']': delimType = TokenType.RIGHT_SQUARE; break;
default : delimType = TokenType.DELIM; break;
}
emitToken(delimType, e);
}
}
private void emitToken(TokenType type, int startOfOutputToken) {
if (tokenBreaksLimit == 0
|| tokenBreaks[tokenBreaksLimit - 1] != startOfOutputToken) {
tokenBreaks = expandIfNecessary(tokenBreaks, tokenBreaksLimit, 1);
tokenBreaks[tokenBreaksLimit++] = startOfOutputToken;
tokenTypes.add(type);
}
}
private void consumeDelim(char ch) {
sb.append(ch);
switch (ch) {
// Prevent token merging.
case '~': case '|': case '^': case '$': case '\\':
case '.': case '+': case '-': case '@': case '/': case '<':
sb.append(' ');
break;
default:
break;
}
++pos;
}
private boolean consumeIgnorable() {
@SuppressWarnings("hiding") // final
String css = this.css;
@SuppressWarnings("hiding") // final
int cssLimit = this.cssLimit;
int posBefore = pos;
while (pos < cssLimit) {
char ch = css.charAt(pos);
if (ch <= 0x20
// Treat a BOM as white-space so that it is ignored at the beginning
// of a file.
|| ch == '\ufeff') {
++pos;
} else if (pos + 1 == cssLimit) {
break;
} else if (ch == '/') {
char next = css.charAt(pos + 1);
if (next == '*') {
pos += 2;
while (pos < cssLimit) {
int ast = css.indexOf('*', pos);
if (ast < 0) {
pos = cssLimit; // Unclosed /* comment */
break;
} else {
// Advance over a run of '*'s.
pos = ast + 1;
while (pos < cssLimit && css.charAt(pos) == '*') {
++pos;
}
if (pos < cssLimit && css.charAt(pos) == '/') {
++pos;
break;
}
}
}
} else if (next == '/') { // Non-standard but widely supported
while (++pos < cssLimit) {
if (isLineTerminator(css.charAt(pos))) { break; }
}
} else {
break;
}
} else if (ch == '<') {
if (pos + 3 < cssLimit
&& '!' == css.charAt(pos + 1)
&& '-' == css.charAt(pos + 2)
&& '-' == css.charAt(pos + 3)) {
pos += 4;
} else {
break;
}
} else if (ch == '-') {
if (pos + 2 < cssLimit
&& '-' == css.charAt(pos + 1)
&& '>' == css.charAt(pos + 2)) {
pos += 3;
} else {
break;
}
} else {
break;
}
}
if (pos == posBefore) {
return false;
} else {
breakOutput();
return true;
}
}
private void breakOutput() {
int last = sb.length() - 1;
if (last >= 0 && sb.charAt(last) != ' ') { sb.append(' '); }
}
private void consumeColumn() {
pos += 2;
sb.append("||");
}
private void consumeMatch(char ch) {
pos += 2;
sb.append(ch).append('=');
}
private void consumeIdent(boolean allowFirstDigit) {
@SuppressWarnings("hiding") // final
int cssLimit = this.cssLimit;
int last = -1, nCodepoints = 0;
int sbAtStart = sb.length();
int posAtStart = pos;
while (pos < cssLimit) {
int posBefore = pos;
int decoded = readCodepoint();
if (decoded == '\\') {
decoded = consumeAndDecodeEscapeSequence();
} else {
++pos;
}
if (decoded >= 0 && isIdentPart(decoded)) {
if (!allowFirstDigit && nCodepoints < 2
&& '0' <= decoded && decoded <= '9') {
// Don't allow encoded identifiers that look like numeric tokens
// like \-1 or ones that start with an encoded decimal digit.
if (last == '-' || last == -1) {
pos = posAtStart;
sb.setLength(sbAtStart);
return;
}
}
sb.appendCodePoint(decoded);
last = decoded;
++nCodepoints;
} else {
pos = posBefore;
return;
}
}
}
private boolean consumeAtKeyword() {
assert css.charAt(pos) == '@';
int bufferLengthBeforeWrite = sb.length();
sb.append('@');
int posBeforeKeyword = ++pos;
consumeIdent(false);
if (pos == posBeforeKeyword) {
--pos; // back up over '@'
sb.setLength(bufferLengthBeforeWrite); // Unwrite the '@'
return false;
} else {
return true;
}
}
private int consumeAndDecodeEscapeSequence() {
@SuppressWarnings("hiding") // final
String css = this.css;
@SuppressWarnings("hiding") // final
int cssLimit = this.cssLimit;
assert css.charAt(pos) == '\\';
if (pos + 1 >= cssLimit) { return -1; }
char esc = css.charAt(pos + 1);
if (isLineTerminator(esc)) { return -1; }
int escLower = esc | 32;
if (('0' <= esc && esc <= '9')
|| ('a' <= escLower && escLower <= 'f')) {
int hexValue = 0;
int hexStart = pos + 1;
int hexLimit = Math.min(pos + 7, cssLimit);
int hexEnd = hexStart;
do {
hexValue = (hexValue << 4)
| (esc <= '9' ? esc - '0' : escLower - ('a' - 10));
++hexEnd;
if (hexEnd == hexLimit) { break; }
esc = css.charAt(hexEnd);
escLower = esc | 32;
} while (('0' <= esc && esc <= '9')
|| ('a' <= escLower && escLower <= 'f'));
if (!Character.isDefined(hexValue)) {
hexValue = 0xfffd;
}
pos = hexEnd;
if (pos < cssLimit) {
// A sequence of hex digits can be followed by a space that allows
// so that code-point U+A followed by the letter 'b' can be rendered
// as "\a b" since "\ab" specifies the single code-point U+AB.
char next = css.charAt(pos);
if (next == ' ' || next == '\t' || isLineTerminator(next)) {
++pos;
}
}
return hexValue;
}
pos += 2;
return esc;
}
private static final long HEX_ENCODED_BITMASK =
(1L << 0) | LINE_TERMINATOR_BITMASK
| (1L << '"') | (1L << '\'') | (1L << '&') | (1L << '<') | (1L << '>');
private static boolean isHexEncoded(int codepoint) {
return (0 <= codepoint && codepoint < 63
&& 0 != ((1L << codepoint) & HEX_ENCODED_BITMASK));
}
private void encodeCharOntoOutput(int codepoint, int last) {
switch (codepoint) {
case '\\': sb.append("\\\\"); break;
case '\0': sb.append("\\0"); break;
case '\n': sb.append("\\a"); break;
case '\f': sb.append("\\c"); break;
case '\r': sb.append("\\d"); break;
case '\"': sb.append("\\22"); break;
case '&': sb.append("\\26"); break;
case '\'': sb.append("\\27"); break;
case '<': sb.append("\\3c"); break;
case '>': sb.append("\\3e"); break;
// The set of escapes above that end with a hex digit must appear in
// HEX_ENCODED_BITMASK.
case '-':
sb.append('-');
break;
default:
if (isHexEncoded(last)
// We need to put a space after a trailing hex digit if the
// next encoded character on the output would be another hex
// digit or a space character. The other space characters
// are handled above.
&& (codepoint == ' ' || codepoint == '\t'
|| ('0' <= codepoint && codepoint <= '9')
|| ('a' <= (codepoint | 32) && (codepoint | 32) <= 'f'))) {
sb.append(' ');
}
sb.appendCodePoint(codepoint);
break;
}
}
private TokenType consumeNumberOrPercentageOrDimension() {
@SuppressWarnings("hiding") // final
String css = this.css;
@SuppressWarnings("hiding") // final
int cssLimit = this.cssLimit;
boolean isZero = true;
int intStart = pos;
if (intStart < cssLimit) {
char ch = css.charAt(intStart);
if (ch == '-' || ch == '+') {
++intStart;
}
}
// Find the integer part after any sign.
int intEnd = intStart;
for (; intEnd < cssLimit; ++intEnd) {
char ch = css.charAt(intEnd);
if (!('0' <= ch && ch <= '9')) { break; }
if (ch != '0') { isZero = false; }
}
// Find a fraction like ".5" or ".".
int fractionStart = intEnd;
int fractionEnd = fractionStart;
if (fractionEnd < cssLimit && '.' == css.charAt(fractionEnd)) {
++fractionEnd;
for (; fractionEnd < cssLimit; ++fractionEnd) {
char ch = css.charAt(fractionEnd);
if (!('0' <= ch && ch <= '9')) { break; }
if (ch != '0') { isZero = false; }
}
}
int exponentStart = fractionEnd;
int exponentIntStart = exponentStart;
int exponentEnd = exponentStart;
boolean isExponentZero = true;
if (exponentStart < cssLimit && 'e' == (css.charAt(exponentStart) | 32)) {
// 'e' and 'e' in "5e-f" for a
exponentEnd = exponentStart + 1;
if (exponentEnd < cssLimit) {
char ch = css.charAt(exponentEnd);
if (ch == '+' || ch == '-') { ++exponentEnd; }
}
exponentIntStart = exponentEnd;
for (; exponentEnd < cssLimit; ++exponentEnd) {
char ch = css.charAt(exponentEnd);
if (!('0' <= ch && ch <= '9')) { break; }
if (ch != '0') { isExponentZero = false; }
}
// Since
// dimension := <number> <ident>
// the below are technically valid dimensions even though they appear
// to have incomplete exponents:
// 5e
// 5ex
// 5e-
if (exponentEnd == exponentIntStart) { // Incomplete exponent.
exponentIntStart = exponentEnd = exponentStart;
isExponentZero = true;
}
}
int unitStart = exponentEnd;
// Skip over space between number and unit.
// Many user-agents allow "5 ex" instead of "5ex".
while (unitStart < cssLimit) {
char ch = css.charAt(unitStart);
if (ch == ' ' || isLineTerminator(ch)) {
++unitStart;
} else {
break;
}
}
if (sb.length() != 0 && isIdentPart(sb.charAt(sb.length() - 1))) {
sb.append(' ');
}
// Normalize the number onto the buffer.
// We will normalize and unit later.
// Skip the sign if it is positive.
if (intStart != pos && '-' == css.charAt(pos) && !isZero) {
sb.append('-');
}
if (isZero) {
sb.append('0');
} else {
// Strip leading zeroes from the integer and exponent and trailing
// zeroes from the fraction.
while (intStart < intEnd && css.charAt(intStart) == '0') { ++intStart; }
while (fractionEnd > fractionStart
&& css.charAt(fractionEnd - 1) == '0') {
--fractionEnd;
}
if (intStart == intEnd) {
sb.append('0'); // .5 -> 0.5
} else {
sb.append(css, intStart, intEnd);
}
if (fractionEnd > fractionStart + 1) { // 5. -> 5; 5.0 -> 5
sb.append(css, fractionStart, fractionEnd);
}
if (!isExponentZero) {
sb.append('e');
// 1e+1 -> 1e1
if ('-' == css.charAt(exponentIntStart - 1)) { sb.append('-'); }
while (exponentIntStart < exponentEnd
&& css.charAt(exponentIntStart) == '0') {
++exponentIntStart;
}
sb.append(css, exponentIntStart, exponentEnd);
}
}
int unitEnd;
TokenType type;
if (unitStart < cssLimit && '%' == css.charAt(unitStart)) {
unitEnd = unitStart + 1;
type = TokenType.PERCENTAGE;
sb.append('%');
} else {
// The grammar says that any identifier following a number is a unit.
int bufferBeforeUnit = sb.length();
pos = unitStart;
consumeIdent(false);
int bufferAfterUnit = sb.length();
boolean knownUnit = isWellKnownUnit(
sb, bufferBeforeUnit, bufferAfterUnit);
if (unitStart == exponentEnd // No intervening space
|| knownUnit) {
unitEnd = pos;
// 3IN -> 3in
for (int i = bufferBeforeUnit; i < bufferAfterUnit; ++i) {
char ch = sb.charAt(i);
if ('A' <= ch && ch <= 'Z') { sb.setCharAt(i, (char) (ch | 32)); }
}
} else {
unitEnd = unitStart = exponentEnd;
sb.setLength(bufferBeforeUnit);
}
type = unitStart == unitEnd
? TokenType.NUMBER
: knownUnit
? TokenType.DIMENSION
: TokenType.BAD_DIMENSION;
}
pos = unitEnd;
if (type != TokenType.PERCENTAGE
&& pos < cssLimit && css.charAt(pos) == '.') {
sb.append(' ');
}
return type;
}
private TokenType consumeString() {
@SuppressWarnings("hiding") // final
String css = this.css;
@SuppressWarnings("hiding") // final
int cssLimit = this.cssLimit;
char delim = css.charAt(pos);
assert delim == '"' || delim == '\'';
++pos;
int startOfStringOnOutput = sb.length();
sb.append('\'');
int last = -1;
boolean closed = false;
while (pos < cssLimit) {
char ch = css.charAt(pos);
if (ch == delim) {
++pos;
closed = true;
break;
}
if (isLineTerminator(ch)) { break; }
int decoded = ch;
if (ch == '\\') {
if (pos + 1 < cssLimit && isLineTerminator(css.charAt(pos+1))) {
// consume it but generate no tokens.
// Lookahead to treat a \r\n sequence as one line-terminator.
if (pos + 2 < cssLimit
&& css.charAt(pos+1) == '\r' && css.charAt(pos+2) == '\n') {
pos += 3;
} else {
pos += 2;
}
continue;
} else {
decoded = consumeAndDecodeEscapeSequence();
if (decoded < 0) {
break;
}
}
} else {
++pos;
}
encodeCharOntoOutput(decoded, last);
last = decoded;
}
if (closed) {
sb.append('\'');
return TokenType.STRING;
} else { // Drop <bad-string>s
sb.setLength(startOfStringOnOutput);
breakOutput();
return TokenType.WHITESPACE;
}
}
private @Nullable TokenType consumeHash() {
assert css.charAt(pos) == '#';
++pos;
int beforeIdent = pos;
consumeIdent(true);
if (pos == beforeIdent) {
pos = beforeIdent - 1;
return null;
}
for (int i = beforeIdent; i < pos; ++i) {
char chLower = (char) (css.charAt(i) | 32);
if (!(('0' <= chLower && chLower <= '9')
|| ('a' <= chLower && chLower <= 'f'))) {
return TokenType.HASH_ID;
}
}
return TokenType.HASH_UNRESTRICTED;
}
private boolean consumeUnicodeRange() {
@SuppressWarnings("hiding") // final
final String css = this.css;
@SuppressWarnings("hiding") // final
final int cssLimit = this.cssLimit;
assert pos < cssLimit && (css.charAt(pos) | 32) == 'u';
final int start = pos;
final int startOfOutput = sb.length();
++pos;
boolean ok = false;
parse:
try {
if (pos == cssLimit || css.charAt(pos) != '+') {
break parse;
}
++pos;
sb.append("U+");
int numStartDigits = 0;
while (pos < cssLimit && numStartDigits < 6) {
char chLower = (char) (css.charAt(pos) | 32);
if (('0' <= chLower && chLower <= '9')
|| ('a' <= chLower && chLower <= 'f')) {
sb.append(chLower);
++numStartDigits;
++pos;
} else {
break;
}
}
if (numStartDigits == 0) {
break parse;
}
boolean hasQmark = false;
while (pos < cssLimit && numStartDigits < 6 && css.charAt(pos) == '?') {
hasQmark = true;
sb.append('?');
++numStartDigits;
++pos;
}
if (numStartDigits == 0) {
break parse;
}
if (pos < cssLimit && css.charAt(pos) == '-') {
if (!hasQmark) {
// Look for end of range.
++pos;
sb.append('-');
int numEndDigits = 0;
while (pos < cssLimit && numEndDigits < 6) {
char chLower = (char) (css.charAt(pos) | 32);
if (('0' <= chLower && chLower <= '9')
|| ('a' <= chLower && chLower <= 'f')) {
++numEndDigits;
++pos;
sb.append(chLower);
} else {
break;
}
}
if (numEndDigits == 0) {
// Back up over '-'
--pos;
sb.append(' ');
}
} else {
sb.append(' ');
}
}
ok = true;
} finally {
if (!ok) {
pos = start;
sb.setLength(startOfOutput);
}
}
return ok;
}
private @Nullable TokenType consumeIdentOrUrlOrFunction() {
int bufferStart = sb.length();
int posBefore = pos;
consumeIdent(false);
if (pos == posBefore) { return null; }
boolean parenAfter = pos < cssLimit && css.charAt(pos) == '(';
if (sb.length() - bufferStart == 3
&& 'u' == (sb.charAt(bufferStart) | 32)
&& 'r' == (sb.charAt(bufferStart + 1) | 32)
&& 'l' == (sb.charAt(bufferStart + 2) | 32)) {
if (parenAfter && consumeUrlValue()) {
sb.setCharAt(bufferStart, 'u');
sb.setCharAt(bufferStart + 1, 'r');
sb.setCharAt(bufferStart + 2, 'l');
return TokenType.URL;
} else {
sb.setLength(bufferStart);
breakOutput();
return TokenType.WHITESPACE;
}
} else if (parenAfter) {
openBracket('(');
++pos;
return TokenType.FUNCTION;
} else {
if (pos + 1 < cssLimit && '.' == css.charAt(pos)) {
// Prevent merging of ident and number as in
// border:solid.1cm black
// when .1 is rewritten to 0.1 becoming
// border:solid0.1cm black
char next = css.charAt(pos + 1);
if ('0' <= next && next <= '9') {
sb.append(' ');
}
}
return TokenType.IDENT;
}
}
private boolean consumeUrlValue() {
@SuppressWarnings("hiding") // final
String css = this.css;
@SuppressWarnings("hiding") // final
int cssLimit = this.cssLimit;
if (pos == cssLimit || css.charAt(pos) != '(') { return false; }
++pos;
// skip space.
for (; pos < cssLimit; ++pos) {
char ch = css.charAt(pos);
if (ch != ' ' && !isLineTerminator(ch)) { break; }
}
// Find the value.
int delim;
if (pos < cssLimit) {
char ch = pos < cssLimit ? css.charAt(pos) : '\0';
if (ch == '"' || ch == '\'') {
delim = ch;
++pos;
} else {
delim = '\0';
}
} else {
return false;
}
sb.append("('");
while (pos < cssLimit) {
int decoded = readCodepoint();
if (delim != 0) {
if (decoded == delim) {
++pos;
break;
}
} else if (decoded <= ' ' || decoded == ')') {
break;
}
if (decoded == '\\') {
decoded = consumeAndDecodeEscapeSequence();
if (decoded < 0) {
return false;
}
} else {
++pos;
}
// Any character not in the RFC 3986 safe set is %-encoded.
if (decoded < URL_SAFE.length && URL_SAFE[decoded]) {
sb.appendCodePoint(decoded);
} else if (decoded < 0x80) {
sb.append('%')
.append(HEX_DIGITS[(decoded >>> 4) & 0xf])
.append(HEX_DIGITS[(decoded >>> 0) & 0xf]);
} else if (decoded < 0x800) {
int octet0 = 0xc0 | ((decoded >>> 6) & 0x1f),
octet1 = 0x80 | (decoded & 0x3f);
sb.append('%')
.append(HEX_DIGITS[(octet0 >>> 4) & 0xf])
.append(HEX_DIGITS[(octet0 >>> 0) & 0xf])
.append('%')
.append(HEX_DIGITS[(octet1 >>> 4) & 0xf])
.append(HEX_DIGITS[(octet1 >>> 0) & 0xf]);
} else if (decoded < 0x10000) {
int octet0 = 0xe0 | ((decoded >>> 12) & 0xf),
octet1 = 0x80 | ((decoded >>> 6) & 0x3f),
octet2 = 0x80 | (decoded & 0x3f);
sb.append('%')
.append(HEX_DIGITS[(octet0 >>> 4) & 0xf])
.append(HEX_DIGITS[(octet0 >>> 0) & 0xf])
.append('%')
.append(HEX_DIGITS[(octet1 >>> 4) & 0xf])
.append(HEX_DIGITS[(octet1 >>> 0) & 0xf])
.append('%')
.append(HEX_DIGITS[(octet2 >>> 4) & 0xf])
.append(HEX_DIGITS[(octet2 >>> 0) & 0xf]);
} else {
int octet0 = 0xf0 | ((decoded >>> 18) & 0x7),
octet1 = 0x80 | ((decoded >>> 12) & 0x3f),
octet2 = 0x80 | ((decoded >>> 6) & 0x3f),
octet3 = 0x80 | (decoded & 0x3f);
sb.append('%')
.append(HEX_DIGITS[(octet0 >>> 4) & 0xf])
.append(HEX_DIGITS[(octet0 >>> 0) & 0xf])
.append('%')
.append(HEX_DIGITS[(octet1 >>> 4) & 0xf])
.append(HEX_DIGITS[(octet1 >>> 0) & 0xf])
.append('%')
.append(HEX_DIGITS[(octet2 >>> 4) & 0xf])
.append(HEX_DIGITS[(octet2 >>> 0) & 0xf])
.append('%')
.append(HEX_DIGITS[(octet3 >>> 4) & 0xf])
.append(HEX_DIGITS[(octet3 >>> 0) & 0xf]);
}
}
// skip space.
for (; pos < cssLimit; ++pos) {
char ch = css.charAt(pos);
if (ch != ' ' && !isLineTerminator(ch)) { break; }
}
if (pos < cssLimit && css.charAt(pos) == ')') {
++pos;
} else {
// broken-url
}
sb.append("')");
return true;
}
/**
* Reads the codepoint at pos, leaving pos at the index of the last code
* unit.
*/
private int readCodepoint() {
@SuppressWarnings("hiding") // final
String css = this.css;
char ch = css.charAt(pos);
if (Character.isHighSurrogate(ch) && pos + 1 < cssLimit) {
char next = css.charAt(pos + 1);
if (Character.isLowSurrogate(next)) {
++pos;
return 0x10000 + (((ch - 0xd800) << 10) | (next - 0xdc00));
}
}
return ch;
}
}
private static final boolean isIdentPart(int cp) {
return cp >= 0x80
? Character.isDefined(cp) && cp != '\ufeff'
: IDENT_PART_ASCII[cp];
}
private static final boolean isDecimal(char ch) {
return '0' <= ch && ch <= '9';
}
private static final boolean[] IDENT_PART_ASCII = new boolean[128];
static {
for (int i = '0'; i <= '9'; ++i) { IDENT_PART_ASCII[i] = true; }
for (int i = 'A'; i <= 'Z'; ++i) { IDENT_PART_ASCII[i] = true; }
for (int i = 'a'; i <= 'z'; ++i) { IDENT_PART_ASCII[i] = true; }
IDENT_PART_ASCII['_'] = true;
IDENT_PART_ASCII['-'] = true;
}
private static final int LINE_TERMINATOR_BITMASK =
(1 << '\n') | (1 << '\r') | (1 << '\f');
private static boolean isLineTerminator(char ch) {
return ch < 0x20 && 0 != (LINE_TERMINATOR_BITMASK & (1 << ch));
}
private static int[] expandIfNecessary(int[] arr, int limit, int needed) {
int neededLength = limit + needed;
int length = arr.length;
if (length >= neededLength) { return arr; }
int[] newArr = new int[Math.max(16, Math.max(neededLength, length * 2))];
System.arraycopy(arr, 0, newArr, 0, limit);
return newArr;
}
private static int[] truncateOrShare(int[] arr, int limit) {
if (limit == 0) { return ZERO_INTS; }
if (limit == arr.length) {
return arr;
}
int[] trunc = new int[limit];
System.arraycopy(arr, 0, trunc, 0, limit);
return trunc;
}
private static final int LENGTH_UNIT_TYPE = 0;
private static final int ANGLE_UNIT_TYPE = 1;
private static final int TIME_UNIT_TYPE = 2;
private static final int FREQUENCY_UNIT_TYPE = 3;
private static final int RESOLUTION_UNIT_TYPE = 4;
/**
* See http://dev.w3.org/csswg/css-values/#lengths and
* http://dev.w3.org/csswg/css-values/#other-units
*/
private static final Trie UNIT_TRIE = new Trie(
ImmutableMap.<String, Integer>builder()
.put("em", LENGTH_UNIT_TYPE)
.put("ex", LENGTH_UNIT_TYPE)
.put("ch", LENGTH_UNIT_TYPE) // Width of zero character
.put("rem", LENGTH_UNIT_TYPE) // Root element font-size
.put("vh", LENGTH_UNIT_TYPE)
.put("vw", LENGTH_UNIT_TYPE)
.put("vmin", LENGTH_UNIT_TYPE)
.put("vmax", LENGTH_UNIT_TYPE)
.put("px", LENGTH_UNIT_TYPE)
.put("mm", LENGTH_UNIT_TYPE)
.put("cm", LENGTH_UNIT_TYPE)
.put("in", LENGTH_UNIT_TYPE)
.put("pt", LENGTH_UNIT_TYPE)
.put("pc", LENGTH_UNIT_TYPE)
.put("deg", ANGLE_UNIT_TYPE)
.put("rad", ANGLE_UNIT_TYPE)
.put("grad", ANGLE_UNIT_TYPE)
.put("turn", ANGLE_UNIT_TYPE)
.put("s", TIME_UNIT_TYPE)
.put("ms", TIME_UNIT_TYPE)
.put("hz", FREQUENCY_UNIT_TYPE)
.put("khz", FREQUENCY_UNIT_TYPE)
.put("dpi", RESOLUTION_UNIT_TYPE)
.put("dpcm", RESOLUTION_UNIT_TYPE)
.put("dppx", RESOLUTION_UNIT_TYPE)
.build());
static boolean isWellKnownUnit(CharSequence s, int start, int end) {
if (start == end) { return false; }
Trie t = UNIT_TRIE;
for (int i = start; i < end; ++i) {
char ch = s.charAt(i);
t = t.lookup('A' <= ch && ch <= 'Z' ? (char) (ch | 32) : ch);
if (t == null) { return false; }
}
return t.isTerminal();
}
static boolean isWellKnownUnit(CharSequence s) {
return isWellKnownUnit(s, 0, s.length());
}
private static final boolean[] URL_SAFE = new boolean[128];
static {
// From RFC 3986
// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
for (int i = 'A'; i <= 'Z'; ++i) { URL_SAFE[i] = true; }
for (int i = 'a'; i <= 'z'; ++i) { URL_SAFE[i] = true; }
for (int i = '0'; i <= '9'; ++i) { URL_SAFE[i] = true; }
URL_SAFE['-'] = true;
URL_SAFE['.'] = true;
URL_SAFE['_'] = true;
URL_SAFE['~'] = true;
// gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
URL_SAFE[':'] = true;
URL_SAFE['/'] = true;
URL_SAFE['?'] = true;
URL_SAFE['#'] = true;
URL_SAFE['['] = true;
URL_SAFE[']'] = true;
URL_SAFE['@'] = true;
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
// / "*" / "+" / "," / ";" / "="
URL_SAFE['!'] = true;
URL_SAFE['$'] = true;
URL_SAFE['&'] = true;
// Only used in obsolete mark rule and special in unquoted URLs or comment
// delimiters.
// URL_SAFE['\''] = true;
// URL_SAFE['('] = true;
// URL_SAFE[')'] = true;
// URL_SAFE['*'] = true;
URL_SAFE['+'] = true;
URL_SAFE[','] = true;
URL_SAFE[';'] = true;
URL_SAFE['='] = true;
// % is used to encode unsafe octets.
URL_SAFE['%'] = true;
}
private static final char[] HEX_DIGITS = {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f'
};
}
| apache-2.0 |
relvaner/actor4j-core | src/test/java/io/actor4j/core/features/ActorFeature.java | 5959 | /*
* Copyright (c) 2015-2021, David A. Bauer. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.actor4j.core.features;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Before;
import org.junit.Test;
import io.actor4j.core.ActorSystem;
import io.actor4j.core.actors.Actor;
import io.actor4j.core.messages.ActorMessage;
import static org.junit.Assert.*;
public class ActorFeature {
protected ActorSystem system;
@Before
public void before() {
system = new ActorSystem();
}
@Test(timeout=5000)
public void test_preStart_addChild() {
CountDownLatch testDone = new CountDownLatch(1);
UUID parent = system.addActor(() -> new Actor("parent") {
protected UUID child;
@Override
public void preStart() {
child = addChild(() -> new Actor("child") {
@Override
public void receive(ActorMessage<?> message) {
testDone.countDown();
}
});
}
@Override
public void receive(ActorMessage<?> message) {
tell(null, 0, child);
}
});
system.start();
system.send(new ActorMessage<>(null, 0, system.SYSTEM_ID, parent));
try {
testDone.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
system.shutdownWithActors(true);
}
@Test(timeout=5000)
public void test_getActorFromPath_getActorPath() {
AtomicReference<UUID> childA = new AtomicReference<>(null);
AtomicReference<UUID> childB = new AtomicReference<>(null);
AtomicReference<UUID> childBA = new AtomicReference<>(null);
AtomicReference<UUID> childBB = new AtomicReference<>(null);
AtomicReference<UUID> childC = new AtomicReference<>(null);
UUID parentA = system.addActor(() -> new Actor("parentA") {
@Override
public void preStart() {
childA.set(addChild(() -> new Actor("childA") {
@Override
public void receive(ActorMessage<?> message) {
}
}));
childB.set(addChild(() -> new Actor("childB") {
@Override
public void preStart() {
childBA.set(addChild(() -> new Actor("childBA") {
@Override
public void receive(ActorMessage<?> message) {
}
}));
childBB.set(addChild(() -> new Actor("childBB") {
@Override
public void receive(ActorMessage<?> message) {
}
}));
}
@Override
public void receive(ActorMessage<?> message) {
}
}));
childC.set(addChild(() -> new Actor("childC") {
@Override
public void receive(ActorMessage<?> message) {
}
}));
}
@Override
public void receive(ActorMessage<?> message) {
}
});
AtomicReference<UUID> child = new AtomicReference<>(null);
AtomicReference<UUID> childWithoutName = new AtomicReference<>(null);
UUID parentB = system.addActor(() -> new Actor("parentB") {
@Override
public void preStart() {
child.set(addChild(() -> new Actor("child") {
@Override
public void receive(ActorMessage<?> message) {
}
}));
childWithoutName.set(addChild(() -> new Actor() {
@Override
public void receive(ActorMessage<?> message) {
}
}));
}
@Override
public void receive(ActorMessage<?> message) {
}
});
system.start(() -> {
assertEquals(null, system.getActorFromPath(null));
assertEquals(system.USER_ID, system.getActorFromPath(""));
assertEquals(system.USER_ID, system.getActorFromPath("/"));
assertEquals("/", system.getActorPath(system.USER_ID));
assertEquals(parentA, system.getActorFromPath("parentA"));
assertEquals(parentA, system.getActorFromPath("/parentA"));
assertEquals("/parentA", system.getActorPath(parentA));
assertEquals(parentA, system.getActorFromPath(parentA.toString()));
assertEquals(childA.get(), system.getActorFromPath("parentA/childA"));
assertEquals("/parentA/childA", system.getActorPath(childA.get()));
assertEquals(childB.get(), system.getActorFromPath("parentA/childB"));
assertEquals("/parentA/childB", system.getActorPath(childB.get()));
assertEquals(childBA.get(), system.getActorFromPath("parentA/childB/childBA"));
assertEquals("/parentA/childB/childBA", system.getActorPath(childBA.get()));
assertEquals(childBB.get(), system.getActorFromPath("parentA/childB/childBB"));
assertEquals("/parentA/childB/childBB", system.getActorPath(childBB.get()));
assertEquals(childC.get(), system.getActorFromPath("parentA/childC"));
assertEquals("/parentA/childC", system.getActorPath(childC.get()));
assertEquals(parentB, system.getActorFromPath("parentB"));
assertEquals(parentB, system.getActorFromPath("/parentB"));
assertEquals(parentB, system.getActorFromPath(parentB.toString()));
assertEquals("/parentB", system.getActorPath(parentB));
assertEquals(child.get(), system.getActorFromPath("parentB/child"));
assertEquals(child.get(), system.getActorFromPath("/parentB/child"));
assertEquals(child.get(), system.getActorFromPath(parentB.toString()+"/"+child.toString()));
assertEquals("/parentB/child", system.getActorPath(child.get()));
assertEquals("/parentB/"+childWithoutName.toString(), system.getActorPath(childWithoutName.get()));
}, null);
system.shutdownWithActors(true);
}
}
| apache-2.0 |
Gaia3D/mago3d | mago3d-user/src/main/java/gaia3d/service/UserGroupService.java | 1453 | package gaia3d.service;
import java.util.List;
import gaia3d.domain.user.UserGroup;
import gaia3d.domain.user.UserGroupMenu;
import gaia3d.domain.user.UserGroupRole;
/**
* 사용자 그룹 관리
*
* @author jeongdae
*
*/
public interface UserGroupService {
/**
* 사용자 그룹 목록
*
* @param userGroup
* @return
*/
List<UserGroup> getListUserGroup(UserGroup userGroup);
/**
* 자식 사용자 그룹 개수
*
* @param userGroupId
* @return
*/
int getChildUserGroupCount(Integer userGroupId);
/**
* 사용자 그룹 정보 취득
* @param userGroupId
* @return
*/
UserGroup getUserGroup(Integer userGroupId);
/**
* 사용자 그룹 정보 취득
* @param userId
* @return
*/
UserGroup getUserGroupByUserId(String userId);
/**
* 자식 사용자 그룹 중 순서가 최대인 사용자 그룹 검색
* @param userGroupId
* @return
*/
UserGroup getMaxViewOrderChildUserGroup(Integer userGroupId);
/**
* 사용자 그룹 메뉴 권한 목록
*
* @param userGroupMenu
* @return
*/
List<UserGroupMenu> getListUserGroupMenu(UserGroupMenu userGroupMenu);
/**
* 사용자 그룹 Role 목록
* @param userGroupRole
* @return
*/
List<UserGroupRole> getListUserGroupRole(UserGroupRole userGroupRole);
/**
* 사용자 그룹 Role Key 목록
* @param userGroupRole
* @return
*/
List<String> getListUserGroupRoleKey(UserGroupRole userGroupRole);
}
| apache-2.0 |
powertac/powertac-server | visualizer2/src/main/java/org/powertac/visualizer/config/package-info.java | 89 | /**
* Spring Framework configuration files.
*/
package org.powertac.visualizer.config;
| apache-2.0 |
NorthernStars/jWumpus | jWumpus/src/de/northernstars/jwumpus/gui/Editor.java | 16146 | package de.northernstars.jwumpus.gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.google.gson.Gson;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;
import de.northernstars.jwumpus.core.WinConditions;
import de.northernstars.jwumpus.core.WumpusMap;
import de.northernstars.jwumpus.core.WumpusObjects;
import de.northernstars.jwumpus.gui.widgets.PaletteButton;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.GridLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.UIManager;
import java.awt.Toolkit;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.KeyStroke;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
import javax.swing.JComboBox;
@SuppressWarnings("serial")
public class Editor extends JFrame {
private static final Logger logger = LogManager.getLogger();
private static final String title = "Map Editor";
private WumpusMap map = null;
private File mapFile = null;
private WumpusObjects selectedTool = null;
private JPanel contentPane;
private JPanel panelMap;
private JTextField txtColumns;
private JTextField txtRows;
private JMenuBar menuBar;
private JMenu mnFile;
private JMenuItem mntmNewMap;
private JMenuItem mntmOpenMap;
private JMenuItem mntmSaveMap;
private JMenuItem mntmSaveMapAs;
private JButton btnUpdateMap;
private JLabel lblNewLabel;
private JTextField txtMapName;
private JMenuItem mntmClose;
private JScrollPane panelPaletteTop;
private JPanel panelPalette;
private JLabel lblPlayerArrows;
private JTextField txtPlayerArrows;
private JLabel lblMaxTimeouts;
private JTextField txtMaxTimeouts;
private JLabel lblMaxTimeoutTime;
private JTextField txtMaxTimeoutTime;
private JLabel lblWinCondition;
private JComboBox<WinConditions> cmbWinCondition;
/**
* Launches the editor.
* @param wumpusMap {@link WumpusMap} to load or null to load empty default map
*/
public static void showEditor(WumpusMap wumpusMap) {
final WumpusMap mWumpusMap = wumpusMap;
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Editor frame = new Editor(mWumpusMap);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Editor(WumpusMap wumpusMap){
this();
if( wumpusMap != null ){
map = wumpusMap;
updateGuiMap();
}
}
/**
* Create the frame.
*/
public Editor() {
setTitle(title);
setIconImage(Toolkit.getDefaultToolkit().getImage(Editor.class.getResource("/de/northernstars/jwumpus/gui/img/map.png")));
setBounds(100, 100, 800, 650);
menuBar = new JMenuBar();
setJMenuBar(menuBar);
mnFile = new JMenu("File");
mnFile.setMnemonic('F');
menuBar.add(mnFile);
mntmNewMap = new JMenuItem("New map");
mntmNewMap.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
mntmNewMap.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newMap();
}
});
mnFile.add(mntmNewMap);
mntmOpenMap = new JMenuItem("Open map");
mntmOpenMap.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
mntmOpenMap.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openMap();
}
});
mnFile.add(mntmOpenMap);
mntmSaveMap = new JMenuItem("Save map");
mntmSaveMap.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
mntmSaveMap.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveMap();
}
});
mnFile.add(mntmSaveMap);
mntmSaveMapAs = new JMenuItem("Save map as");
mntmSaveMapAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK));
mntmSaveMapAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveMapAs();
}
});
mnFile.add(mntmSaveMapAs);
mntmClose = new JMenuItem("Close");
mntmClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK));
mntmClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
mnFile.add(mntmClose);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("default:grow"),
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,},
new RowSpec[] {
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
RowSpec.decode("default:grow"),
FormFactory.RELATED_GAP_ROWSPEC,}));
panelMap = new JPanel();
panelMap.setBorder(new TitledBorder(null, "Map", TitledBorder.LEADING, TitledBorder.TOP, null, null));
contentPane.add(panelMap, "2, 2, 1, 3, fill, fill");
panelMap.setLayout(new GridLayout(4, 4, 0, 0));
JPanel panelMapData = new JPanel();
panelMapData.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Map data", TitledBorder.LEADING, TitledBorder.TOP, null, null));
contentPane.add(panelMapData, "4, 2, fill, fill");
panelMapData.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("default:grow"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("default:grow"),
FormFactory.RELATED_GAP_COLSPEC,},
new RowSpec[] {
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,}));
JLabel lblNewLabel1 = new JLabel("Columns:");
lblNewLabel1.setHorizontalAlignment(SwingConstants.RIGHT);
panelMapData.add(lblNewLabel1, "2, 4, right, default");
txtColumns = new JTextField();
txtColumns.setText("5");
panelMapData.add(txtColumns, "4, 4, fill, default");
txtColumns.setColumns(3);
JLabel lblNewLabel2 = new JLabel("Rows:");
lblNewLabel2.setHorizontalAlignment(SwingConstants.RIGHT);
panelMapData.add(lblNewLabel2, "2, 2, right, default");
txtRows = new JTextField();
txtRows.setText("5");
panelMapData.add(txtRows, "4, 2, fill, default");
txtRows.setColumns(3);
btnUpdateMap = new JButton("Update map");
btnUpdateMap.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int mapDimension[] = getMapDimensionFromGui();
int playerArrows = getPlayerArrowsFromGui();
int maxTimeouts = getMaxTimeouts();
long timeoutTime = getMaxTimeoutTime();
WinConditions winCondition = cmbWinCondition.getItemAt( cmbWinCondition.getSelectedIndex() );
String mapName = txtMapName.getText();
if( map != null
&& mapDimension[0] > 0 && mapDimension[1] > 0 ){
map.setRows(mapDimension[0]);
map.setColumns(mapDimension[1]);
map.setMapName(mapName);
map.setPlayerArrows(playerArrows);
map.setMaxTimeouts(maxTimeouts);
map.setMaxTimeoutTime(timeoutTime);
map.setWinCondition(winCondition);
updateGuiMap();
}
}
});
lblNewLabel = new JLabel("Name:");
lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT);
panelMapData.add(lblNewLabel, "2, 6, right, default");
txtMapName = new JTextField();
txtMapName.setText("Wumpus World");
panelMapData.add(txtMapName, "4, 6, fill, default");
txtMapName.setColumns(10);
lblPlayerArrows = new JLabel("Player arrows:");
lblPlayerArrows.setHorizontalAlignment(SwingConstants.RIGHT);
panelMapData.add(lblPlayerArrows, "2, 8, right, default");
txtPlayerArrows = new JTextField();
txtPlayerArrows.setText("1");
panelMapData.add(txtPlayerArrows, "4, 8, fill, default");
txtPlayerArrows.setColumns(10);
lblMaxTimeouts = new JLabel("Max timeouts:");
lblMaxTimeouts.setHorizontalAlignment(SwingConstants.RIGHT);
panelMapData.add(lblMaxTimeouts, "2, 10, right, default");
txtMaxTimeouts = new JTextField();
txtMaxTimeouts.setText("3");
panelMapData.add(txtMaxTimeouts, "4, 10, fill, default");
txtMaxTimeouts.setColumns(10);
lblMaxTimeoutTime = new JLabel("Max timeout time [ms]:");
lblMaxTimeoutTime.setHorizontalAlignment(SwingConstants.RIGHT);
panelMapData.add(lblMaxTimeoutTime, "2, 12, right, default");
txtMaxTimeoutTime = new JTextField();
txtMaxTimeoutTime.setText("10");
panelMapData.add(txtMaxTimeoutTime, "4, 12, fill, default");
txtMaxTimeoutTime.setColumns(10);
lblWinCondition = new JLabel("Win condition:");
lblWinCondition.setHorizontalAlignment(SwingConstants.CENTER);
panelMapData.add(lblWinCondition, "2, 14, 3, 1");
cmbWinCondition = new JComboBox<WinConditions>();
cmbWinCondition.setModel( new DefaultComboBoxModel<WinConditions>(WinConditions.values()) );
panelMapData.add(cmbWinCondition, "2, 16, 3, 1, fill, default");
panelMapData.add(btnUpdateMap, "2, 18, 3, 1");
panelPaletteTop = new JScrollPane();
panelPaletteTop.setBorder(new TitledBorder(null, "Palette", TitledBorder.LEADING, TitledBorder.TOP, null, null));
contentPane.add(panelPaletteTop, "4, 4, fill, fill");
panelPalette = new JPanel();
panelPaletteTop.setViewportView(panelPalette);
panelPalette.setLayout(new GridLayout(0, 1, 5, 5));
// update palette
setPalette();
// create new map
newMap();
}
/**
* Sets palette objects
*/
private void setPalette(){
// clear palette
panelPalette.removeAll();
for( WumpusObjects tool : WumpusObjects.values() ){
// add new PaletteButton to gui panel
panelPalette.add( new PaletteButton(this, tool) );
}
// update gui panel
panelPalette.repaint();
panelPalette.validate();
}
/**
* @return {@link Integer} array {@code [rows, cloumns]} with dimension of map, set in gui.
*/
private int[] getMapDimensionFromGui(){
try{
int rows = Integer.parseInt(txtRows.getText());
int columns = Integer.parseInt(txtColumns.getText());
return new int[]{rows, columns};
}catch (NumberFormatException e){
logger.error("Rows or columns field contains no integer value.");
}
return new int[]{0,0};
}
/**
* @return {@link Integer} number of arrows for player on map
*/
private int getPlayerArrowsFromGui(){
try{
int arrows = Integer.parseInt(txtPlayerArrows.getText());
return arrows;
}catch (NumberFormatException e){
logger.error("Player arrows field contains no integer value.");
}
return 0;
}
/**
* @return {@link Integer} maximum number of timeouts before player is dead
*/
private int getMaxTimeouts(){
try{
int timeouts = Integer.parseInt(txtMaxTimeouts.getText());
return timeouts;
}catch (NumberFormatException e){
logger.error("Max timeouts is no integer value");
}
return 3;
}
/**
* @return {@link Long} of maximum response time of ai
*/
private long getMaxTimeoutTime(){
try{
long timeout = Long.parseLong(txtMaxTimeoutTime.getText());
return timeout;
}catch (NumberFormatException e){
logger.error("Max timeouts is no number");
}
return 10;
}
/**
* Creates a new map
*/
private void newMap(){
// create new map
int mapDimension[] = getMapDimensionFromGui();
String mapName = txtMapName.getText();
map = new WumpusMap(mapDimension[0], mapDimension[1], mapName);
mapFile = null;
logger.debug("Created new map with " + mapDimension[0] +" rows and " + mapDimension[1] + " columns.");
// update gui
updateGuiMap();
}
/**
* Opens a map from file
*/
private void openMap(){
// create file chooser dialog and open it
JFileChooser chooser = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("jWumpus map files (.map)", "map");
chooser.addChoosableFileFilter(filter);
chooser.setFileFilter(filter);
chooser.setAcceptAllFileFilterUsed(false);
if( chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION ){
mapFile = chooser.getSelectedFile();
try{
if( mapFile.exists() && mapFile.canRead() ){
map = (new Gson()).fromJson(new FileReader(mapFile), WumpusMap.class);
updateGuiMap();
}
else{
logger.error("Can not read from file " + mapFile.getPath());
}
}catch (FileNotFoundException e){
logger.error("Can not find file " + mapFile.getPath());
}
}
}
/**
* Saves map to set mapFile
*/
private void saveMap(){
if( mapFile != null ){
try{
// check if file exsits
if( !mapFile.exists() ){
// check file extension
if( !mapFile.getPath().endsWith(".map") ){
mapFile = new File(mapFile.getPath() + ".map");
}
// check if file is readable
if( !mapFile.createNewFile() ){
logger.error("Could not create file " + mapFile.getPath());
return;
}
}
// write data to file
if( mapFile.canWrite() ){
BufferedWriter out = new BufferedWriter( new FileWriter(mapFile) );
out.write( (new Gson()).toJson(map) );
out.close();
}
else{
logger.error("Can not write to file " + mapFile.getPath());
}
}catch (IOException e){
logger.error("Error while writing data to file " + mapFile.getPath());
}
}
else{
saveMapAs();
}
}
/**
* Saves map as new file
*/
private void saveMapAs(){
// create file chooser dialog and open it
JFileChooser chooser = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("jWumpus map files (.map)", "map");
chooser.addChoosableFileFilter(filter);
chooser.setFileFilter(filter);
chooser.setAcceptAllFileFilterUsed(false);
chooser.setSelectedFile(new File("wumpus world.map"));
if( chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION ){
// save file
mapFile = chooser.getSelectedFile();
saveMap();
}
}
/**
* Updates the current map on gui
*/
public void updateGuiMap(){
if( map != null ){
// show map dimension and frame title
txtRows.setText( Integer.toString(map.getRows()) );
txtColumns.setText( Integer.toString(map.getColumns()) );
txtMapName.setText( map.getMapName() );
txtMaxTimeouts.setText( Integer.toString(map.getMaxTimeouts()) );
txtMaxTimeoutTime.setText( Long.toString(map.getMaxTimeoutTime()) );
cmbWinCondition.setSelectedIndex( map.getWinCondition().ordinal() );
setTitle(title + " - " + map.getMapName());
// update gui map
MainFrame.updateGuiMap(this, map, panelMap);
}
}
/**
* Sets the {@code WumpusObjects} tool selected from palette panel
* @param tool
*/
public void setTool(WumpusObjects tool){
selectedTool = tool;
}
/**
* @return Currently selected {@code WumpusObjects} tool or {@code null} if no tool selected
*/
public WumpusObjects getTool(){
return selectedTool;
}
}
| apache-2.0 |
stevenhva/InfoLearn_OpenOLAT | src/main/java/org/olat/course/nodes/projectbroker/ProjectStateColumnRenderer.java | 3379 | /**
* OLAT - Online Learning and Training<br>
* http://www.olat.org
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br>
* University of Zurich, Switzerland.
* <hr>
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* This file has been modified by the OpenOLAT community. Changes are licensed
* under the Apache 2.0 license as the original file.
*/
package org.olat.course.nodes.projectbroker;
import java.util.Locale;
import org.olat.core.gui.components.table.CustomCellRenderer;
import org.olat.core.gui.render.Renderer;
import org.olat.core.gui.render.StringOutput;
import org.olat.core.gui.translator.PackageTranslator;
import org.olat.core.logging.AssertException;
import org.olat.core.util.Util;
import org.olat.course.nodes.projectbroker.datamodel.Project;
/**
* This renderer is used by the ProjectListController to render the 'Project-State' column.
* The renderer distinguish between render for table content (with HTML) and render for export (no HTML code).
*
* @author Christian Guretzki
*/
public class ProjectStateColumnRenderer implements CustomCellRenderer {
/**
* Renderer for project-broker state-column. Render the following state as bold : STATE_FINAL_ENROLLED,
* STATE_PROV_ENROLLED and STATE_ENROLLED e.g. '<b>eingeschrieben</b>'.
* When the renderer is null, no HTML tags will be added. The 'val' will be translated in any case.
*
* @param val must be from type String and one of the state-i18n keys
* @see org.olat.core.gui.components.table.CustomCellRenderer#render(org.olat.core.gui.render.StringOutput, org.olat.core.gui.render.Renderer, java.lang.Object, java.util.Locale, int, java.lang.String)
*/
@Override
public void render(StringOutput sb, Renderer renderer, Object val, Locale locale, int alignment, String action) {
String projectState;
PackageTranslator translator = new PackageTranslator( Util.getPackageName(this.getClass()) , locale);
if (val==null) {
// don't render nulls
return;
}
if (val instanceof String) {
projectState = (String)val;
} else {
throw new AssertException("ProjectStateColumnRenderer: Wrong object type, could only render String");
}
if (renderer==null) {
// if no renderer is set, then we assume it's a table export - in which case we don't want the htmls (<b>)
sb.append(translator.translate(projectState));
} else {
// add <b> for certain values
if ( projectState.equals(Project.STATE_FINAL_ENROLLED)
|| projectState.equals(Project.STATE_PROV_ENROLLED)
|| projectState.equals(Project.STATE_ENROLLED) ) {
sb.append("<b>");
sb.append(translator.translate(projectState));
sb.append("</b>");
} else {
sb.append(translator.translate(projectState));
}
}
}
}
| apache-2.0 |
mches/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/implementation/ExceptionMethod.java | 9386 | package net.bytebuddy.implementation;
import lombok.EqualsAndHashCode;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.scaffold.InstrumentedType;
import net.bytebuddy.implementation.bytecode.*;
import net.bytebuddy.implementation.bytecode.constant.TextConstant;
import net.bytebuddy.implementation.bytecode.member.MethodInvocation;
import org.objectweb.asm.MethodVisitor;
import static net.bytebuddy.matcher.ElementMatchers.isConstructor;
import static net.bytebuddy.matcher.ElementMatchers.takesArguments;
/**
* This implementation causes a {@link java.lang.Throwable} to be thrown when the instrumented method is invoked.
* Be aware that the Java Virtual machine does not care about exception declarations and will throw any
* {@link java.lang.Throwable} from any method even if the method does not declared a checked exception.
*/
@EqualsAndHashCode
public class ExceptionMethod implements Implementation, ByteCodeAppender {
/**
* The type of the exception that is thrown.
*/
private final TypeDescription throwableType;
/**
* The construction delegation which is responsible for creating the exception to be thrown.
*/
private final ConstructionDelegate constructionDelegate;
/**
* Creates a new instance of an implementation for throwing throwables.
*
* @param throwableType The type of the exception to be thrown.
* @param constructionDelegate A delegate that is responsible for calling the isThrowable's constructor.
*/
public ExceptionMethod(TypeDescription throwableType, ConstructionDelegate constructionDelegate) {
this.throwableType = throwableType;
this.constructionDelegate = constructionDelegate;
}
/**
* Creates an implementation that creates a new instance of the given isThrowable type on each method invocation
* which is then thrown immediately. For this to be possible, the given type must define a default constructor
* which is visible from the instrumented type.
*
* @param exceptionType The type of the isThrowable.
* @return An implementation that will throw an instance of the isThrowable on each method invocation of the
* instrumented methods.
*/
public static Implementation throwing(Class<? extends Throwable> exceptionType) {
return throwing(new TypeDescription.ForLoadedType(exceptionType));
}
/**
* Creates an implementation that creates a new instance of the given isThrowable type on each method invocation
* which is then thrown immediately. For this to be possible, the given type must define a default constructor
* which is visible from the instrumented type.
*
* @param exceptionType The type of the isThrowable.
* @return An implementation that will throw an instance of the isThrowable on each method invocation of the
* instrumented methods.
*/
public static Implementation throwing(TypeDescription exceptionType) {
if (!exceptionType.isAssignableTo(Throwable.class)) {
throw new IllegalArgumentException(exceptionType + " does not extend throwable");
}
return new ExceptionMethod(exceptionType, new ConstructionDelegate.ForDefaultConstructor(exceptionType));
}
/**
* Creates an implementation that creates a new instance of the given isThrowable type on each method invocation
* which is then thrown immediately. For this to be possible, the given type must define a constructor that
* takes a single {@link java.lang.String} as its argument.
*
* @param exceptionType The type of the isThrowable.
* @param message The string that is handed to the constructor. Usually an exception message.
* @return An implementation that will throw an instance of the isThrowable on each method invocation of the
* instrumented methods.
*/
public static Implementation throwing(Class<? extends Throwable> exceptionType, String message) {
return throwing(new TypeDescription.ForLoadedType(exceptionType), message);
}
/**
* Creates an implementation that creates a new instance of the given isThrowable type on each method invocation
* which is then thrown immediately. For this to be possible, the given type must define a constructor that
* takes a single {@link java.lang.String} as its argument.
*
* @param exceptionType The type of the isThrowable.
* @param message The string that is handed to the constructor. Usually an exception message.
* @return An implementation that will throw an instance of the isThrowable on each method invocation of the
* instrumented methods.
*/
public static Implementation throwing(TypeDescription exceptionType, String message) {
if (!exceptionType.isAssignableTo(Throwable.class)) {
throw new IllegalArgumentException(exceptionType + " does not extend throwable");
}
return new ExceptionMethod(exceptionType, new ConstructionDelegate.ForStringConstructor(exceptionType, message));
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public ByteCodeAppender appender(Target implementationTarget) {
return this;
}
@Override
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
StackManipulation.Size stackSize = new StackManipulation.Compound(
constructionDelegate.make(),
Throw.INSTANCE
).apply(methodVisitor, implementationContext);
return new Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
/**
* A construction delegate is responsible for calling a Throwable's constructor.
*/
public interface ConstructionDelegate {
/**
* Creates a stack manipulation that creates pushes all constructor arguments onto the operand stack
* and subsequently calls the constructor.
*
* @return A stack manipulation for constructing a isThrowable.
*/
StackManipulation make();
/**
* A construction delegate that calls the default constructor.
*/
@EqualsAndHashCode
class ForDefaultConstructor implements ConstructionDelegate {
/**
* The type of the exception that is to be thrown.
*/
private final TypeDescription exceptionType;
/**
* The constructor that is used for creating the exception.
*/
private final MethodDescription targetConstructor;
/**
* Creates a new construction delegate that calls a default constructor.
*
* @param exceptionType The type of the isThrowable.
*/
public ForDefaultConstructor(TypeDescription exceptionType) {
this.exceptionType = exceptionType;
this.targetConstructor = exceptionType.getDeclaredMethods()
.filter(isConstructor().and(takesArguments(0))).getOnly();
}
@Override
public StackManipulation make() {
return new StackManipulation.Compound(
TypeCreation.of(exceptionType),
Duplication.SINGLE,
MethodInvocation.invoke(targetConstructor));
}
}
/**
* A construction delegate that calls a constructor that takes a single string as its argument.
*/
@EqualsAndHashCode
class ForStringConstructor implements ConstructionDelegate {
/**
* The type of the exception that is to be thrown.
*/
private final TypeDescription exceptionType;
/**
* The constructor that is used for creating the exception.
*/
private final MethodDescription targetConstructor;
/**
* The {@link java.lang.String} that is to be passed to the exception's constructor.
*/
private final String message;
/**
* Creates a new construction delegate that calls a constructor by handing it the given string.
*
* @param exceptionType The type of the isThrowable.
* @param message The string that is handed to the constructor.
*/
public ForStringConstructor(TypeDescription exceptionType, String message) {
this.exceptionType = exceptionType;
this.targetConstructor = exceptionType.getDeclaredMethods()
.filter(isConstructor().and(takesArguments(String.class))).getOnly();
this.message = message;
}
@Override
public StackManipulation make() {
return new StackManipulation.Compound(
TypeCreation.of(exceptionType),
Duplication.SINGLE,
new TextConstant(message),
MethodInvocation.invoke(targetConstructor));
}
}
}
}
| apache-2.0 |
pmwmedia/tinylog | tinylog-api/src/test/java/org/tinylog/provider/NopLoggingProviderTest.java | 3418 | /*
* Copyright 2016 Martin Winandy
*
* 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.tinylog.provider;
import org.junit.Before;
import org.junit.Test;
import org.tinylog.Level;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link NopLoggingProvider}.
*/
public final class NopLoggingProviderTest {
private NopLoggingProvider provider;
/**
* Initializes NOP logging provider.
*/
@Before
public void init() {
provider = new NopLoggingProvider();
}
/**
* Verifies that there is an associated NOP context provider.
*/
@Test
public void getContextProvider() {
assertThat(provider.getContextProvider()).isInstanceOf(NopContextProvider.class);
}
/**
* Verifies that the minimum global severity level is {@link Level#OFF}.
*/
@Test
public void getGlobalMinimumLevel() {
assertThat(provider.getMinimumLevel()).isEqualTo(Level.OFF);
}
/**
* Verifies that the minimum severity level for a tag is {@link Level#OFF}.
*/
@Test
public void getTaggedMinimumLevel() {
assertThat(provider.getMinimumLevel(null)).isEqualTo(Level.OFF);
assertThat(provider.getMinimumLevel("test")).isEqualTo(Level.OFF);
}
/**
* Verifies that all severity levels for untagged log entries are disabled.
*/
@Test
public void isEnabledUntagged() {
assertThat(provider.isEnabled(0, null, Level.TRACE)).isFalse();
assertThat(provider.isEnabled(1, null, Level.DEBUG)).isFalse();
assertThat(provider.isEnabled(2, null, Level.INFO)).isFalse();
assertThat(provider.isEnabled(3, null, Level.WARN)).isFalse();
assertThat(provider.isEnabled(4, null, Level.ERROR)).isFalse();
}
/**
* Verifies that all severity levels for tagged log entries are disabled.
*/
@Test
public void isEnabledTagged() {
assertThat(provider.isEnabled(0, "test", Level.TRACE)).isFalse();
assertThat(provider.isEnabled(1, "test", Level.DEBUG)).isFalse();
assertThat(provider.isEnabled(2, "test", Level.INFO)).isFalse();
assertThat(provider.isEnabled(3, "test", Level.WARN)).isFalse();
assertThat(provider.isEnabled(4, "test", Level.ERROR)).isFalse();
}
/**
* Verifies that {@link NopLoggingProvider#log(int, String, Level, Throwable, Object, Object...)} is invokable
* without throwing any exceptions.
*/
@Test
public void logWithDepthIndex() {
provider.log(0, null, Level.DEBUG, null, null, (Object[]) null);
provider.log(1, null, Level.ERROR, null, null, (Object[]) null);
}
/**
* Verifies that {@link NopLoggingProvider#log(String, String, Level, Throwable, Object, Object...)} is invokable
* without throwing any exceptions.
*/
@Test
public void logWithLoggerClass() {
provider.log(NopLoggingProvider.class.getName(), null, Level.DEBUG, null, null, (Object[]) null);
}
/**
* Verifies that {@code shutdown()} method is invokable without throwing any exceptions.
*/
@Test
public void shutdown() {
provider.shutdown();
}
}
| apache-2.0 |
yangjunlin-const/WhileTrueCoding | JavaBase/src/main/java/com/yjl/javabase/thinkinjava/reusing/Wind.java | 443 | package com.yjl.javabase.thinkinjava.reusing;//: reusing/Wind.java
// Inheritance & upcasting.
class Instrument {
public void play() {}
static void tune(Instrument i) {
// ...
i.play();
}
}
// Wind objects are instruments
// because they have the same interface:
public class Wind extends Instrument {
public static void main(String[] args) {
Wind flute = new Wind();
Instrument.tune(flute); // Upcasting
}
} ///:~
| apache-2.0 |
GeorgeTea/practice | design-patterns/src/template/CaffeineBeverage.java | 613 | package template;
/**
* Created by george on 6/3/15.
*/
public abstract class CaffeineBeverage {
public void prepareRecipe() {
boilWater();
brew();
pourInCup();
if (customerWantsCondiments()) {
addCondiments();
}
}
protected void boilWater() {
System.out.println("Boiling water");
}
protected abstract void brew();
protected void pourInCup() {
System.out.println("Pouring into cup");
}
protected abstract void addCondiments();
protected boolean customerWantsCondiments() {
return true;
}
}
| apache-2.0 |
OSGP/Platform | osgp-adapter-ws-tariffswitching/src/main/java/org/opensmartgridplatform/adapter/ws/tariffswitching/application/mapping/ws/TariffScheduleToScheduleConverter.java | 2921 | /**
* Copyright 2015 Smart Society Services B.V.
*
* 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
*/
package org.opensmartgridplatform.adapter.ws.tariffswitching.application.mapping.ws;
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
import org.opensmartgridplatform.adapter.ws.schema.tariffswitching.schedulemanagement.TariffSchedule;
import org.opensmartgridplatform.adapter.ws.schema.tariffswitching.schedulemanagement.TariffValue;
import org.opensmartgridplatform.domain.core.exceptions.ValidationException;
import org.opensmartgridplatform.domain.core.valueobjects.ActionTimeType;
import org.opensmartgridplatform.domain.core.valueobjects.LightValue;
import org.opensmartgridplatform.domain.core.valueobjects.ScheduleEntry;
import org.opensmartgridplatform.domain.core.valueobjects.WeekDayType;
import ma.glasnost.orika.CustomConverter;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.metadata.Type;
public class TariffScheduleToScheduleConverter extends CustomConverter<TariffSchedule, ScheduleEntry> {
@Override
public ScheduleEntry convert(final TariffSchedule source, final Type<? extends ScheduleEntry> destinationType,
final MappingContext context) {
final ScheduleEntry schedule = new ScheduleEntry();
// Copy values
schedule.setWeekDay(this.mapperFacade.map(source.getWeekDay(), WeekDayType.class));
schedule.setStartDay(this.mapperFacade.map(source.getStartDay(), DateTime.class));
schedule.setEndDay(this.mapperFacade.map(source.getEndDay(), DateTime.class));
schedule.setTime(source.getTime());
schedule.setIndex(source.getIndex());
schedule.setIsEnabled(source.isIsEnabled());
schedule.setMinimumLightsOn(source.getMinimumLightsOn());
try {
// Set the lightvalue
// For now a High tariff means the Relay is switched off (Situation
// in Zaltbommel)
// schedule.setLightValue( Arrays.asList(new LightValue(null,
// !source.isHigh(), null)) )
final List<LightValue> lightValues = new ArrayList<>();
for (final TariffValue tariffValue : source.getTariffValue()) {
final LightValue lightValue = new LightValue(tariffValue.getIndex(), !tariffValue.isHigh(), null);
lightValues.add(lightValue);
}
schedule.setLightValue(lightValues);
} catch (final ValidationException e) {
throw new IllegalArgumentException(e);
}
// Set defaults for Tariff schedules
schedule.setActionTime(ActionTimeType.ABSOLUTETIME);
schedule.setTriggerType(null);
return schedule;
}
}
| apache-2.0 |
vam-google/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/HttpJsonZoneOperationCallableFactory.java | 3556 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.compute.v1.stub;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.httpjson.ApiMessage;
import com.google.api.gax.httpjson.HttpJsonCallSettings;
import com.google.api.gax.httpjson.HttpJsonCallableFactory;
import com.google.api.gax.httpjson.HttpJsonStubCallableFactory;
import com.google.api.gax.rpc.BatchingCallSettings;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import javax.annotation.Generated;
import javax.annotation.Nullable;
// AUTO-GENERATED DOCUMENTATION AND CLASS
/**
* HTTP callable factory implementation for compute.
*
* <p>This class is for advanced usage.
*/
@Generated("by gapic-generator")
@BetaApi("The surface for use by generated code is not stable yet and may change in the future.")
public class HttpJsonZoneOperationCallableFactory
implements HttpJsonStubCallableFactory<ApiMessage, BackgroundResource> {
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createUnaryCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
UnaryCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createUnaryCallable(
httpJsonCallSettings, callSettings, clientContext);
}
@BetaApi(
"The surface for long-running operations is not stable yet and may change in the future.")
@Override
@Nullable
public <RequestT, ResponseT, MetadataT>
OperationCallable<RequestT, ResponseT, MetadataT> createOperationCallable(
HttpJsonCallSettings<RequestT, ApiMessage> httpJsonCallSettings,
OperationCallSettings<RequestT, ResponseT, MetadataT> operationCallSettings,
ClientContext clientContext,
BackgroundResource operationsStub) {
return null;
}
@Override
public <RequestT, ResponseT, PagedListResponseT>
UnaryCallable<RequestT, PagedListResponseT> createPagedCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
PagedCallSettings<RequestT, ResponseT, PagedListResponseT> pagedCallSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createPagedCallable(
httpJsonCallSettings, pagedCallSettings, clientContext);
}
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createBatchingCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
BatchingCallSettings<RequestT, ResponseT> batchingCallSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createBatchingCallable(
httpJsonCallSettings, batchingCallSettings, clientContext);
}
}
| apache-2.0 |
sdinot/hipparchus | hipparchus-optim/src/test/java/org/hipparchus/optim/nonlinear/vector/leastsquares/SequentialGaussNewtonOptimizerWithLUTest.java | 4467 | /*
* Licensed to the Hipparchus project under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The Hipparchus project licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hipparchus.optim.nonlinear.vector.leastsquares;
import java.io.IOException;
import org.hipparchus.exception.LocalizedCoreFormats;
import org.hipparchus.exception.MathIllegalStateException;
import org.hipparchus.linear.LUDecomposer;
import org.hipparchus.optim.LocalizedOptimFormats;
import org.hipparchus.optim.SimpleVectorValueChecker;
import org.hipparchus.optim.nonlinear.vector.leastsquares.LeastSquaresProblem.Evaluation;
import org.junit.Assert;
import org.junit.Test;
/**
* <p>Some of the unit tests are re-implementations of the MINPACK <a
* href="http://www.netlib.org/minpack/ex/file17">file17</a> and <a
* href="http://www.netlib.org/minpack/ex/file22">file22</a> test files.
* The redistribution policy for MINPACK is available <a
* href="http://www.netlib.org/minpack/disclaimer">here</a>/
*
*/
public class SequentialGaussNewtonOptimizerWithLUTest
extends AbstractSequentialLeastSquaresOptimizerAbstractTest {
@Override
public int getMaxIterations() {
return 1000;
}
@Override
public void defineOptimizer(Evaluation evaluation) {
this.optimizer = new SequentialGaussNewtonOptimizer().
withDecomposer(new LUDecomposer(1.0e-11)).
withFormNormalEquations(true).
withEvaluation(evaluation);
}
@Override
@Test
public void testMoreEstimatedParametersSimple() {
try {
/*
* Exception is expected with this optimizer
*/
super.testMoreEstimatedParametersSimple();
fail(optimizer);
} catch (MathIllegalStateException e) {
Assert.assertEquals(LocalizedOptimFormats.UNABLE_TO_SOLVE_SINGULAR_PROBLEM,
e.getSpecifier());
}
}
@Override
@Test
public void testMoreEstimatedParametersUnsorted() {
try {
/*
* Exception is expected with this optimizer
*/
super.testMoreEstimatedParametersUnsorted();
fail(optimizer);
} catch (MathIllegalStateException e) {
Assert.assertEquals(LocalizedOptimFormats.UNABLE_TO_SOLVE_SINGULAR_PROBLEM,
e.getSpecifier());
}
}
@Test
public void testMaxEvaluations() throws Exception {
try {
CircleVectorial circle = new CircleVectorial();
circle.addPoint( 30.0, 68.0);
circle.addPoint( 50.0, -6.0);
circle.addPoint(110.0, -20.0);
circle.addPoint( 35.0, 15.0);
circle.addPoint( 45.0, 97.0);
LeastSquaresProblem lsp = builder(circle)
.checkerPair(new SimpleVectorValueChecker(1e-30, 1e-30))
.maxIterations(Integer.MAX_VALUE)
.start(new double[]{98.680, 47.345})
.build();
defineOptimizer(null);
optimizer.optimize(lsp);
fail(optimizer);
} catch (MathIllegalStateException e) {
Assert.assertEquals(LocalizedCoreFormats.MAX_COUNT_EXCEEDED, e.getSpecifier());
}
}
@Override
@Test
public void testHahn1()
throws IOException {
/*
* TODO This test leads to a singular problem with the Gauss-Newton
* optimizer. This should be inquired.
*/
try {
super.testHahn1();
} catch (MathIllegalStateException e) {
Assert.assertEquals(LocalizedOptimFormats.UNABLE_TO_SOLVE_SINGULAR_PROBLEM, e.getSpecifier());
}
}
}
| apache-2.0 |
googleads/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202105/DealErrorReason.java | 5310 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.admanager.jaxws.v202105;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for DealError.Reason.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="DealError.Reason">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="CANNOT_ADD_LINE_ITEM_WHEN_SOLD"/>
* <enumeration value="CANNOT_ARCHIVE_LINE_ITEM_WHEN_SOLD"/>
* <enumeration value="CANNOT_ARCHIVE_PROPOSAL_WHEN_SOLD"/>
* <enumeration value="CANNOT_CHANGE_FIELD_REQUIRING_BUYER_APPROVAL"/>
* <enumeration value="CANNOT_GET_SELLER_ID"/>
* <enumeration value="CAN_ONLY_EXECUTE_IF_LOCAL_EDITS"/>
* <enumeration value="MISSING_PROPOSAL_LINE_ITEMS"/>
* <enumeration value="MISSING_ENVIRONMENT"/>
* <enumeration value="MISSING_AD_EXCHANGE_PROPERTY"/>
* <enumeration value="CANNOT_FIND_PROPOSAL_IN_MARKETPLACE"/>
* <enumeration value="CANNOT_GET_PRODUCT"/>
* <enumeration value="NEW_VERSION_FROM_BUYER"/>
* <enumeration value="PROPOSAL_OUT_OF_SYNC_WITH_MARKETPLACE"/>
* <enumeration value="NO_PROPOSAL_CHANGES_FOUND"/>
* <enumeration value="UNKNOWN"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "DealError.Reason")
@XmlEnum
public enum DealErrorReason {
/**
*
* Cannot add new {@link ProposalLineItem proposal line items} to a {@link Proposal} when
* {@link Proposal#isSold} is {@code true}.
*
*
*/
CANNOT_ADD_LINE_ITEM_WHEN_SOLD,
/**
*
* Cannot archive {@link ProposalLineItem proposal line items} from a {@link Proposal} when
* {@link Proposal#isSold} is {@code true}.
*
*
*/
CANNOT_ARCHIVE_LINE_ITEM_WHEN_SOLD,
/**
*
* Cannot archive a {@link Proposal} when {@link Proposal#isSold} is {@code true}.
*
*
*/
CANNOT_ARCHIVE_PROPOSAL_WHEN_SOLD,
/**
*
* Cannot change a field that requires buyer approval during the current operation.
*
*
*/
CANNOT_CHANGE_FIELD_REQUIRING_BUYER_APPROVAL,
/**
*
* Cannot find seller ID for the {@link Proposal}.
*
*
*/
CANNOT_GET_SELLER_ID,
/**
*
* {@link Proposal} must be marked as editable by {@link EditProposalsForNegotiation} before
* performing requested action.
*
*
*/
CAN_ONLY_EXECUTE_IF_LOCAL_EDITS,
/**
*
* {@link Proposal} contains no {@link ProposalLineItem proposal line items}.
*
*
*/
MISSING_PROPOSAL_LINE_ITEMS,
/**
*
* No environment set for {@link Proposal}.
*
*
*/
MISSING_ENVIRONMENT,
/**
*
* The Ad Exchange property is not associated with the current network.
*
*
*/
MISSING_AD_EXCHANGE_PROPERTY,
/**
*
* Cannot find {@link Proposal} in Marketplace.
*
*
*/
CANNOT_FIND_PROPOSAL_IN_MARKETPLACE,
/**
*
* No {@link Product} exists for buyer-initiated programmatic {@link Proposal proposals}.
*
*
*/
CANNOT_GET_PRODUCT,
/**
*
* A new version of the {@link Proposal} was sent from buyer, cannot execute the requested
* action before performing {@link DiscardLocalVersionEdits}.
*
*
*/
NEW_VERSION_FROM_BUYER,
/**
*
* A new version of the {@link Proposal} exists in Marketplace, cannot execute the requested
* action before the proposal is synced to newest revision.
*
*
*/
PROPOSAL_OUT_OF_SYNC_WITH_MARKETPLACE,
/**
*
* No {@link Proposal} changes were found.
*
*
*/
NO_PROPOSAL_CHANGES_FOUND,
/**
*
* The value returned if the actual value is not exposed by the requested API version.
*
*
*/
UNKNOWN;
public String value() {
return name();
}
public static DealErrorReason fromValue(String v) {
return valueOf(v);
}
}
| apache-2.0 |
quarkusio/quarkus | extensions/spring-data-jpa/deployment/src/test/java/io/quarkus/spring/data/deployment/LoginEvent.java | 901 | package io.quarkus.spring.data.deployment;
import java.time.ZonedDateTime;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class LoginEvent {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private User user;
private ZonedDateTime zonedDateTime;
private boolean processed;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public ZonedDateTime getZonedDateTime() {
return zonedDateTime;
}
public void setZonedDateTime(ZonedDateTime zonedDateTime) {
this.zonedDateTime = zonedDateTime;
}
public boolean isProcessed() {
return processed;
}
public void setProcessed(boolean processed) {
this.processed = processed;
}
}
| apache-2.0 |
gouravshenoy/airavata | modules/test-suite/multi-tenanted-airavata/src/main/java/org/apache/airavata/testsuite/multitenantedairavata/utils/ComputeResourceProperties.java | 1793 | /**
*
* 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.airavata.testsuite.multitenantedairavata.utils;
/**
* Created by Ajinkya on 12/14/16.
*/
public class ComputeResourceProperties {
private String computeResourceId;
private String jobSubmissionId;
public String getComputeResourceId() {
return computeResourceId;
}
public void setComputeResourceId(String computeResourceId) {
this.computeResourceId = computeResourceId;
}
public String getJobSubmissionId() {
return jobSubmissionId;
}
public void setJobSubmissionId(String jobSubmissionId) {
this.jobSubmissionId = jobSubmissionId;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ComputeResourceProperties{");
sb.append("computeResourceId='").append(computeResourceId).append('\'');
sb.append(", jobSubmissionId='").append(jobSubmissionId).append('\'');
sb.append('}');
return sb.toString();
}
}
| apache-2.0 |
oehme/analysing-gradle-performance | my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p458/Production9166.java | 1963 | package org.gradle.test.performance.mediummonolithicjavaproject.p458;
public class Production9166 {
private Production9163 property0;
public Production9163 getProperty0() {
return property0;
}
public void setProperty0(Production9163 value) {
property0 = value;
}
private Production9164 property1;
public Production9164 getProperty1() {
return property1;
}
public void setProperty1(Production9164 value) {
property1 = value;
}
private Production9165 property2;
public Production9165 getProperty2() {
return property2;
}
public void setProperty2(Production9165 value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
} | apache-2.0 |
Geomatys/sis | core/sis-metadata/src/test/java/org/apache/sis/metadata/iso/citation/DefaultCitationDateTest.java | 2143 | /*
* 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.metadata.iso.citation;
import java.util.Date;
import org.opengis.metadata.citation.DateType;
import org.opengis.metadata.citation.CitationDate;
import org.apache.sis.util.ComparisonMode;
import org.apache.sis.test.TestCase;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests {@link DefaultCitationDate}, especially the copy constructor.
*
* @author Martin Desruisseaux (Geomatys)
* @version 0.3
* @since 0.3
* @module
*/
public final strictfp class DefaultCitationDateTest extends TestCase {
/**
* Tests the copy constructor.
*
* @see <a href="http://jira.geotoolkit.org/browse/GEOTK-170">GEOTK-170</a>
*/
@Test
public void testCopyConstructor() {
final CitationDate original = new CitationDate() {
@Override public Date getDate() {return new Date(1305716658508L);}
@Override public DateType getDateType() {return DateType.CREATION;}
};
final DefaultCitationDate copy = new DefaultCitationDate(original);
assertEquals(new Date(1305716658508L), copy.getDate());
assertEquals(DateType.CREATION, copy.getDateType());
assertTrue (copy.equals(original, ComparisonMode.BY_CONTRACT));
assertFalse(copy.equals(original, ComparisonMode.STRICT)); // Opportunist test.
}
}
| apache-2.0 |
devexmile/tunetz | app/src/main/java/com/devexmile/tunetz/vijanatz/VijanaTzActivity.java | 6495 | package com.devexmile.tunetz.vijanatz;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.devexmile.tunetz.R;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.purplebrain.adbuddiz.sdk.AdBuddiz;
public class VijanaTzActivity extends AppCompatActivity implements View.OnClickListener {
public int diskImage = 2;
private AdView mAdView;
private Button mGuideButton;
/*
* Return true if the device has a network adapter that is capable of
* accessing the network.
*/
protected static boolean networkEnabled(ConnectivityManager connec) {
// ARE WE CONNECTED TO THE NET
if (connec == null) {
return false;
}
try {
if (connec.getNetworkInfo(1) != null
&& connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED)
return true;
else return connec.getNetworkInfo(0) != null
&& connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED;
} catch (NullPointerException exception) {
return false;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vijanatz);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mGuideButton = (Button) findViewById(R.id.schedule);
mGuideButton.setOnClickListener(this);
// Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
// values/strings.xml.
mAdView = (AdView) findViewById(R.id.ad_view);
AdBuddiz.showAd(this); // this = current Activity
// Create an ad request. Check your logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
// Start loading the ad in the background.
mAdView.loadAd(adRequest);
/*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
// check connections before downloading..
if (!networkEnabled(cm)) {
Toast.makeText(this, "No Network Connection", Toast.LENGTH_LONG)
.show();
}
getFragmentManager()
.beginTransaction()
.replace(R.id.vijanatz_banner_container,
new VijanaTzBannerFragment()).commit();
}
@Override
public void onClick(View v) {
final CharSequence[] items = {"", "", ""
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("VijanaTZ Radio guide");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// Do something with the selection
// mGuideButton.setText(items[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
// Method to rotate the disc images
public void swapDisk(View view) {
final ImageView diskView = (ImageView) findViewById(R.id.vijana_diskImage);
diskView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (diskImage == 0)
diskView.setImageResource(R.drawable.medium_kington);
return true;
}
});
// rotate through disk images
if (diskImage == 0) {
// swap to disk 1
diskView.setImageResource(R.drawable.medium_tribe);
diskImage = 1;
} else if (diskImage == 1) {
// swap to disk 2
diskView.setImageResource(R.drawable.medium_kdictext);
diskImage = 2;
} else if (diskImage == 2) {
diskView.setImageResource(R.drawable.medium_tribe);
diskImage = 3;
} else if (diskImage == 3) {
diskView.setImageResource(R.drawable.medium_chronic);
diskImage = 0;
}
}
public void guideMenu(View view) {
Toast.makeText(this, "CloudsFM Guide", Toast.LENGTH_SHORT)
.show();
}
public void dislikeButton(View view) {
Toast.makeText(this, "Dislike", Toast.LENGTH_LONG)
.show();
}
public void likeButton(View view) {
Toast.makeText(this, "Like", Toast.LENGTH_LONG)
.show();
}
public void playPause(View view) {
}
public void gohome(View view) {
this.finish();
}
/**
* Called when leaving the activity
*/
@Override
public void onPause() {
if (mAdView != null) {
mAdView.pause();
}
super.onPause();
}
/**
* Called when returning to the activity
*/
@Override
public void onResume() {
super.onResume();
if (mAdView != null) {
mAdView.resume();
}
}
/**
* Called before the activity is destroyed
*/
@Override
public void onDestroy() {
if (mAdView != null) {
mAdView.destroy();
}
super.onDestroy();
}
}
| apache-2.0 |
nevenr/vertx-auth | vertx-auth-jdbc/src/main/java/io/vertx/ext/auth/jdbc/impl/AbstractHashingStrategy.java | 1166 | package io.vertx.ext.auth.jdbc.impl;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.ext.auth.PRNG;
import io.vertx.ext.auth.jdbc.JDBCHashStrategy;
public abstract class AbstractHashingStrategy implements JDBCHashStrategy {
private final PRNG random;
protected JsonArray nonces;
AbstractHashingStrategy(Vertx vertx) {
random = new PRNG(vertx);
}
@Override
public String generateSalt() {
byte[] salt = new byte[32];
random.nextBytes(salt);
return bytesToHex(salt);
}
private final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
String bytesToHex(byte[] bytes) {
char[] chars = new char[bytes.length * 2];
for (int i = 0; i < bytes.length; i++) {
int x = 0xFF & bytes[i];
chars[i * 2] = HEX_CHARS[x >>> 4];
chars[1 + i * 2] = HEX_CHARS[0x0F & x];
}
return new String(chars);
}
@Override
public String getHashedStoredPwd(JsonArray row) {
return row.getString(0);
}
@Override
public String getSalt(JsonArray row) {
return row.getString(1);
}
@Override
public void setNonces(JsonArray nonces) {
this.nonces = nonces;
}
}
| apache-2.0 |
halober/ovirt-engine | backend/manager/modules/restapi/interface/definition/src/main/java/org/ovirt/engine/api/resource/AffinityGroupsResource.java | 929 | package org.ovirt.engine.api.resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.ovirt.engine.api.model.AffinityGroup;
import org.ovirt.engine.api.model.AffinityGroups;
@Produces({ ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML })
public interface AffinityGroupsResource {
@GET
public AffinityGroups list();
@POST
@Consumes({ ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML })
public Response add(AffinityGroup affinityGroup);
@DELETE
@Path("{id}")
public Response remove(@PathParam("id") String id);
@Path("{id}")
public AffinityGroupResource getAffinityGroupResource(@PathParam("id") String id);
}
| apache-2.0 |
danfickle/cpp-to-java-source-converter | src/main/java/com/github/danfickle/cpptojavasourceconverter/models/ExpressionModels.java | 29621 | package com.github.danfickle.cpptojavasourceconverter.models;
import java.util.ArrayList;
import java.util.List;
public class ExpressionModels
{
interface PlainString
{
public String toStringPlain();
}
public abstract static class MExpression
{}
public abstract static class MArrayExpression extends MExpression
{
public MExpression operand;
public List<MExpression> subscript = new ArrayList<MExpression>(1);
}
public abstract static class MFieldReferenceExpression extends MExpression
{
public MExpression object;
public String field;
abstract String toStringLhOnly();
abstract String toStringRhOnly();
}
public abstract static class MInfixExpression extends MExpression
{
public MExpression left;
public MExpression right;
public String operator;
}
public abstract static class MPrefixExpression extends MExpression
{
public MExpression operand;
public String operator;
}
public abstract static class MPostfixExpression extends MExpression
{
public MExpression operand;
public String operator;
}
public abstract static class MIdentityExpression extends MExpression implements PlainString
{
public String ident;
}
public abstract static class MDeleteExpression extends MExpression
{
public MExpression operand;
}
public abstract static class MFunctionCallExpressionParent extends MExpression
{
public MExpression name;
public List<MExpression> args = new ArrayList<MExpression>();
}
static String getStringLhs(MExpression model)
{
if (model instanceof MFieldReferenceExpression)
{
return ((MFieldReferenceExpression) model).object.toString();
}
else if (model instanceof MBracketExpression)
{
return getStringLhs(((MBracketExpression) model).operand);
}
else
{
assert(false);
return null;
}
}
static String getStringRhs(MExpression model)
{
if (model instanceof MFieldReferenceExpression)
{
return ((MFieldReferenceExpression) model).field;
}
else if (model instanceof MBracketExpression)
{
return getStringRhs(((MBracketExpression) model).operand);
}
else
{
assert(false);
return null;
}
}
static String getPlainString(MExpression model)
{
if (model instanceof PlainString)
{
return ((PlainString) model).toStringPlain();
}
else if (model instanceof MLiteralExpression)
{
return ((MLiteralExpression) model).literal;
}
else if (model instanceof MBracketExpression)
{
return "(" + getPlainString(((MBracketExpression) model).operand) + ")";
}
else if (!(model instanceof MFieldReferenceExpression))
{
return model.toString();
}
else
{
return null;
}
}
static String joinExpressions(List<MExpression> exprs)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < exprs.size(); i++)
{
sb.append(exprs.get(i).toString());
if (i != exprs.size() - 1)
sb.append(", ");
}
return sb.toString();
}
/**
* Note: MStringExpression breaks the MVC architecture.
*/
public static class MStringExpression extends MExpression
{
public String contents;
@Override
public String toString()
{
return String.format("%s", this.contents);
}
}
public static class MMultiExpression extends MExpression
{
public List<MExpression> exprs = new ArrayList<MExpression>();
@Override
public String toString()
{
return joinExpressions(exprs);
}
}
public static class MAddressOfExpressionArrayItem extends MArrayExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("%s.addressOf()", plain);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.%s.addressOf()", lhs, rhs);
}
}
}
public static class MPostfixExpressionNumberInc extends MPostfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("%s.postInc()", plain);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.%s.postInc()", lhs, rhs);
}
}
}
public static class MPostfixExpressionNumberDec extends MPostfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("%s.postDec()", plain);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.%s.postDec()", lhs, rhs);
}
}
}
public static class MPrefixExpressionNumberInc extends MPrefixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("%s.set(%s + 1)", plain, this.operand);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.%s.set(%s + 1)", lhs, rhs, this.operand);
}
}
}
public static class MPrefixExpressionNumberDec extends MPrefixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("%s.set(%s - 1)", plain, this.operand);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.%s.set(%s - 1)", lhs, rhs, this.operand);
}
}
}
public static class MValueOfExpressionNumber extends MExpression
{
public MExpression operand;
public String type;
@Override
public String toString()
{
return String.format("%s.valueOf(%s)", this.type, this.operand);
}
}
public static class MValueOfExpressionArray extends MExpression
{
public List<MExpression> operands;
public String type;
@Override
public String toString()
{
return String.format("%s.create(%s)", this.type, joinExpressions(this.operands));
}
}
public static class MValueOfExpressionPtr extends MExpression
{
public MExpression operand;
public String type;
@Override
public String toString()
{
return String.format("%s.valueOf(%s)", this.type, this.operand);
}
}
public static class MInfixExpressionWithPtrOnLeft extends MInfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.left);
if (plain != null)
{
return String.format("%s.ptrOffset(%s%s)", plain, this.operator, this.right);
}
else
{
String lhs = getStringLhs(this.left);
String rhs = getStringRhs(this.left);
return String.format("%s.%s.ptrOffset(%s%s)", lhs, rhs, this.operator, this.right);
}
}
}
public static class MInfixExpressionWithPtrOnRight extends MInfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.right);
if (plain != null)
{
return String.format("%s.ptrOffset(%s%s)", plain, this.operator, this.left);
}
else
{
String lhs = getStringLhs(this.right);
String rhs = getStringRhs(this.right);
return String.format("%s.%s.ptrOffset(%s%s)", lhs, rhs, this.operator, this.left);
}
}
}
public static class MInfixExpressionPtrComparison extends MInfixExpression
{
@Override
public String toString()
{
String right2 = getPlainString(this.right);
String left2 = getPlainString(this.left);
if (right2 != null)
{
right2 = String.format("%s.ptrCompare()", right2);
}
else
{
String lhs = getStringLhs(this.right);
String rhs = getStringRhs(this.right);
right2 = String.format("%s.%s.ptrCompare()", lhs, rhs);
}
if (left2 != null)
{
left2 = String.format("%s.ptrCompare()", left2);
}
else
{
String lhs = getStringLhs(this.left);
String rhs = getStringRhs(this.left);
left2 = String.format("%s.%s.ptrCompare()", lhs, rhs);
}
return String.format("%s %s %s", left2, this.operator, right2);
}
}
public static class MCompoundWithPtrOnLeft extends MInfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.left);
if (plain != null)
{
return String.format("%s.ptrAdjust(%s%s)", plain, this.operator, this.right);
}
else
{
String lhs = getStringLhs(this.left);
String rhs = getStringRhs(this.left);
return String.format("%s.%s.ptrAdjust(%s%s)", lhs, rhs, this.operator, this.right);
}
}
}
public static class MPtrCopy extends MExpression
{
public MExpression operand;
@Override
public String toString()
{
return String.format("%s", this.operand);
}
}
public static class MInfixAssignmentWithPtrOnLeft extends MInfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.left);
if (plain != null)
{
return String.format("%s = %s", plain, this.right);
}
else
{
String lhs = getStringLhs(this.left);
String rhs = getStringRhs(this.left);
return String.format("%s.%s = %s", lhs, rhs, this.right);
}
}
}
public static class MRefWrapper extends MExpression
{
public MExpression operand;
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return plain;
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.%s", lhs, rhs);
}
}
}
public static class MAddressOfExpressionPtr extends MExpression
{
public MExpression operand;
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("%s.ptrAddressOf()", plain);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.%s.ptrAddressOf()", lhs, rhs);
}
}
}
public static class MBracketExpression extends MExpression
{
public MExpression operand;
@Override
public String toString()
{
return String.format("(%s)", this.operand);
}
}
public static class MArrayExpressionPtr extends MArrayExpression implements PlainString
{
@Override
public String toString()
{
return this.toStringPlain() + ".get()";
}
@Override
public String toStringPlain()
{
String operand;
String plain = getPlainString(this.operand);
if (plain != null)
{
operand = String.format("%s", plain);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
operand = String.format("%s.%s", lhs, rhs);
}
return String.format("%s.ptrOffset(%s)", operand, joinExpressions(this.subscript));
}
}
public static class MInfixExpressionWithBitfieldOnLeft extends MInfixExpression
{
@Override
public String toString()
{
return String.format("%s %s %s", this.left, this.operator, this.right);
}
}
public static class MInfixAssignmentWithNumberOnLeft extends MInfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.left);
if (plain != null)
{
return String.format("%s.set(%s)", plain, this.right);
}
else
{
String lhs = getStringLhs(this.left);
String rhs = getStringRhs(this.left);
return String.format("%s.%s.set(%s)", lhs, rhs, this.right);
}
}
}
public static class MInfixWithNumberOnLeft extends MInfixExpression
{
@Override
public String toString()
{
return String.format("%s %s %s", this.left, this.operator, this.right);
}
}
public static class MCompoundWithNumberOnLeft extends MInfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.left);
if (plain != null)
{
return String.format("%s.set(%s %s %s)", plain, this.left, this.operator, this.right);
}
else
{
String lhs = getStringLhs(this.left);
String rhs = getStringRhs(this.left);
return String.format("%s.%s.set(%s %s %s)", lhs, rhs, this.left, this.operator, this.right);
}
}
}
public static class MInfixExpressionWithDerefOnLeft extends MInfixExpression
{
@Override
public String toString()
{
return String.format("%s %s %s", this.left, this.operator, this.right);
}
}
public static class MInfixAssignmentWithBitfieldOnLeft extends MInfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.left);
if (plain != null)
{
return String.format("set%s(%s)", plain, this.right);
}
else
{
String lhs = getStringLhs(this.left);
String rhs = getStringRhs(this.left);
return String.format("%s.set%s(%s)", lhs, rhs, this.right);
}
}
}
public static class MInfixAssignmentWithDerefOnLeft extends MInfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.left);
if (plain != null)
{
return String.format("%s.set(%s)", plain, this.right);
}
else
{
String lhs = getStringLhs(this.left);
String rhs = getStringRhs(this.left);
return String.format("%s.%s.set(%s)", lhs, rhs, this.right);
}
}
}
public static class MCompoundWithBitfieldOnLeft extends MInfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.left);
if (plain != null)
{
return String.format("set%s(%s %s %s)", plain, this.left, this.operator, this.right);
}
else
{
String lhs = getStringLhs(this.left);
String rhs = getStringRhs(this.left);
return String.format("%s.set%s(%s %s %s)", lhs, rhs, this.left, this.operator, this.right);
}
}
}
public static class MCompoundWithDerefOnLeft extends MInfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.left);
if (plain != null)
{
return String.format("%s.set(%s %s %s)", plain, this.left, this.operator, this.right);
}
else
{
String lhs = getStringLhs(this.left);
String rhs = getStringRhs(this.left);
return String.format("%s.%s.set(%s %s %s)", lhs, rhs, this.left, this.operator, this.right);
}
}
}
public static class MInfixExpressionPlain extends MInfixExpression
{
@Override
public String toString()
{
return String.format("%s %s %s", this.left, this.operator, this.right);
}
}
public static class MIdentityExpressionPlain extends MIdentityExpression
{
@Override
public String toString()
{
return String.format("%s", this.ident);
}
@Override
public String toStringPlain()
{
return this.toString();
}
}
public static class MIdentityExpressionBitfield extends MIdentityExpression
{
@Override
public String toString()
{
return String.format("get%s()", this.ident);
}
public String toStringPlain()
{
return String.format("%s", this.ident);
}
}
public static class MIdentityExpressionNumber extends MIdentityExpression
{
@Override
public String toString()
{
return String.format("%s.get()", this.ident);
}
@Override
public String toStringPlain()
{
return String.format("%s", this.ident);
}
}
public static class MIdentityExpressionPtr extends MIdentityExpression
{
@Override
public String toString()
{
return String.format("%s.ptrCopy()", this.ident);
}
@Override
public String toStringPlain()
{
return String.format("%s", this.ident);
}
}
public static class MIdentityExpressionDeref extends MIdentityExpression
{
@Override
public String toString()
{
return String.format("%s.get()", this.ident);
}
@Override
public String toStringPlain()
{
return String.format("%s", this.ident);
}
}
public static class MIdentityExpressionEnumerator extends MIdentityExpression
{
public String enumName;
@Override
public String toString()
{
return String.format("%s.%s.val", this.enumName, this.ident);
}
@Override
public String toStringPlain()
{
return this.ident;
}
}
public static class MTernaryExpression extends MExpression
{
public MExpression condition;
public MExpression negative;
public MExpression positive;
@Override
public String toString()
{
return String.format("%s ? %s : %s", this.condition, this.positive, this.negative);
}
}
public static class MFieldReferenceExpressionPlain extends MFieldReferenceExpression
{
@Override
public String toString()
{
return String.format("%s.%s", this.object, this.field);
}
@Override
String toStringLhOnly()
{
return this.object.toString();
}
@Override
String toStringRhOnly()
{
return this.field;
}
}
public static class MFieldReferenceExpressionBitfield extends MFieldReferenceExpression
{
@Override
public String toString()
{
return String.format("%s.get%s()", this.object, this.field);
}
@Override
public String toStringLhOnly()
{
return String.format("%s", this.object);
}
@Override
public String toStringRhOnly()
{
return String.format("%s", this.field);
}
}
public static class MFieldReferenceExpressionNumber extends MFieldReferenceExpression
{
@Override
public String toString()
{
return String.format("%s.%s.get()", this.object, this.field);
}
@Override
public String toStringLhOnly()
{
return String.format("%s", this.object);
}
@Override
public String toStringRhOnly()
{
return String.format("%s", this.field);
}
}
public static class MFieldReferenceExpressionPtr extends MFieldReferenceExpression
{
@Override
public String toString()
{
return String.format("%s.%s.ptrCopy()", this.object, this.field);
}
@Override
public String toStringLhOnly()
{
return String.format("%s", this.object);
}
@Override
public String toStringRhOnly()
{
return String.format("%s", this.field);
}
}
public static class MFieldReferenceExpressionDeref extends MFieldReferenceExpression
{
@Override
public String toString()
{
return String.format("%s.%s.get()", this.object, this.field);
}
@Override
public String toStringLhOnly()
{
return String.format("%s", this.object);
}
@Override
public String toStringRhOnly()
{
return String.format("%s", this.field);
}
}
public static class MFieldReferenceExpressionEnumerator extends MFieldReferenceExpression
{
@Override
public String toString()
{
return String.format("%s.%s", this.object, this.field);
}
@Override
String toStringLhOnly()
{
return this.object.toString();
}
@Override
String toStringRhOnly()
{
return this.field;
}
}
public static class MFunctionCallExpression extends MFunctionCallExpressionParent
{
@Override
public String toString()
{
return String.format("%s(%s)", this.name, joinExpressions(this.args));
}
}
public static class MClassInstanceCreation extends MFunctionCallExpressionParent
{
@Override
public String toString()
{
return String.format("new %s(%s)", this.name, joinExpressions(this.args));
}
}
public static class MLiteralExpression extends MExpression
{
public String literal;
@Override
public String toString()
{
return literal;
}
}
public static class MPrefixExpressionPlain extends MPrefixExpression
{
@Override
public String toString()
{
return String.format("%s%s", this.operator, this.operand);
}
}
public static class MAddressOfExpression extends MExpression
{
public MExpression operand;
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("%s.addressOf()", plain);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.%s.addressOf()", lhs, rhs);
}
}
}
public static class MPostfixExpressionPlain extends MPostfixExpression
{
@Override
public String toString()
{
return String.format("%s%s", this.operand, this.operator);
}
}
public static class MPostfixExpressionPointerInc extends MPostfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("%s.ptrPostInc()", plain);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.%s.ptrPostInc()", lhs, rhs);
}
}
}
public static class MPostfixExpressionPointerDec extends MPostfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("%s.ptrPostDec()", plain);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.%s.ptrPostDec()", lhs, rhs);
}
}
}
public static class MPrefixExpressionPointerInc extends MPrefixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("%s.ptrAdjust(1)", plain);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.%s.ptrAdjust(1)", lhs, rhs);
}
}
}
public static class MPrefixExpressionPointerDec extends MPrefixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("%s.ptrAdjust(-1)", plain);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.%s.ptrAdjust(-1)", lhs, rhs);
}
}
}
public static class MPrefixExpressionPointer extends MPrefixExpression
{
@Override
public String toString()
{
return String.format("%s%s", this.operator, this.operand);
}
}
public static class MPrefixExpressionPointerStar extends MPrefixExpression implements PlainString
{
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("%s.get()", plain);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.%s.get()", lhs, rhs);
}
}
@Override
public String toStringPlain()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("%s", plain);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.%s", lhs, rhs);
}
}
}
public static class MPostfixExpressionBitfieldInc extends MPostfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("postInc%s()", plain);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.postInc%s()", lhs, rhs);
}
}
}
public static class MPostfixExpressionBitfieldDec extends MPostfixExpression
{
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("postDec%s()", plain);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.postDec%s()", lhs, rhs);
}
}
}
public static class MPrefixExpressionBitfieldInc extends MPrefixExpression
{
public MExpression set;
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("set%s(%s + 1)", plain, this.operand);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.set%s(%s + 1)", lhs, rhs, this.operand);
}
}
}
public static class MPrefixExpressionBitfieldDec extends MPrefixExpression
{
public MExpression set;
@Override
public String toString()
{
String plain = getPlainString(this.operand);
if (plain != null)
{
return String.format("set%s(%s - 1)", plain, this.operand);
}
else
{
String lhs = getStringLhs(this.operand);
String rhs = getStringRhs(this.operand);
return String.format("%s.set%s(%s - 1)", lhs, rhs, this.operand);
}
}
}
public static class MPrefixExpressionBitfield extends MPrefixExpression
{
public MExpression set;
@Override
public String toString()
{
return String.format("%s%s", this.operator, this.operand);
}
}
public static class MCastExpression extends MExpression
{
public MExpression operand;
public String type;
@Override
public String toString()
{
return String.format("(%s) %s", this.type, this.operand);
}
}
public static class MCastExpressionToEnum extends MExpression
{
public MExpression operand;
public String type;
@Override
public String toString()
{
return String.format("%s.fromValue(%s)", this.type, this.operand);
}
}
public static class MDeleteObjectSingle extends MDeleteExpression
{
@Override
public String toString()
{
return String.format("DestructHelper.destruct(%s)", this.operand);
}
}
public static class MDeleteObjectMultiple extends MDeleteExpression
{
@Override
public String toString()
{
return String.format("DestructHelper.destructArray(%s)", this.operand);
}
}
public static class MEmptyExpression extends MExpression
{
@Override
public String toString()
{
return String.format("%s", "/* Empty expression */");
}
}
public static class MNewArrayExpression extends MExpression
{
public List<MExpression> sizes = new ArrayList<MExpression>();
public String type;
@Override
public String toString()
{
return String.format("%sMulti.create(%s)", this.type, joinExpressions(this.sizes));
}
}
public static class MNewArrayExpressionObject extends MExpression
{
public List<MExpression> sizes = new ArrayList<MExpression>();
public String type;
@Override
public String toString()
{
return String.format("PTR.newObjPtr(CreateHelper.allocateArray(%s.class, %s", this.type, joinExpressions(this.sizes));
}
}
public static class MNewExpression extends MExpression
{
public String type;
public MExpression argument;
@Override
public String toString()
{
return String.format("PTR.new%sPtr(%s)", this.type, this.argument);
}
}
public static class MNewExpressionObject extends MExpression
{
public String type;
public List<MExpression> arguments = new ArrayList<MExpression>();
@Override
public String toString()
{
return String.format("new %s(%s)", this.type, joinExpressions(this.arguments));
}
}
public static class MAddItemCall extends MExpression
{
public MExpression operand;
public int nextFreeStackId;
@Override
public String toString()
{
return String.format("StackHelper.addItem(%s, %d, __stack)", this.operand, this.nextFreeStackId);
}
}
public static class MOverloadedMethodUnary extends MExpression
{
public String method;
public MExpression object;
public boolean withNullArgForPostIncAndDec;
@Override
public String toString()
{
return String.format("%s.%s(%s)", this.object, this.method, this.withNullArgForPostIncAndDec ? "null" : "");
}
}
public static class MOverloadedFunctionUnary extends MExpression
{
public String function;
public MExpression object;
public boolean withNullArgForPostIncAndDec;
@Override
public String toString()
{
return String.format("%s(%s%s)", this.function, this.object, this.withNullArgForPostIncAndDec ? ", null" : "");
}
}
public static class MOverloadedMethodInfix extends MExpression
{
public String method;
public MExpression object;
public MExpression right;
@Override
public String toString()
{
return String.format("%s.%s(%s)", this.object, this.method, this.right);
}
}
public static class MOverloadedFunctionInfix extends MExpression
{
public String function;
public MExpression left;
public MExpression right;
@Override
public String toString()
{
return String.format("%s(%s, %s)", this.function, this.left, this.right);
}
}
public static class MOverloadedMethodFuncCall extends MExpression
{
public MExpression object;
public List<MExpression> args = new ArrayList<MExpression>();
@Override
public String toString()
{
return String.format("%s.opFunctionCall(%s)", this.object, joinExpressions(this.args));
}
}
public static class MOverloadedMethodSubscript extends MExpression
{
public MExpression object;
public MExpression subscript;
@Override
public String toString()
{
return String.format("%s.opSubscript(%s)", this.object, this.subscript);
}
}
public static class MOverloadedMethodCast extends MExpression
{
public MExpression object;
public String name;
@Override
public String toString()
{
return String.format("%s.%s()", this.object, this.name);
}
}
}
| apache-2.0 |
majinkai/pinpoint | bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java | 3917 | /*
* Copyright 2014 NAVER Corp.
*
* 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.navercorp.pinpoint.bootstrap.config;
import com.navercorp.pinpoint.common.annotations.InterfaceAudience;
import com.navercorp.pinpoint.common.annotations.VisibleForTesting;
import java.util.List;
import java.util.Map;
/**
* @author Woonduk Kang(emeroad)
*/
public interface ProfilerConfig {
int getInterceptorRegistrySize();
String getCollectorSpanServerIp();
int getCollectorSpanServerPort();
String getCollectorStatServerIp();
int getCollectorStatServerPort();
String getCollectorTcpServerIp();
int getCollectorTcpServerPort();
int getStatDataSenderWriteQueueSize();
int getStatDataSenderSocketSendBufferSize();
int getStatDataSenderSocketTimeout();
String getStatDataSenderSocketType();
String getStatDataSenderTransportType();
int getSpanDataSenderWriteQueueSize();
int getSpanDataSenderSocketSendBufferSize();
boolean isTcpDataSenderCommandAcceptEnable();
boolean isTcpDataSenderCommandActiveThreadEnable();
boolean isTcpDataSenderCommandActiveThreadCountEnable();
boolean isTcpDataSenderCommandActiveThreadDumpEnable();
boolean isTcpDataSenderCommandActiveThreadLightDumpEnable();
boolean isTraceAgentActiveThread();
boolean isTraceAgentDataSource();
int getDataSourceTraceLimitSize();
boolean isDeadlockMonitorEnable();
long getDeadlockMonitorInterval();
int getSpanDataSenderSocketTimeout();
String getSpanDataSenderSocketType();
String getSpanDataSenderTransportType();
int getSpanDataSenderChunkSize();
int getStatDataSenderChunkSize();
boolean isProfileEnable();
int getJdbcSqlCacheSize();
boolean isTraceSqlBindValue();
int getMaxSqlBindValueSize();
boolean isSamplingEnable();
int getSamplingRate();
boolean isIoBufferingEnable();
int getIoBufferingBufferSize();
String getProfilerJvmVendorName();
String getProfilerOSName();
int getProfileJvmStatCollectIntervalMs();
int getProfileJvmStatBatchSendCount();
boolean isProfilerJvmStatCollectDetailedMetrics();
long getAgentInfoSendRetryInterval();
@InterfaceAudience.Private
@VisibleForTesting
boolean getStaticResourceCleanup();
Filter<String> getProfilableClassFilter();
List<String> getApplicationTypeDetectOrder();
List<String> getDisabledPlugins();
String getApplicationServerType();
int getCallStackMaxDepth();
boolean isPropagateInterceptorException();
String getProfileInstrumentEngine();
boolean isSupportLambdaExpressions();
boolean isInstrumentMatcherEnable();
InstrumentMatcherCacheConfig getInstrumentMatcherCacheConfig();
boolean isProxyHttpHeaderEnable();
HttpStatusCodeErrors getHttpStatusCodeErrors();
String getInjectionModuleFactoryClazzName();
String getApplicationNamespace();
String readString(String propertyName, String defaultValue);
int readInt(String propertyName, int defaultValue);
DumpType readDumpType(String propertyName, DumpType defaultDump);
long readLong(String propertyName, long defaultValue);
List<String> readList(String propertyName);
boolean readBoolean(String propertyName, boolean defaultValue);
Map<String, String> readPattern(String propertyNamePatternRegex);
}
| apache-2.0 |
kirillkrohmal/krohmal | chapter_009/crudservlet/src/main/java/ru/job4j/controller/UserServlet.java | 2077 | package ru.job4j.controller;
import ru.job4j.validate.ValidateService;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
/**
* Created by Comp on 06.11.2017.
*/
public class UserServlet extends HttpServlet {
private final ValidateService logic = ValidateService.getInstance();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
req.setAttribute("users", this.logic.values());
RequestDispatcher requestDispatcher = req.getRequestDispatcher("views/ViewUsers.jsp");
requestDispatcher.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter printWriter = new PrintWriter(resp.getOutputStream());
printWriter.append(makeAction(req) ? "action done" : "action error");
printWriter.flush();
}
private boolean makeAction(HttpServletRequest req) {
String action = req.getParameter("action");
int id = Integer.parseInt(req.getParameter("id"));
String name = req.getParameter("name");
String login = req.getParameter("login");
String email = req.getParameter("email");
Timestamp createDate = Timestamp.valueOf(req.getParameter("createDate"));
if ("add".equals(action)) {
logic.add(name, email, login, createDate);
return true;
}
if ("update".equals(action)) {
logic.update(id, name, email, login, createDate);
return true;
}
if ("delete".equals(action)) {
logic.delete(id);
return true;
}
return false;
}
}
| apache-2.0 |
fengsmith/mybatis-3 | src/main/java/org/apache/ibatis/session/Configuration.java | 27727 | /**
* Copyright 2009-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.session;
import org.apache.ibatis.binding.MapperRegistry;
import org.apache.ibatis.builder.CacheRefResolver;
import org.apache.ibatis.builder.ResultMapResolver;
import org.apache.ibatis.builder.annotation.MethodResolver;
import org.apache.ibatis.builder.xml.XMLStatementBuilder;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.cache.decorators.FifoCache;
import org.apache.ibatis.cache.decorators.LruCache;
import org.apache.ibatis.cache.decorators.SoftCache;
import org.apache.ibatis.cache.decorators.WeakCache;
import org.apache.ibatis.cache.impl.PerpetualCache;
import org.apache.ibatis.datasource.jndi.JndiDataSourceFactory;
import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;
import org.apache.ibatis.executor.*;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.loader.ProxyFactory;
import org.apache.ibatis.executor.loader.cglib.CglibProxyFactory;
import org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.resultset.DefaultResultSetHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl;
import org.apache.ibatis.logging.jdk14.Jdk14LoggingImpl;
import org.apache.ibatis.logging.log4j.Log4jImpl;
import org.apache.ibatis.logging.log4j2.Log4j2Impl;
import org.apache.ibatis.logging.nologging.NoLoggingImpl;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.InterceptorChain;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.scripting.LanguageDriverRegistry;
import org.apache.ibatis.scripting.defaults.RawLanguageDriver;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.transaction.Transaction;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.apache.ibatis.transaction.managed.ManagedTransactionFactory;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeAliasRegistry;
import org.apache.ibatis.type.TypeHandlerRegistry;
import java.util.*;
/**
* @author Clinton Begin
*/
public class Configuration {
protected Environment environment;
protected boolean safeRowBoundsEnabled = false;
protected boolean safeResultHandlerEnabled = true;
protected boolean mapUnderscoreToCamelCase = false;
protected boolean aggressiveLazyLoading = true;
protected boolean multipleResultSetsEnabled = true;
protected boolean useGeneratedKeys = false;
protected boolean useColumnLabel = true;
protected boolean cacheEnabled = true;
protected boolean callSettersOnNulls = false;
protected String logPrefix;
protected Class <? extends Log> logImpl;
protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;
protected JdbcType jdbcTypeForNull = JdbcType.OTHER;
protected Set<String> lazyLoadTriggerMethods = new HashSet<String>(Arrays.asList(new String[] { "equals", "clone", "hashCode", "toString" }));
protected Integer defaultStatementTimeout;
protected Integer defaultFetchSize;
protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;
protected Properties variables = new Properties();
protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
protected ObjectFactory objectFactory = new DefaultObjectFactory();
protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();
protected MapperRegistry mapperRegistry = new MapperRegistry(this);
protected boolean lazyLoadingEnabled = false;
protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL
protected String databaseId;
/**
* Configuration factory class.
* Used to create Configuration for loading deserialized unread properties.
*
* @see <a href='https://code.google.com/p/mybatis/issues/detail?id=300'>Issue 300</a> (google code)
*/
protected Class<?> configurationFactory;
protected final InterceptorChain interceptorChain = new InterceptorChain();
protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry();
protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry();
protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry();
protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection");
protected final Map<String, Cache> caches = new StrictMap<Cache>("Caches collection");
protected final Map<String, ResultMap> resultMaps = new StrictMap<ResultMap>("Result Maps collection");
protected final Map<String, ParameterMap> parameterMaps = new StrictMap<ParameterMap>("Parameter Maps collection");
protected final Map<String, KeyGenerator> keyGenerators = new StrictMap<KeyGenerator>("Key Generators collection");
protected final Set<String> loadedResources = new HashSet<String>();
protected final Map<String, XNode> sqlFragments = new StrictMap<XNode>("XML fragments parsed from previous mappers");
protected final Collection<XMLStatementBuilder> incompleteStatements = new LinkedList<XMLStatementBuilder>();
protected final Collection<CacheRefResolver> incompleteCacheRefs = new LinkedList<CacheRefResolver>();
protected final Collection<ResultMapResolver> incompleteResultMaps = new LinkedList<ResultMapResolver>();
protected final Collection<MethodResolver> incompleteMethods = new LinkedList<MethodResolver>();
/*
* A map holds cache-ref relationship. The key is the namespace that
* references a cache bound to another namespace and the value is the
* namespace which the actual cache is bound to.
*/
protected final Map<String, String> cacheRefMap = new HashMap<String, String>();
public Configuration(Environment environment) {
this();
this.environment = environment;
}
public Configuration() {
typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class);
typeAliasRegistry.registerAlias("JNDI", JndiDataSourceFactory.class);
typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class);
typeAliasRegistry.registerAlias("UNPOOLED", UnpooledDataSourceFactory.class);
typeAliasRegistry.registerAlias("PERPETUAL", PerpetualCache.class);
typeAliasRegistry.registerAlias("FIFO", FifoCache.class);
typeAliasRegistry.registerAlias("LRU", LruCache.class);
typeAliasRegistry.registerAlias("SOFT", SoftCache.class);
typeAliasRegistry.registerAlias("WEAK", WeakCache.class);
typeAliasRegistry.registerAlias("DB_VENDOR", VendorDatabaseIdProvider.class);
typeAliasRegistry.registerAlias("XML", XMLLanguageDriver.class);
typeAliasRegistry.registerAlias("RAW", RawLanguageDriver.class);
typeAliasRegistry.registerAlias("SLF4J", Slf4jImpl.class);
typeAliasRegistry.registerAlias("COMMONS_LOGGING", JakartaCommonsLoggingImpl.class);
typeAliasRegistry.registerAlias("LOG4J", Log4jImpl.class);
typeAliasRegistry.registerAlias("LOG4J2", Log4j2Impl.class);
typeAliasRegistry.registerAlias("JDK_LOGGING", Jdk14LoggingImpl.class);
typeAliasRegistry.registerAlias("STDOUT_LOGGING", StdOutImpl.class);
typeAliasRegistry.registerAlias("NO_LOGGING", NoLoggingImpl.class);
typeAliasRegistry.registerAlias("CGLIB", CglibProxyFactory.class);
typeAliasRegistry.registerAlias("JAVASSIST", JavassistProxyFactory.class);
languageRegistry.setDefaultDriverClass(XMLLanguageDriver.class);
languageRegistry.register(RawLanguageDriver.class);
}
public String getLogPrefix() {
return logPrefix;
}
public void setLogPrefix(String logPrefix) {
this.logPrefix = logPrefix;
}
public Class<? extends Log> getLogImpl() {
return logImpl;
}
@SuppressWarnings("unchecked")
public void setLogImpl(Class<?> logImpl) {
if (logImpl != null) {
this.logImpl = (Class<? extends Log>) logImpl;
LogFactory.useCustomLogging(this.logImpl);
}
}
public boolean isCallSettersOnNulls() {
return callSettersOnNulls;
}
public void setCallSettersOnNulls(boolean callSettersOnNulls) {
this.callSettersOnNulls = callSettersOnNulls;
}
public String getDatabaseId() {
return databaseId;
}
public void setDatabaseId(String databaseId) {
this.databaseId = databaseId;
}
public Class<?> getConfigurationFactory() {
return configurationFactory;
}
public void setConfigurationFactory(Class<?> configurationFactory) {
this.configurationFactory = configurationFactory;
}
public boolean isSafeResultHandlerEnabled() {
return safeResultHandlerEnabled;
}
public void setSafeResultHandlerEnabled(boolean safeResultHandlerEnabled) {
this.safeResultHandlerEnabled = safeResultHandlerEnabled;
}
public boolean isSafeRowBoundsEnabled() {
return safeRowBoundsEnabled;
}
public void setSafeRowBoundsEnabled(boolean safeRowBoundsEnabled) {
this.safeRowBoundsEnabled = safeRowBoundsEnabled;
}
public boolean isMapUnderscoreToCamelCase() {
return mapUnderscoreToCamelCase;
}
public void setMapUnderscoreToCamelCase(boolean mapUnderscoreToCamelCase) {
this.mapUnderscoreToCamelCase = mapUnderscoreToCamelCase;
}
public void addLoadedResource(String resource) {
loadedResources.add(resource);
}
public boolean isResourceLoaded(String resource) {
return loadedResources.contains(resource);
}
public Environment getEnvironment() {
return environment;
}
public void setEnvironment(Environment environment) {
this.environment = environment;
}
public AutoMappingBehavior getAutoMappingBehavior() {
return autoMappingBehavior;
}
public void setAutoMappingBehavior(AutoMappingBehavior autoMappingBehavior) {
this.autoMappingBehavior = autoMappingBehavior;
}
public boolean isLazyLoadingEnabled() {
return lazyLoadingEnabled;
}
public void setLazyLoadingEnabled(boolean lazyLoadingEnabled) {
this.lazyLoadingEnabled = lazyLoadingEnabled;
}
public ProxyFactory getProxyFactory() {
return proxyFactory;
}
public void setProxyFactory(ProxyFactory proxyFactory) {
if (proxyFactory == null) {
proxyFactory = new JavassistProxyFactory();
}
this.proxyFactory = proxyFactory;
}
public boolean isAggressiveLazyLoading() {
return aggressiveLazyLoading;
}
public void setAggressiveLazyLoading(boolean aggressiveLazyLoading) {
this.aggressiveLazyLoading = aggressiveLazyLoading;
}
public boolean isMultipleResultSetsEnabled() {
return multipleResultSetsEnabled;
}
public void setMultipleResultSetsEnabled(boolean multipleResultSetsEnabled) {
this.multipleResultSetsEnabled = multipleResultSetsEnabled;
}
public Set<String> getLazyLoadTriggerMethods() {
return lazyLoadTriggerMethods;
}
public void setLazyLoadTriggerMethods(Set<String> lazyLoadTriggerMethods) {
this.lazyLoadTriggerMethods = lazyLoadTriggerMethods;
}
public boolean isUseGeneratedKeys() {
return useGeneratedKeys;
}
public void setUseGeneratedKeys(boolean useGeneratedKeys) {
this.useGeneratedKeys = useGeneratedKeys;
}
public ExecutorType getDefaultExecutorType() {
return defaultExecutorType;
}
public void setDefaultExecutorType(ExecutorType defaultExecutorType) {
this.defaultExecutorType = defaultExecutorType;
}
public boolean isCacheEnabled() {
return cacheEnabled;
}
public void setCacheEnabled(boolean cacheEnabled) {
this.cacheEnabled = cacheEnabled;
}
public Integer getDefaultStatementTimeout() {
return defaultStatementTimeout;
}
public void setDefaultStatementTimeout(Integer defaultStatementTimeout) {
this.defaultStatementTimeout = defaultStatementTimeout;
}
public Integer getDefaultFetchSize() {
return defaultFetchSize;
}
public void setDefaultFetchSize(Integer defaultFetchSize) {
this.defaultFetchSize = defaultFetchSize;
}
public boolean isUseColumnLabel() {
return useColumnLabel;
}
public void setUseColumnLabel(boolean useColumnLabel) {
this.useColumnLabel = useColumnLabel;
}
public LocalCacheScope getLocalCacheScope() {
return localCacheScope;
}
public void setLocalCacheScope(LocalCacheScope localCacheScope) {
this.localCacheScope = localCacheScope;
}
public JdbcType getJdbcTypeForNull() {
return jdbcTypeForNull;
}
public void setJdbcTypeForNull(JdbcType jdbcTypeForNull) {
this.jdbcTypeForNull = jdbcTypeForNull;
}
public Properties getVariables() {
return variables;
}
public void setVariables(Properties variables) {
this.variables = variables;
}
public TypeHandlerRegistry getTypeHandlerRegistry() {
return typeHandlerRegistry;
}
public TypeAliasRegistry getTypeAliasRegistry() {
return typeAliasRegistry;
}
/**
* @since 3.2.2
*/
public MapperRegistry getMapperRegistry() {
return mapperRegistry;
}
public ReflectorFactory getReflectorFactory() {
return reflectorFactory;
}
public void setReflectorFactory(ReflectorFactory reflectorFactory) {
this.reflectorFactory = reflectorFactory;
}
public ObjectFactory getObjectFactory() {
return objectFactory;
}
public void setObjectFactory(ObjectFactory objectFactory) {
this.objectFactory = objectFactory;
}
public ObjectWrapperFactory getObjectWrapperFactory() {
return objectWrapperFactory;
}
public void setObjectWrapperFactory(ObjectWrapperFactory objectWrapperFactory) {
this.objectWrapperFactory = objectWrapperFactory;
}
/**
* @since 3.2.2
*/
public List<Interceptor> getInterceptors() {
return interceptorChain.getInterceptors();
}
public LanguageDriverRegistry getLanguageRegistry() {
return languageRegistry;
}
public void setDefaultScriptingLanguage(Class<?> driver) {
if (driver == null) {
driver = XMLLanguageDriver.class;
}
getLanguageRegistry().setDefaultDriverClass(driver);
}
public LanguageDriver getDefaultScriptingLanuageInstance() {
return languageRegistry.getDefaultDriver();
}
public MetaObject newMetaObject(Object object) {
return MetaObject.forObject(object, objectFactory, objectWrapperFactory, reflectorFactory);
}
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
return parameterHandler;
}
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
ResultHandler resultHandler, BoundSql boundSql) {
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}
public Executor newExecutor(Transaction transaction) {
return newExecutor(transaction, defaultExecutorType);
}
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
public void addKeyGenerator(String id, KeyGenerator keyGenerator) {
keyGenerators.put(id, keyGenerator);
}
public Collection<String> getKeyGeneratorNames() {
return keyGenerators.keySet();
}
public Collection<KeyGenerator> getKeyGenerators() {
return keyGenerators.values();
}
public KeyGenerator getKeyGenerator(String id) {
return keyGenerators.get(id);
}
public boolean hasKeyGenerator(String id) {
return keyGenerators.containsKey(id);
}
public void addCache(Cache cache) {
caches.put(cache.getId(), cache);
}
public Collection<String> getCacheNames() {
return caches.keySet();
}
public Collection<Cache> getCaches() {
return caches.values();
}
public Cache getCache(String id) {
return caches.get(id);
}
public boolean hasCache(String id) {
return caches.containsKey(id);
}
public void addResultMap(ResultMap rm) {
resultMaps.put(rm.getId(), rm);
checkLocallyForDiscriminatedNestedResultMaps(rm);
checkGloballyForDiscriminatedNestedResultMaps(rm);
}
public Collection<String> getResultMapNames() {
return resultMaps.keySet();
}
public Collection<ResultMap> getResultMaps() {
return resultMaps.values();
}
public ResultMap getResultMap(String id) {
return resultMaps.get(id);
}
public boolean hasResultMap(String id) {
return resultMaps.containsKey(id);
}
public void addParameterMap(ParameterMap pm) {
parameterMaps.put(pm.getId(), pm);
}
public Collection<String> getParameterMapNames() {
return parameterMaps.keySet();
}
public Collection<ParameterMap> getParameterMaps() {
return parameterMaps.values();
}
public ParameterMap getParameterMap(String id) {
return parameterMaps.get(id);
}
public boolean hasParameterMap(String id) {
return parameterMaps.containsKey(id);
}
public void addMappedStatement(MappedStatement ms) {
mappedStatements.put(ms.getId(), ms);
}
public Collection<String> getMappedStatementNames() {
buildAllStatements();
return mappedStatements.keySet();
}
public Collection<MappedStatement> getMappedStatements() {
buildAllStatements();
return mappedStatements.values();
}
public Collection<XMLStatementBuilder> getIncompleteStatements() {
return incompleteStatements;
}
public void addIncompleteStatement(XMLStatementBuilder incompleteStatement) {
incompleteStatements.add(incompleteStatement);
}
public Collection<CacheRefResolver> getIncompleteCacheRefs() {
return incompleteCacheRefs;
}
public void addIncompleteCacheRef(CacheRefResolver incompleteCacheRef) {
incompleteCacheRefs.add(incompleteCacheRef);
}
public Collection<ResultMapResolver> getIncompleteResultMaps() {
return incompleteResultMaps;
}
public void addIncompleteResultMap(ResultMapResolver resultMapResolver) {
incompleteResultMaps.add(resultMapResolver);
}
public void addIncompleteMethod(MethodResolver builder) {
incompleteMethods.add(builder);
}
public Collection<MethodResolver> getIncompleteMethods() {
return incompleteMethods;
}
public MappedStatement getMappedStatement(String id) {
return this.getMappedStatement(id, true);
}
public MappedStatement getMappedStatement(String id, boolean validateIncompleteStatements) {
if (validateIncompleteStatements) {
buildAllStatements();
}
return mappedStatements.get(id);
}
public Map<String, XNode> getSqlFragments() {
return sqlFragments;
}
public void addInterceptor(Interceptor interceptor) {
interceptorChain.addInterceptor(interceptor);
}
public void addMappers(String packageName, Class<?> superType) {
mapperRegistry.addMappers(packageName, superType);
}
public void addMappers(String packageName) {
mapperRegistry.addMappers(packageName);
}
public <T> void addMapper(Class<T> type) {
mapperRegistry.addMapper(type);
}
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
public boolean hasMapper(Class<?> type) {
return mapperRegistry.hasMapper(type);
}
public boolean hasStatement(String statementName) {
return hasStatement(statementName, true);
}
public boolean hasStatement(String statementName, boolean validateIncompleteStatements) {
if (validateIncompleteStatements) {
buildAllStatements();
}
return mappedStatements.containsKey(statementName);
}
public void addCacheRef(String namespace, String referencedNamespace) {
cacheRefMap.put(namespace, referencedNamespace);
}
/*
* Parses all the unprocessed statement nodes in the cache. It is recommended
* to call this method once all the mappers are added as it provides fail-fast
* statement validation.
*/
protected void buildAllStatements() {
if (!incompleteResultMaps.isEmpty()) {
synchronized (incompleteResultMaps) {
// This always throws a BuilderException.
incompleteResultMaps.iterator().next().resolve();
}
}
if (!incompleteCacheRefs.isEmpty()) {
synchronized (incompleteCacheRefs) {
// This always throws a BuilderException.
incompleteCacheRefs.iterator().next().resolveCacheRef();
}
}
if (!incompleteStatements.isEmpty()) {
synchronized (incompleteStatements) {
// This always throws a BuilderException.
incompleteStatements.iterator().next().parseStatementNode();
}
}
if (!incompleteMethods.isEmpty()) {
synchronized (incompleteMethods) {
// This always throws a BuilderException.
incompleteMethods.iterator().next().resolve();
}
}
}
/*
* Extracts namespace from fully qualified statement id.
*
* @param statementId
* @return namespace or null when id does not contain period.
*/
protected String extractNamespace(String statementId) {
int lastPeriod = statementId.lastIndexOf('.');
return lastPeriod > 0 ? statementId.substring(0, lastPeriod) : null;
}
// Slow but a one time cost. A better solution is welcome.
protected void checkGloballyForDiscriminatedNestedResultMaps(ResultMap rm) {
if (rm.hasNestedResultMaps()) {
for (Map.Entry<String, ResultMap> entry : resultMaps.entrySet()) {
Object value = entry.getValue();
if (value instanceof ResultMap) {
ResultMap entryResultMap = (ResultMap) value;
if (!entryResultMap.hasNestedResultMaps() && entryResultMap.getDiscriminator() != null) {
Collection<String> discriminatedResultMapNames = entryResultMap.getDiscriminator().getDiscriminatorMap().values();
if (discriminatedResultMapNames.contains(rm.getId())) {
entryResultMap.forceNestedResultMaps();
}
}
}
}
}
}
// Slow but a one time cost. A better solution is welcome. // todo 不懂
protected void checkLocallyForDiscriminatedNestedResultMaps(ResultMap rm) {
if (!rm.hasNestedResultMaps() && rm.getDiscriminator() != null) {
for (Map.Entry<String, String> entry : rm.getDiscriminator().getDiscriminatorMap().entrySet()) {
String discriminatedResultMapName = entry.getValue();
if (hasResultMap(discriminatedResultMapName)) {
ResultMap discriminatedResultMap = resultMaps.get(discriminatedResultMapName);
if (discriminatedResultMap.hasNestedResultMaps()) {
rm.forceNestedResultMaps();
break;
}
}
}
}
}
protected static class StrictMap<V> extends HashMap<String, V> {
private static final long serialVersionUID = -4950446264854982944L;
private String name;
public StrictMap(String name, int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
this.name = name;
}
public StrictMap(String name, int initialCapacity) {
super(initialCapacity);
this.name = name;
}
public StrictMap(String name) {
super();
this.name = name;
}
public StrictMap(String name, Map<String, ? extends V> m) {
super(m);
this.name = name;
}
@SuppressWarnings("unchecked")
public V put(String key, V value) {
if (containsKey(key)) {
throw new IllegalArgumentException(name + " already contains value for " + key);
}
if (key.contains(".")) {
final String shortKey = getShortName(key);
if (super.get(shortKey) == null) {
super.put(shortKey, value);
} else {
super.put(shortKey, (V) new Ambiguity(shortKey));
}
}
return super.put(key, value);
}
public V get(Object key) {
V value = super.get(key);
if (value == null) {
throw new IllegalArgumentException(name + " does not contain value for " + key);
}
if (value instanceof Ambiguity) {
throw new IllegalArgumentException(((Ambiguity) value).getSubject() + " is ambiguous in " + name
+ " (try using the full name including the namespace, or rename one of the entries)");
}
return value;
}
private String getShortName(String key) {
final String[] keyparts = key.split("\\.");
return keyparts[keyparts.length - 1];
}
protected static class Ambiguity {
private String subject;
public Ambiguity(String subject) {
this.subject = subject;
}
public String getSubject() {
return subject;
}
}
}
}
| apache-2.0 |
googleapis/java-common-protos | proto-google-common-protos/src/main/java/com/google/cloud/audit/RequestMetadataOrBuilder.java | 8575 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/audit/audit_log.proto
package com.google.cloud.audit;
public interface RequestMetadataOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.audit.RequestMetadata)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The IP address of the caller.
* For caller from internet, this will be public IPv4 or IPv6 address.
* For caller from a Compute Engine VM with external IP address, this
* will be the VM's external IP address. For caller from a Compute
* Engine VM without external IP address, if the VM is in the same
* organization (or project) as the accessed resource, `caller_ip` will
* be the VM's internal IPv4 address, otherwise the `caller_ip` will be
* redacted to "gce-internal-ip".
* See https://cloud.google.com/compute/docs/vpc/ for more information.
* </pre>
*
* <code>string caller_ip = 1;</code>
*
* @return The callerIp.
*/
java.lang.String getCallerIp();
/**
*
*
* <pre>
* The IP address of the caller.
* For caller from internet, this will be public IPv4 or IPv6 address.
* For caller from a Compute Engine VM with external IP address, this
* will be the VM's external IP address. For caller from a Compute
* Engine VM without external IP address, if the VM is in the same
* organization (or project) as the accessed resource, `caller_ip` will
* be the VM's internal IPv4 address, otherwise the `caller_ip` will be
* redacted to "gce-internal-ip".
* See https://cloud.google.com/compute/docs/vpc/ for more information.
* </pre>
*
* <code>string caller_ip = 1;</code>
*
* @return The bytes for callerIp.
*/
com.google.protobuf.ByteString getCallerIpBytes();
/**
*
*
* <pre>
* The user agent of the caller.
* This information is not authenticated and should be treated accordingly.
* For example:
* + `google-api-python-client/1.4.0`:
* The request was made by the Google API client for Python.
* + `Cloud SDK Command Line Tool apitools-client/1.0 gcloud/0.9.62`:
* The request was made by the Google Cloud SDK CLI (gcloud).
* + `AppEngine-Google; (+http://code.google.com/appengine; appid:
* s~my-project`:
* The request was made from the `my-project` App Engine app.
* </pre>
*
* <code>string caller_supplied_user_agent = 2;</code>
*
* @return The callerSuppliedUserAgent.
*/
java.lang.String getCallerSuppliedUserAgent();
/**
*
*
* <pre>
* The user agent of the caller.
* This information is not authenticated and should be treated accordingly.
* For example:
* + `google-api-python-client/1.4.0`:
* The request was made by the Google API client for Python.
* + `Cloud SDK Command Line Tool apitools-client/1.0 gcloud/0.9.62`:
* The request was made by the Google Cloud SDK CLI (gcloud).
* + `AppEngine-Google; (+http://code.google.com/appengine; appid:
* s~my-project`:
* The request was made from the `my-project` App Engine app.
* </pre>
*
* <code>string caller_supplied_user_agent = 2;</code>
*
* @return The bytes for callerSuppliedUserAgent.
*/
com.google.protobuf.ByteString getCallerSuppliedUserAgentBytes();
/**
*
*
* <pre>
* The network of the caller.
* Set only if the network host project is part of the same GCP organization
* (or project) as the accessed resource.
* See https://cloud.google.com/compute/docs/vpc/ for more information.
* This is a scheme-less URI full resource name. For example:
* "//compute.googleapis.com/projects/PROJECT_ID/global/networks/NETWORK_ID"
* </pre>
*
* <code>string caller_network = 3;</code>
*
* @return The callerNetwork.
*/
java.lang.String getCallerNetwork();
/**
*
*
* <pre>
* The network of the caller.
* Set only if the network host project is part of the same GCP organization
* (or project) as the accessed resource.
* See https://cloud.google.com/compute/docs/vpc/ for more information.
* This is a scheme-less URI full resource name. For example:
* "//compute.googleapis.com/projects/PROJECT_ID/global/networks/NETWORK_ID"
* </pre>
*
* <code>string caller_network = 3;</code>
*
* @return The bytes for callerNetwork.
*/
com.google.protobuf.ByteString getCallerNetworkBytes();
/**
*
*
* <pre>
* Request attributes used in IAM condition evaluation. This field contains
* request attributes like request time and access levels associated with
* the request.
* To get the whole view of the attributes used in IAM
* condition evaluation, the user must also look into
* `AuditLog.authentication_info.resource_attributes`.
* </pre>
*
* <code>.google.rpc.context.AttributeContext.Request request_attributes = 7;</code>
*
* @return Whether the requestAttributes field is set.
*/
boolean hasRequestAttributes();
/**
*
*
* <pre>
* Request attributes used in IAM condition evaluation. This field contains
* request attributes like request time and access levels associated with
* the request.
* To get the whole view of the attributes used in IAM
* condition evaluation, the user must also look into
* `AuditLog.authentication_info.resource_attributes`.
* </pre>
*
* <code>.google.rpc.context.AttributeContext.Request request_attributes = 7;</code>
*
* @return The requestAttributes.
*/
com.google.rpc.context.AttributeContext.Request getRequestAttributes();
/**
*
*
* <pre>
* Request attributes used in IAM condition evaluation. This field contains
* request attributes like request time and access levels associated with
* the request.
* To get the whole view of the attributes used in IAM
* condition evaluation, the user must also look into
* `AuditLog.authentication_info.resource_attributes`.
* </pre>
*
* <code>.google.rpc.context.AttributeContext.Request request_attributes = 7;</code>
*/
com.google.rpc.context.AttributeContext.RequestOrBuilder getRequestAttributesOrBuilder();
/**
*
*
* <pre>
* The destination of a network activity, such as accepting a TCP connection.
* In a multi hop network activity, the destination represents the receiver of
* the last hop. Only two fields are used in this message, Peer.port and
* Peer.ip. These fields are optionally populated by those services utilizing
* the IAM condition feature.
* </pre>
*
* <code>.google.rpc.context.AttributeContext.Peer destination_attributes = 8;</code>
*
* @return Whether the destinationAttributes field is set.
*/
boolean hasDestinationAttributes();
/**
*
*
* <pre>
* The destination of a network activity, such as accepting a TCP connection.
* In a multi hop network activity, the destination represents the receiver of
* the last hop. Only two fields are used in this message, Peer.port and
* Peer.ip. These fields are optionally populated by those services utilizing
* the IAM condition feature.
* </pre>
*
* <code>.google.rpc.context.AttributeContext.Peer destination_attributes = 8;</code>
*
* @return The destinationAttributes.
*/
com.google.rpc.context.AttributeContext.Peer getDestinationAttributes();
/**
*
*
* <pre>
* The destination of a network activity, such as accepting a TCP connection.
* In a multi hop network activity, the destination represents the receiver of
* the last hop. Only two fields are used in this message, Peer.port and
* Peer.ip. These fields are optionally populated by those services utilizing
* the IAM condition feature.
* </pre>
*
* <code>.google.rpc.context.AttributeContext.Peer destination_attributes = 8;</code>
*/
com.google.rpc.context.AttributeContext.PeerOrBuilder getDestinationAttributesOrBuilder();
}
| apache-2.0 |
anjalshireesh/gluster-ovirt-poc | frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/users/UserGroupListModel.java | 2277 | package org.ovirt.engine.ui.uicommonweb.models.users;
import java.util.Collections;
import org.ovirt.engine.core.compat.*;
import org.ovirt.engine.ui.uicompat.*;
import org.ovirt.engine.core.common.businessentities.*;
import org.ovirt.engine.core.common.vdscommands.*;
import org.ovirt.engine.core.common.queries.*;
import org.ovirt.engine.core.common.action.*;
import org.ovirt.engine.ui.frontend.*;
import org.ovirt.engine.ui.uicommonweb.*;
import org.ovirt.engine.ui.uicommonweb.models.*;
import org.ovirt.engine.core.common.*;
import org.ovirt.engine.core.common.businessentities.*;
import org.ovirt.engine.ui.uicommonweb.*;
import org.ovirt.engine.ui.uicommonweb.models.*;
@SuppressWarnings("unused")
public class UserGroupListModel extends SearchableListModel
{
public DbUser getEntity()
{
return (DbUser)((super.getEntity() instanceof DbUser) ? super.getEntity() : null);
}
public void setEntity(DbUser value)
{
super.setEntity(value);
}
public UserGroupListModel()
{
setTitle("Directory Groups");
}
@Override
protected void OnEntityChanged()
{
super.OnEntityChanged();
if (getEntity() != null)
{
java.util.ArrayList<UserGroup> items = new java.util.ArrayList<UserGroup>();
for (String groupFullName : getEntity().getgroups().split("[,]", -1))
{
items.add(CreateUserGroup(groupFullName));
}
setItems(items);
}
else
{
setItems(null);
}
}
private static UserGroup CreateUserGroup(String groupFullName)
{
// Parse 'groupFullName' (representation: Domain/OrganizationalUnit/Group)
int firstIndexOfSlash = groupFullName.indexOf('/');
int lastIndexOfSlash = groupFullName.lastIndexOf('/');
String domain = firstIndexOfSlash >= 0 ? groupFullName.substring(0, firstIndexOfSlash) : "";
String groupName = lastIndexOfSlash >= 0 ? groupFullName.substring(lastIndexOfSlash+1) : "";
String organizationalUnit = lastIndexOfSlash > firstIndexOfSlash ? groupFullName.substring(0, lastIndexOfSlash).substring(firstIndexOfSlash+1) : "";
UserGroup tempVar = new UserGroup();
tempVar.setGroupName(groupName);
tempVar.setOrganizationalUnit(organizationalUnit);
tempVar.setDomain(domain);
return tempVar;
}
@Override
protected String getListName() {
return "UserGroupListModel";
}
} | apache-2.0 |
Pardus-Engerek/engerek | model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ComplexConstructionConsumer.java | 1256 | /**
* Copyright (c) 2017 Evolveum
*
* 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.evolveum.midpoint.model.impl.lens.projector;
import com.evolveum.midpoint.model.impl.lens.AbstractConstruction;
import com.evolveum.midpoint.model.impl.lens.ConstructionPack;
import com.evolveum.midpoint.prism.delta.DeltaMapTriple;
/**
* @author semancik
*
*/
public interface ComplexConstructionConsumer<K, T extends AbstractConstruction> {
boolean before(K key);
void onAssigned(K key, String desc);
void onUnchangedValid(K key, String desc);
void onUnchangedInvalid(K key, String desc);
void onUnassigned(K key, String desc);
void after(K key, String desc, DeltaMapTriple<K, ConstructionPack<T>> constructionMapTriple);
}
| apache-2.0 |
ephemeralin/java-training | chapter_002/src/main/java/ru/job4j/inheritance/Doctor.java | 1232 | package ru.job4j.inheritance;
/**
* Created by ephemeralin on 15.05.17.
*/
public class Doctor extends Human {
/**
* The Degree.
*/
private int degree;
/**
* The Number of assistance.
*/
private int numberOfAssistance;
/**
* Instantiates a new Doctor.
*
* @param name the name
* @param age the age
* @param location the location
* @param status the status
*/
public Doctor(String name, int age, String location, String status) {
super(name, age, location, status);
}
/**
* Treat.
*
* @param pacient the pacient
*/
public void treat(Client pacient) {
String nameOfPacient = pacient.getName();
while (pacient.isIll()) {
pacient.getMeds(10);
}
System.out.printf("%s treats %s", this.getName(), nameOfPacient);
System.out.println();
}
/**
* Gets degree.
*
* @return the degree
*/
public int getDegree() {
return degree;
}
/**
* Gets number of assistance.
*
* @return the number of assistance
*/
public int getNumberOfAssistance() {
return numberOfAssistance;
}
}
| apache-2.0 |
jerrinot/hazelcast-stabilizer | simulator/src/main/java/com/hazelcast/simulator/coordinator/TestCaseRunner.java | 17426 | /*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.simulator.coordinator;
import com.hazelcast.simulator.common.TestCase;
import com.hazelcast.simulator.common.TestPhase;
import com.hazelcast.simulator.coordinator.registry.Registry;
import com.hazelcast.simulator.coordinator.registry.TestData;
import com.hazelcast.simulator.coordinator.registry.WorkerData;
import com.hazelcast.simulator.protocol.CoordinatorClient;
import com.hazelcast.simulator.protocol.core.SimulatorAddress;
import com.hazelcast.simulator.protocol.operation.SimulatorOperation;
import com.hazelcast.simulator.worker.operations.CreateTestOperation;
import com.hazelcast.simulator.worker.operations.StartPhaseOperation;
import com.hazelcast.simulator.worker.operations.StopRunOperation;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static com.hazelcast.simulator.common.TestPhase.GLOBAL_PREPARE;
import static com.hazelcast.simulator.common.TestPhase.GLOBAL_TEARDOWN;
import static com.hazelcast.simulator.common.TestPhase.GLOBAL_VERIFY;
import static com.hazelcast.simulator.common.TestPhase.LOCAL_PREPARE;
import static com.hazelcast.simulator.common.TestPhase.LOCAL_TEARDOWN;
import static com.hazelcast.simulator.common.TestPhase.LOCAL_VERIFY;
import static com.hazelcast.simulator.common.TestPhase.RUN;
import static com.hazelcast.simulator.common.TestPhase.SETUP;
import static com.hazelcast.simulator.coordinator.registry.TestData.CompletedStatus.FAILED;
import static com.hazelcast.simulator.coordinator.registry.TestData.CompletedStatus.SUCCESS;
import static com.hazelcast.simulator.utils.CommonUtils.await;
import static com.hazelcast.simulator.utils.CommonUtils.getElapsedSeconds;
import static com.hazelcast.simulator.utils.CommonUtils.rethrow;
import static com.hazelcast.simulator.utils.CommonUtils.sleepSeconds;
import static com.hazelcast.simulator.utils.CommonUtils.sleepUntilMs;
import static com.hazelcast.simulator.utils.FormatUtils.formatPercentage;
import static com.hazelcast.simulator.utils.FormatUtils.padRight;
import static com.hazelcast.simulator.utils.FormatUtils.secondsToHuman;
import static java.lang.Math.min;
import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Responsible for running a single {@link TestCase}.
* <p>
* Multiple TestCases can be run in parallel, by having multiple TestCaseRunners in parallel.
*/
public final class TestCaseRunner {
private static final int RUN_PHASE_LOG_INTERVAL_SECONDS = 30;
private static final int WAIT_FOR_PHASE_COMPLETION_LOG_INTERVAL_SECONDS = 30;
private static final int WAIT_FOR_PHASE_COMPLETION_LOG_VERBOSE_DELAY_SECONDS = 300;
private static final Logger LOGGER = Logger.getLogger(TestCaseRunner.class);
private final TestData test;
private final TestCase testCase;
private final TestSuite testSuite;
private final CoordinatorClient client;
private final FailureCollector failureCollector;
private final PerformanceStatsCollector performanceStatsCollector;
private final String prefix;
private final Map<TestPhase, CountDownLatch> testPhaseSyncMap;
private final boolean isVerifyEnabled;
private final TargetType targetType;
private final int targetCount;
private final int performanceMonitorIntervalSeconds;
private final int logRunPhaseIntervalSeconds;
private final List<WorkerData> targets;
private final WorkerData globalTarget;
@SuppressWarnings("checkstyle:parameternumber")
public TestCaseRunner(TestData test,
List<WorkerData> targets,
CoordinatorClient client,
Map<TestPhase, CountDownLatch> testPhaseSyncMap,
FailureCollector failureCollector,
Registry registry,
PerformanceStatsCollector performanceStatsCollector,
int performanceMonitorIntervalSeconds) {
this.test = test;
this.testCase = test.getTestCase();
this.testSuite = test.getTestSuite();
this.client = client;
this.failureCollector = failureCollector;
this.performanceStatsCollector = performanceStatsCollector;
this.prefix = padRight(testCase.getId(), testSuite.getMaxTestCaseIdLength() + 1);
this.testPhaseSyncMap = testPhaseSyncMap;
this.targets = targets;
this.globalTarget = targets.iterator().next();
this.isVerifyEnabled = testSuite.isVerifyEnabled();
this.targetType = testSuite.getWorkerQuery().getTargetType().resolvePreferClient(registry.hasClientWorkers());
this.targetCount = targets.size();
this.performanceMonitorIntervalSeconds = performanceMonitorIntervalSeconds;
if (performanceMonitorIntervalSeconds > 0) {
this.logRunPhaseIntervalSeconds = min(performanceMonitorIntervalSeconds, RUN_PHASE_LOG_INTERVAL_SECONDS);
} else {
this.logRunPhaseIntervalSeconds = RUN_PHASE_LOG_INTERVAL_SECONDS;
}
}
public boolean run() {
logDetails();
test.initStartTime();
try {
run0();
} catch (TestCaseAbortedException e) {
log(e.getMessage());
// unblock other TestCaseRunner threads, if fail fast is not set and they have no failures on their own
TestPhase testPhase = e.testPhase;
while (testPhase != null) {
decrementAndGetCountDownLatch(testPhase);
testPhase = testPhase.getNextTestPhaseOrNull();
}
} catch (Exception e) {
throw rethrow(e);
} finally {
test.setCompletedStatus(hasFailure() ? FAILED : SUCCESS);
}
return test.getCompletedStatus() == SUCCESS;
}
private void run0() {
createTest();
LOGGER.info(format("Worker for global test phases will be %s (%s)",
globalTarget.getAddress(), globalTarget.getParameters().getWorkerType()));
executePhase(SETUP);
executePhase(LOCAL_PREPARE);
executePhase(GLOBAL_PREPARE);
executeRun();
if (isVerifyEnabled) {
executePhase(GLOBAL_VERIFY);
executePhase(LOCAL_VERIFY);
} else {
log("Skipping Test verification");
}
executePhase(GLOBAL_TEARDOWN);
executePhase(LOCAL_TEARDOWN);
}
private void logDetails() {
LOGGER.info(format("Test %s using %s workers [%s]",
testCase.getId(), targets.size(), WorkerData.toAddressString(targets)));
}
private void createTest() {
log("Starting Test initialization");
invokeOnTargets(new CreateTestOperation(testCase));
log("Completed Test initialization");
}
private void invokeOnTargets(SimulatorOperation op) {
Map<WorkerData, Future> futures = submitToTargets(false, op);
awaitCompletion(futures);
}
private Map<WorkerData, Future> submitToTargets(boolean singleTarget, SimulatorOperation op) {
Map<WorkerData, Future> futures = new HashMap<WorkerData, Future>();
if (singleTarget) {
Future f = client.submit(globalTarget.getAddress(), op);
futures.put(globalTarget, f);
} else {
for (WorkerData worker : targets) {
Future f = client.submit(worker.getAddress(), op);
futures.put(worker, f);
}
}
return futures;
}
private void awaitCompletion(Map<WorkerData, Future> futures) {
for (Map.Entry<WorkerData, Future> entry : futures.entrySet()) {
Future f = entry.getValue();
try {
f.get();
} catch (InterruptedException e) {
throw new RuntimeException();
} catch (ExecutionException e) {
throw new RuntimeException(e.getCause());
}
}
}
private void executePhase(TestPhase phase) {
if (hasFailure()) {
throw new TestCaseAbortedException("Skipping Test " + phase.desc() + " (critical failure)", phase);
}
log("Starting Test " + phase.desc());
test.setTestPhase(phase);
Map<WorkerData, Future> futures = submitToTargets(
phase.isGlobal(), new StartPhaseOperation(phase, testCase.getId()));
waitForPhaseCompletion(phase, futures);
log("Completed Test " + phase.desc());
waitForGlobalTestPhaseCompletion(phase);
}
@SuppressWarnings("checkstyle:npathcomplexity")
private void executeRun() {
if (test.isStopRequested()) {
log(format("Skipping %s, test stopped.", RUN));
return;
}
test.setTestPhase(RUN);
Map<WorkerData, Future> futures = startRun();
long startMs = currentTimeMillis();
int durationSeconds = testSuite.getDurationSeconds();
long durationMs;
long timeoutMs;
if (durationSeconds == 0) {
log("Test will run until it stops");
timeoutMs = Long.MAX_VALUE;
durationMs = Long.MAX_VALUE;
} else {
durationMs = SECONDS.toMillis(durationSeconds);
long warmupSeconds = MILLISECONDS.toSeconds(testCase.getWarmupMillis());
if (warmupSeconds > 0) {
log(format("Test will run for %s with a warmup period of %s",
secondsToHuman(durationSeconds),
secondsToHuman(warmupSeconds)));
} else {
log(format("Test will run for %s without warmup", secondsToHuman(durationSeconds)));
}
timeoutMs = startMs + durationMs;
}
long nextSleepUntilMs = startMs;
int iteration = 0;
for (; ; ) {
nextSleepUntilMs += SECONDS.toMillis(1);
sleepUntilMs(nextSleepUntilMs);
if (hasFailure()) {
log("Critical failure detected, aborting RUN phase");
break;
}
long nowMs = currentTimeMillis();
if (nowMs > timeoutMs || isAllDone(futures) || test.isStopRequested()) {
log("Test finished run");
break;
}
iteration++;
if (iteration % logRunPhaseIntervalSeconds == 0) {
logProgress(nowMs - startMs, durationMs);
}
}
stopRun();
waitForPhaseCompletion(RUN, futures);
logFinalPerformanceInfo(startMs);
waitForGlobalTestPhaseCompletion(RUN);
}
private boolean isAllDone(Map<WorkerData, Future> futures) {
for (Future f : futures.values()) {
if (!f.isDone()) {
return false;
}
}
return true;
}
private void logFinalPerformanceInfo(long startMs) {
// the running time of the test is current time minus the start time. We can't rely on testsuite duration
// due to premature abortion of a test. Or if the test has no explicit duration configured
long durationWithWarmupMillis = currentTimeMillis() - startMs;
// then we need to subtract the warmup.
long durationMillis = durationWithWarmupMillis - testCase.getWarmupMillis();
if (performanceMonitorIntervalSeconds > 0) {
LOGGER.info(testCase.getId() + " Waiting for all performance info");
sleepSeconds(performanceMonitorIntervalSeconds);
LOGGER.info("Performance " + testCase.getId() + "\n"
+ performanceStatsCollector.detailedPerformanceInfo(testCase.getId(), durationMillis));
}
}
/**
* Starts running the test. This call is asynchronous. It will not wait for the running to complete. It will
* return a map of futures (one for each target worker) that can be used to sync on completion.
*/
private Map<WorkerData, Future> startRun() {
log(format("Starting run on %s workers", targetType.toString(targetCount)));
log(format("Test run using workers %s", WorkerData.toAddressString(targets)));
return submitToTargets(false, new StartPhaseOperation(RUN, testCase.getId()));
}
private void stopRun() {
log("Stopping test");
Map<WorkerData, Future> futures = submitToTargets(false, new StopRunOperation(testCase.getId()));
try {
waitForPhaseCompletion(RUN, futures);
log("Stopping test completed");
} catch (TestCaseAbortedException e) {
log(e.getMessage());
}
}
private void logProgress(long elapsedMs, long durationMs) {
String msg;
if (durationMs == Long.MAX_VALUE) {
msg = format("Running %s", secondsToHuman(MILLISECONDS.toSeconds(elapsedMs)));
} else {
msg = format("Running %s (%s%%)",
secondsToHuman(MILLISECONDS.toSeconds(elapsedMs)),
formatPercentage(elapsedMs, durationMs));
}
if (performanceMonitorIntervalSeconds > 0) {
msg += performanceStatsCollector.formatIntervalPerformanceNumbers(testCase.getId());
}
LOGGER.info(prefix + msg);
}
private void waitForPhaseCompletion(TestPhase testPhase, Map<WorkerData, Future> futures) {
int completedWorkers = 0;
int expectedWorkers = futures.size();
long started = System.nanoTime();
while (completedWorkers < expectedWorkers) {
sleepSeconds(1);
if (hasFailure()) {
throw new TestCaseAbortedException(
format("Waiting for %s completion aborted (critical failure)", testPhase.desc()), testPhase);
}
completedWorkers = 0;
for (Future f : futures.values()) {
if (f.isDone()) {
completedWorkers++;
}
}
logMissingWorkers(testPhase, completedWorkers, expectedWorkers, started, futures);
}
}
private void logMissingWorkers(TestPhase testPhase, int completedWorkers, int expectedWorkers,
long started, Map<WorkerData, Future> futures) {
long elapsed = getElapsedSeconds(started);
if (elapsed % WAIT_FOR_PHASE_COMPLETION_LOG_INTERVAL_SECONDS != 0) {
return;
}
if (elapsed < WAIT_FOR_PHASE_COMPLETION_LOG_VERBOSE_DELAY_SECONDS || completedWorkers == expectedWorkers) {
log(format("Waiting %s for %s completion (%d/%d workers)", secondsToHuman(elapsed), testPhase.desc(),
completedWorkers, expectedWorkers));
return;
}
// verbose logging of missing workers
List<SimulatorAddress> missingWorkers = new ArrayList<SimulatorAddress>();
for (Map.Entry<WorkerData, Future> entry : futures.entrySet()) {
if (!entry.getValue().isDone()) {
missingWorkers.add(entry.getKey().getAddress());
}
}
log(format("Waiting %s for %s completion (%d/%d workers) (missing workers: %s)", secondsToHuman(elapsed),
testPhase.desc(), completedWorkers, expectedWorkers, missingWorkers));
}
private void waitForGlobalTestPhaseCompletion(TestPhase testPhase) {
if (testPhaseSyncMap == null) {
return;
}
CountDownLatch latch = decrementAndGetCountDownLatch(testPhase);
if (!hasFailure()) {
await(latch);
}
LOGGER.info(testCase.getId() + " completed waiting for global TestPhase " + testPhase.desc());
}
private CountDownLatch decrementAndGetCountDownLatch(TestPhase testPhase) {
if (testPhaseSyncMap == null) {
return new CountDownLatch(0);
}
CountDownLatch latch = testPhaseSyncMap.get(testPhase);
latch.countDown();
return latch;
}
private void log(String msg) {
LOGGER.info(prefix + msg);
}
private boolean hasFailure() {
return failureCollector.hasCriticalFailure(testCase.getId())
|| failureCollector.hasCriticalFailure() && testSuite.isFailFast();
}
private static final class TestCaseAbortedException extends RuntimeException {
private TestPhase testPhase;
TestCaseAbortedException(String message, TestPhase testPhase) {
super(message);
this.testPhase = testPhase;
}
}
}
| apache-2.0 |
yecjl/AndroidStudyDemo | 01_MobileSafe/md5/src/androidTest/java/com/study/md5/ExampleInstrumentedTest.java | 730 | package com.study.md5;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.study.md5", appContext.getPackageName());
}
}
| apache-2.0 |
Danny-Hazelcast/hazelcast-stabilizer | simulator/src/main/java/com/hazelcast/simulator/protocol/core/TestProcessorManager.java | 3353 | /*
* Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.simulator.protocol.core;
import com.hazelcast.simulator.protocol.operation.SimulatorOperation;
import com.hazelcast.simulator.protocol.processors.OperationProcessor;
import com.hazelcast.simulator.protocol.processors.TestOperationProcessor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static com.hazelcast.simulator.protocol.core.AddressLevel.TEST;
import static com.hazelcast.simulator.protocol.core.ResponseType.FAILURE_TEST_NOT_FOUND;
/**
* Manages {@link OperationProcessor} and {@link SimulatorAddress} instances for tests.
*/
public class TestProcessorManager {
private final ConcurrentMap<Integer, SimulatorAddress> testAddresses = new ConcurrentHashMap<Integer, SimulatorAddress>();
private final ConcurrentMap<Integer, TestOperationProcessor> testProcessors
= new ConcurrentHashMap<Integer, TestOperationProcessor>();
private final SimulatorAddress localAddress;
private final int agentIndex;
private final int workerIndex;
public TestProcessorManager(SimulatorAddress localAddress) {
this.localAddress = localAddress;
this.agentIndex = localAddress.getAgentIndex();
this.workerIndex = localAddress.getWorkerIndex();
}
public TestOperationProcessor getTest(int testIndex) {
return testProcessors.get(testIndex);
}
public void addTest(int testIndex, TestOperationProcessor processor) {
SimulatorAddress testAddress = new SimulatorAddress(TEST, agentIndex, workerIndex, testIndex);
testAddresses.put(testIndex, testAddress);
testProcessors.put(testIndex, processor);
}
public void removeTest(int testIndex) {
testAddresses.remove(testIndex);
testProcessors.remove(testIndex);
}
public void processOnAllTests(Response response, SimulatorOperation operation, SimulatorAddress source) {
for (Map.Entry<Integer, TestOperationProcessor> entry : testProcessors.entrySet()) {
ResponseType responseType = entry.getValue().process(operation, source);
response.addResponse(testAddresses.get(entry.getKey()), responseType);
}
}
public void processOnTest(Response response, SimulatorOperation operation, SimulatorAddress source, int testAddressIndex) {
OperationProcessor processor = testProcessors.get(testAddressIndex);
if (processor == null) {
response.addResponse(localAddress, FAILURE_TEST_NOT_FOUND);
} else {
ResponseType responseType = processor.process(operation, source);
response.addResponse(testAddresses.get(testAddressIndex), responseType);
}
}
}
| apache-2.0 |