text
stringlengths
7
1.01M
package com.zhangbz.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.zhangbz.domain.User; import com.zhangbz.util.JDBCUtils; public class MySqlUserDao implements UserDao{ public void addUser(User user) { String sql = "insert into users values(null,'"+user.getUsername()+"','"+user.getPassword()+"','"+user.getNickname()+"','"+user.getEmail()+"')"; Connection conn = null; Statement stat = null; ResultSet rs = null; try { conn = JDBCUtils.getConn(); stat = conn.createStatement(); stat.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { JDBCUtils.close(rs, stat, conn); } } public User findUserByUNandPSW(String username, String password) { String sql = "select * from users where username='"+username+"' and password='"+password+"'"; Connection conn = null; Statement stat = null; ResultSet rs = null; try { conn = JDBCUtils.getConn(); stat = conn.createStatement(); rs = stat.executeQuery(sql); if (rs.next()) { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); user.setNickname(rs.getString("nickname")); user.setEmail(rs.getString("email")); return user; } else { return null; } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { JDBCUtils.close(rs, stat, conn); } } public User findUserByUserName(String username) { String sql = "select * from users where username='"+username+"'"; Connection conn = null; Statement stat = null; ResultSet rs = null; try { conn = JDBCUtils.getConn(); stat = conn.createStatement(); rs = stat.executeQuery(sql); if (rs.next()) { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); user.setNickname(rs.getString("nickname")); user.setEmail(rs.getString("email")); return user; } else { return null; } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { JDBCUtils.close(rs, stat, conn); } } }
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2015 the original author or authors. */ package org.assertj.core.api.abstract_; import static org.mockito.Mockito.verify; import java.util.ArrayList; import java.util.List; import org.assertj.core.api.AbstractAssert; import org.assertj.core.api.AbstractAssertBaseTest; import org.assertj.core.api.Assertions; import org.assertj.core.api.ConcreteAssert; import org.junit.Test; /** * Tests for <code>{@link AbstractAssert#isSameAs(Object)}</code>. * * @author Alex Ruiz * @author Mikhail Mazursky */ public class AbstractAssert_isSameAs_Test extends AbstractAssertBaseTest { @Override protected ConcreteAssert invoke_api_method() { return assertions.isSameAs(8L); } @Override protected void verify_internal_effects() { verify(objects).assertSame(getInfo(assertions), getActual(assertions), 8L); } @Test public void should_be_loosely_typed1() { List<String> expected = new ArrayList<>(); List<? extends String> actual = expected; Assertions.assertThat(actual).isSameAs(expected); } @Test public void should_be_loosely_typed2() { List<? extends String> expected = new ArrayList<>(); List<? extends String> actual = expected; Assertions.assertThat(actual).isSameAs(expected); } }
package com.android305.lights.dialogs; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import com.android305.lights.R; public class DeleteLampConfirmationDialog extends DialogFragment { public final static String TAG = DeleteLampConfirmationDialog.class.getSimpleName(); private final static String LAMP_NAME_EXTRA = "lamp"; private final static String POSITION_EXTRA = "position"; public interface DeleteLampConfirmationListener { void onDeleteLamp(int position); } public static DeleteLampConfirmationDialog newInstance(@NonNull String lampName, int position) { DeleteLampConfirmationDialog dialog = new DeleteLampConfirmationDialog(); Bundle args = new Bundle(); args.putString(LAMP_NAME_EXTRA, lampName); args.putInt(POSITION_EXTRA, position); dialog.setArguments(args); return dialog; } private DeleteLampConfirmationListener mListener; private String mLampName; private int mPosition; @TargetApi(22) @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (DeleteLampConfirmationListener) getTargetFragment(); } catch (ClassCastException e) { throw new RuntimeException("Class " + getTargetFragment().toString() + " must implement DeleteLampConfirmationListener"); } } @TargetApi(23) @Override public void onAttach(Context context) { super.onAttach(context); try { mListener = (DeleteLampConfirmationListener) getTargetFragment(); } catch (ClassCastException e) { throw new RuntimeException("Context " + getTargetFragment().toString() + " must implement DeleteLampConfirmationListener"); } } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Bundle args = getArguments(); mLampName = args.getString(LAMP_NAME_EXTRA); mPosition = args.getInt(POSITION_EXTRA); assert mLampName != null; AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(R.string.confirmation); builder.setMessage(String.format(getContext().getString(R.string.delete_confirm), mLampName)); builder.setNegativeButton(android.R.string.no, null); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mListener.onDeleteLamp(mPosition); } }); return builder.create(); } }
/** * 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.atlas.web.resources; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.core.ResourceContext; import org.apache.atlas.AtlasClient; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.typedef.AtlasTypesDef; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.json.TypesSerialization; import org.apache.atlas.repository.converters.TypeConverterUtil; import org.apache.atlas.utils.AtlasPerfTracer; import org.apache.atlas.web.rest.TypesREST; import org.apache.atlas.web.util.Servlets; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; /** * This class provides RESTful API for Types. * * A type is the description of any representable item; * e.g. a Hive table * * You could represent any meta model representing any domain using these types. */ @Path("types") @Singleton @Service @Deprecated public class TypesResource { private static final Logger LOG = LoggerFactory.getLogger(TypesResource.class); private static final Logger PERF_LOG = AtlasPerfTracer.getPerfLogger("rest.TypesResource"); private static AtlasTypeRegistry typeRegistry; private final TypesREST typesREST; @Inject public TypesResource(AtlasTypeRegistry typeRegistry, TypesREST typesREST) { this.typeRegistry = typeRegistry; this.typesREST = typesREST; } @Context private ResourceContext resourceContext; /** * Submits a type definition corresponding to a given type representing a meta model of a * domain. Could represent things like Hive Database, Hive Table, etc. */ @POST @Consumes({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON}) @Produces(Servlets.JSON_MEDIA_TYPE) public Response submit(@Context HttpServletRequest request) { if (LOG.isDebugEnabled()) { LOG.debug("==> TypesResource.submit()"); } AtlasPerfTracer perf = null; if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "TypesResource.submit()"); } JSONArray typesResponse = new JSONArray(); try { final String typeDefinition = Servlets.getRequestPayload(request); if (LOG.isDebugEnabled()) { LOG.debug("Creating type with definition {} ", typeDefinition); } AtlasTypesDef createTypesDef = TypeConverterUtil.toAtlasTypesDef(typeDefinition, typeRegistry); AtlasTypesDef createdTypesDef = typesREST.createAtlasTypeDefs(createTypesDef); List<String> typeNames = TypeConverterUtil.getTypeNames(createdTypesDef); for (int i = 0; i < typeNames.size(); i++) { final String name = typeNames.get(i); typesResponse.put(new JSONObject() {{ put(AtlasClient.NAME, name); }}); } JSONObject response = new JSONObject(); response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId()); response.put(AtlasClient.TYPES, typesResponse); return Response.status(ClientResponse.Status.CREATED).entity(response).build(); } catch (AtlasBaseException e) { LOG.error("Type creation failed", e); throw new WebApplicationException(Servlets.getErrorResponse(e)); } catch (IllegalArgumentException e) { LOG.error("Unable to persist types", e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST)); } catch (WebApplicationException e) { LOG.error("Unable to persist types", e); throw e; } catch (Throwable e) { LOG.error("Unable to persist types", e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR)); } finally { AtlasPerfTracer.log(perf); if (LOG.isDebugEnabled()) { LOG.debug("<== TypesResource.submit()"); } } } /** * Update of existing types - if the given type doesn't exist, creates new type * Allowed updates are: * 1. Add optional attribute * 2. Change required to optional attribute * 3. Add super types - super types shouldn't contain any required attributes * @param request * @return */ @PUT @Consumes({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON}) @Produces(Servlets.JSON_MEDIA_TYPE) public Response update(@Context HttpServletRequest request) { if (LOG.isDebugEnabled()) { LOG.debug("==> TypesResource.update()"); } AtlasPerfTracer perf = null; if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "TypesResource.update()"); } JSONArray typesResponse = new JSONArray(); try { final String typeDefinition = Servlets.getRequestPayload(request); if (LOG.isDebugEnabled()) { LOG.debug("Updating type with definition {} ", typeDefinition); } AtlasTypesDef updateTypesDef = TypeConverterUtil.toAtlasTypesDef(typeDefinition, typeRegistry); AtlasTypesDef updatedTypesDef = typesREST.updateAtlasTypeDefs(updateTypesDef); List<String> typeNames = TypeConverterUtil.getTypeNames(updatedTypesDef); for (int i = 0; i < typeNames.size(); i++) { final String name = typeNames.get(i); typesResponse.put(new JSONObject() {{ put(AtlasClient.NAME, name); }}); } JSONObject response = new JSONObject(); response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId()); response.put(AtlasClient.TYPES, typesResponse); return Response.ok().entity(response).build(); } catch (AtlasBaseException e) { LOG.error("Unable to persist types", e); throw new WebApplicationException(Servlets.getErrorResponse(e)); } catch (IllegalArgumentException e) { LOG.error("Unable to persist types", e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST)); } catch (WebApplicationException e) { LOG.error("Unable to persist types", e); throw e; } catch (Throwable e) { LOG.error("Unable to persist types", e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR)); } finally { AtlasPerfTracer.log(perf); if (LOG.isDebugEnabled()) { LOG.debug("<== TypesResource.update()"); } } } /** * Fetch the complete definition of a given type name which is unique. * * @param typeName name of a type which is unique. */ @GET @Path("{typeName}") @Produces(Servlets.JSON_MEDIA_TYPE) public Response getDefinition(@Context HttpServletRequest request, @PathParam("typeName") String typeName) { if (LOG.isDebugEnabled()) { LOG.debug("==> TypesResource.getDefinition({})", typeName); } AtlasPerfTracer perf = null; if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "TypesResource.getDefinition(" + typeName + ")"); } JSONObject response = new JSONObject(); try { TypesDef typesDef = TypeConverterUtil.toTypesDef(typeRegistry.getType(typeName), typeRegistry);; String typeDefinition = TypesSerialization.toJson(typesDef); response.put(AtlasClient.TYPENAME, typeName); response.put(AtlasClient.DEFINITION, new JSONObject(typeDefinition)); response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId()); return Response.ok(response).build(); } catch (AtlasBaseException e) { LOG.error("Unable to get type definition for type {}", typeName, e); throw new WebApplicationException(Servlets.getErrorResponse(e)); } catch (JSONException | IllegalArgumentException e) { LOG.error("Unable to get type definition for type {}", typeName, e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST)); } catch (WebApplicationException e) { LOG.error("Unable to get type definition for type {}", typeName, e); throw e; } catch (Throwable e) { LOG.error("Unable to get type definition for type {}", typeName, e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR)); } finally { AtlasPerfTracer.log(perf); if (LOG.isDebugEnabled()) { LOG.debug("<== TypesResource.getDefinition({})", typeName); } } } /** * Return the list of type names in the type system which match the specified filter. * * @return list of type names * @param typeCategory returns types whose relationshipCategory is the given typeCategory * @param supertype returns types which contain the given supertype * @param notsupertype returns types which do not contain the given supertype * * Its possible to specify combination of these filters in one request and the conditions are combined with AND * For example, typeCategory = TRAIT && supertype contains 'X' && supertype !contains 'Y' * If there is no filter, all the types are returned */ @GET @Produces(Servlets.JSON_MEDIA_TYPE) public Response getTypesByFilter(@Context HttpServletRequest request, @QueryParam("type") String typeCategory, @QueryParam("supertype") String supertype, @QueryParam("notsupertype") String notsupertype) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> TypesResource.getTypesByFilter({}, {}, {})", typeCategory, supertype, notsupertype); } AtlasPerfTracer perf = null; if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "TypesResource.getTypesByFilter(" + typeCategory + ", " + supertype + ", " + notsupertype + ")"); } JSONObject response = new JSONObject(); try { List<String> result = TypeConverterUtil.getTypeNames(typesREST.getTypeDefHeaders(request)); response.put(AtlasClient.RESULTS, new JSONArray(result)); response.put(AtlasClient.COUNT, result.size()); response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId()); return Response.ok(response).build(); } catch (AtlasBaseException e) { LOG.warn("TypesREST exception: {} {}", e.getClass().getSimpleName(), e.getMessage()); throw new WebApplicationException(Servlets.getErrorResponse(e)); } catch (WebApplicationException e) { LOG.error("Unable to get types list", e); throw e; } catch (Throwable e) { LOG.error("Unable to get types list", e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR)); } finally { AtlasPerfTracer.log(perf); if (LOG.isDebugEnabled()) { LOG.debug("<== TypesResource.getTypesByFilter({}, {}, {})", typeCategory, supertype, notsupertype); } } } }
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.sync.userdata; import android.content.Context; import com.google.samples.apps.iosched.sync.userdata.firebase.FirebaseUserDataSyncHelper; /** * A simple factory to isolate the decision of which synchelper should be used. */ public class UserDataSyncHelperFactory { public static AbstractUserDataSyncHelper buildSyncHelper(Context context, String accountName) { return new FirebaseUserDataSyncHelper(context, accountName); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Persistencia; import Negocio.Entregador; import Negocio.Ingrediente; import Negocio.Lote; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * * @author aluno */ public class DaoEntregador implements DaoFabricaObjetos{ @Override public boolean incluir(Object o) { Entregador e = (Entregador) o; DaoManipular dM = new DaoManipular(); String sql = "insert into Entregador(ID_ent, CPF_ent, Nome_ent, Veiculo_ent" + ", DataNasc_ent, Salario_ent, FotoURL_ent) values(?, ?, ?, ?, ?" + ", ?, ?)"; PreparedString inst = new PreparedString(sql); inst.setInt(1, e.getID()); inst.setString(2, e.getCpf()); inst.setString(3, e.getNome()); inst.setString(4, e.getVeiculo()); inst.setString(5, e.getDataNascimento()); inst.setFloat(6, e.getSalario()); inst.setString(7, e.getFotoURL()); return(dM.getCadastrar(inst.getPreparedString())); } @Override public boolean alterar(Object o) { Entregador e = (Entregador) o; DaoManipular dM = new DaoManipular(); String sql = "update Entregador set CPF_ent = ?, Nome_ent = ?, Veiculo_ent = ?" + ", DataNasc_ent = ?, Salario_ent = ?, FotoURL_ent = ? where ID_ent = ?"; PreparedString inst = new PreparedString(sql); inst.setString(1, e.getCpf()); inst.setString(2, e.getNome()); inst.setString(3, e.getVeiculo()); inst.setString(4, e.getDataNascimento()); inst.setFloat(5, e.getSalario()); inst.setString(6, e.getFotoURL()); inst.setInt(7, e.getID()); return (dM.getCadastrar(inst.getPreparedString())); } @Override public boolean excluir(int chave1, int chave2) { DaoManipular dM = new DaoManipular(); String inst = "delete from Entregador where ID_ent = "+chave1; return (dM.getCadastrar(inst)); } @Override public Entregador busca(int chave1, int chave2) { String inst = "select * from Entregador where ID_ent = "+chave1; Entregador e = null; try { DaoManipular dM = new DaoManipular(); ResultSet rS = dM.getConsultar(inst); if (rS.next()) { e = new Entregador(); e.setID(rS.getInt("ID_ent")); e.setCpf(rS.getString("CPF_ent")); e.setDataNascimento(rS.getString("DataNasc_ent")); e.setFotoURL(rS.getString("FotoURL_ent")); e.setNome(rS.getString("Nome_ent")); e.setSalario(rS.getFloat("Salario_ent")); e.setVeiculo(rS.getString("Veiculo_ent")); } }catch(Exception ex) { ex.printStackTrace(); } return e; } @Override public List<Object> carrega() { String inst="select * from Entregador order by ID_ent"; List<Object> lista = new ArrayList<>(); Entregador e; DaoEntregador dE; try { DaoManipular dM = new DaoManipular(); try (ResultSet rS = dM.getConsultar(inst)) { if (rS != null) { dE = new DaoEntregador(); while (rS.next()) { e = dE.busca(rS.getInt("ID_ent"), 0); lista.add(e); } } } } catch(SQLException ex){ System.out.println("problemas ao selecionar o Numero " + ex.getSQLState()); } return(lista); } @Override public int verificaChave(int chave) { int total = -1; String inst = "Select count(Entregador_ped) as total from Pedido where Entregador_ped = "+chave; try { DaoManipular dM = new DaoManipular(); ResultSet rS = dM.getConsultar(inst); if (rS.next()) total = rS.getInt("Total"); }catch (SQLException e) { System.out.println("Problemas na consulta da chave " + e.getSQLState()); } return(total); } }
package com.lnpdit.woofarm.utils; import de.greenrobot.event.EventBus; /** * eventbus * @author huanyu * 类名称:EventCache * 创建时间:2014-10-27 下午1:40:58 */ public class EventCache { public static EventBus commandActivity = new EventBus();//通用 public static EventBus errorHttp = new EventBus();//请求失败 public static EventBus opAnswerEvent = new EventBus();//解答时限 public static EventBus msgNotiEvent = new EventBus(); }
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ package com.sun.star.wizards.common; // import com.sun.star.beans.XPropertySet; import com.sun.star.uno.AnyConverter; import com.sun.star.uno.TypeClass; /** * A class for helping with all kinds of numerical conversions. * Optional or named parameters in SO are of the Object type in Java. * These objects must be converted to the right simple value type. * Unfortunately, StarBasic does not know the original desired type, * and a value that should be a "Float" is delivered as "Byte". This class * handles the conversions of these types.<br> * This class does not log warnings (or throws Exceptions) when the precision * of a value is lost. */ public class NumericalHelper { public static final int UNKNOWN_TYPE = -32768; public static final int BYTE_TYPE = 0; public static final int SHORT_TYPE = 1; public static final int INT_TYPE = 2; public static final int LONG_TYPE = 3; public static final int FLOAT_TYPE = 4; public static final int DOUBLE_TYPE = 5; public static final int CHAR_TYPE = 6; public static final int STRING_TYPE = -1; public static final int BOOLEAN_TYPE = -2; public static final int ARRAY_TYPE = -3; public static final int SEQUENCE_TYPE = -4; public static final int ASCII_VALUE_0 = 48; public static final int ASCII_VALUE_A = 65; public static final int COUNT_CHARS_IN_ALPHABET = 26; private static final int HEX_BASE = 16; private static final int DEC_BASE = 10; private static final int ASCII_LETTER_A_OFFSET = 55; /** * private c'tor to prevent instantiation */ private NumericalHelper() { // private c'tor, so no one can instantiate } /** * get the type of an object: returns all types that can possibly converted * with this class. * @param obj an object that is checked for conversion * @return the type of the object */ public static int getType(Object obj) { try { TypeObject aTypeObject = getTypeObject(obj); return aTypeObject.iType; } catch (com.sun.star.lang.IllegalArgumentException e) { // ignore this one; just return unknown type } return UNKNOWN_TYPE; } /** * get a byte value from the object * @param aValue * @return a byte * @throws com.sun.star.lang.IllegalArgumentException if the object cannot be converted */ public static byte toByte(Object aValue) throws com.sun.star.lang.IllegalArgumentException { byte retValue = 0; // boolean hasConversionWarning = false; TypeObject aTypeObject = getTypeObject(aValue); switch (aTypeObject.iType) { case BYTE_TYPE: retValue = getByte(aTypeObject); break; case CHAR_TYPE: retValue = (byte) getChar(aTypeObject); break; case SHORT_TYPE: retValue = (byte) getShort(aTypeObject); break; case INT_TYPE: retValue = (byte) getInt(aTypeObject); break; case LONG_TYPE: retValue = (byte) getLong(aTypeObject); break; case FLOAT_TYPE: retValue = (byte) getFloat(aTypeObject); break; case DOUBLE_TYPE: retValue = (byte) getDouble(aTypeObject); break; case STRING_TYPE: try { Byte b = new Byte((String) aTypeObject.aValue); retValue = b.byteValue(); } catch (java.lang.NumberFormatException e) { throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert to byte: " + aTypeObject.aValue); } break; case BOOLEAN_TYPE: retValue = getBool(aTypeObject) ? (byte) -1 : (byte) 0; break; default: throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert this type: " + aValue.getClass().getName()); } return retValue; } /** * get a char value from the object * @param aValue * @return a char * @throws com.sun.star.lang.IllegalArgumentException if the object cannot be converted */ public static char toChar(Object aValue) throws com.sun.star.lang.IllegalArgumentException { char retValue = 0; boolean hasConversionWarning = false; TypeObject aTypeObject = getTypeObject(aValue); switch (aTypeObject.iType) { case CHAR_TYPE: retValue = getChar(aTypeObject); break; case BYTE_TYPE: retValue = (char) getByte(aTypeObject); break; case SHORT_TYPE: retValue = (char) getShort(aTypeObject); break; case INT_TYPE: retValue = (char) getInt(aTypeObject); break; case LONG_TYPE: retValue = (char) getLong(aTypeObject); break; case FLOAT_TYPE: retValue = (char) getFloat(aTypeObject); break; case DOUBLE_TYPE: retValue = (char) getDouble(aTypeObject); break; case STRING_TYPE: try { String s = (String) aTypeObject.aValue; if (s.length() > 0) { retValue = s.charAt(0); } else { retValue = (char) 0; } } catch (java.lang.NumberFormatException e) { throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert to char: " + aTypeObject.aValue); } break; case BOOLEAN_TYPE: retValue = getBool(aTypeObject) ? (char) -1 : (char) 0; break; default: throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert this type: " + aValue.getClass().getName()); } return retValue; } /** * get a short value from the object * @param aValue * @return a short * @throws com.sun.star.lang.IllegalArgumentException if the object cannot be converted */ public static short toShort(Object aValue) throws com.sun.star.lang.IllegalArgumentException { short retValue = 0; TypeObject aTypeObject = getTypeObject(aValue); switch (aTypeObject.iType) { case BYTE_TYPE: retValue = (short) getByte(aTypeObject); break; case CHAR_TYPE: retValue = (byte) getChar(aTypeObject); break; case SHORT_TYPE: retValue = getShort(aTypeObject); break; case INT_TYPE: retValue = (short) getInt(aTypeObject); break; case LONG_TYPE: retValue = (short) getLong(aTypeObject); break; case FLOAT_TYPE: retValue = (short) getFloat(aTypeObject); break; case DOUBLE_TYPE: retValue = (short) getDouble(aTypeObject); break; case STRING_TYPE: try { Short s = new Short((String) aTypeObject.aValue); retValue = s.shortValue(); } catch (java.lang.NumberFormatException e) { throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert to short: " + aTypeObject.aValue); } break; case BOOLEAN_TYPE: retValue = getBool(aTypeObject) ? (short) -1 : (short) 0; break; default: throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert this type: " + aValue.getClass().getName()); } return retValue; } public static boolean isValidAndNumerical(Object aValue) throws com.sun.star.lang.IllegalArgumentException { if (aValue != null) { if (!AnyConverter.isVoid(aValue)) { return (NumericalHelper.isNumerical(aValue)); } } return false; } public static boolean isValidAndBoolean(Object aValue) throws com.sun.star.lang.IllegalArgumentException { if (aValue != null) { if (!AnyConverter.isVoid(aValue)) { int nType = AnyConverter.getType(aValue).getTypeClass().getValue(); return (nType == TypeClass.BOOLEAN_value); } } return false; } public static boolean isValid(Object aValue) { if (aValue != null) { if (!AnyConverter.isVoid(aValue)) { return true; } } return false; } /** @param aValue a object this can contain anything @return true, if the parameter aValue is type of real numbers @deprecate, use isRealNumber() instead. */ public static boolean isNumerical(Object aValue) { try { TypeObject aTypeObject = getTypeObject(aValue); switch (aTypeObject.iType) { case BYTE_TYPE: case CHAR_TYPE: case SHORT_TYPE: case INT_TYPE: case LONG_TYPE: case DOUBLE_TYPE: case FLOAT_TYPE: return true; default: return false; } } catch (com.sun.star.lang.IllegalArgumentException e) { return false; } } /** @param _aValue a object this can contain anything @return true, if the parameter aValue is type of real numbers see also http://en.wikipedia.org/wiki/Mathematics */ public static boolean isRealNumber(Object _aValue) { return isNumerical(_aValue); } /** @param aValue a object this can contain anything * @return true, if the value is type of any integer values. double / float are not(!) integer values * @throws com.sun.star.lang.IllegalArgumentException */ public static boolean isInteger(Object aValue) throws com.sun.star.lang.IllegalArgumentException { TypeObject aTypeObject = getTypeObject(aValue); switch (aTypeObject.iType) { case BYTE_TYPE: case CHAR_TYPE: case SHORT_TYPE: case INT_TYPE: case LONG_TYPE: return true; default: return false; } } /** * Can a given object be converted to a String array? * @param aValue the object to test * @return true, if the object can be converted to a String array. */ public static boolean isStringArray(Object aValue) { try { toStringArray(aValue); return true; } catch (com.sun.star.lang.IllegalArgumentException e) { // ignore } return false; } /** * Can a given object be converted to an int array? * @param aValue the object to test * @return true, if the object can be converted to an Integer array. */ public static boolean isIntegerArray(Object aValue) { try { toIntArray(aValue); return true; } catch (com.sun.star.lang.IllegalArgumentException e) { // ignore } return false; } // public static int toIntWithErrorMessage(Object _aValue) throws com.sun.star.script.BasicErrorException{ // try { // return toInt(_aValue); // } // catch(com.sun.star.lang.IllegalArgumentException e) { // DebugHelper.exception(BasicErrorCode.SbERR_CONVERSION, PropertyNames.EMPTY_STRING); // return 0; // }} // // // public static String toStringWithErrorMessage(Object _aValue) throws com.sun.star.script.BasicErrorException{ // try { // return toString(_aValue); // } // catch(com.sun.star.lang.IllegalArgumentException e) { // DebugHelper.exception(BasicErrorCode.SbERR_CONVERSION, PropertyNames.EMPTY_STRING); // return PropertyNames.EMPTY_STRING; // }} // // // public static int toIntWithErrorMessage(Object _aValue, int _ndefaultValue) throws com.sun.star.script.BasicErrorException{ // try { // return toInt(_aValue, _ndefaultValue); // } // catch(com.sun.star.uno.Exception e) { // DebugHelper.exception(BasicErrorCode.SbERR_CONVERSION, PropertyNames.EMPTY_STRING); // return 0; // }} // // public static boolean toBooleanWithErrorMessage(Object _oObject, int _nTrueField, int _nFalseField) throws com.sun.star.script.BasicErrorException{ // return toBooleanWithErrorMessage(_oObject, new int[]{_nTrueField}, new int[]{_nFalseField}); // } // // // public static boolean toBooleanWithErrorMessage(Object _oObject) throws com.sun.star.script.BasicErrorException{ // try{ // return toBoolean(_oObject); // } // catch (java.lang.Exception e){ // DebugHelper.exception(BasicErrorCode.SbERR_BAD_ARGUMENT, PropertyNames.EMPTY_STRING); // return false; // } // } // // // public static boolean toBooleanWithErrorMessage(Object _oObject, int[] _nTrueFields, int[] _nFalseFields) throws com.sun.star.script.BasicErrorException{ // try{ // int nValue = NumericalHelper.toIntWithErrorMessage(_oObject); // if (ContainerUtilities.FieldInIntTable(_nTrueFields, nValue) > -1){ // return true; // } // else if (ContainerUtilities.FieldInIntTable(_nFalseFields, nValue) > -1){ // return false; // } // else{ // DebugHelper.exception(BasicErrorCode.SbERR_OUT_OF_RANGE, PropertyNames.EMPTY_STRING); // return false; // } // }catch (java.lang.Exception e){ // DebugHelper.exception(BasicErrorCode.SbERR_OUT_OF_RANGE, PropertyNames.EMPTY_STRING); // return false; // }} // // // public static boolean toBooleanWithErrorMessage(Object _oObject, int _nTrueField, int _nFalseField, boolean _bdefaultValue) throws com.sun.star.script.BasicErrorException{ // return toBooleanWithErrorMessage(_oObject, new int[]{_nTrueField}, new int[]{_nFalseField}, _bdefaultValue); // } // // // public static boolean toBooleanWithErrorMessage(Object _oObject, int[] _nTrueFields, int[] _nFalseFields, boolean _bdefaultValue) throws com.sun.star.script.BasicErrorException{ // try{ // if ((_oObject == null) || (AnyConverter.isVoid(_oObject))){ // return _bdefaultValue; // } // else{ // int nValue = NumericalHelper.toIntWithErrorMessage(_oObject); // if (ContainerUtilities.FieldInIntTable(_nTrueFields, nValue) > -1){ // return true; // } // else if (ContainerUtilities.FieldInIntTable(_nFalseFields, nValue) > -1){ // return false; // } // else{ // DebugHelper.exception(BasicErrorCode.SbERR_OUT_OF_RANGE, PropertyNames.EMPTY_STRING); // return false; // } // } // }catch (java.lang.Exception e){ // DebugHelper.exception(BasicErrorCode.SbERR_OUT_OF_RANGE, PropertyNames.EMPTY_STRING); // return false; // }} /** * get an int value from the object * @param aValue * @return an int * @throws com.sun.star.lang.IllegalArgumentException if the object cannot be converted */ public static int toInt(Object aValue) throws com.sun.star.lang.IllegalArgumentException { int retValue = 0; TypeObject aTypeObject = getTypeObject(aValue); switch (aTypeObject.iType) { case BYTE_TYPE: retValue = (int) getByte(aTypeObject); break; case CHAR_TYPE: retValue = (int) getChar(aTypeObject); break; case SHORT_TYPE: retValue = (int) getShort(aTypeObject); break; case INT_TYPE: retValue = getInt(aTypeObject); break; case LONG_TYPE: retValue = (int) getLong(aTypeObject); break; case FLOAT_TYPE: retValue = (int) getFloat(aTypeObject); break; case DOUBLE_TYPE: retValue = (int) getDouble(aTypeObject); break; case STRING_TYPE: try { Integer i = new Integer((String) aTypeObject.aValue); retValue = i.intValue(); } catch (java.lang.NumberFormatException e) { throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert to int: " + aTypeObject.aValue); } break; case BOOLEAN_TYPE: retValue = getBool(aTypeObject) ? -1 : 0; break; default: throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert this type: " + aValue.getClass().getName()); } return retValue; } /** * get a long value from the object * @param aValue * @return a long * @throws com.sun.star.lang.IllegalArgumentException if the object cannot be converted */ public static long toLong(Object aValue) throws com.sun.star.lang.IllegalArgumentException { long retValue = 0; TypeObject aTypeObject = getTypeObject(aValue); switch (aTypeObject.iType) { case BYTE_TYPE: retValue = (long) getByte(aTypeObject); break; case CHAR_TYPE: retValue = (long) getChar(aTypeObject); break; case SHORT_TYPE: retValue = (long) getShort(aTypeObject); break; case INT_TYPE: retValue = (long) getInt(aTypeObject); break; case LONG_TYPE: retValue = getLong(aTypeObject); break; case FLOAT_TYPE: retValue = (long) getFloat(aTypeObject); break; case DOUBLE_TYPE: retValue = (long) getDouble(aTypeObject); break; case STRING_TYPE: try { Long l = new Long((String) aTypeObject.aValue); retValue = l.longValue(); } catch (java.lang.NumberFormatException e) { throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert to short: " + aTypeObject.aValue); } break; case BOOLEAN_TYPE: retValue = getBool(aTypeObject) ? -1 : 0; break; default: throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert this type: " + aValue.getClass().getName()); } return retValue; } /** * get a float value from the object * @param aValue * @return a float * @throws com.sun.star.lang.IllegalArgumentException if the object cannot be converted */ public static float toFloat(Object aValue) throws com.sun.star.lang.IllegalArgumentException { float retValue = (float) 0.0; TypeObject aTypeObject = getTypeObject(aValue); switch (aTypeObject.iType) { case BYTE_TYPE: retValue = (float) getByte(aTypeObject); break; case CHAR_TYPE: retValue = (float) getChar(aTypeObject); break; case SHORT_TYPE: retValue = (float) getShort(aTypeObject); break; case INT_TYPE: retValue = (float) getInt(aTypeObject); break; case LONG_TYPE: retValue = (float) getLong(aTypeObject); break; case FLOAT_TYPE: retValue = getFloat(aTypeObject); break; case DOUBLE_TYPE: retValue = (float) getDouble(aTypeObject); break; case STRING_TYPE: try { Float f = new Float((String) aTypeObject.aValue); retValue = f.floatValue(); } catch (java.lang.NumberFormatException e) { throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert to short: " + aTypeObject.aValue); } break; case BOOLEAN_TYPE: retValue = getBool(aTypeObject) ? (float) -1 : (float) 0; break; default: throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert this type: " + aValue.getClass().getName()); } return retValue; } /** * get a double value from the object * @param aValue * @return a double * @throws com.sun.star.lang.IllegalArgumentException if the object cannot be converted */ public static double toDouble(Object aValue) throws com.sun.star.lang.IllegalArgumentException { double retValue = 0.0; TypeObject aTypeObject = getTypeObject(aValue); switch (aTypeObject.iType) { case BYTE_TYPE: retValue = (double) getByte(aTypeObject); break; case CHAR_TYPE: retValue = (double) getChar(aTypeObject); break; case SHORT_TYPE: retValue = (double) getShort(aTypeObject); break; case INT_TYPE: retValue = (double) getInt(aTypeObject); break; case LONG_TYPE: retValue = (double) getLong(aTypeObject); break; case FLOAT_TYPE: retValue = (double) getFloat(aTypeObject); break; case DOUBLE_TYPE: retValue = getDouble(aTypeObject); break; case STRING_TYPE: try { Float f = new Float((String) aTypeObject.aValue); retValue = f.floatValue(); } catch (java.lang.NumberFormatException e) { throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert to short: " + aTypeObject.aValue); } break; case BOOLEAN_TYPE: retValue = getBool(aTypeObject) ? (double) -1 : (double) 0; break; default: throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert this type: " + aValue.getClass().getName()); } return retValue; } /** * get a String value from the object * @param aValue * @return a String * @throws com.sun.star.lang.IllegalArgumentException if the object cannot be converted */ public static String toString(Object aValue) throws com.sun.star.lang.IllegalArgumentException { String retValue = null; TypeObject aTypeObject = getTypeObject(aValue); switch (aTypeObject.iType) { case BYTE_TYPE: retValue = aTypeObject.aValue.toString(); break; case CHAR_TYPE: retValue = aTypeObject.aValue.toString(); break; case SHORT_TYPE: retValue = aTypeObject.aValue.toString(); break; case INT_TYPE: retValue = aTypeObject.aValue.toString(); break; case LONG_TYPE: retValue = aTypeObject.aValue.toString(); break; case FLOAT_TYPE: retValue = aTypeObject.aValue.toString(); break; case DOUBLE_TYPE: retValue = aTypeObject.aValue.toString(); break; case STRING_TYPE: retValue = (String) aTypeObject.aValue; break; case BOOLEAN_TYPE: retValue = aTypeObject.aValue.toString(); break; case ARRAY_TYPE: retValue = new String(toByteArray((aValue))); break; default: throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert this type: " + aValue.getClass().getName()); } return retValue; } /** * get a boolean value from the object * @param aValue * @return a boolean * @throws com.sun.star.lang.IllegalArgumentException if the object cannot be converted */ public static boolean toBoolean(Object aValue) throws com.sun.star.lang.IllegalArgumentException { boolean retValue = true; TypeObject aTypeObject = getTypeObject(aValue); switch (aTypeObject.iType) { case BYTE_TYPE: retValue = (((Byte) aTypeObject.aValue).byteValue() != 0); break; case CHAR_TYPE: retValue = (((Character) aTypeObject.aValue).charValue() != 0); break; case SHORT_TYPE: retValue = (((Short) aTypeObject.aValue).shortValue() != 0); break; case INT_TYPE: retValue = (((Integer) aTypeObject.aValue).intValue() != 0); break; case LONG_TYPE: retValue = (((Long) aTypeObject.aValue).longValue() != 0); break; case FLOAT_TYPE: retValue = (((Float) aTypeObject.aValue).floatValue() != 0); break; case DOUBLE_TYPE: retValue = (((Double) aTypeObject.aValue).doubleValue() != 0); break; case STRING_TYPE: try { Boolean b = Boolean.valueOf((String) aTypeObject.aValue); retValue = b.booleanValue(); } catch (java.lang.NumberFormatException e) { throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert to short: " + aTypeObject.aValue); } break; case BOOLEAN_TYPE: retValue = ((Boolean) aTypeObject.aValue).booleanValue(); break; default: throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert this type: " + aValue.getClass().getName()); } return retValue; } /** * get an int array from an object * @param anArrayValue a value that is constructed into an array * @return an integer array * @throws com.sun.star.lang.IllegalArgumentException */ public static int[] toIntArray(Object anArrayValue) throws com.sun.star.lang.IllegalArgumentException { int[] retValue = null; TypeObject aTypeObject = getTypeObject(anArrayValue); if (aTypeObject.iType == SEQUENCE_TYPE) { aTypeObject = convertSequenceToObjectArray(aTypeObject); } if (aTypeObject.iType == ARRAY_TYPE) { Object[] obj = (Object[]) aTypeObject.aValue; retValue = new int[obj.length]; for (int i = 0; i < obj.length; i++) { retValue[i] = toInt(obj[i]); } } else { // object is not really an array retValue = new int[] { toInt(anArrayValue) }; } return retValue; } /** * get an byte array from an object * @param anArrayValue a value that is constructed into an array * @return a byte array * @throws com.sun.star.lang.IllegalArgumentException */ public static byte[] toByteArray(Object anArrayValue) throws com.sun.star.lang.IllegalArgumentException { byte[] retValue = null; TypeObject aTypeObject = getTypeObject(anArrayValue); if (aTypeObject.iType == SEQUENCE_TYPE) { aTypeObject = convertSequenceToObjectArray(aTypeObject); } if (aTypeObject.iType == ARRAY_TYPE) { Object[] obj = (Object[]) aTypeObject.aValue; retValue = new byte[obj.length]; for (int i = 0; i < obj.length; i++) { retValue[i] = toByte(obj[i]); } } else { // object is not really an array retValue = new byte[] { toByte(anArrayValue) }; } return retValue; } /** * get a short array from an object * @param anArrayValue a value that is constructed into an array * @return a short array * @throws com.sun.star.lang.IllegalArgumentException */ public static short[] toShortArray(Object anArrayValue) throws com.sun.star.lang.IllegalArgumentException { short[] retValue = null; TypeObject aTypeObject = getTypeObject(anArrayValue); if (aTypeObject.iType == SEQUENCE_TYPE) { aTypeObject = convertSequenceToObjectArray(aTypeObject); } if (aTypeObject.iType == ARRAY_TYPE) { Object[] obj = (Object[]) aTypeObject.aValue; retValue = new short[obj.length]; for (int i = 0; i < obj.length; i++) { retValue[i] = toShort(obj[i]); } } else { // object is not really an array retValue = new short[] { toShort(anArrayValue) }; } return retValue; } /** * get a string array from an object * @param anArrayValue a value that is constructed into an array * @return a short array * @throws com.sun.star.lang.IllegalArgumentException */ public static String[] toStringArray(Object anArrayValue) throws com.sun.star.lang.IllegalArgumentException { String[] retValue = null; TypeObject aTypeObject = getTypeObject(anArrayValue); if (aTypeObject.iType == SEQUENCE_TYPE) { aTypeObject = convertSequenceToObjectArray(aTypeObject); } if (aTypeObject.iType == ARRAY_TYPE) { Object[] obj = (Object[]) aTypeObject.aValue; retValue = new String[obj.length]; for (int i = 0; i < obj.length; i++) { retValue[i] = toString(obj[i]); } } else { // object is not really an array retValue = new String[] { toString(anArrayValue) }; } return retValue; } /** * get an int from an object * @param _aValue a value that is constructed into an int * @param _ndefaultValue the value that is returned, if conversion fails, or if 'aValue' is null * @return an int value * @throws java.lang.Exception */ public static int toInt(Object _aValue, int _ndefaultValue) throws Exception { int nreturn = _ndefaultValue; try { if ((_aValue != null) && (!(AnyConverter.isVoid(_aValue)))) { if (isInteger(_aValue)) { nreturn = toInt(_aValue); } else { DebugHelper.exception(1/* BasicErrorCode.SbERR_CONVERSION*/, PropertyNames.EMPTY_STRING); } } } catch (com.sun.star.uno.Exception e) { DebugHelper.exception(1 /*BasicErrorCode.SbERR_METHOD_FAILED*/, PropertyNames.EMPTY_STRING); } return nreturn; } /** * get a long from an object * @param aValue a value that is constructed into a long * @param defaultValue the value that is returned, if conversion fails * @return a long value */ public static long toLong(Object aValue, long defaultValue) { try { return toLong(aValue); } catch (com.sun.star.lang.IllegalArgumentException e) { // ignore exception } return defaultValue; } /** * get a float from an object * @param aValue a value that is constructed into a float * @param defaultValue the value that is returned, if conversion fails * @return a long value */ public static float toFloat(Object aValue, float defaultValue) { try { return toFloat(aValue); } catch (com.sun.star.lang.IllegalArgumentException e) { // ignore exception } return defaultValue; } /** * get a double from an object * @param aValue a value that is constructed into a double * @param defaultValue the value that is returned, if conversion fails * @return a double value */ public static double toDouble(Object aValue, double defaultValue) { try { return toDouble(aValue); } catch (com.sun.star.lang.IllegalArgumentException e) { // ignore exception } return defaultValue; } /** * get a string from an object * @param aValue a value that is constructed into a string * @param defaultValue the value that is returned, if conversion fails * @return a string value */ public static String toString(Object aValue, String defaultValue) { try { return toString(aValue); } catch (com.sun.star.lang.IllegalArgumentException e) { // ignore exception } return defaultValue; } /** * get a boolean from an object * @param aValue a value that is constructed into a boolean * @param defaultValue the value that is returned, if conversion fails * @return a boolean value */ public static boolean toBoolean(Object aValue, boolean defaultValue) { try { return toBoolean(aValue); } catch (com.sun.star.lang.IllegalArgumentException e) { // ignore exception } return defaultValue; } /** * get a int array from an object * @param anArrayValue a value that is constructed into an int array * @param defaultValue the value that is returned, if conversion fails * @return an int array */ public static int[] toIntArray(Object anArrayValue, int[] defaultValue) { try { return toIntArray(anArrayValue); } catch (com.sun.star.lang.IllegalArgumentException e) { // ignore exception } return defaultValue; } /** * get a short array from an object * @param anArrayValue a value that is constructed into a short array * @param defaultValue the value that is returned, if conversion fails * @return a short array */ public static short[] toShortArray(Object anArrayValue, short[] defaultValue) { try { return toShortArray(anArrayValue); } catch (com.sun.star.lang.IllegalArgumentException e) { // ignore exception } return defaultValue; } /** * get a string array from an object * @param anArrayValue a value that is constructed into a string array * @param defaultValue the value that is returned, if conversion fails * @return a string array */ public static String[] toStringArray(Object anArrayValue, String[] defaultValue) { try { return toStringArray(anArrayValue); } catch (com.sun.star.lang.IllegalArgumentException e) { // ignore exception } return defaultValue; } /** * get a hexadecimal representation from a number * @param number the number to transform * @return a String with the hex code of the number */ public static String getHexStringFromNumber(long number) { TransformNumToHex num = new TransformNumToHex(number); return num.getResult(); } /** * Get the roman equivalent to an arabic number, e.g. 17 -> XVII. * The allowed range for numbers goes from 1 to 3999. These can be * converted using ASCII letters (3999 -> MMMCMXCIX). * @param n the arabic number * @return the roman equivalent as string * @throws BasicErrorException if the number cannot be converted. */ // public static String getRomanEquivalent(int n) // throws com.sun.star.script.BasicErrorException { // return RomanNumbering.getRomanEquivalent(n); // } /** * get the type object from the given object * @param aValue an object representing a (numerical) value; can also be an 'any' * @return a type object: the object together with the its type information * @throws com.sun.star.lang.IllegalArgumentException if the object is unknown */ private static TypeObject getTypeObject(Object aValue) throws com.sun.star.lang.IllegalArgumentException { TypeObject aTypeObject = new TypeObject(); if (aValue == null || AnyConverter.isVoid(aValue)) { throw new com.sun.star.lang.IllegalArgumentException("Cannot convert a null object."); } int type = AnyConverter.getType(aValue).getTypeClass().getValue(); switch (type) { case TypeClass.CHAR_value: aTypeObject.iType = CHAR_TYPE; aTypeObject.aValue = new Character(AnyConverter.toChar(aValue)); break; case TypeClass.BYTE_value: aTypeObject.iType = BYTE_TYPE; aTypeObject.aValue = new Byte(AnyConverter.toByte(aValue)); break; case TypeClass.SHORT_value: aTypeObject.iType = SHORT_TYPE; aTypeObject.aValue = new Short(AnyConverter.toShort(aValue)); break; case TypeClass.LONG_value: aTypeObject.iType = INT_TYPE; aTypeObject.aValue = new Integer(AnyConverter.toInt(aValue)); break; case TypeClass.HYPER_value: aTypeObject.iType = LONG_TYPE; aTypeObject.aValue = new Long(AnyConverter.toLong(aValue)); break; case TypeClass.FLOAT_value: aTypeObject.iType = FLOAT_TYPE; aTypeObject.aValue = new Float(AnyConverter.toFloat(aValue)); break; case TypeClass.DOUBLE_value: aTypeObject.iType = DOUBLE_TYPE; aTypeObject.aValue = new Double(AnyConverter.toDouble(aValue)); break; case TypeClass.STRING_value: aTypeObject.iType = STRING_TYPE; aTypeObject.aValue = AnyConverter.toString(aValue); break; case TypeClass.BOOLEAN_value: aTypeObject.iType = BOOLEAN_TYPE; aTypeObject.aValue = Boolean.valueOf(AnyConverter.toBoolean(aValue)); break; case TypeClass.ARRAY_value: aTypeObject.iType = ARRAY_TYPE; aTypeObject.aValue = new Object[] { AnyConverter.toArray(aValue) }; break; case TypeClass.SEQUENCE_value: aTypeObject.iType = SEQUENCE_TYPE; aTypeObject.aValue = aValue; break; default: throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert this type: " + aValue.getClass().getName()); } return aTypeObject; } /** * get the simple byte type */ private static byte getByte(TypeObject typeObject) throws com.sun.star.lang.IllegalArgumentException { if (typeObject.iType != BYTE_TYPE) { throw new com.sun.star.lang.IllegalArgumentException( "Given argument is not a byte type."); } return ((Byte) typeObject.aValue).byteValue(); } /** * get the simple char type */ private static char getChar(TypeObject typeObject) throws com.sun.star.lang.IllegalArgumentException { if (typeObject.iType != CHAR_TYPE) { throw new com.sun.star.lang.IllegalArgumentException( "Given argument is not a char type."); } return ((Character) typeObject.aValue).charValue(); } /** * get the simple short type */ private static short getShort(TypeObject typeObject) throws com.sun.star.lang.IllegalArgumentException { if (typeObject.iType != SHORT_TYPE) { throw new com.sun.star.lang.IllegalArgumentException( "Given argument is not a short type."); } return ((Short) typeObject.aValue).shortValue(); } /** * get the simple int type * @param typeObject * @return * @throws com.sun.star.lang.IllegalArgumentException */ static int getInt(TypeObject typeObject) throws com.sun.star.lang.IllegalArgumentException { if (typeObject.iType != INT_TYPE) { throw new com.sun.star.lang.IllegalArgumentException( "Given argument is not an int type."); } return ((Integer) typeObject.aValue).intValue(); } /** * get the simple float type * @throws com.sun.star.lang.IllegalArgumentException */ static float getFloat(TypeObject typeObject) throws com.sun.star.lang.IllegalArgumentException { if (typeObject.iType != FLOAT_TYPE) { throw new com.sun.star.lang.IllegalArgumentException( "Given argument is not a float type."); } return ((Float) typeObject.aValue).floatValue(); } /** * get the simple double type */ private static double getDouble(TypeObject typeObject) throws com.sun.star.lang.IllegalArgumentException { if (typeObject.iType != DOUBLE_TYPE) { throw new com.sun.star.lang.IllegalArgumentException( "Given argument is not a double type."); } return ((Double) typeObject.aValue).doubleValue(); } /** * get the simple long type */ private static long getLong(TypeObject typeObject) throws com.sun.star.lang.IllegalArgumentException { if (typeObject.iType != LONG_TYPE) { throw new com.sun.star.lang.IllegalArgumentException( "Given argument is not a long type."); } return ((Long) typeObject.aValue).longValue(); } /** * get the simple boolean type */ private static boolean getBool(TypeObject typeObject) throws com.sun.star.lang.IllegalArgumentException { if (typeObject.iType != BOOLEAN_TYPE) { throw new com.sun.star.lang.IllegalArgumentException( "Given argument is not a boolean type."); } return ((Boolean) typeObject.aValue).booleanValue(); } /** * a class to contain a type and a value for easier conversions */ private static class TypeObject { public int iType; public Object aValue; } /** * simple class to construct a hexadecimal value from a long number */ private static class TransformNumToHex { private StringBuffer val; public TransformNumToHex(long number) { val = new StringBuffer(); transform(number); } private void transform(long number) { int index = (int) (number % HEX_BASE); number = number / HEX_BASE; if (index < DEC_BASE) { val.insert(0, index); } else { val.insert(0, (char) (ASCII_LETTER_A_OFFSET + index)); } if (number > 0) { transform(number); } } public String getResult() { return val.toString(); } } private static TypeObject convertSequenceToObjectArray( TypeObject sourceObject) throws com.sun.star.lang.IllegalArgumentException { TypeObject destObject = new TypeObject(); Object array = sourceObject.aValue; destObject.iType = ARRAY_TYPE; Class c = array.getClass(); Object[] aShortVal = null; if (c.equals(byte[].class)) { byte[] vals = (byte[]) array; aShortVal = new Object[vals.length]; for (int i = 0; i < vals.length; i++) { aShortVal[i] = new Byte(vals[i]); } } else if (c.equals(short[].class)) { short[] vals = (short[]) array; aShortVal = new Object[vals.length]; for (int i = 0; i < vals.length; i++) { aShortVal[i] = new Short(vals[i]); } } else if (c.equals(int[].class)) { int[] vals = (int[]) array; aShortVal = new Object[vals.length]; for (int i = 0; i < vals.length; i++) { aShortVal[i] = new Integer(vals[i]); } } else if (c.equals(long[].class)) { long[] vals = (long[]) array; aShortVal = new Object[vals.length]; for (int i = 0; i < vals.length; i++) { aShortVal[i] = new Long(vals[i]); } } else if (c.equals(float[].class)) { float[] vals = (float[]) array; aShortVal = new Object[vals.length]; for (int i = 0; i < vals.length; i++) { aShortVal[i] = new Float(vals[i]); } } else if (c.equals(double[].class)) { double[] vals = (double[]) array; aShortVal = new Object[vals.length]; for (int i = 0; i < vals.length; i++) { aShortVal[i] = new Double(vals[i]); } } else if (c.equals(boolean[].class)) { boolean[] vals = (boolean[]) array; aShortVal = new Object[vals.length]; for (int i = 0; i < vals.length; i++) { aShortVal[i] = Boolean.valueOf(vals[i]); } } // if nothing did match, try this if (aShortVal == null) { try { aShortVal = (Object[]) array; } catch (java.lang.ClassCastException e) { // unknown type cannot be converted throw new com.sun.star.lang.IllegalArgumentException( "Cannot convert unknown type: '" + e.getMessage() + "'"); } } destObject.aValue = aShortVal; return destObject; } // public static boolean isObjectNumericRepresentation(Object _oValue, NumberFormatter _oNumberFormatter, XPropertySet _xPropertySet) throws com.sun.star.script.BasicErrorException{ // try{ // int nNumberFormat = AnyConverter.toInt(_xPropertySet.getPropertyValue("NumberFormat")); // if (AnyConverter.isString(_oValue)){ // String sCellContent = AnyConverter.toString(_oValue); // try{ // _oNumberFormatter.convertStringToNumber(nNumberFormat, sCellContent); // return true; // }catch (Exception e){ // return false; // } // } // else{ // return true; // } // } // catch (com.sun.star.uno.Exception e){ // DebugHelper.exception(1 /*BasicErrorCode.SbERR_METHOD_FAILED*/, PropertyNames.EMPTY_STRING); // return false; // }} /** * Helper class for roman numbering */ private static class RomanNumbering { /** the used roman lettesrs **/ private static final String[] ROMAN_EQUIV = new String[] { "I", "V", "X", "L", "C", "D", "M" }; /** max number that can be converted **/ private static final int MAX_NUMBER = 3999; /** min number that can be converted **/ private static final int MIN_NUMBER = 1; /** ASCII code for the number 0 **/ private static final int ASCII_CODE_0 = 48; /** special number for the conversion algorithm **/ private static final int FOUR = 4; /** special number for the conversion algorithm **/ private static final int FIVE = 5; /** special number for the conversion algorithm **/ private static final int NINE = 9; /** * Get the roman equivalent to an arabic number, e.g. 17 -> XVII. * The allowed range for numbers goes from 1 to 3999. These can be * converted using ASCII letters (3999 -> MMMCMXCIX). * @param n the arabic number * @return the roman equivalent as string * @throws BasicErrorException if the number cannot be converted. */ public static String getRomanEquivalent(int n) throws Exception { StringBuffer romanNumber = new StringBuffer(); try { if (n > MAX_NUMBER || n < MIN_NUMBER) { DebugHelper.exception(1 /*BasicErrorCode.SbERR_OUT_OF_RANGE*/, PropertyNames.EMPTY_STRING); } String number = NumericalHelper.toString(new Integer(n)); /* converison idea: every digit is written with a maximum of two * different roman symbols, using three in total, e.g. CC, CD, * DCC, CM for the hundreds (meaning 200, 400, 700 and 900). * So every digit is converted separately with regard to the * special cases 4 and 9. */ int symbolIndex = 0; for (int i = number.length() - 1; i >= 0; i--) { StringBuffer romanDigit = new StringBuffer(); int b = (int) number.charAt(i) - ASCII_CODE_0; if (b == FOUR) { // special case IV romanDigit.append(ROMAN_EQUIV[symbolIndex]); romanDigit.append(ROMAN_EQUIV[symbolIndex + 1]); } else if (b == NINE) { // special case IX romanDigit.append(ROMAN_EQUIV[symbolIndex]); romanDigit.append(ROMAN_EQUIV[symbolIndex + 2]); } else { if (b >= FIVE) { // special case V romanDigit.append(ROMAN_EQUIV[symbolIndex + 1]); b = b - FIVE; } for (int j = 0; j < b; j++) { // append I's romanDigit.append(ROMAN_EQUIV[symbolIndex]); } } // next group of three symbols symbolIndex += 2; // append in reverse: we are starting at the right romanNumber.append(romanDigit.reverse()); } } catch (com.sun.star.lang.IllegalArgumentException e) { DebugHelper.exception(e); } // reverse again to get the number return romanNumber.reverse().toString(); } } public static boolean representsIntegerNumber(double _dblvalue) { double dblsecvalue = (double) ((int) _dblvalue); return Double.compare(_dblvalue, dblsecvalue) == 0; } public static double roundDouble(Double _Dblvalue, int _ndecimals) { return roundDouble(_Dblvalue.doubleValue(), _ndecimals); } public static double roundDouble(double _dblvalue, int _ndecimals) { double dblfactor = java.lang.Math.pow(10.0, (double) _ndecimals); return ((double) ((int) (_dblvalue * dblfactor))) / dblfactor; } }
/* * 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.druid.server.metrics; import org.apache.druid.java.util.emitter.EmittingLogger; import org.apache.druid.java.util.emitter.core.Event; import org.apache.druid.java.util.emitter.service.ServiceEmitter; import javax.annotation.Nullable; import java.util.Map; public class ExceptionCapturingServiceEmitter extends ServiceEmitter { private volatile Class exceptionClass; private volatile String exceptionMessage; private volatile String stackTrace; public ExceptionCapturingServiceEmitter() { super("", "", null); } @Override public void emit(Event event) { //noinspection unchecked final Map<String, Object> dataMap = (Map<String, Object>) event.toMap().get("data"); final Class exceptionClass = (Class) dataMap.get(EmittingLogger.EXCEPTION_TYPE_KEY); if (exceptionClass != null) { final String exceptionMessage = (String) dataMap.get(EmittingLogger.EXCEPTION_MESSAGE_KEY); final String stackTrace = (String) dataMap.get(EmittingLogger.EXCEPTION_STACK_TRACE_KEY); this.exceptionClass = exceptionClass; this.exceptionMessage = exceptionMessage; this.stackTrace = stackTrace; } } @Nullable public Class getExceptionClass() { return exceptionClass; } @Nullable public String getExceptionMessage() { return exceptionMessage; } @Nullable public String getStackTrace() { return stackTrace; } }
/* * Copyright 2007 Sascha Weinreuter * * 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.intellij.plugins.relaxNG; import org.intellij.plugins.testUtil.CopyFile; /** * Created by IntelliJ IDEA. * User: sweinreuter * Date: 25.07.2007 */ @CopyFile("*.rng") public class RngIndexHighlightingTest extends AbstractIndexTest { @Override public String getTestDataPath() { return "highlighting/rng"; } public void testInspectionUnusedDefine1() throws Throwable { doHighlightingTest("unused-define-1.rng"); } public void testInspectionUnusedDefine2() throws Throwable { doHighlightingTest("unused-define-2.rng"); } public void testInspectionDefine1() throws Throwable { doHighlightingTest("used-define-1.rng"); } public void testInspectionDefine2() throws Throwable { doHighlightingTest("used-define-2.rng"); } public void testInspectionDefine3() throws Throwable { doHighlightingTest("used-define-3-include.rng"); } public void testIncludedGrammarWithoutStart() throws Throwable { // adding a <weak_warning> tag doesn't work because it seems to prevent the index to recognize the file // because the replacement is done *after* building the index :( doCustomHighlighting("included-grammar.rng", false, false); } public void testBackwardIncludeRef() throws Throwable { doHighlightingTest("backward-include-ref.rng"); } public void testUnrelatedBackwardIncludeRef() throws Throwable { doHighlightingTest("backward-with-include.rng"); } }
package no.vegvesen.ixn.serviceprovider; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; @EnableWebMvc @Configuration @ComponentScan({ "no.vegvesen.ixn.serviceprovider" }) public class OnboardStrictWebConfig implements WebMvcConfigurer{ @Override public void configureMessageConverters( List<HttpMessageConverter<?>> messageConverters) { messageConverters.add(strictJsonMessageConverter()); } static MappingJackson2HttpMessageConverter strictJsonMessageConverter() { MappingJackson2HttpMessageConverter strictJsonMessageConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper strictObjectMapper = new ObjectMapper(); strictObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); strictJsonMessageConverter.setObjectMapper(strictObjectMapper); return strictJsonMessageConverter; } }
/* * Copyright 2012 Kantega AS * * 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.kantega.revoc.source; import org.kantega.revoc.config.Config; import org.apache.commons.io.IOUtils; import org.w3c.dom.*; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.net.*; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipEntry; /** * */ public class MavenSourceArtifactSourceSource implements SourceSource { private final Map<String, MavenSourceInfo> mavenInfoMap = new HashMap<String, MavenSourceInfo>(); private final Map<String, JarFile> sourceFileMap = new HashMap<String, JarFile>(); private File mavenDownloads; private String mavenRepo; public MavenSourceArtifactSourceSource() { String mavenDownloadsEnv = Config.getProperty("REVOC_MAVEN_DOWNLOAD"); String mavenRepo = Config.getProperty("REVOC_MAVEN_REPO"); if(mavenDownloadsEnv != null && mavenRepo != null) { File mavenDir = new File(mavenDownloadsEnv); mavenDir.mkdirs(); this.mavenDownloads = mavenDir; if(!mavenRepo.endsWith("/")) { mavenRepo +="/"; } this.mavenRepo = mavenRepo; } } public String[] getSource(String className, ClassLoader classLoader) { URL resource = classLoader.getResource(className + ".class"); String filePath = getFilePath(resource); if (filePath == null) { return null; } try { MavenSourceInfo info; synchronized (mavenInfoMap) { if (!mavenInfoMap.containsKey(filePath)) { mavenInfoMap.put(filePath, parseInfo(filePath, resource)); } info = mavenInfoMap.get(filePath); } JarFile sourceFile; synchronized (sourceFileMap) { if(!sourceFileMap.containsKey(filePath)) { sourceFileMap.put(filePath, getSourceFile(filePath, info)); } sourceFile = sourceFileMap.get(filePath); } if(sourceFile == null) { return null; } String sourcePath = className.replace('.', '/') + ".java"; ZipEntry entry = sourceFile.getEntry(sourcePath); if (entry == null) { return null; } InputStream inputStream = sourceFile.getInputStream(entry); List<String> lines = IOUtils.readLines(inputStream); return lines.toArray(new String[lines.size()]); } catch (IOException e) { throw new RuntimeException(e); } } private JarFile getSourceFile(String filePath, MavenSourceInfo info) throws IOException { if(!filePath.endsWith(".jar")) { return null; } File sourceJar; if(info == null) { sourceJar = new File(filePath.substring(0, filePath.lastIndexOf(".jar")) +"-sources.jar"); } else { File m2Repo = new File(System.getProperty("user.home"), ".m2/repository"); sourceJar = new File(m2Repo, getSourceFileMavenPath(info)); if (!sourceJar.exists()) { sourceJar = new File(new File(filePath).getParentFile(), getSourceArtifactName(info)); } } if (!sourceJar.exists()) { if(mavenDownloads != null && info != null) { File downLoad = downloadMavenSource(info); if(downLoad != null) { sourceJar = downLoad; } } if(!sourceJar.exists()) { return null; } } return new JarFile(sourceJar); } private File downloadMavenSource(MavenSourceInfo info) { File downloadFile = new File(mavenDownloads, getSourceFileMavenPath(info)); if(info.getVersion().contains("-SNAPSHOT")) { downloadFile.delete(); } if(downloadFile.exists()) { return downloadFile; } downloadFile.getParentFile().mkdirs(); File tempFile = new File(downloadFile.getParentFile(), "_tmp" + downloadFile.getName()); try { URL remoteSourceURL = new URL(this.mavenRepo + getSourceFileDownloadMavenPath(info)); InputStream stream = remoteSourceURL.openStream(); FileOutputStream output = new FileOutputStream(tempFile); IOUtils.copy(stream, output); output.close(); tempFile.renameTo(downloadFile); return downloadFile; } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } } private String getSourceFileMavenPath(MavenSourceInfo info) { StringBuilder sb = new StringBuilder(); appendArtifactDirectory(info, sb); sb.append(getSourceArtifactName(info)); return sb.toString(); } private String getSourceFileDownloadMavenPath(MavenSourceInfo info) { StringBuilder sb = new StringBuilder(); appendArtifactDirectory(info, sb); if(info.getVersion().contains("SNAPSHOT")) { sb.append(resolveSnapshotFileName(info, sb.toString())); } else { sb.append(getSourceArtifactName(info)); } return sb.toString(); } private void appendArtifactDirectory(MavenSourceInfo info, StringBuilder sb) { sb.append(info.getGroupId().replace('.', '/')).append("/"); sb.append(info.getArtifactId()).append("/"); sb.append(info.getVersion()).append("/"); } private String resolveSnapshotFileName(MavenSourceInfo info, String artifactUrl) { try { URL url = new URL(this.mavenRepo + artifactUrl + "maven-metadata.xml"); final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.addRequestProperty("Cache-Control", "max-age=0"); urlConnection.addRequestProperty("User-Agent", "Apache-Maven/3.0"); InputStream inputStream = urlConnection.getInputStream(); final Document doc = builder.parse(inputStream); inputStream.close(); Element versioning = (Element) doc.getDocumentElement().getElementsByTagName("versioning").item(0); Element snapshotVersions = (Element) versioning.getElementsByTagName("snapshotVersions").item(0); NodeList snapshotVersion = snapshotVersions.getElementsByTagName("snapshotVersion"); for(int i = 0; i < snapshotVersion.getLength(); i++) { final Element versioningElement = (Element) snapshotVersion.item(i); String value= getText((Element) versioningElement.getElementsByTagName("value").item(0)); return info.getArtifactId() + "-" + value + "-sources.jar"; } return null; } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } private String getText(Element versionNode) { StringBuilder text = new StringBuilder(); for (int t = 0; t < versionNode.getChildNodes().getLength(); t++) { final Node node = versionNode.getChildNodes().item(t); if (node instanceof Text) { text.append(((Text) node).getData()); } } return text.toString(); } private String getSourceArtifactName(MavenSourceInfo info) { StringBuilder sb = new StringBuilder(); sb.append(info.getArtifactId()).append("-").append(info.getVersion()).append("-sources.jar"); return sb.toString(); } private String getFilePath(URL resource) { if (resource == null) { return null; } if (!resource.getProtocol().equals("jar")) { return null; } String filePath = resource.getPath(); if (!filePath.startsWith("file:") || !filePath.contains("!")) { return null; } filePath = filePath.substring("file:".length()); return URLDecoder.decode(filePath.substring(0, filePath.indexOf("!"))); } private MavenSourceInfo parseInfo(String filePath, URL resource) { File file = new File(filePath); JarFile jarFile = null; boolean isNewFile = false; try { URLConnection urlConnection = resource.openConnection(); if (urlConnection instanceof JarURLConnection) { jarFile = ((JarURLConnection) urlConnection).getJarFile(); } else { jarFile = new JarFile(file); isNewFile = true; } Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String prefix = "META-INF/maven/"; String propSuffix = "/pom.properties"; if (entry.getName().startsWith(prefix) && entry.getName().endsWith(propSuffix)) { Properties props = new Properties(); InputStream inputStream = jarFile.getInputStream(entry); props.load(inputStream); inputStream.close(); String groupId = props.getProperty("groupId"); String artifactId = props.getProperty("artifactId"); String version = props.getProperty("version"); if (file.getName().startsWith(artifactId + "-" + version)) { return new MavenSourceInfo(groupId, artifactId, version); } } } return null; } catch (IOException e) { throw new RuntimeException(e); } finally { if (isNewFile) { if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } } private class MavenSourceInfo { private final String groupId; private final String artifactId; private final String version; private JarFile sourceFile; public MavenSourceInfo(String groupId, String artifactId, String version) { this.groupId = groupId; this.artifactId = artifactId; this.version = version; } public String getArtifactId() { return artifactId; } public String getGroupId() { return groupId; } public String getVersion() { return version; } public void setSourceFile(JarFile sourceFile) { this.sourceFile = sourceFile; } public JarFile getSourceFile() { return sourceFile; } } public static void main(String[] args) throws IOException { URL url = new URL("http://nexus.kantega.lan/content/repositories/snapshots/no/kantega/davexchange/1.6.16-SNAPSHOT/maven-metadata.xml"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.addRequestProperty("Cache-Control", "max-age=0"); urlConnection.addRequestProperty("User-Agent", "Apache-Maven/3.0"); InputStream inputStream = urlConnection.getInputStream(); String content = IOUtils.toString(inputStream); System.out.println(content); } }
package org.codehaus.prometheus.newrepeater; /** * Created by IntelliJ IDEA. * User: alarmnummer * Date: Dec 23, 2007 * Time: 10:17:11 AM * To change this template use File | Settings | File Templates. */ public class Group { }
package com.quicktron.gateway; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * ${DESCRIPTION} * * @author lance xu * @date2018年10月28日 16:55 */ @SpringBootApplication @EnableDiscoveryClient public class GatewayApplication { public static void main(String[] args) { new SpringApplicationBuilder(GatewayApplication.class).run(); } }
package com.smoothstack.asyncprocessing.tasklets; import com.sun.jmx.snmp.tasks.Task; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.batch.repeat.RepeatStatus; public class DownloadTasklet implements Tasklet, StepExecutionListener { @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { System.out.println("Download Failed .... "); return RepeatStatus.FINISHED; } @Override public void beforeStep(StepExecution stepExecution) { } @Override public ExitStatus afterStep(StepExecution stepExecution) { return ExitStatus.FAILED; } }
package hangman.util; import com.google.common.util.concurrent.Striped; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.Lock; import java.util.function.Supplier; import static org.apache.commons.lang3.Validate.isTrue; import static org.apache.commons.lang3.Validate.notNull; /** * Monitor protecting code from race conditions by utilizing {@link java.util.concurrent.locks.ReentrantLock}. * Available configuration options are: * - concurrencyLevel: number of threads accessing critical section at the same time, * - time: maximum time to wait for access to critical section, * - unit: time unit for the {@code time} parameter. * * @param <K> the type of key value that monitor is locking on * @param <V> the type of protected value */ public class AccessMonitor<K, V> { private final Striped<Lock> locks; private final long time; private final TimeUnit unit; /** * Create instance of object * * @param concurrencyLevel number of thread expected to access protected section simultaneously * @param time the maximum time to wait for obtaining the lock * @param unit the time unit of the time argument */ public AccessMonitor(int concurrencyLevel, long time, TimeUnit unit) { isTrue(concurrencyLevel > 0); isTrue(time > 0); notNull(unit); this.locks = Striped.lazyWeakLock(concurrencyLevel); this.time = time; this.unit = unit; } /** * Execute task in safe manner: prevents race conditions * Monitor tries to obtain the lock for specified period of time. * If the lock is not available {@link TimeoutException} is thrown * * @param key key to lock on * @param task task to execute * @return value of the operation * @throws InterruptedException * @throws TimeoutException */ public V execute(K key, Supplier<V> task) throws InterruptedException, TimeoutException { notNull(key); notNull(task); final Lock lock = locks.get(key); if (lock.tryLock(time, unit)) { try { return task.get(); } finally { lock.unlock(); } } else { throw new TimeoutException("Acquiring lock timeout"); } } /** * Execute task in safe manner: prevent race conditions * Operation won't throw checked exception. In case of lock accessing failure {@link MonitorException} is thrown * * @param key key to lock on * @param task task to execute * @return value of the operation * @throws MonitorException on lock acquiring failure */ public V tryExecute(K key, Supplier<V> task) { try { return execute(key, task); } catch (InterruptedException | TimeoutException e) { throw new MonitorException(e); } } public static class MonitorException extends RuntimeException { public MonitorException(Throwable cause) { super(cause); } } }
package org.fusesource.fabric.itests.smoke; import org.apache.curator.framework.CuratorFramework; import org.fusesource.fabric.api.Container; import org.fusesource.fabric.itests.paxexam.support.ContainerBuilder; import org.fusesource.fabric.itests.paxexam.support.FabricTestSupport; import org.fusesource.fabric.itests.paxexam.support.Provision; import org.fusesource.fabric.itests.paxexam.support.WaitForConfigurationChange; import org.fusesource.tooling.testing.pax.exam.karaf.ServiceLocator; import org.junit.After; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.options.DefaultCompositeOption; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerMethod; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.fusesource.fabric.zookeeper.utils.ZooKeeperUtils.exists; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @RunWith(PaxExam.class) @ExamReactorStrategy(PerMethod.class) public class ContainerUpgradeAndRollbackTest extends FabricTestSupport { @After public void tearDown() throws InterruptedException { ContainerBuilder.destroy(); } /** * This tests the simple scenario of * 1. create a child container * 2. create a new version * 3. modify the profile of the new version * 4. upgrade all containers * 5. verify that child is provisioned according to the new version * 6. rollback containers. * 7. verify that the child is provisioned according to the old version. * * @throws Exception */ @Ignore @Test public void testContainerUpgradeAndRollback() throws Exception { System.out.println(executeCommand("fabric:create -n")); Set<Container> containers = ContainerBuilder.create().withName("camel").withProfiles("feature-camel").assertProvisioningResult().build(); System.out.println(executeCommand("fabric:version-create --parent 1.0 1.1")); //Make sure that the profile change has been applied before changing the version CountDownLatch latch = WaitForConfigurationChange.on(getFabricService()); System.out.println(executeCommand("fabric:profile-edit --features camel-hazelcast feature-camel 1.1")); latch.await(5, TimeUnit.SECONDS); System.out.println(executeCommand("fabric:profile-display --version 1.1 feature-camel")); System.out.println(executeCommand("fabric:container-upgrade --all 1.1")); Provision.provisioningSuccess(containers, PROVISION_TIMEOUT); System.out.println(executeCommand("fabric:container-list")); for (Container container : containers) { assertEquals("Container should have version 1.1", "1.1", container.getVersion().getId()); String bundles = executeCommand("container-connect -u admin -p admin " + container.getId() + " osgi:list -s | grep camel-hazelcast"); System.out.println(executeCommand("fabric:container-list")); assertNotNull(bundles); System.out.println(bundles); assertFalse("Expected camel-hazelcast installed.", bundles.isEmpty()); } System.out.println(executeCommand("fabric:container-rollback --all 1.0")); Provision.provisioningSuccess(containers, PROVISION_TIMEOUT); System.out.println(executeCommand("fabric:container-list")); for (Container container : containers) { assertEquals("Container should have version 1.0", "1.0", container.getVersion().getId()); String bundles = executeCommand("container-connect -u admin -p admin " + container.getId() + " osgi:list -s | grep camel-hazelcast"); assertNotNull(bundles); System.out.println(bundles); assertTrue("Expected no camel-hazelcast installed.", bundles.isEmpty()); } } /** * The purpose of this test is that everything works ok, even if the container is created after the version. * This is a test for the issue: http://fusesource.com/issues/browse/FABRIC-363 * * @throws Exception */ @Ignore @Test public void testContainerAfterVersionUpgradeAndDowngrade() throws Exception { System.out.println(executeCommand("fabric:create -n")); //TODO: We have sporadic failures here, due to containers not being upgraded, without a tiny little sleep period. Thread.sleep(5000); System.out.println(executeCommand("fabric:version-create --parent 1.0 1.1")); Set<Container> containers = ContainerBuilder.create().withName("camel").withProfiles("feature-camel").assertProvisioningResult().build(); //Make sure that the profile change has been applied before changing the version CountDownLatch latch = WaitForConfigurationChange.on(getFabricService()); System.out.println(executeCommand("fabric:profile-edit --features camel-hazelcast feature-camel 1.1")); latch.await(5, TimeUnit.SECONDS); System.out.println(executeCommand("fabric:container-upgrade --all 1.1")); Provision.provisioningSuccess(containers, PROVISION_TIMEOUT); System.out.println(executeCommand("fabric:container-list")); for (Container container : containers) { assertEquals("Container should have version 1.1", "1.1", container.getVersion().getId()); String bundles = executeCommand("container-connect -u admin -p admin " + container.getId() + " osgi:list -s | grep camel-hazelcast"); System.out.println(executeCommand("fabric:container-list")); assertNotNull(bundles); System.out.println(bundles); assertFalse("Expected camel-hazelcast installed.", bundles.isEmpty()); } System.out.println(executeCommand("fabric:container-rollback --all 1.0")); Provision.provisioningSuccess(containers, PROVISION_TIMEOUT); System.out.println(executeCommand("fabric:container-list")); for (Container container : containers) { assertEquals("Container should have version 1.0", "1.0", container.getVersion().getId()); String bundles = executeCommand("container-connect -u admin -p admin " + container.getId() + " osgi:list -s | grep camel-hazelcast"); assertNotNull(bundles); System.out.println(bundles); assertTrue("Expected no camel-hazelcast installed.", bundles.isEmpty()); } } /** * This is a test for http://fusesource.com/issues/browse/FABRIC-367. * * @throws Exception */ @Test public void testContainerAfterVersionDowngrade() throws Exception { System.out.println(executeCommand("fabric:create -n")); System.out.println(executeCommand("fabric:version-create --parent 1.0 1.1")); System.out.println(executeCommand("fabric:container-upgrade --all 1.1")); Set<Container> containers = ContainerBuilder.create().withName("camel").withProfiles("feature-camel").assertProvisioningResult().build(); System.out.println(executeCommand("fabric:container-rollback --all 1.0")); Provision.provisioningSuccess(containers, PROVISION_TIMEOUT); for (Container container : containers) { assertEquals("Container should have version 1.0", "1.0", container.getVersion().getId()); assertNotNull(exists(ServiceLocator.getOsgiService(CuratorFramework.class), "/fabric/configs/versions/1.0/containers/" + container.getId())); } } @Configuration public Option[] config() { return new Option[]{ new DefaultCompositeOption(fabricDistributionConfiguration()) }; } }
/** * Copyright (c) 2015-present, Peel Technologies, Inc. * All rights reserved. */ package com.peel.react.rnos; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.modules.core.DeviceEventManagerModule; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; public final class RNOS extends ReactContextBaseJavaModule implements LifecycleEventListener { /* package */ static final String TAG = "RNOS"; /* package */ final ConnectivityManager mConnectivityManager; /* package */ final ConnectivityBroadcastReceiver mConnectivityBroadcastReceiver; public RNOS(ReactApplicationContext reactContext) { super(reactContext); mConnectivityManager = (ConnectivityManager) reactContext.getSystemService(Context.CONNECTIVITY_SERVICE); mConnectivityBroadcastReceiver = new ConnectivityBroadcastReceiver(); reactContext.addLifecycleEventListener(this); } @Override public String getName() { return TAG; } @Override public Map<String, Object> getConstants() { // set constants as initial values final Map<String, Object> constants = new HashMap<>(); final Map<String, Object> networkMap = new HashMap<>(); try { // extract bundle to map final Bundle networkInterfaces = getNetworkInterfaces(); for (String key : networkInterfaces.keySet()) { networkMap.put(key, networkInterfaces.get(key)); } } catch (SocketException e) { e.printStackTrace(); } constants.put("networkInterfaces", networkMap); return constants; } @Override public void onHostResume() { registerReceiver(); } @Override public void onHostPause() { unregisterReceiver(); } @Override public void onHostDestroy() { unregisterReceiver(); } private void registerReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); getReactApplicationContext().registerReceiver(mConnectivityBroadcastReceiver, filter); mConnectivityBroadcastReceiver.setRegistered(true); } private void unregisterReceiver() { if (mConnectivityBroadcastReceiver.isRegistered()) { getReactApplicationContext().unregisterReceiver(mConnectivityBroadcastReceiver); mConnectivityBroadcastReceiver.setRegistered(false); } } public void updateAndSendOsInfo() { Bundle osInfo = new Bundle(); try { final Bundle networkInterfaces = getNetworkInterfaces(); osInfo.putBundle("networkInterfaces", networkInterfaces); } catch (SocketException e) { e.printStackTrace(); } final ReactContext reactContext = getReactApplicationContext(); reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("rn-os-info", Arguments.fromBundle(osInfo)); } private Bundle getNetworkInterfaces() throws SocketException { Bundle ifaces = new Bundle(); Enumeration<NetworkInterface> list = NetworkInterface.getNetworkInterfaces(); while (list.hasMoreElements()) { final NetworkInterface iface = list.nextElement(); String mac = "00:00:00:00:00:00"; boolean internal = true; try { internal = iface.isLoopback(); } catch (SocketException se) { // keep calm and query on se.printStackTrace(); } try { final byte[] macBytes = iface.getHardwareAddress(); if (macBytes != null) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < macBytes.length; i++) { sb.append(String.format("%02X%s", macBytes[i], (i < macBytes.length - 1) ? ":" : "")); } mac = sb.toString(); } } catch (SocketException se) { // keep calm and query on se.printStackTrace(); } for (InterfaceAddress address : iface.getInterfaceAddresses()) { Bundle ifaceInfo = new Bundle(); ifaceInfo.putBoolean("internal", internal); ifaceInfo.putString("mac", mac); InetAddress inet = address.getAddress(); // getHostAddress adds %scope_id for ipv6 String hostAddress = inet.getHostAddress(); int end = hostAddress.indexOf("%"); if (end > -1) { hostAddress = hostAddress.substring(0, end); } ifaceInfo.putString("address", hostAddress); if (inet instanceof Inet6Address) { ifaceInfo.putString("family", "IPv6"); ifaceInfo.putInt("scopeid", ((Inet6Address) inet).getScopeId()); } else { ifaceInfo.putString("family", "IPv4"); } String netmask = ""; short prefixLength = address.getNetworkPrefixLength(); if (inet instanceof Inet4Address) { final int value = 0xffffffff << (32 - prefixLength); netmask = String.format("%d.%d.%d.%d", (value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF); } else { final long[] value = new long[] { 0xffffffffffffffffl, 0xffffffffffffffffl }; if (prefixLength <= 64) { value[1] = value[1] << (64 - prefixLength); } else { value[1] = 0; value[0] = value[0] << (64 - (prefixLength - 64)); } for (long crtLong : value) { //for every long: it should be two of them for (int i = 0; i < 4; i++) { //we display in total 4 parts for every long netmask += (netmask.length() == 0 ? "" : ":") + ((crtLong & 0xFFFF) == 0 ? "" : Long.toHexString(crtLong & 0xFFFF)); crtLong = crtLong >> 16; } } } ifaceInfo.putString("netmask", netmask); Bundle[] bundles = (Bundle[]) ifaces.getParcelableArray(iface.getDisplayName()); if (bundles == null) { bundles = new Bundle[] { ifaceInfo }; } else { Bundle[] tmp = Arrays.copyOf(bundles, bundles.length + 1); tmp[bundles.length] = ifaceInfo; bundles = tmp; } ifaces.putParcelableArray(iface.getDisplayName(), bundles); } } return ifaces; } /** * Class that receives intents whenever the connection type changes. * NB: It is possible on some devices to receive certain connection type changes multiple times. */ private class ConnectivityBroadcastReceiver extends BroadcastReceiver { //TODO: Remove registered check when source of crash is found. t9846865 private boolean isRegistered = false; public void setRegistered(boolean registered) { isRegistered = registered; } public boolean isRegistered() { return isRegistered; } @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { updateAndSendOsInfo(); } } } }
package org.codingeasy.shiroplus.loader.admin.server.models.request; /** * 实例的查询条件 * @author : KangNing Hu */ public class InstanceRequest extends RequestPage{ /** * 服务名称 */ private String name; /** * ip */ private String ip; public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
/* * Copyright 2022 Patrik Karlström. * * 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 se.trixon.almond.util.swing.dialogs.about; import org.apache.commons.lang3.StringUtils; import se.trixon.almond.util.AboutModel; /** * * @author Patrik Karlström */ public class TranslationTab extends BaseListTab { private transient final AboutModel mAboutModel; public TranslationTab(AboutModel aboutModel) { super(); mAboutModel = aboutModel; init(); } private void init() { String[] translators = StringUtils.split(mAboutModel.getTranslation(), ";"); StringBuilder builder = new StringBuilder(); for (String translator : translators) { builder.append(LIST_SIGN).append(translator).append("\n"); } editorPane.setText(builder.toString()); } }
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.kie.workbench.common.stunner.core.registry.impl; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.Supplier; import javax.annotation.PreDestroy; import javax.enterprise.context.Dependent; import javax.enterprise.inject.Typed; import javax.inject.Inject; import org.kie.workbench.common.stunner.core.api.FactoryManager; import org.kie.workbench.common.stunner.core.definition.adapter.AdapterManager; import org.kie.workbench.common.stunner.core.definition.adapter.DefinitionAdapter; @Dependent @Typed(DefaultDefinitionsCacheRegistry.class) public class DefaultDefinitionsCacheRegistry implements DefinitionsCacheRegistry { private final FactoryManager factoryManager; private final AdapterManager adapterManager; private Map<String, DefinitionHolder> definitionsById; private Map<String, DefinitionHolder> definitionsByType; @Inject public DefaultDefinitionsCacheRegistry(final FactoryManager factoryManager, final AdapterManager adapterManager) { this.factoryManager = factoryManager; this.adapterManager = adapterManager; } @SuppressWarnings("unchecked") public DefaultDefinitionsCacheRegistry useStorage(final Supplier<Map<String, ?>> storageSupplier) { this.definitionsById = (Map<String, DefinitionHolder>) storageSupplier.get(); this.definitionsByType = (Map<String, DefinitionHolder>) storageSupplier.get(); return this; } @Override public Object getDefinitionByType(final Class<Object> type) { DefinitionHolder holder = definitionsByType.get(type.getName()); if (null == holder) { holder = registerInstance(factoryManager.newDefinition(type)); } return holder.instance; } @Override public Object getDefinitionById(final String id) { return getDefinitionHolder(id).instance; } private DefinitionHolder getDefinitionHolder(final String id) { DefinitionHolder holder = definitionsById.get(id); if (null == holder) { holder = registerInstance(factoryManager.newDefinition(id)); } return holder; } @Override public void clear() { definitionsById.clear(); definitionsByType.clear(); } @Override public void register(final Object instance) { registerInstance(instance); } @Override public boolean remove(final Object instance) { final Class<?> type = instance.getClass(); final DefinitionAdapter<Object> adapter = getAdapter(type); final String id = adapter.getId(instance).value(); definitionsByType.remove(type.getName()); return null != definitionsById.remove(id); } @Override public boolean contains(final Object instance) { final Class<?> type = instance.getClass(); final DefinitionAdapter<Object> adapter = getAdapter(type); final String id = adapter.getId(instance).value(); return definitionsById.containsKey(id); } @Override public boolean isEmpty() { return definitionsById.isEmpty(); } @PreDestroy public void destroy() { clear(); definitionsById = null; definitionsByType = null; } @Override public Set<String> getLabels(final String id) { return getDefinitionHolder(id).labels; } private DefinitionHolder registerInstance(final Object instance) { final Class<?> type = instance.getClass(); final DefinitionAdapter<Object> adapter = getAdapter(type); final String id = adapter.getId(instance).value(); final Set<String> labels = adapter.getLabels(instance); final DefinitionHolder holder = new DefinitionHolder(instance, labels); definitionsById.put(id, holder); definitionsByType.put(type.getName(), holder); return holder; } private DefinitionAdapter<Object> getAdapter(final Class<?> type) { return adapterManager.registry().getDefinitionAdapter(type); } private static class DefinitionHolder { private final Object instance; private final Set<String> labels; private DefinitionHolder(final Object instance, final Set<String> labels) { this.instance = instance; this.labels = new HashSet<>(labels); } } }
/* * Copyright (c) 2016 Network New Technologies 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.networknt.schema; import com.fasterxml.jackson.databind.JsonNode; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class JsonMetaSchema { private static final Logger logger = LoggerFactory .getLogger(JsonMetaSchema.class); private static Map<String, String> UNKNOWN_KEYWORDS = new ConcurrentHashMap<String, String>(); static PatternFormat pattern(String name, String regex) { return new PatternFormat(name, regex); } public static final List<Format> COMMON_BUILTIN_FORMATS = new ArrayList<Format>(); // this section contains formats that is common for all specification versions. static { COMMON_BUILTIN_FORMATS.add(pattern("time", "^\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?$")); COMMON_BUILTIN_FORMATS.add(pattern("ip-address", "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")); COMMON_BUILTIN_FORMATS.add(pattern("ipv4", "^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$")); COMMON_BUILTIN_FORMATS.add(pattern("ipv6", "^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$")); // From RFC 3986 // ALPHA [A-Za-z] // DIGIT [0-9] // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) // => [A-Za-z][A-Za-z0-9+.-]* // unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" // => [A-Za-z0-9._~\-] // gen-delims [:/?#\[\]@] // sub-delims [!$&'()*+,;=] // reserved = = gen-delims / sub-delims // => [:/?#\[\]@!$&'()*+,;=] // pct-encoded = "%" HEXDIG HEXDIG // => [A-Za-z0-9%] (approximation) // pchar = unreserved / pct-encoded / sub-delims / ":" / "@" // => [A-Za-z0-9._~\-%!$&'()*+,;=:@] // userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) // => [A-Za-z0-9._~\-%!$&'()*+,;=:]* // host = IP-literal / IPv4address / reg-name // => [A-Za-z0-9._~\-!$&'()*+,;=%:\[\]]* (approximation) // port = *DIGiT // => [0-9]* // authority = [ userinfo "@" ] host [ ":" port ] // => ([A-Za-z0-9._~\-%!$&'()*+,;=:]*@)?[A-Za-z0-9._~\-!$&'()*+,;=%:\[\]]*(:[0-9]*)? // hier-part = "//" authority path-abempty // / path-absolute // / path-rootless // / path-empty // => (\/\/([A-Za-z0-9._~\-%!$&'()*+,;=:]*@)?[A-Za-z0-9._~\-!$&'()*+,;=%:\[\]]*(:[0-9]*)?)?[A-Za-z0-9._~\-%!$&'()*+,;=:@\/]* (approximation) // query = *( pchar / "/" / "?" ) // => [A-Za-z0-9._~\-%!$&'()*+,;=:@\/?]* // fragment = *( pchar / "/" / "?" ) // => [A-Za-z0-9._~\-%!$&'()*+,;=:@\/?]* // uri = scheme ":" hier-part [ "?" query ] [ "#" fragment ] COMMON_BUILTIN_FORMATS.add(pattern("uri", "^[A-Za-z][A-Za-z0-9+.-]*:(\\/\\/([A-Za-z0-9._~\\-%!$&'()*+,;=:]*@)?[A-Za-z0-9._~\\-!$&'()*+,;=%:\\[\\]]*(:[0-9]*)?)?[A-Za-z0-9._~\\-%!$&'()*+,;=:@\\/]*([?][A-Za-z0-9._~\\-%!$&'()*+,;=:@\\/?]*)?([#][A-Za-z0-9._~\\-%!$&'()*+,;=:@\\/?]*)?")); COMMON_BUILTIN_FORMATS.add(pattern("color", "(#?([0-9A-Fa-f]{3,6})\\b)|(aqua)|(black)|(blue)|(fuchsia)|(gray)|(green)|(lime)|(maroon)|(navy)|(olive)|(orange)|(purple)|(red)|(silver)|(teal)|(white)|(yellow)|(rgb\\(\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*,\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*,\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*\\))|(rgb\\(\\s*(\\d?\\d%|100%)+\\s*,\\s*(\\d?\\d%|100%)+\\s*,\\s*(\\d?\\d%|100%)+\\s*\\))")); COMMON_BUILTIN_FORMATS.add(pattern("hostname", "^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*$")); COMMON_BUILTIN_FORMATS.add(pattern("alpha", "^[a-zA-Z]+$")); COMMON_BUILTIN_FORMATS.add(pattern("alphanumeric", "^[a-zA-Z0-9]+$")); COMMON_BUILTIN_FORMATS.add(pattern("phone", "^\\+(?:[0-9] ?){6,14}[0-9]$")); COMMON_BUILTIN_FORMATS.add(pattern("utc-millisec", "^[0-9]+(\\.?[0-9]+)?$")); COMMON_BUILTIN_FORMATS.add(pattern("style", "\\s*(.+?):\\s*([^;]+);?")); } public static class Builder { private Map<String, Keyword> keywords = new HashMap<String, Keyword>(); private Map<String, Format> formats = new HashMap<String, Format>(); private String uri; private String idKeyword = "id"; public Builder(String uri) { this.uri = uri; } private static Map<String, Keyword> createKeywordsMap(Map<String, Keyword> kwords, Map<String, Format> formats) { final Map<String, Keyword> map = new HashMap<String, Keyword>(); for (Map.Entry<String, Keyword> type : kwords.entrySet()) { String keywordName = type.getKey(); Keyword keyword = type.getValue(); if (ValidatorTypeCode.FORMAT.getValue().equals(keywordName)) { if (!(keyword instanceof FormatKeyword)) { throw new IllegalArgumentException("Overriding the keyword 'format' is not supported"); } // ignore - format keyword will be created again below. } else { map.put(keyword.getValue(), keyword); } } final FormatKeyword formatKeyword = new FormatKeyword(ValidatorTypeCode.FORMAT, formats); map.put(formatKeyword.getValue(), formatKeyword); return Collections.unmodifiableMap(map); } public Builder addKeyword(Keyword keyword) { this.keywords.put(keyword.getValue(), keyword); return this; } public Builder addKeywords(Collection<? extends Keyword> keywords) { for (Keyword keyword : keywords) { this.keywords.put(keyword.getValue(), keyword); } return this; } public Builder addFormat(Format format) { this.formats.put(format.getName(), format); return this; } public Builder addFormats(Collection<? extends Format> formats) { for (Format format : formats) { addFormat(format); } return this; } public Builder idKeyword(String idKeyword) { this.idKeyword = idKeyword; return this; } public JsonMetaSchema build() { // create builtin keywords with (custom) formats. final Map<String, Keyword> kwords = createKeywordsMap(keywords, formats); return new JsonMetaSchema(uri, idKeyword, kwords); } } private final String uri; private final String idKeyword; private final Map<String, Keyword> keywords; private JsonMetaSchema(String uri, String idKeyword, Map<String, Keyword> keywords) { if (StringUtils.isBlank(uri)) { throw new IllegalArgumentException("uri must not be null or blank"); } if (StringUtils.isBlank(idKeyword)) { throw new IllegalArgumentException("idKeyword must not be null or blank"); } if (keywords == null) { throw new IllegalArgumentException("keywords must not be null "); } this.uri = uri; this.idKeyword = idKeyword; this.keywords = keywords; } public static JsonMetaSchema getV4() { return new Version4().getInstance(); } public static JsonMetaSchema getV6() { return new Version6().getInstance(); } public static JsonMetaSchema getV7() { return new Version7().getInstance(); } public static JsonMetaSchema getV201909() { return new Version201909().getInstance(); } /** * Builder without keywords or formats. * <p> * Use {@link #getV4()} for the Draft 4 Metaschema, or if you need a builder based on Draft4, use * * <code> * JsonMetaSchema.builder("http://your-metaschema-uri", JsonSchemaFactory.getDraftV4()).build(); * </code> * * @param uri the URI of the metaschema that will be defined via this builder. * @return a builder instance without any keywords or formats - usually not what one needs. */ public static Builder builder(String uri) { return new Builder(uri); } /** * @param uri the URI of your new JsonMetaSchema that will be defined via this builder. * @param blueprint the JsonMetaSchema to base your custom JsonMetaSchema on. * @return a builder instance preconfigured to be the same as blueprint, but with a different uri. */ public static Builder builder(String uri, JsonMetaSchema blueprint) { FormatKeyword formatKeyword = (FormatKeyword) blueprint.keywords.get(ValidatorTypeCode.FORMAT.getValue()); if (formatKeyword == null) { throw new IllegalArgumentException("The formatKeyword did not exist - blueprint is invalid."); } return builder(uri) .idKeyword(blueprint.idKeyword) .addKeywords(blueprint.keywords.values()) .addFormats(formatKeyword.getFormats()); } public String readId(JsonNode schemaNode) { return readText(schemaNode, idKeyword); } public JsonNode getNodeByFragmentRef(String ref, JsonNode node) { boolean supportsAnchor = keywords.containsKey("$anchor"); String refName = supportsAnchor ? ref.substring(1) : ref; String fieldToRead = supportsAnchor ? "$anchor" : idKeyword; boolean nodeContainsRef = refName.equals(readText(node, fieldToRead)); if (nodeContainsRef) { return node; } else { Iterator<JsonNode> children = node.elements(); while (children.hasNext()) { JsonNode refNode = getNodeByFragmentRef(ref, children.next()); if (refNode != null) { return refNode; } } } return null; } private String readText(JsonNode node, String field) { JsonNode idNode = node.get(field); if (idNode == null || !idNode.isTextual()) { return null; } return idNode.textValue(); } public String getUri() { return uri; } public JsonValidator newValidator(ValidationContext validationContext, String schemaPath, String keyword /* keyword */, JsonNode schemaNode, JsonSchema parentSchema, String customMessage) { try { Keyword kw = keywords.get(keyword); if (kw == null) { if (UNKNOWN_KEYWORDS.put(keyword, keyword) == null) { logger.warn("Unknown keyword " + keyword + " - you should define your own Meta Schema. If the keyword is irrelevant for validation, just use a NonValidationKeyword"); } return null; } kw.setCustomMessage(customMessage); return kw.newValidator(schemaPath, schemaNode, parentSchema, validationContext); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof JsonSchemaException) { logger.error("Error:", e); throw (JsonSchemaException) e.getTargetException(); } else { logger.warn("Could not load validator " + keyword); throw new JsonSchemaException(e.getTargetException()); } } catch (JsonSchemaException e) { throw e; } catch (Exception e) { logger.warn("Could not load validator " + keyword); throw new JsonSchemaException(e); } } }
package ui; import model.*; public class FlyerDemo { // NOTE: this project accompanies the Abstract Classes video public static void main(String[] args) { Bird birdie = new Bird(); Airplane planie = new Airplane(); Cafe cafePlane = new Airplane(); Flyer flyerPlane = new Airplane(); PrivatePlane pp = new PrivatePlane(); birdie.fly(); cafePlane.serveDrinks(); FlyerDemo fd = new FlyerDemo(); fd.luxuryTakeoff(pp); fd.lunchService(cafePlane); fd.firstPartOfFlight(planie); } public void luxuryTakeoff(PrivatePlane p) { p.takeOff(); p.bringWarmTowels(); } public void lunchService(Cafe c) { c.serveDrinks(); c.serveSnacks(); } public void firstPartOfFlight(Airplane a) { a.takeOff(); a.serveDrinks(); } }
package com.ifeng.at.testagent.rpc; import android.util.Log; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.net.Socket; import java.util.HashMap; import java.util.Map; /** * Owner lixintong */ public class RpcClient { private Socket clientSocket; private String TAG = "RpcClient "; private Gson gson = new Gson(); private Writer writer; private BufferedReader reader; private Map<Integer, RequestHandler> handlers = new HashMap<>(); public void addHandler(int ver, RequestHandler requestHandler){ handlers.put(ver, requestHandler); } public void startAndBlock(String host, int port, String deviceId) throws IOException { Log.i(TAG, "connect to "+host+" id="+deviceId); clientSocket = new Socket(host, port); //绑定server reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8")); writer = new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8"); registerToServer(deviceId); listenToServer(); clientSocket.close(); } private void registerToServer(String deviceId) throws IOException { RPCMessage registerMsg = new RPCMessage(); registerMsg.setMsgId(1); registerMsg.setName("register"); registerMsg.setMsgType(RPCMessage.RPCCall); registerMsg.getArgs().add(deviceId); writer.write(gson.toJson(registerMsg) + '\n'); writer.flush(); String serverResponse = reader.readLine(); //TODO } /** * 监听server 请求 * * @throws IOException */ private void listenToServer() throws IOException { StringBuilder requestBuffer = new StringBuilder(); requestBuffer.append(reader.readLine()); while (true) { if (!"".equals(requestBuffer.toString()) && !"null".equals(requestBuffer.toString())) {//server 无数据请求时,requestBuffer为"null" Log.i(TAG, "keyword request :" + requestBuffer.toString()); RPCMessage message = RPCMessage.fromJson(decode(requestBuffer.toString())); RPCMessage response; if(message.getMsgType() == RPCMessage.RPC_KILL_SIGNAL){ // receive kill signal response = RPCMessage.makeKillSignal(); String responseJson = encode(gson.toJson(response)) + "\n"; writer.write(responseJson); writer.flush(); break; } try { response = handlers.get(message.getVersion()).handle(message); response.setMsgType(RPCMessage.RPCResult); response.setMsgId(message.getMsgId()); } catch (Throwable e) { response = makeErrorResponse(message, e); } Log.i(TAG, "keyword decode response :" + decode(gson.toJson(response))); String responseJson = encode(gson.toJson(response)) + "\n"; writer.write(responseJson); writer.flush(); } requestBuffer.delete(0, requestBuffer.length()); requestBuffer.append(reader.readLine()); } } private RPCMessage makeErrorResponse(RPCMessage request, Throwable e) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); e.printStackTrace(printWriter); Map<String, Object> entity = new HashMap<>(); entity.put("type", e.getClass().getName()); entity.put("detail message", stringWriter.toString()); return RPCMessage.makeFailResult("未知错误-请联系管理员", entity); } private String decode(String srcStr) { srcStr = srcStr.replace("%e", "%"); srcStr = srcStr.replace("%n", "\n"); return srcStr; } private String encode(String srcStr) { srcStr = srcStr.replace("%", "%e"); srcStr = srcStr.replace("\n", "%n"); return srcStr; } }
package com.waltsai.colorfulpuff; import com.waltsai.colorfulpuff.core.ModParticles; import com.waltsai.colorfulpuff.entity.ModEntityInitalizer; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; @Environment(EnvType.CLIENT) public class ClientModInit implements ClientModInitializer { @Override public void onInitializeClient() { ModEntityInitalizer.setupRenderers(); ModEntityInitalizer.registerModels(); ModParticles.registerParticles(); } }
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.oxm.xstream; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * XStream {@link Converter} that supports all classes, but throws exceptions for * (un)marshalling. * * <p>The main purpose of this class is to * {@linkplain com.thoughtworks.xstream.XStream#registerConverter(com.thoughtworks.xstream.converters.Converter, int) register} * this converter as a catch-all last converter with a * {@linkplain com.thoughtworks.xstream.XStream#PRIORITY_NORMAL normal} * or higher priority, in addition to converters that explicitly handle the domain * classes that should be supported. As a result, default XStream converters with * lower priorities and possible security vulnerabilities do not get invoked. * * <p>For instance: * <pre class="code"> * XStreamMarshaller unmarshaller = new XStreamMarshaller(); * unmarshaller.getXStream().registerConverter(new MyDomainClassConverter(), XStream.PRIORITY_VERY_HIGH); * unmarshaller.getXStream().registerConverter(new CatchAllConverter(), XStream.PRIORITY_NORMAL); * MyDomainClass myObject = unmarshaller.unmarshal(source); * </pre * * @author Arjen Poutsma * @since 3.2.5 */ public class CatchAllConverter implements Converter { @Override public boolean canConvert(Class type) { return true; } @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { throw new UnsupportedOperationException("Marshalling not supported"); } @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { throw new UnsupportedOperationException("Unmarshalling not supported"); } }
/* * Copyright 2013 JBoss by Red Hat. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.executor.cdi.commands; import javax.enterprise.inject.spi.BeanManager; import org.apache.commons.lang3.StringUtils; import org.jbpm.executor.cdi.CDIUtils; import org.kie.api.runtime.process.WorkItem; import org.kie.internal.executor.api.Command; import org.kie.internal.executor.api.CommandContext; import org.kie.internal.executor.api.ExecutionResults; import org.kie.internal.executor.api.ExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Simple command to log the contextual data and return empty results. After attempting to get BeanManager * and creating simple CDI bean based on given class name as parameter. * Just for demo purpose. * */ public class CDIPrintOutCommand implements Command{ private static final Logger logger = LoggerFactory.getLogger(CDIPrintOutCommand.class); public ExecutionResults execute(CommandContext ctx) { BeanManager manager = CDIUtils.lookUpBeanManager(ctx); String clazz = (String) getParameter(ctx, "CDIBeanClassName"); if (StringUtils.isEmpty(clazz)) { clazz = ExecutorService.class.getName(); } try { Object cdiBean = CDIUtils.createBean(Class.forName(clazz), manager); logger.info("CDI bean created {}", cdiBean); } catch (Exception e) { logger.error("Error while creating CDI bean from jbpm executor", e); } logger.info("Command executed on executor with data {}", ctx.getData()); ExecutionResults executionResults = new ExecutionResults(); return executionResults; } protected Object getParameter(CommandContext commandContext, String parameterName) { if (commandContext.getData(parameterName) != null) { return commandContext.getData(parameterName); } WorkItem workItem = (WorkItem) commandContext.getData("workItem"); if (workItem != null) { return workItem.getParameter(parameterName); } return null; } }
// // File: PrefPane.java // import java.awt.*; import java.awt.event.*; public class PrefPane extends Frame implements ActionListener { protected Button okButton; protected Label prefsText; protected TextField time; private Object parent; public int the_time; public PrefPane(Object prnt) { super(); this.setLayout(new BorderLayout(40, 40)); this.setFont(new Font ("SansSerif", Font.BOLD, 14)); parent = prnt; prefsText = new Label ("Time limit:"); time = new TextField("3", 5); time.setSize(10,10); Panel textPanel = new Panel(new FlowLayout(FlowLayout.CENTER, 20, 20)); textPanel.add(prefsText); textPanel.add(time); this.add (textPanel, BorderLayout.NORTH); okButton = new Button("OK"); Panel buttonPanel = new Panel(new FlowLayout(FlowLayout.CENTER, 10, 10)); buttonPanel.add (okButton); okButton.addActionListener(this); this.add(buttonPanel, BorderLayout.SOUTH); this.setSize(200,120); } public void actionPerformed(ActionEvent newEvent) { the_time = Integer.valueOf(time.getText()).intValue(); setVisible(false); } }
package com.spike.giantdataanalysis.model.algorithms.graph.cycle; import com.spike.giantdataanalysis.model.algorithms.graph.core.Graph; import com.spike.giantdataanalysis.model.algorithms.graph.core.IDFS.IDFSWithFather; /** * 无向图中环检测: 使用深度优先搜索. * @author zhoujiagen */ public class CycleDetection implements IDFSWithFather<Graph> { private boolean[] marked; // 顶点是否访问过, 索引: 顶点 private boolean hasCycle = false; // 是否有环标志 public CycleDetection(Graph G) { this.marked = new boolean[G.V()]; for (int s = 0; s < G.V(); s++) { if (!marked[s]) { this.dfs(G, s, s); } } } // 通过顶点u访问其邻接顶点v的深度优先搜索 @Override public void dfs(Graph G, int v, int u) { marked[v] = true; for (int w : G.adj(v)) { if (!marked[w]) { this.dfs(G, w, v); } else if (w != u) { // w已访问过, 构成环(u->v->w->u) hasCycle = true; } } } public boolean hasCycle() { return hasCycle; } }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE113_HTTP_Response_Splitting__console_readLine_addCookieServlet_52b.java Label Definition File: CWE113_HTTP_Response_Splitting.label.xml Template File: sources-sinks-52b.tmpl.java */ /* * @description * CWE: 113 HTTP Response Splitting * BadSource: console_readLine Read data from the console using readLine() * GoodSource: A hardcoded string * Sinks: addCookieServlet * GoodSink: URLEncode input * BadSink : querystring to addCookie() * Flow Variant: 52 Data flow: data passed as an argument from one method to another to another in three different classes in the same package * * */ import javax.servlet.http.*; public class CWE113_HTTP_Response_Splitting__console_readLine_addCookieServlet_52b { public void badSink(String data , HttpServletRequest request, HttpServletResponse response) throws Throwable { (new CWE113_HTTP_Response_Splitting__console_readLine_addCookieServlet_52c()).badSink(data , request, response); } /* goodG2B() - use goodsource and badsink */ public void goodG2BSink(String data , HttpServletRequest request, HttpServletResponse response) throws Throwable { (new CWE113_HTTP_Response_Splitting__console_readLine_addCookieServlet_52c()).goodG2BSink(data , request, response); } /* goodB2G() - use badsource and goodsink */ public void goodB2GSink(String data , HttpServletRequest request, HttpServletResponse response) throws Throwable { (new CWE113_HTTP_Response_Splitting__console_readLine_addCookieServlet_52c()).goodB2GSink(data , request, response); } }
/* * Copyright (C) 2016 The Dagger 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 dagger.functional.producers.subcomponent; import com.google.common.util.concurrent.ListenableFuture; import dagger.Component; import dagger.Module; import dagger.Provides; import dagger.producers.ProducerModule; import dagger.producers.Produces; import dagger.producers.Production; import dagger.producers.ProductionComponent; import dagger.producers.ProductionSubcomponent; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Qualifier; final class SubcomponentsWithBoundExecutor { @Qualifier @interface FromParent {} @Qualifier @interface FromChild {} @Qualifier @interface FromGrandchild {} static final class CountingExecutor implements Executor { private final AtomicInteger executionCount; CountingExecutor(AtomicInteger executionCount) { this.executionCount = executionCount; } @Override public void execute(Runnable runnable) { executionCount.incrementAndGet(); runnable.run(); } } @Module static final class ExecutorModule { private final AtomicInteger constructionCount; private final AtomicInteger executionCount; ExecutorModule(AtomicInteger constructionCount, AtomicInteger executionCount) { this.constructionCount = constructionCount; this.executionCount = executionCount; } @Provides @Production Executor executor() { constructionCount.incrementAndGet(); return new CountingExecutor(executionCount); } } @Module static final class ParentModule { @Provides @FromParent static String fromParent() { return "parent"; } } @Component(modules = {ParentModule.class, ExecutorModule.class}) interface ParentComponent { InjectsChildBuilder injectsChildBuilder(); ChildComponent.Builder newChildComponentBuilder(); } @ProducerModule static final class ParentProducerModule { @Produces @FromParent static String fromParent() { return "parentproduction"; } } @ProductionComponent(modules = {ParentProducerModule.class, ExecutorModule.class}) interface ParentProductionComponent { ChildComponent.Builder newChildComponentBuilder(); @ProductionComponent.Builder interface Builder { Builder executorModule(ExecutorModule executorModule); ParentProductionComponent build(); } } @ProducerModule static final class ChildProducerModule { @Produces @FromChild static String fromChild(@FromParent String fromParent) { return "child:" + fromParent; } } @ProductionSubcomponent(modules = ChildProducerModule.class) interface ChildComponent { @FromChild ListenableFuture<String> fromChild(); GrandchildComponent.Builder newGrandchildComponentBuilder(); GrandchildComponentWithoutBuilder newGrandchildComponent(); @ProductionSubcomponent.Builder interface Builder { ChildComponent build(); } } static final class InjectsChildBuilder { private final Provider<ChildComponent.Builder> childBuilder; @Inject InjectsChildBuilder(Provider<ChildComponent.Builder> childBuilder) { this.childBuilder = childBuilder; } ChildComponent.Builder childBuilder() { return childBuilder.get(); } } @ProducerModule static final class GrandchildProducerModule { @Produces @FromGrandchild static String fromGranchild(@FromChild String fromChild) { return "grandchild:" + fromChild; } } @ProductionSubcomponent(modules = GrandchildProducerModule.class) interface GrandchildComponent { @FromGrandchild ListenableFuture<String> fromGrandchild(); @ProductionSubcomponent.Builder interface Builder { GrandchildComponent build(); } } @ProductionSubcomponent(modules = GrandchildProducerModule.class) interface GrandchildComponentWithoutBuilder { @FromGrandchild ListenableFuture<String> fromGrandchild(); } private SubcomponentsWithBoundExecutor() {} }
package com.springapp.mvc.utils; import com.springapp.mvc.bean.Blog; import com.springapp.mvc.bean.User; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; /** * Created by Xr on 2016/8/27. */ public class StringUtils { private static Properties props = new Properties(); static { props.setProperty(Velocity.INPUT_ENCODING, "GBK"); props.setProperty(Velocity.RESOURCE_LOADER, "class"); props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); } /** * User用户字符串替换 * @param str 需要替换的字符串 * @param user User实例 * @return 替换好后的字符串 */ public static String getString(String str, User user) { VelocityEngine ve = new VelocityEngine(props); VelocityContext vc = new VelocityContext(); vc.put("email", user.getEmail()); vc.put("nickname", user.getNickname()); vc.put("username", user.getEmail()); vc.put("password", MD5Utils.getMD5(user.getPassword())); vc.put("reg_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); StringWriter sw = new StringWriter(); ve.evaluate(vc, sw, "", str); return sw.toString(); } /** * blog字段替换 * @param str * @param blog * @return */ public static String getString(String str, Blog blog) { VelocityEngine ve = new VelocityEngine(props); VelocityContext vc = new VelocityContext(); //('${id}', '${title}', '${create_time}', '${author}', '${authority}', '${content}') vc.put("id", blog.getId()); vc.put("title", blog.getTitle()); vc.put("create_time", blog.getCreate_time()); vc.put("author", blog.getAuthor()); vc.put("authority", blog.getAuthority()); vc.put("content", blog.getContent()); StringWriter sw = new StringWriter(); ve.evaluate(vc, sw, "", str); return sw.toString(); } /** * 判断空值 * @param str * @return 如果值str是空或者"",返回"",否则返回str */ public static String nvl(String str) { if (null != str && !str.isEmpty()) { return str; } return ""; } }
/* * 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.shardingsphere.mode.repository.cluster.zookeeper; import com.google.common.base.Strings; import lombok.Getter; import lombok.Setter; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.CuratorFrameworkFactory.Builder; import org.apache.curator.framework.api.ACLProvider; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.CuratorCache; import org.apache.curator.framework.recipes.cache.CuratorCacheListener; import org.apache.curator.framework.recipes.cache.TreeCacheEvent; import org.apache.curator.framework.recipes.locks.InterProcessLock; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.utils.CloseableUtils; import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepositoryConfiguration; import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEvent; import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEvent.Type; import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEventListener; import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepository; import org.apache.shardingsphere.mode.repository.cluster.zookeeper.handler.CuratorZookeeperExceptionHandler; import org.apache.shardingsphere.mode.repository.cluster.zookeeper.props.ZookeeperProperties; import org.apache.shardingsphere.mode.repository.cluster.zookeeper.props.ZookeeperPropertyKey; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException.OperationTimeoutException; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; /** * Registry repository of ZooKeeper. */ public final class CuratorZookeeperRepository implements ClusterPersistRepository { private final Map<String, CuratorCache> caches = new HashMap<>(); private CuratorFramework client; private final Builder builder = CuratorFrameworkFactory.builder(); private final Map<String, InterProcessLock> locks = new ConcurrentHashMap<>(); @Getter @Setter private Properties props = new Properties(); @Override public void init(final ClusterPersistRepositoryConfiguration config) { ZookeeperProperties zookeeperProps = new ZookeeperProperties(props); client = buildCuratorClient(config, zookeeperProps); initCuratorClient(zookeeperProps); } private CuratorFramework buildCuratorClient(final ClusterPersistRepositoryConfiguration config, final ZookeeperProperties zookeeperProps) { int retryIntervalMilliseconds = zookeeperProps.getValue(ZookeeperPropertyKey.RETRY_INTERVAL_MILLISECONDS); int maxRetries = zookeeperProps.getValue(ZookeeperPropertyKey.MAX_RETRIES); int timeToLiveSeconds = zookeeperProps.getValue(ZookeeperPropertyKey.TIME_TO_LIVE_SECONDS); int operationTimeoutMilliseconds = zookeeperProps.getValue(ZookeeperPropertyKey.OPERATION_TIMEOUT_MILLISECONDS); builder.connectString(config.getServerLists()) .retryPolicy(new ExponentialBackoffRetry(retryIntervalMilliseconds, maxRetries, retryIntervalMilliseconds * maxRetries)) .namespace(config.getNamespace()); if (0 != timeToLiveSeconds) { builder.sessionTimeoutMs(timeToLiveSeconds * 1000); } if (0 != operationTimeoutMilliseconds) { builder.connectionTimeoutMs(operationTimeoutMilliseconds); } String digest = zookeeperProps.getValue(ZookeeperPropertyKey.DIGEST); if (!Strings.isNullOrEmpty(digest)) { builder.authorization(ZookeeperPropertyKey.DIGEST.getKey(), digest.getBytes(StandardCharsets.UTF_8)) .aclProvider(new ACLProvider() { @Override public List<ACL> getDefaultAcl() { return ZooDefs.Ids.CREATOR_ALL_ACL; } @Override public List<ACL> getAclForPath(final String path) { return ZooDefs.Ids.CREATOR_ALL_ACL; } }); } return builder.build(); } private void initCuratorClient(final ZookeeperProperties zookeeperProps) { client.start(); try { int retryIntervalMilliseconds = zookeeperProps.getValue(ZookeeperPropertyKey.RETRY_INTERVAL_MILLISECONDS); int maxRetries = zookeeperProps.getValue(ZookeeperPropertyKey.MAX_RETRIES); if (!client.blockUntilConnected(retryIntervalMilliseconds * maxRetries, TimeUnit.MILLISECONDS)) { client.close(); throw new OperationTimeoutException(); } } catch (final InterruptedException | OperationTimeoutException ex) { CuratorZookeeperExceptionHandler.handleException(ex); } } @Override public String get(final String key) { CuratorCache cache = findTreeCache(key); if (null == cache) { return getDirectly(key); } Optional<ChildData> resultInCache = cache.get(key); if (resultInCache.isPresent()) { return null == resultInCache.get().getData() ? null : new String(resultInCache.get().getData(), StandardCharsets.UTF_8); } return getDirectly(key); } private CuratorCache findTreeCache(final String key) { return caches.entrySet().stream().filter(entry -> key.startsWith(entry.getKey())).findFirst().map(Entry::getValue).orElse(null); } @Override public List<String> getChildrenKeys(final String key) { try { List<String> result = client.getChildren().forPath(key); result.sort(Comparator.reverseOrder()); return result; // CHECKSTYLE:OFF } catch (final Exception ex) { // CHECKSTYLE:ON CuratorZookeeperExceptionHandler.handleException(ex); return Collections.emptyList(); } } @Override public void persist(final String key, final String value) { try { if (!isExisted(key)) { client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(key, value.getBytes(StandardCharsets.UTF_8)); } else { update(key, value); } // CHECKSTYLE:OFF } catch (final Exception ex) { // CHECKSTYLE:ON CuratorZookeeperExceptionHandler.handleException(ex); } } private void update(final String key, final String value) { try { client.setData().forPath(key, value.getBytes(StandardCharsets.UTF_8)); // CHECKSTYLE:OFF } catch (final Exception ex) { // CHECKSTYLE:ON CuratorZookeeperExceptionHandler.handleException(ex); } } private String getDirectly(final String key) { try { return new String(client.getData().forPath(key), StandardCharsets.UTF_8); // CHECKSTYLE:OFF } catch (final Exception ex) { // CHECKSTYLE:ON CuratorZookeeperExceptionHandler.handleException(ex); return null; } } private boolean isExisted(final String key) { try { return null != client.checkExists().forPath(key); // CHECKSTYLE:OFF } catch (final Exception ex) { // CHECKSTYLE:ON CuratorZookeeperExceptionHandler.handleException(ex); return false; } } @Override public void persistEphemeral(final String key, final String value) { try { if (isExisted(key)) { client.delete().deletingChildrenIfNeeded().forPath(key); } client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(key, value.getBytes(StandardCharsets.UTF_8)); // CHECKSTYLE:OFF } catch (final Exception ex) { // CHECKSTYLE:ON CuratorZookeeperExceptionHandler.handleException(ex); } } @Override public void delete(final String key) { try { if (isExisted(key)) { client.delete().deletingChildrenIfNeeded().forPath(key); } // CHECKSTYLE:OFF } catch (final Exception ex) { // CHECKSTYLE:ON CuratorZookeeperExceptionHandler.handleException(ex); } } @Override public void watch(final String key, final DataChangedEventListener listener) { String path = key + PATH_SEPARATOR; if (!caches.containsKey(path)) { addCacheData(key); CuratorCache cache = caches.get(path); CuratorCacheListener curatorCacheListener = CuratorCacheListener.builder() .forTreeCache(client, (framework, treeCacheListener) -> { Type changedType = getChangedType(treeCacheListener.getType()); if (Type.IGNORED != changedType) { listener.onChange(new DataChangedEvent(treeCacheListener.getData().getPath(), new String(treeCacheListener.getData().getData(), StandardCharsets.UTF_8), changedType)); } }).afterInitialized().build(); cache.listenable().addListener(curatorCacheListener); } } private void addCacheData(final String cachePath) { CuratorCache cache = CuratorCache.build(client, cachePath); try { cache.start(); // CHECKSTYLE:OFF } catch (final Exception ex) { // CHECKSTYLE:ON CuratorZookeeperExceptionHandler.handleException(ex); } caches.put(cachePath + PATH_SEPARATOR, cache); } private Type getChangedType(final TreeCacheEvent.Type type) { switch (type) { case NODE_ADDED: return Type.ADDED; case NODE_UPDATED: return Type.UPDATED; case NODE_REMOVED: return Type.DELETED; default: return Type.IGNORED; } } @Override public boolean tryLock(final String key, final long time, final TimeUnit unit) { try { return getLock(key).acquire(time, unit); // CHECKSTYLE:OFF } catch (final Exception ex) { // CHECKSTYLE:ON CuratorZookeeperExceptionHandler.handleException(ex); return false; } } @Override public void releaseLock(final String key) { try { if (availableLock(key)) { locks.get(key).release(); } // CHECKSTYLE:OFF } catch (final Exception ex) { // CHECKSTYLE:ON CuratorZookeeperExceptionHandler.handleException(ex); } } private InterProcessLock getLock(final String key) { if (availableLock(key)) { return locks.get(key); } InterProcessLock lock = new InterProcessMutex(client, key); locks.put(key, lock); return lock; } private boolean availableLock(final String key) { return Objects.nonNull(locks.get(key)); } @Override public void close() { caches.values().forEach(CuratorCache::close); waitForCacheClose(); CloseableUtils.closeQuietly(client); } /* TODO wait 500ms, close cache before close client, or will throw exception * Because of asynchronous processing, may cause client to close * first and cache has not yet closed the end. * Wait for new version of Curator to fix this. * BUG address: https://issues.apache.org/jira/browse/CURATOR-157 */ private void waitForCacheClose() { try { Thread.sleep(500L); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); } } @Override public String getType() { return "ZooKeeper"; } }
import org.junit.Test; import static org.junit.Assert.*; public class TestPalindrome { // You must use this palindrome, and not instantiate // new Palindromes, or the autograder might be upset. static Palindrome palindrome = new Palindrome(); @Test public void testWordToDeque() { Deque d = palindrome.wordToDeque("persiflage"); String actual = ""; for (int i = 0; i < "persiflage".length(); i++) { actual += d.removeFirst(); } assertEquals("persiflage", actual); } @Test public void testIsPalindrome() { assertTrue(palindrome.isPalindrome("")); assertTrue(palindrome.isPalindrome("a")); assertFalse(palindrome.isPalindrome("Abba")); assertTrue(palindrome.isPalindrome("aba")); assertTrue(palindrome.isPalindrome("mom")); assertTrue(palindrome.isPalindrome("noon")); assertTrue(palindrome.isPalindrome("racecar")); assertFalse(palindrome.isPalindrome("cat")); assertFalse(palindrome.isPalindrome("aaaaab")); assertFalse(palindrome.isPalindrome("light")); assertTrue(palindrome.isPalindrome("G")); } @Test public void testIsPalindromeOffByOne() { OffByOne test = new OffByOne(); assertTrue(palindrome.isPalindrome("", test)); assertTrue(palindrome.isPalindrome("a", test)); assertTrue(palindrome.isPalindrome("G", test)); assertTrue(palindrome.isPalindrome("flake", test)); assertFalse(palindrome.isPalindrome("awesome", test)); } }
package com.zms.zpc.emulator.board.pci; import com.zms.zpc.emulator.board.MotherBoard; import com.zms.zpc.emulator.board.helper.BaseIODevice; import com.zms.zpc.emulator.board.time.IntervalTimer; import com.zms.zpc.emulator.debug.DummyDebugger; import javax.sound.midi.*; import java.io.*; import java.net.URI; import java.util.logging.*; /** * Created by 张小美 on 2019-06-15. * Copyright 2002-2016 */ public class PCSpeaker extends BaseIODevice { private static final DummyDebugger LOGGING = DummyDebugger.getLogger(PCSpeaker.class.getName()); private static final int SPEAKER_SAMPLE_RATE = 22050; private static final int SPEAKER_MAX_FREQ = SPEAKER_SAMPLE_RATE >> 1; private static final int SPEAKER_MIN_FREQ = 10; private static final int SPEAKER_VOLUME = 16000; private static final int SPEAKER_OFF = 0, SPEAKER_ON = 2, SPEAKER_PIT_ON = 3, SPEAKER_PIT_OFF = 1; private int dummyRefreshClock, speakerOn, lastNote, currentNote, velocity = 90, waitingForPit; private IntervalTimer pit; private boolean enabled = true, ioportRegistered; private Synthesizer synthesizer; private Receiver receiver; private ShortMessage message = new ShortMessage(); private Instrument[] instruments; private MidiChannel cc; // current channel public int mode; public MotherBoard mb; public PCSpeaker(MotherBoard mb) { this.mb=mb; ioportRegistered = false; if (enabled) { configure(); } this.init(); } protected void init() { for (int address : ioPortsRequested()) { mb.ios.register(address,this); } this.pit=mb.timer; this.ioportRegistered=true; } public void enable(boolean value) { if (!value) { enabled = false; } else { enabled = true; configure(); } } private void configure() { try { if (synthesizer == null) { if ((synthesizer = MidiSystem.getSynthesizer()) == null) { LOGGING.log(Level.INFO, "couldn't get MIDI synthesizer failed"); enabled = false; return; } } synthesizer.open(); receiver = synthesizer.getReceiver(); } catch (MidiUnavailableException e) { LOGGING.log(Level.INFO, "pc speaker disabled", e); enabled = false; return; } catch (Exception e) { LOGGING.log(Level.INFO, "pc speaker disabled", e); enabled = false; return; } Soundbank sb = synthesizer.getDefaultSoundbank(); if (sb == null) { System.out.println("Warning: loading remote soundbank."); try { sb = MidiSystem.getSoundbank(new URI("http://www.classicdosgames.com/soundbank.gm").toURL()); } catch (Exception e) { e.printStackTrace(); } } if (sb != null) { instruments = sb.getInstruments(); synthesizer.loadInstrument(instruments[0]); } MidiChannel[] channels = synthesizer.getChannels(); cc = channels[0]; programChange(80); //80 = load square wave instrument } private int getNote() { double freq = IntervalTimer.PIT_FREQ / pit.getInitialCount(2); //actual frequency in Hz if (freq > SPEAKER_MAX_FREQ) freq = SPEAKER_MAX_FREQ; if (freq < SPEAKER_MIN_FREQ) freq = SPEAKER_MIN_FREQ; return frequencyToNote(freq); } public static int frequencyToNote(double f) { double ans = 12 * (Math.log(f) - Math.log(440)) / Math.log(2); return (int) ans + 69; } private void playNote(int note) { try { message.setMessage(ShortMessage.NOTE_ON, 0, note, velocity); } catch (InvalidMidiDataException e) { e.printStackTrace(); } receiver.send(message, -1); } private void stopNote(int note) { try { message.setMessage(ShortMessage.NOTE_OFF, 0, note, velocity); } catch (InvalidMidiDataException e) { e.printStackTrace(); } receiver.send(message, -1); } public synchronized void play() { waitingForPit++; if ((enabled) && (waitingForPit == 2)) { if (pit.getMode(2) != 3) return; lastNote = currentNote; currentNote = getNote(); stopNote(lastNote); playNote(currentNote); } } private void programChange(int program) { if (instruments != null) { synthesizer.loadInstrument(instruments[program]); } cc.programChange(program); } public void saveState(DataOutput output) throws IOException { output.writeInt(dummyRefreshClock); output.writeInt(speakerOn); } public void loadState(DataInput input) throws IOException { ioportRegistered = false; dummyRefreshClock = input.readInt(); speakerOn = input.readInt(); } public int[] ioPortsRequested() { return new int[]{0x61}; } public int ioPortRead8(int address) { int out = pit.getOut(2); dummyRefreshClock ^= 1; return (speakerOn << 1) | (pit.getGate(2) ? 1 : 0) | (out << 5) | (dummyRefreshClock << 4); } public int ioPortRead16(int address) { return (0xff & ioPortRead8(address)) | (0xff00 & (ioPortRead8(address + 1) << 8)); } public int ioPortRead32(int address) { return (0xffff & ioPortRead16(address)) | (0xffff0000 & (ioPortRead16(address + 2) << 16)); } public synchronized void ioPortWrite8(int address, int data) { if (!enabled) return; speakerOn = (data >> 1) & 1; pit.setGate(2, (data & 1) != 0); if ((data & 1) == 1) { if (speakerOn == 1) { //connect speaker to PIT mode = SPEAKER_PIT_ON; waitingForPit = 0; //play(); } else { //leave speaker disconnected from following PIT mode = SPEAKER_PIT_OFF; stopNote(currentNote); } } else { // zero bit is 0, speaker follows bit 1 mode = SPEAKER_OFF; stopNote(currentNote); if (speakerOn != 0) LOGGING.log(Level.INFO, "manual speaker management not implemented"); } } public void ioPortWrite16(int address, int data) { this.ioPortWrite8(address, data); this.ioPortWrite8(address + 1, data >> 8); } public void ioPortWrite32(int address, int data) { this.ioPortWrite16(address, data); this.ioPortWrite16(address + 2, data >> 16); } public boolean initialised() { return ioportRegistered && (pit != null); } public void reset() { pit = null; ioportRegistered = false; } public boolean updated() { return ioportRegistered && pit.updated(); } }
/** * Copyright 2017 Yahoo Holdings 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.yahoo.athenz.container.filter; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.fail; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import org.testng.annotations.Test; public class RateLimitFilterTest { private class RateLimitFilterChain implements FilterChain { @Override public void doFilter(ServletRequest request, ServletResponse servletResponse) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) servletResponse; response.setStatus(200); } } @Test public void testDefaultRateLimitFilter() throws Exception { RateLimitFilter filter = new RateLimitFilter(); assertNotNull(filter); MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("GET"); request.setRequestURI("/"); MockHttpServletResponse response = new MockHttpServletResponse(); RateLimitFilterChain chain = new RateLimitFilterChain(); try { filter.doFilter(request, response, chain); } catch (IOException e) { fail(); } catch (ServletException e) { fail(); } assertEquals(response.getStatus(), 200); } }
/* * The MIT License * * Copyright: Copyright (C) 2014 T2Ti.COM * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * The author may be contacted at: t2ti.com@gmail.com * * @author Claudio de Barros (T2Ti.com) * @version 2.0 */ package com.t2tierp.patrimonio.cliente; import org.openswing.swing.client.GridControl; import org.openswing.swing.mdi.client.InternalFrame; public class PatrimTipoMovimentacaoGrid extends InternalFrame { public PatrimTipoMovimentacaoGrid(PatrimTipoMovimentacaoGridController controller) { initComponents(); gridControl1.setController(controller); gridControl1.setGridDataLocator(controller); } public GridControl getGrid1() { return gridControl1; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jPanel1 = new javax.swing.JPanel(); insertButton1 = new org.openswing.swing.client.InsertButton(); deleteButton1 = new org.openswing.swing.client.DeleteButton(); reloadButton1 = new org.openswing.swing.client.ReloadButton(); navigatorBar1 = new org.openswing.swing.client.NavigatorBar(); gridControl1 = new org.openswing.swing.client.GridControl(); textColumn6 = new org.openswing.swing.table.columns.client.TextColumn(); textColumn4 = new org.openswing.swing.table.columns.client.TextColumn(); textColumn5 = new org.openswing.swing.table.columns.client.TextColumn(); setTitle("T2Ti ERP - Controle Patrimonial"); setPreferredSize(new java.awt.Dimension(700, 400)); getContentPane().setLayout(new java.awt.GridBagLayout()); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Patrim Tipo Movimentacao")); jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); jPanel1.add(insertButton1); jPanel1.add(deleteButton1); jPanel1.add(reloadButton1); jPanel1.add(navigatorBar1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; getContentPane().add(jPanel1, gridBagConstraints); gridControl1.setDeleteButton(deleteButton1); gridControl1.setFunctionId("patrimTipoMovimentacao"); gridControl1.setInsertButton(insertButton1); gridControl1.setNavBar(navigatorBar1); gridControl1.setReloadButton(reloadButton1); gridControl1.setValueObjectClassName("com.t2tierp.patrimonio.java.PatrimTipoMovimentacaoVO"); gridControl1.getColumnContainer().setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); textColumn6.setColumnName("tipo"); textColumn6.setHeaderColumnName("Tipo"); textColumn6.setHeaderFont(new java.awt.Font("Arial", 1, 11)); // NOI18N textColumn6.setPreferredWidth(150); gridControl1.getColumnContainer().add(textColumn6); textColumn4.setColumnName("nome"); textColumn4.setHeaderColumnName("Nome"); textColumn4.setHeaderFont(new java.awt.Font("Arial", 1, 11)); // NOI18N textColumn4.setPreferredWidth(150); gridControl1.getColumnContainer().add(textColumn4); textColumn5.setColumnName("descricao"); textColumn5.setHeaderColumnName("Descricao"); textColumn5.setHeaderFont(new java.awt.Font("Arial", 1, 11)); // NOI18N textColumn5.setPreferredWidth(300); gridControl1.getColumnContainer().add(textColumn5); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; getContentPane().add(gridControl1, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private org.openswing.swing.client.DeleteButton deleteButton1; private org.openswing.swing.client.GridControl gridControl1; private org.openswing.swing.client.InsertButton insertButton1; private javax.swing.JPanel jPanel1; private org.openswing.swing.client.NavigatorBar navigatorBar1; private org.openswing.swing.client.ReloadButton reloadButton1; private org.openswing.swing.table.columns.client.TextColumn textColumn4; private org.openswing.swing.table.columns.client.TextColumn textColumn5; private org.openswing.swing.table.columns.client.TextColumn textColumn6; // End of variables declaration//GEN-END:variables }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/v2beta1/agent.proto package com.google.cloud.dialogflow.v2beta1; /** * * * <pre> * The response message for [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.ExportAgentResponse} */ public final class ExportAgentResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2beta1.ExportAgentResponse) ExportAgentResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ExportAgentResponse.newBuilder() to construct. private ExportAgentResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ExportAgentResponse() {} @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ExportAgentResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } 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; case 10: { java.lang.String s = input.readStringRequireUtf8(); agentCase_ = 1; agent_ = s; break; } case 18: { agentCase_ = 2; agent_ = input.readBytes(); break; } default: { if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.AgentProto .internal_static_google_cloud_dialogflow_v2beta1_ExportAgentResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.AgentProto .internal_static_google_cloud_dialogflow_v2beta1_ExportAgentResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.ExportAgentResponse.class, com.google.cloud.dialogflow.v2beta1.ExportAgentResponse.Builder.class); } private int agentCase_ = 0; private java.lang.Object agent_; public enum AgentCase implements com.google.protobuf.Internal.EnumLite { AGENT_URI(1), AGENT_CONTENT(2), AGENT_NOT_SET(0); private final int value; private AgentCase(int value) { this.value = value; } /** @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static AgentCase valueOf(int value) { return forNumber(value); } public static AgentCase forNumber(int value) { switch (value) { case 1: return AGENT_URI; case 2: return AGENT_CONTENT; case 0: return AGENT_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public AgentCase getAgentCase() { return AgentCase.forNumber(agentCase_); } public static final int AGENT_URI_FIELD_NUMBER = 1; /** * * * <pre> * The URI to a file containing the exported agent. This field is populated * only if `agent_uri` is specified in `ExportAgentRequest`. * </pre> * * <code>string agent_uri = 1;</code> */ public java.lang.String getAgentUri() { java.lang.Object ref = ""; if (agentCase_ == 1) { ref = agent_; } 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 (agentCase_ == 1) { agent_ = s; } return s; } } /** * * * <pre> * The URI to a file containing the exported agent. This field is populated * only if `agent_uri` is specified in `ExportAgentRequest`. * </pre> * * <code>string agent_uri = 1;</code> */ public com.google.protobuf.ByteString getAgentUriBytes() { java.lang.Object ref = ""; if (agentCase_ == 1) { ref = agent_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (agentCase_ == 1) { agent_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AGENT_CONTENT_FIELD_NUMBER = 2; /** * * * <pre> * The exported agent. * Example for how to export an agent to a zip file via a command line: * &lt;pre&gt;curl &#92; * 'https://dialogflow.googleapis.com/v2beta1/projects/&amp;lt;project_name&amp;gt;/agent:export'&#92; * -X POST &#92; * -H 'Authorization: Bearer '$(gcloud auth application-default * print-access-token) &#92; * -H 'Accept: application/json' &#92; * -H 'Content-Type: application/json' &#92; * --compressed &#92; * --data-binary '{}' &#92; * | grep agentContent | sed -e 's/.*"agentContent": "&#92;([^"]*&#92;)".*&#47;&#92;1/' &#92; * | base64 --decode &gt; &amp;lt;agent zip file&amp;gt;&lt;/pre&gt; * </pre> * * <code>bytes agent_content = 2;</code> */ public com.google.protobuf.ByteString getAgentContent() { if (agentCase_ == 2) { return (com.google.protobuf.ByteString) agent_; } return com.google.protobuf.ByteString.EMPTY; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (agentCase_ == 1) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, agent_); } if (agentCase_ == 2) { output.writeBytes(2, (com.google.protobuf.ByteString) agent_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (agentCase_ == 1) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, agent_); } if (agentCase_ == 2) { size += com.google.protobuf.CodedOutputStream.computeBytesSize( 2, (com.google.protobuf.ByteString) agent_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dialogflow.v2beta1.ExportAgentResponse)) { return super.equals(obj); } com.google.cloud.dialogflow.v2beta1.ExportAgentResponse other = (com.google.cloud.dialogflow.v2beta1.ExportAgentResponse) obj; boolean result = true; result = result && getAgentCase().equals(other.getAgentCase()); if (!result) return false; switch (agentCase_) { case 1: result = result && getAgentUri().equals(other.getAgentUri()); break; case 2: result = result && getAgentContent().equals(other.getAgentContent()); break; case 0: default: } result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); switch (agentCase_) { case 1: hash = (37 * hash) + AGENT_URI_FIELD_NUMBER; hash = (53 * hash) + getAgentUri().hashCode(); break; case 2: hash = (37 * hash) + AGENT_CONTENT_FIELD_NUMBER; hash = (53 * hash) + getAgentContent().hashCode(); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.v2beta1.ExportAgentResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ExportAgentResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ExportAgentResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ExportAgentResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ExportAgentResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ExportAgentResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ExportAgentResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.ExportAgentResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ExportAgentResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.ExportAgentResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ExportAgentResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.ExportAgentResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.dialogflow.v2beta1.ExportAgentResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The response message for [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.ExportAgentResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2beta1.ExportAgentResponse) com.google.cloud.dialogflow.v2beta1.ExportAgentResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.AgentProto .internal_static_google_cloud_dialogflow_v2beta1_ExportAgentResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.AgentProto .internal_static_google_cloud_dialogflow_v2beta1_ExportAgentResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.ExportAgentResponse.class, com.google.cloud.dialogflow.v2beta1.ExportAgentResponse.Builder.class); } // Construct using com.google.cloud.dialogflow.v2beta1.ExportAgentResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); agentCase_ = 0; agent_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2beta1.AgentProto .internal_static_google_cloud_dialogflow_v2beta1_ExportAgentResponse_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ExportAgentResponse getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2beta1.ExportAgentResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ExportAgentResponse build() { com.google.cloud.dialogflow.v2beta1.ExportAgentResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ExportAgentResponse buildPartial() { com.google.cloud.dialogflow.v2beta1.ExportAgentResponse result = new com.google.cloud.dialogflow.v2beta1.ExportAgentResponse(this); if (agentCase_ == 1) { result.agent_ = agent_; } if (agentCase_ == 2) { result.agent_ = agent_; } result.agentCase_ = agentCase_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dialogflow.v2beta1.ExportAgentResponse) { return mergeFrom((com.google.cloud.dialogflow.v2beta1.ExportAgentResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.v2beta1.ExportAgentResponse other) { if (other == com.google.cloud.dialogflow.v2beta1.ExportAgentResponse.getDefaultInstance()) return this; switch (other.getAgentCase()) { case AGENT_URI: { agentCase_ = 1; agent_ = other.agent_; onChanged(); break; } case AGENT_CONTENT: { setAgentContent(other.getAgentContent()); break; } case AGENT_NOT_SET: { break; } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.dialogflow.v2beta1.ExportAgentResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.dialogflow.v2beta1.ExportAgentResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int agentCase_ = 0; private java.lang.Object agent_; public AgentCase getAgentCase() { return AgentCase.forNumber(agentCase_); } public Builder clearAgent() { agentCase_ = 0; agent_ = null; onChanged(); return this; } /** * * * <pre> * The URI to a file containing the exported agent. This field is populated * only if `agent_uri` is specified in `ExportAgentRequest`. * </pre> * * <code>string agent_uri = 1;</code> */ public java.lang.String getAgentUri() { java.lang.Object ref = ""; if (agentCase_ == 1) { ref = agent_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (agentCase_ == 1) { agent_ = s; } return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The URI to a file containing the exported agent. This field is populated * only if `agent_uri` is specified in `ExportAgentRequest`. * </pre> * * <code>string agent_uri = 1;</code> */ public com.google.protobuf.ByteString getAgentUriBytes() { java.lang.Object ref = ""; if (agentCase_ == 1) { ref = agent_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (agentCase_ == 1) { agent_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The URI to a file containing the exported agent. This field is populated * only if `agent_uri` is specified in `ExportAgentRequest`. * </pre> * * <code>string agent_uri = 1;</code> */ public Builder setAgentUri(java.lang.String value) { if (value == null) { throw new NullPointerException(); } agentCase_ = 1; agent_ = value; onChanged(); return this; } /** * * * <pre> * The URI to a file containing the exported agent. This field is populated * only if `agent_uri` is specified in `ExportAgentRequest`. * </pre> * * <code>string agent_uri = 1;</code> */ public Builder clearAgentUri() { if (agentCase_ == 1) { agentCase_ = 0; agent_ = null; onChanged(); } return this; } /** * * * <pre> * The URI to a file containing the exported agent. This field is populated * only if `agent_uri` is specified in `ExportAgentRequest`. * </pre> * * <code>string agent_uri = 1;</code> */ public Builder setAgentUriBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); agentCase_ = 1; agent_ = value; onChanged(); return this; } /** * * * <pre> * The exported agent. * Example for how to export an agent to a zip file via a command line: * &lt;pre&gt;curl &#92; * 'https://dialogflow.googleapis.com/v2beta1/projects/&amp;lt;project_name&amp;gt;/agent:export'&#92; * -X POST &#92; * -H 'Authorization: Bearer '$(gcloud auth application-default * print-access-token) &#92; * -H 'Accept: application/json' &#92; * -H 'Content-Type: application/json' &#92; * --compressed &#92; * --data-binary '{}' &#92; * | grep agentContent | sed -e 's/.*"agentContent": "&#92;([^"]*&#92;)".*&#47;&#92;1/' &#92; * | base64 --decode &gt; &amp;lt;agent zip file&amp;gt;&lt;/pre&gt; * </pre> * * <code>bytes agent_content = 2;</code> */ public com.google.protobuf.ByteString getAgentContent() { if (agentCase_ == 2) { return (com.google.protobuf.ByteString) agent_; } return com.google.protobuf.ByteString.EMPTY; } /** * * * <pre> * The exported agent. * Example for how to export an agent to a zip file via a command line: * &lt;pre&gt;curl &#92; * 'https://dialogflow.googleapis.com/v2beta1/projects/&amp;lt;project_name&amp;gt;/agent:export'&#92; * -X POST &#92; * -H 'Authorization: Bearer '$(gcloud auth application-default * print-access-token) &#92; * -H 'Accept: application/json' &#92; * -H 'Content-Type: application/json' &#92; * --compressed &#92; * --data-binary '{}' &#92; * | grep agentContent | sed -e 's/.*"agentContent": "&#92;([^"]*&#92;)".*&#47;&#92;1/' &#92; * | base64 --decode &gt; &amp;lt;agent zip file&amp;gt;&lt;/pre&gt; * </pre> * * <code>bytes agent_content = 2;</code> */ public Builder setAgentContent(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } agentCase_ = 2; agent_ = value; onChanged(); return this; } /** * * * <pre> * The exported agent. * Example for how to export an agent to a zip file via a command line: * &lt;pre&gt;curl &#92; * 'https://dialogflow.googleapis.com/v2beta1/projects/&amp;lt;project_name&amp;gt;/agent:export'&#92; * -X POST &#92; * -H 'Authorization: Bearer '$(gcloud auth application-default * print-access-token) &#92; * -H 'Accept: application/json' &#92; * -H 'Content-Type: application/json' &#92; * --compressed &#92; * --data-binary '{}' &#92; * | grep agentContent | sed -e 's/.*"agentContent": "&#92;([^"]*&#92;)".*&#47;&#92;1/' &#92; * | base64 --decode &gt; &amp;lt;agent zip file&amp;gt;&lt;/pre&gt; * </pre> * * <code>bytes agent_content = 2;</code> */ public Builder clearAgentContent() { if (agentCase_ == 2) { agentCase_ = 0; agent_ = null; onChanged(); } return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2beta1.ExportAgentResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2beta1.ExportAgentResponse) private static final com.google.cloud.dialogflow.v2beta1.ExportAgentResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2beta1.ExportAgentResponse(); } public static com.google.cloud.dialogflow.v2beta1.ExportAgentResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ExportAgentResponse> PARSER = new com.google.protobuf.AbstractParser<ExportAgentResponse>() { @java.lang.Override public ExportAgentResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ExportAgentResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ExportAgentResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ExportAgentResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ExportAgentResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
package com.rs.game.player.content.pet; import java.io.Serializable; /** * A class containing pet details for a certain pet. * * @author Emperor * */ public final class PetDetails implements Serializable { /** * The serial UID. */ private static final long serialVersionUID = -8863494278992020170L; /** * The hunger rate. */ private double hunger = 0.0; /** * The growth rate. */ private double growth = 0.0; /** * The current stage of the pet (0 - baby, 1 - grown, 2 - overgrown). */ private int stage; /** * Constructs a new {@code PetDetails} {@code Object}. * * @param growth * The growth value. */ public PetDetails(double growth) { this.growth = growth; } /** * Increases the hunger value by the given amount. * * @param amount * The amount. */ public void updateHunger(double amount) { hunger += amount; if (hunger < 0.0) { hunger = 0.0; } else if (hunger > 100.0) { hunger = 100.0; } } /** * Increases the growth value by the given amount. * * @param amount * The amount. */ public void updateGrowth(double amount) { growth += amount; if (growth < 0.0) { growth = 0.0; } else if (growth > 100.0) { growth = 100.0; } } /** * Gets the hunger. * * @return The hunger. */ public double getHunger() { return hunger; } /** * Gets the growth. * * @return The growth. */ public double getGrowth() { return growth; } /** * Gets the stage. * * @return The stage. */ public int getStage() { return stage; } /** * Sets the stage. * * @param stage * The stage to set. */ public void setStage(int stage) { this.stage = stage; } }
package sort; import java.util.Arrays; public class code164 { public int maximumGap(int[] nums) { if (nums.length < 2 || nums == null){ return 0; } Arrays.sort(nums); int res = 0; for (int i = 0 ; i <nums.length-1; i++){ res = Math.max(nums[i+1] - nums[i], res); } return res; } //归并排序 public void sort(int[] nums, int low, int high){ if (low >= high){ return; } int mid = (low + high)/2; sort(nums, low, mid); sort(nums, mid+1, high); mergeSort(nums, low, mid, high); } public void mergeSort(int[] nums, int low, int mid, int high){ int[] tmp = new int[high - low + 1]; int i = low; int j = mid+1; int k = 0; while (i <= mid && j <= high){ if (nums[i] <= nums[j]){ tmp[k++] = nums[i++]; }else{ tmp[k++] = nums[j++]; } } while (i <= mid){ tmp[k++] = nums[i++]; } while (j <= high){ tmp[k++] = nums[j++]; } for (int x = 0; x<tmp.length; x++){ nums[low + x] = tmp[x]; } } //冒泡排序 public void bubbleSort(int[] nums){ for (int i = 0; i< nums.length - 1; i++){ boolean flag = false; for (int j = 0; j< nums.length-i-1; j++){ if (nums[j] > nums[j+1]){ int change = nums[j+1]; nums[j+1] = nums[j]; nums[j] = change; flag = true; } } if (flag == false){ break; } } } //快速排序 }
package casts.IsInstanceNoRefute; public class Bar implements SimpleInterface { public int getInt() { return 0; } }
import javax.swing.*; import java.awt.event.*; public class Main extends JDialog { private JPanel contentPane; private JButton trimLogsButton; private JTextArea textArea1; private JTextArea textArea2; private JTextArea textArea3; public Main() { setContentPane(contentPane); setModal(true); getRootPane().setDefaultButton(trimLogsButton); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onCancel(); } }); // call onCancel() on ESCAPE contentPane.registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); trimLogsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { Trim trim = new Trim(textArea1, textArea2, textArea3); } }); } private void onCancel() { // add your code here if necessary dispose(); } public static void main(String[] args) { Main dialog = new Main(); dialog.pack(); dialog.setVisible(true); System.exit(0); } }
package com.stylefeng.guns.modular.foundation.controller; import com.stylefeng.guns.core.base.controller.BaseController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.beans.factory.annotation.Autowired; import com.stylefeng.guns.core.log.LogObjectHolder; import org.springframework.web.bind.annotation.RequestParam; import com.stylefeng.guns.modular.system.model.MaterialAttr; import com.stylefeng.guns.modular.foundation.service.IMaterialAttrService; /** * 材料属性管理控制器 * * @author fengshuonan * @Date 2018-10-26 20:52:07 */ @Controller @RequestMapping("/materialAttr") public class MaterialAttrController extends BaseController { private String PREFIX = "/foundation/materialAttr/"; @Autowired private IMaterialAttrService materialAttrService; /** * 跳转到材料属性管理首页 */ @RequestMapping("") public String index() { return PREFIX + "materialAttr.html"; } /** * 跳转到添加材料属性管理 */ @RequestMapping("/materialAttr_add") public String materialAttrAdd() { return PREFIX + "materialAttr_add.html"; } /** * 跳转到修改材料属性管理 */ @RequestMapping("/materialAttr_update/{materialAttrId}") public String materialAttrUpdate(@PathVariable Integer materialAttrId, Model model) { MaterialAttr materialAttr = materialAttrService.selectById(materialAttrId); model.addAttribute("item",materialAttr); LogObjectHolder.me().set(materialAttr); return PREFIX + "materialAttr_edit.html"; } /** * 获取材料属性管理列表 */ @RequestMapping(value = "/list") @ResponseBody public Object list(String condition) { return materialAttrService.selectList(null); } /** * 新增材料属性管理 */ @RequestMapping(value = "/add") @ResponseBody public Object add(MaterialAttr materialAttr) { materialAttrService.insert(materialAttr); return SUCCESS_TIP; } /** * 删除材料属性管理 */ @RequestMapping(value = "/delete") @ResponseBody public Object delete(@RequestParam Integer materialAttrId) { materialAttrService.deleteById(materialAttrId); return SUCCESS_TIP; } /** * 修改材料属性管理 */ @RequestMapping(value = "/update") @ResponseBody public Object update(MaterialAttr materialAttr) { materialAttrService.updateById(materialAttr); return SUCCESS_TIP; } /** * 材料属性管理详情 */ @RequestMapping(value = "/detail/{materialAttrId}") @ResponseBody public Object detail(@PathVariable("materialAttrId") Integer materialAttrId) { return materialAttrService.selectById(materialAttrId); } }
package com.example.demo.modelo; import javax.persistence.*; import java.util.List; /** * @author Bruno Nogueira de Oliveira * @date 23/08/17. */ @Entity @Table(name = "pessoa") public class Pessoa { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long codigo; @Column(length = 80, nullable = false) private String nome; @Column(length = 11, nullable = false) private String cpf; @OneToMany(mappedBy = "pessoa") private List<Endereco> enderecos; @OneToMany(mappedBy = "pessoa") private List<Telefone> telefones; public Long getCodigo() { return codigo; } public void setCodigo(Long codigo) { this.codigo = codigo; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public List<Endereco> getEnderecos() { return enderecos; } public void setEnderecos(List<Endereco> enderecos) { this.enderecos = enderecos; } public List<Telefone> getTelefones() { return telefones; } public void setTelefones(List<Telefone> telefones) { this.telefones = telefones; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pessoa pessoa = (Pessoa) o; return getCodigo() != null ? getCodigo().equals(pessoa.getCodigo()) : pessoa.getCodigo() == null; } @Override public int hashCode() { return getCodigo() != null ? getCodigo().hashCode() : 0; } }
/* *ADVERTENCIA : Este programa esta protegido por la ley de derechos de autor. *La reproducci?n o distribuci?n il?cita de este programa o de cualquiera de *sus partes esta penado por la ley con severas sanciones civiles y penales, *y ser?n objeto de todas las sanciones legales que correspondan. */ package com.bydan.erp.inventario.util; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.HashSet; import java.util.ArrayList; import java.io.Serializable; import java.util.Date; import com.bydan.framework.erp.business.entity.DatoGeneral; import com.bydan.framework.erp.business.entity.GeneralEntityConstantesFunciones; @SuppressWarnings("unused") public class SegmentoProductoConstantesFuncionesAdditional extends GeneralEntityConstantesFunciones { public SegmentoProductoConstantesFuncionesAdditional () { } }
package org.irods.jargon.rest.domain; import javax.xml.bind.annotation.XmlElement; /** * <pre> * Object to hold GenQuery request conditions. A condition contains a column * name, the condition's operator, and the value for the test. * * The following is a sample XML representation of the condition: * * {@code * <condition> * <column>META_DATA_ATTR_NAME</column> * <operator>LIKE</operator> * <value>ABC</value> * </condition> * } * </pre> * * @author jjames */ public class GenQueryCondition { /** The column. */ private String column = ""; /** The operator. */ private String operator = ""; /** Single values */ private String value = null; /** List of values for "IN" clause. */ private GenQueryConditionValueList valueList = null; public GenQueryCondition() { } public GenQueryCondition(String col, String op, String val) { column = col; operator = op; value = val; } public GenQueryCondition(String col, String op, GenQueryConditionValueList valList) { column = col; operator = op; valueList = valList; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "[Condition: column=" + column + " operator=" + operator + " value=" + valueList + "]"; } /** * Gets the column. * * @return the column */ @XmlElement(name = "column", required = true) public String getColumn() { return column; } /** * Sets the column. * * @param column * the new column */ public void setColumn(String column) { this.column = column; } /** * Gets the value. * * @return the value */ @XmlElement(name = "value", required = false) public String getValue() { return value; } /** * Sets the value. * * @param value * the new value */ public void setValue(String value) { this.value = value; } @XmlElement(name = "value_list", required = false) public GenQueryConditionValueList getValueList() { return valueList; } public void setValueList(GenQueryConditionValueList v) { this.valueList = v; } /** * Gets the operator. * * @return the operator */ @XmlElement(name = "operator", required = true) public String getOperator() { return operator; } /** * Sets the operator. * * @param operator * the new operator */ public void setOperator(String operator) { this.operator = operator; } }
package net.CyanWool.entity.meta; import java.util.ArrayList; import java.util.List; import org.spacehq.mc.protocol.data.game.values.setting.ChatVisibility; import org.spacehq.mc.protocol.data.game.values.setting.SkinPart; import org.spacehq.mc.protocol.packet.ingame.client.ClientSettingsPacket; public final class ClientSettings { private final String locale; private final int viewDistance; private final boolean chatColors; private ChatVisibility chatVisibility; private List<SkinPart> skinParts; public ClientSettings(ClientSettingsPacket packet) { this(packet.getLocale(), packet.getRenderDistance(), packet.getChatVisibility(), packet.getUseChatColors(), packet.getVisibleParts()); } public ClientSettings(String locale, int viewDistance, ChatVisibility chatFlags, boolean chatColors, List<SkinPart> skinParts) { this.locale = locale; this.viewDistance = viewDistance; this.chatVisibility = chatFlags; this.chatColors = chatColors; this.skinParts = skinParts; } public String getLocale() { return locale; } public int getViewDistance() { return viewDistance; } public ChatVisibility getChatFlags() { return chatVisibility; } public boolean showChat() { return chatVisibility == ChatVisibility.FULL; } public boolean showCommands() { return chatVisibility != ChatVisibility.SYSTEM; } public boolean showChatColors() { return chatColors; } public List<SkinPart> getSkinParts() { return skinParts; } public static ClientSettings getDEFAULT() { List<SkinPart> list = new ArrayList<SkinPart>(); list.add(SkinPart.CAPE); list.add(SkinPart.HAT); list.add(SkinPart.JACKET); list.add(SkinPart.LEFT_PANTS_LEG); list.add(SkinPart.LEFT_SLEEVE); list.add(SkinPart.RIGHT_PANTS_LEG); list.add(SkinPart.RIGHT_SLEEVE); ClientSettings settings = new ClientSettings("en_US", 8, ChatVisibility.FULL, true, list); // Normal // - // 8 return settings; } @Override public String toString() { return "ClientSettings{" + "locale='" + locale + '\'' + ", viewDistance=" + viewDistance + ", chatFlags=" + chatVisibility.name() + ", chatColors=" + chatColors + ", skinFlags=" + skinParts + '}'; } }
/* * Copyright (c) 2011-2017 Nexmo Inc * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.nexmo.quickstart.voice; import com.fasterxml.jackson.databind.ObjectMapper; import com.nexmo.client.voice.ncco.ConnectNcco; import com.nexmo.client.voice.ncco.Ncco; import spark.Route; import spark.Spark; import static com.nexmo.quickstart.Util.envVar; public class ConnectInboundCall { public static void main(String[] args) { final String RECIPIENT_NUMBER = envVar("RECIPIENT_NUMBER"); final String NEXMO_NUMBER = envVar("NEXMO_NUMBER"); /* * Route to answer incoming calls with an NCCO response. */ Route answerRoute = (req, res) -> { ConnectNcco connect = new ConnectNcco(RECIPIENT_NUMBER); connect.setFrom(NEXMO_NUMBER); Ncco[] nccos = new Ncco[]{connect}; res.type("application/json"); // com.fasterxml.jackson.databind.ObjectMapper; return new ObjectMapper().writer().writeValueAsString(nccos); }; Spark.port(3000); Spark.get("/webhooks/answer", answerRoute); Spark.post("/webhooks/answer", answerRoute); } }
/* * Copyright 2017 Javier A. Ortiz Bultron javier.ortiz.78@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.validation.manager.core.db; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.codehaus.jackson.annotate.JsonIgnore; /** * * @author Javier A. Ortiz Bultron javier.ortiz.78@gmail.com */ @Entity @Table(name = "workflow") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Workflow.findAll", query = "SELECT w FROM Workflow w") , @NamedQuery(name = "Workflow.findById", query = "SELECT w FROM Workflow w WHERE w.id = :id") , @NamedQuery(name = "Workflow.findByWorkflowName", query = "SELECT w FROM Workflow w WHERE w.workflowName = :workflowName")}) public class Workflow implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "id") @GeneratedValue(strategy = GenerationType.TABLE, generator = "WFGEN") @TableGenerator(name = "WFGEN", table = "vm_id", pkColumnName = "table_name", valueColumnName = "last_id", pkColumnValue = "workflow", initialValue = 1_000, allocationSize = 1) private Integer id; @Basic(optional = false) @NotNull @Size(min = 1, max = 255) @Column(name = "workflow_name") private String workflowName; @OneToMany(cascade = CascadeType.ALL, mappedBy = "workflow") private List<WorkflowInstance> workflowInstanceList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "workflow") private List<WorkflowStep> workflowStepList; public Workflow() { } public Workflow(String workflowName) { this.workflowName = workflowName; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getWorkflowName() { return workflowName; } public void setWorkflowName(String workflowName) { this.workflowName = workflowName; } @XmlTransient @JsonIgnore public List<WorkflowInstance> getWorkflowInstanceList() { return workflowInstanceList; } public void setWorkflowInstanceList(List<WorkflowInstance> workflowInstanceList) { this.workflowInstanceList = workflowInstanceList; } @XmlTransient @JsonIgnore public List<WorkflowStep> getWorkflowStepList() { return workflowStepList; } public void setWorkflowStepList(List<WorkflowStep> workflowStepList) { this.workflowStepList = workflowStepList; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Workflow)) { return false; } Workflow other = (Workflow) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "com.validation.manager.core.db.Workflow[ id=" + id + " ]"; } }
package algorithmia.ValidationValuePresent; import com.algorithmia.Algorithmia; import com.algorithmia.AlgorithmiaClient; import com.algorithmia.TypeToken; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import static java.lang.Boolean.TRUE; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class ValidationValuePresentSystemIT { private static String API_KEY = null; private static String API_ADDRESS = null; private static String ALGORITHM_DESCRIPTOR = null; private static final TypeToken<OutputData> OUTPUT_DATA_TYPE = new TypeToken<OutputData>() {}; private AlgorithmiaClient client = null; @BeforeClass public static void loadConfig() { Config config = ConfigFactory.load().getConfig("algorithmia"); API_KEY = config.getString("simpleApiKey"); API_ADDRESS = config.getString("apiAddress"); ALGORITHM_DESCRIPTOR = config.getString("algorithm.descriptor"); } @Before public void setUp() { client = Algorithmia.client(API_KEY, API_ADDRESS); } @After public void tearDown() { if (client != null) { try { client.close(); } catch (IOException ignore) { // silently ignore } } } @Test public void validationRuleIsTriggeredWhenInputContainsAValue() throws Exception { String inputContainingValue = "{\"value\":\"some-value\"}"; OutputData output = client.algo(ALGORITHM_DESCRIPTOR).pipe(inputContainingValue).as(OUTPUT_DATA_TYPE); assertThat(output.triggered, is(TRUE)); } }
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { Integer val; public boolean isValidBST(TreeNode root) { if (null == root) return true; if (!isValidBST(root.left)) return false; if (null != val && val >= root.val) return false; val = root.val; return isValidBST(root.right); } }
package model.dao; import model.ModelUsuario; import conexoes.ConexaoMySql; import java.util.ArrayList; /** * * @author Leandro */ public class NaoUsar_DAOUsuario extends ConexaoMySql { /** * grava Usuario * @param pModelUsuario * return int */ public int salvarUsuarioDAO(ModelUsuario pModelUsuario){ try { this.conectar(); return this.insertSQL( "INSERT INTO tbl_usuarios (" + "nome," + "login," + "senha" + ") VALUES (" + "'" + pModelUsuario.getNome() + "'," + "'" + pModelUsuario.getLogin() + "'," + "'" + pModelUsuario.getSenha() + "'" + ");" ); }catch(Exception e){ e.printStackTrace(); return 0; }finally{ this.fecharConexao(); } } /** * recupera Usuario * @param pCodigo * return ModelUsuario */ public ModelUsuario getUsuarioDAO(int pCodigo){ ModelUsuario modelUsuario = new ModelUsuario(); try { this.conectar(); this.executarSQL( "SELECT " + "pk_codigo," + "nome," + "login," + "senha" + " FROM" + " tbl_usuarios" + " WHERE" + " pk_codigo = '" + pCodigo + "'" + ";" ); while(this.getResultSet().next()){ modelUsuario.setCodigo(this.getResultSet().getInt(1)); modelUsuario.setNome(this.getResultSet().getString(2)); modelUsuario.setLogin(this.getResultSet().getString(3)); modelUsuario.setSenha(this.getResultSet().getString(4)); } }catch(Exception e){ e.printStackTrace(); }finally{ this.fecharConexao(); } return modelUsuario; } /** * recupera Usuario * @param pLogin * return ModelUsuario */ public ModelUsuario getUsuarioDAO(String pLogin){ ModelUsuario modelUsuario = new ModelUsuario(); try { this.conectar(); this.executarSQL( "SELECT " + "pk_codigo," + "nome," + "login," + "senha" + " FROM" + " tbl_usuarios" + " WHERE" + " login = '" + pLogin + "'" + ";" ); while(this.getResultSet().next()){ modelUsuario.setCodigo(this.getResultSet().getInt(1)); modelUsuario.setNome(this.getResultSet().getString(2)); modelUsuario.setLogin(this.getResultSet().getString(3)); modelUsuario.setSenha(this.getResultSet().getString(4)); } }catch(Exception e){ e.printStackTrace(); }finally{ this.fecharConexao(); } return modelUsuario; } /** * recupera Usuario * @param pCodigo * return ModelUsuario */ public boolean getUsuarioDAO(ModelUsuario pModelUsuario){ try { this.conectar(); this.executarSQL( "SELECT " + "pk_codigo," + "nome," + "login," + "senha" + " FROM" + " tbl_usuarios" + " WHERE" + " login = '" + pModelUsuario.getLogin()+ "' AND senha = '" + pModelUsuario.getSenha() + "' " + ";" ); if (getResultSet().next()) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); return false; } finally { this.fecharConexao(); } } /** * recupera uma lista de Usuario * return ArrayList */ public ArrayList<ModelUsuario> getListaUsuarioDAO(){ ArrayList<ModelUsuario> listamodelUsuario = new ArrayList(); ModelUsuario modelUsuario = new ModelUsuario(); try { this.conectar(); this.executarSQL( "SELECT " + "pk_codigo," + "nome," + "login," + "senha" + " FROM" + " tbl_usuarios" + ";" ); while(this.getResultSet().next()){ modelUsuario = new ModelUsuario(); modelUsuario.setCodigo(this.getResultSet().getInt(1)); modelUsuario.setNome(this.getResultSet().getString(2)); modelUsuario.setLogin(this.getResultSet().getString(3)); modelUsuario.setSenha(this.getResultSet().getString(4)); listamodelUsuario.add(modelUsuario); } }catch(Exception e){ e.printStackTrace(); }finally{ this.fecharConexao(); } return listamodelUsuario; } /** * atualiza Usuario * @param pModelUsuario * return boolean */ public boolean atualizarUsuarioDAO(ModelUsuario pModelUsuario){ try { this.conectar(); return this.executarUpdateDeleteSQL( "UPDATE tbl_usuarios SET " + "pk_codigo = '" + pModelUsuario.getCodigo() + "'," + "nome = '" + pModelUsuario.getNome() + "'," + "login = '" + pModelUsuario.getLogin() + "'," + "senha = '" + pModelUsuario.getSenha() + "'" + " WHERE " + "pk_codigo = '" + pModelUsuario.getCodigo() + "'" + ";" ); }catch(Exception e){ e.printStackTrace(); return false; }finally{ this.fecharConexao(); } } /** * exclui Usuario * @param pCodigo * return boolean */ public boolean excluirUsuarioDAO(int pCodigo){ try { this.conectar(); return this.executarUpdateDeleteSQL( "DELETE FROM tbl_usuarios " + " WHERE " + "pk_codigo = '" + pCodigo + "'" + ";" ); }catch(Exception e){ e.printStackTrace(); return false; }finally{ this.fecharConexao(); } } }
package org.dd4t.caching.impl; import org.dd4t.caching.CacheDependency; /** * Basic implementation class for a CacheDependency. Supports creation through constructor as well as setters. * * @author Rogier Oudshoorn * */ public class CacheDependencyImpl implements CacheDependency{ private int publicationId; private int itemId; public CacheDependencyImpl(int dependingPublicationId, int dependingItemId) { this.publicationId = dependingPublicationId; this.itemId = dependingItemId; } @Override public int getPublicationId() { return publicationId; } @Override public int getItemId() { return itemId; } void setPublicationId(int dependingPublicationId){ publicationId = dependingPublicationId; } void setItemId(int dependingItemId){ this.itemId = dependingItemId; } }
/** * Copyright 2011-2021 Asakusa Framework Team. * * 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.asakusafw.lang.compiler.analyzer.util; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.lang.reflect.Type; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import org.junit.Test; /** * Test for {@link TypeInfo}. */ public class TypeInfoTest { /** * invoke {@code Object}. */ @Test public void invoke_object() { List<Type> invoked = TypeInfo.invoke(Object.class, String.class); assertThat(invoked.size(), is(0)); } /** * invoke direct parent. */ @Test public void invoke_parent() { List<Type> invoked = TypeInfo.invoke(ArrayList.class, StringList.class); assertThat(invoked.size(), is(1)); assertThat(invoked.get(0), is((Type) String.class)); } /** * invoke ancestor. */ @Test public void invoke_ancestor() { List<Type> invoked = TypeInfo.invoke(AbstractCollection.class, StringList.class); assertThat(invoked.size(), is(1)); assertThat(invoked.get(0), is((Type) String.class)); } /** * invoke interface. */ @Test public void invoke_interface() { List<Type> invoked = TypeInfo.invoke(List.class, StringList.class); assertThat(invoked.size(), is(1)); assertThat(invoked.get(0), is((Type) String.class)); } /** * invoke ancestor interface. */ @Test public void invoke_interface_ancestor() { List<Type> invoked = TypeInfo.invoke(Collection.class, StringList.class); assertThat(invoked.size(), is(1)); assertThat(invoked.get(0), is((Type) String.class)); } /** * invoke interface from interface. */ @Test public void invoke_interface_from_interface() { List<Type> invoked = TypeInfo.invoke(List.class, IStringList.class); assertThat(invoked.size(), is(1)); assertThat(invoked.get(0), is((Type) String.class)); } /** * invoke ancestor interface from interface. */ @Test public void invoke_interface_ancestor_from_interface() { List<Type> invoked = TypeInfo.invoke(Collection.class, IStringList.class); assertThat(invoked.size(), is(1)); assertThat(invoked.get(0), is((Type) String.class)); } /** * invoke unrelated. */ @Test public void invoke_unrelated() { List<Type> invoked = TypeInfo.invoke(Set.class, IStringList.class); assertThat(invoked, is(nullValue())); } /** * erase raw. */ @Test public void erase_raw() { assertThat(TypeInfo.erase(String.class), is((Object) String.class)); } /** * erase parameterized. */ @Test public void erase_parameterized() { assertThat(TypeInfo.erase(StringList.class.getGenericSuperclass()), is((Object) ArrayList.class)); } /** * of raw. */ @Test public void of_raw() { TypeInfo info = TypeInfo.of(String.class); assertThat(info.toString(), info.getRawType(), is((Object) String.class)); assertThat(info.getTypeArguments(), is(empty())); } /** * of raw. */ @Test public void of_parameterized() { TypeInfo info = TypeInfo.of(StringList.class.getGenericSuperclass()); assertThat(info.toString(), info.getRawType(), is((Object) ArrayList.class)); assertThat(info.getTypeArguments(), contains((Object) String.class)); assertThat(info.getErasedTypeArguments(), contains((Object) String.class)); } /** * of build. */ @Test public void of_build() { TypeInfo info = TypeInfo.of(List.class, Integer.class); assertThat(info.toString(), info.getRawType(), is((Object) List.class)); assertThat(info.getTypeArguments(), contains((Object) Integer.class)); assertThat(info.getErasedTypeArguments(), contains((Object) Integer.class)); } private static class StringList extends ArrayList<String> { private static final long serialVersionUID = 1L; } private interface IStringList extends List<String> { // no members } }
/* * Copyright 2016-2021 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.migrationhubstrategyrecommendations.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Rank of business goals based on priority. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/migrationhubstrategy-2020-02-19/PrioritizeBusinessGoals" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PrioritizeBusinessGoals implements Serializable, Cloneable, StructuredPojo { /** * <p> * Rank of business goals based on priority. * </p> */ private BusinessGoals businessGoals; /** * <p> * Rank of business goals based on priority. * </p> * * @param businessGoals * Rank of business goals based on priority. */ public void setBusinessGoals(BusinessGoals businessGoals) { this.businessGoals = businessGoals; } /** * <p> * Rank of business goals based on priority. * </p> * * @return Rank of business goals based on priority. */ public BusinessGoals getBusinessGoals() { return this.businessGoals; } /** * <p> * Rank of business goals based on priority. * </p> * * @param businessGoals * Rank of business goals based on priority. * @return Returns a reference to this object so that method calls can be chained together. */ public PrioritizeBusinessGoals withBusinessGoals(BusinessGoals businessGoals) { setBusinessGoals(businessGoals); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getBusinessGoals() != null) sb.append("BusinessGoals: ").append(getBusinessGoals()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PrioritizeBusinessGoals == false) return false; PrioritizeBusinessGoals other = (PrioritizeBusinessGoals) obj; if (other.getBusinessGoals() == null ^ this.getBusinessGoals() == null) return false; if (other.getBusinessGoals() != null && other.getBusinessGoals().equals(this.getBusinessGoals()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getBusinessGoals() == null) ? 0 : getBusinessGoals().hashCode()); return hashCode; } @Override public PrioritizeBusinessGoals clone() { try { return (PrioritizeBusinessGoals) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.migrationhubstrategyrecommendations.model.transform.PrioritizeBusinessGoalsMarshaller.getInstance().marshall(this, protocolMarshaller); } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.maven.webapp.handlers.artifact; import com.google.common.io.Files; import com.microsoft.azure.maven.deploytarget.DeployTarget; import com.microsoft.azure.maven.webapp.deploytarget.DeploymentSlotDeployTarget; import com.microsoft.azure.maven.webapp.deploytarget.WebAppDeployTarget; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ArtifactHandlerUtils { public static final String DEFAULT_APP_SERVICE_JAR_NAME = "app.jar"; /** * Interfaces WebApp && DeploymentSlot define their own warDeploy API separately. * Ideally, it should be defined in their base interface WebAppBase. * {@link com.microsoft.azure.management.appservice.WebAppBase} * Comparing to abstracting an adapter for WebApp && DeploymentSlot, we choose a lighter solution: * work around to get the real implementation of warDeploy. */ public static Runnable getRealWarDeployExecutor(final DeployTarget target, final File war, final String path) throws MojoExecutionException { if (target instanceof WebAppDeployTarget) { return new Runnable() { @Override public void run() { ((WebAppDeployTarget) target).warDeploy(war, path); } }; } if (target instanceof DeploymentSlotDeployTarget) { return new Runnable() { @Override public void run() { ((DeploymentSlotDeployTarget) target).warDeploy(war, path); } }; } throw new MojoExecutionException( "The type of deploy target is unknown, supported types are WebApp and DeploymentSlot."); } public static boolean performActionWithRetry(final Runnable runnable, final int maxRetryTimes, final Log log) { int retryCount = 0; while (retryCount < maxRetryTimes) { retryCount += 1; try { runnable.run(); return true; } catch (Exception e) { log.info(String.format("Exception occurred during deployment: %s, retry immediately(%d/%d)...", e.getMessage(), retryCount, maxRetryTimes)); } } return false; } public static String getContextPathFromFileName(final String stagingDirectoryPath, final String filePath) throws MojoExecutionException { if (StringUtils.isEmpty(stagingDirectoryPath)) { throw new MojoExecutionException( "Can not get the context path because the staging directory path is null or empty. ."); } if (StringUtils.isEmpty(filePath)) { throw new MojoExecutionException("Can not get the context path because the file path is null or empty"); } return Paths.get(stagingDirectoryPath).relativize(Paths.get(filePath).getParent()).toString(); } public static List<File> getArtifacts(final File directory) { final File[] files = directory.listFiles(); return Arrays.stream(files).filter(File::isFile).collect(Collectors.toList()); } public static boolean areAllWarFiles(final List<File> allArtifacts) { for (final File artifacts : allArtifacts) { if (!"war".equalsIgnoreCase(Files.getFileExtension(artifacts.getName()))) { return false; } } return true; } public static boolean hasWarFiles(final List<File> allArtifacts) { for (final File artifacts : allArtifacts) { if ("war".equalsIgnoreCase(Files.getFileExtension(artifacts.getName()))) { return true; } } return false; } }
/** * Copyright (C) 2011-2015 The XDocReport Team <xdocreport@googlegroups.com> * * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package fr.opensagres.poi.xwpf.converter.core.styles.paragraph; import java.math.BigInteger; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule.Enum; import fr.opensagres.poi.xwpf.converter.core.ParagraphLineSpacing; import fr.opensagres.poi.xwpf.converter.core.utils.DxaUtil; /** * <p> * 17.3.1.33 spacing (Spacing Between Lines and Above/Below Paragraph) This element specifies the inter-line and * inter-paragraph spacing which shall be applied to the contents of this paragraph when it is displayed by a consumer. * If this element is omitted on a given paragraph, each of its values is determined by the setting previously set at * any level of the style hierarchy (i.e. that previous setting remains unchanged). If this setting is never specified * in the style hierarchy, then the paragraph shall have no spacing applied to its lines, or above and below its * contents. [Example: Consider the following WordprocessingML paragraph: <w:pPr> <w:spacing w:after="200" w:line="276" * w:lineRule="auto" /> </w:pPr> This paragraph specifies that it must have at least 200 twentieths of a point after the * last line in each paragraph, and that the spacing in each line should be automatically calculated based on a 1.15 * times (276 divided by 240) the normal single spacing calculation. end example] * </p> */ public class ParagraphLineSpacingValueProvider extends AbstractSpacingParagraphValueProvider<ParagraphLineSpacing> { protected static final float LINE_SPACING_FACTOR = 240f; public static final ParagraphLineSpacingValueProvider INSTANCE = new ParagraphLineSpacingValueProvider(); @Override protected ParagraphLineSpacing getValue( CTSpacing spacing ) { // // spacing before // BigInteger before = spacing.getBefore(); // Float spaceBefore = null; // if ( before != null ) // { // spaceBefore = DxaUtil.dxa2points( before ); // } // // // spacing after // BigInteger after = spacing.getAfter(); // Float spaceAfter = null; // if ( after != null ) // { // spaceAfter = DxaUtil.dxa2points( after ); // } // line Float lineHeight = null; Float lineMultiple = null; BigInteger line = spacing.getLine(); if ( line == null ) { return null; } // Specifies how the spacing between lines is calculated as stored in the line attribute. Enum lineRule = spacing.getLineRule(); if ( lineRule == null ) { // If this attribute is omitted, then it shall be assumed to be of a value auto if a line attribute // value is present. lineRule = STLineSpacingRule.AUTO; } if ( lineRule == STLineSpacingRule.AUTO ) { // The lineRule attribute value of auto specifies that the value of the line attribute is to be // interpreted in 240ths of a single line height lineMultiple = line.floatValue() / LINE_SPACING_FACTOR; } else { lineHeight = DxaUtil.dxa2points( line ); } return new ParagraphLineSpacing( null, null, lineHeight, lineMultiple ); } }
/** * Copyright 2007-2016, 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.gateway.transport.wseb.filter; import static org.kaazing.gateway.transport.bridge.CachingMessageEncoder.IO_MESSAGE_ENCODER; import java.nio.ByteBuffer; import java.util.Arrays; import org.kaazing.gateway.transport.bridge.CachingMessageEncoder; import org.kaazing.gateway.transport.ws.WsMessage; import org.kaazing.gateway.transport.ws.WsPingMessage; import org.kaazing.gateway.transport.ws.WsPongMessage; import org.kaazing.gateway.transport.ws.util.WsUtils; import org.kaazing.mina.core.buffer.IoBufferAllocatorEx; import org.kaazing.mina.core.buffer.IoBufferEx; import org.kaazing.mina.netty.util.threadlocal.VicariousThreadLocal; public class WsebFrameEscapeZeroAndNewLineEncoder extends WsebFrameEncoder { static protected final int cacheSize = 1024; //cache size when read direct ByteBuffer static final byte BINARY_TYPE_BYTE = (byte) 0x80; static final byte SPECIFIED_LENGTH_TEXT_TYPE_BYTE = (byte) 0x81; private static final byte[] EMPTY_PING_BYTES = new byte[]{(byte)0x89, (byte)0x7f, (byte)0x30}; //escaped private static final byte[] EMPTY_PONG_BYTES = new byte[]{(byte)0x8A, (byte)0x7f, (byte)0x30}; //escaped public WsebFrameEscapeZeroAndNewLineEncoder(IoBufferAllocatorEx<?> allocator) { this(IO_MESSAGE_ENCODER, allocator); } public WsebFrameEscapeZeroAndNewLineEncoder(CachingMessageEncoder cachingEncoder, IoBufferAllocatorEx<?> allocator) { super(cachingEncoder, allocator); } protected final ThreadLocal<byte[]> readCacheRef = new VicariousThreadLocal<byte[]>() { @Override protected byte[] initialValue() { return new byte[cacheSize]; } }; private final ThreadLocal<byte[]> writeCacheRef = new VicariousThreadLocal<byte[]>() { @Override protected byte[] initialValue() { return new byte[cacheSize * 2]; } }; private IoBufferEx escapeZeroAndNewLine(IoBufferAllocatorEx<?> allocator, int flags, IoBufferEx decoded, ByteBuffer prefix) { if (decoded.hasArray()) { return escapeZeroAndNewLineWithHeap(allocator, flags, decoded, prefix); } else { return escapeZeroAndNewLineWithDirect(allocator, flags, decoded, prefix); } } private IoBufferEx escapeZeroAndNewLineWithDirect(IoBufferAllocatorEx<?> allocator, int flags, IoBufferEx decoded, ByteBuffer prefix) { byte[] readCache = readCacheRef.get(); byte[] writeCache = writeCacheRef.get(); final int decodedInitialPosition = decoded.position(); final int decodedLimit = decoded.limit(); ByteBuffer encodedBuf = null; int[] encodedArrayInsertionCount = new int[1]; ByteBuffer emptyArray = ByteBuffer.allocate(0); //pass an empty array as prefix while(decoded.hasRemaining()) { int bytesToRead = decoded.remaining(); if (bytesToRead > cacheSize) { bytesToRead = cacheSize; } // read data from decoded buffer decoded.get(readCache, 0, bytesToRead); // escape encode encodedArrayInsertionCount[0] = 0; doEscapeZeroAndNewline(readCache, 0, 0, bytesToRead, writeCache, encodedArrayInsertionCount, emptyArray); // write data to encodedBuffer if (encodedBuf == null && encodedArrayInsertionCount[0] > 0) { int currentPosition = decoded.position(); //first escaped char found, allocate decodedBuf now, maximam size is (read so far + insertedCount + 2 * remaining data ) int totalSize = prefix.remaining() + currentPosition - decodedInitialPosition + encodedArrayInsertionCount[0]; //read so far + insertedCount totalSize += 2 * decoded.remaining(); encodedBuf = ByteBuffer.allocateDirect(totalSize); encodedBuf.put(prefix); //copy data has been read from previous loops if (currentPosition > cacheSize) { //set position and limit to previously read range decoded.position(decodedInitialPosition); decoded.limit(currentPosition - bytesToRead); encodedBuf.put(decoded.buf()); //move position and limit back decoded.limit(decodedLimit); decoded.position(currentPosition); } } // now put this block if we have found escape char if (encodedBuf != null) { encodedBuf.put(writeCache, 0, bytesToRead + encodedArrayInsertionCount[0]); } // move to next block } if (encodedBuf != null) { encodedBuf.flip(); return allocator.wrap(encodedBuf); } //no escape char found, return prefix + decodedBuf decoded.position(decodedInitialPosition); decoded.limit(decodedLimit); encodedBuf = ByteBuffer.allocateDirect(prefix.remaining() + decoded.remaining()); encodedBuf.put(prefix); encodedBuf.put(decoded.buf()); encodedBuf.flip(); return allocator.wrap(encodedBuf); } private IoBufferEx escapeZeroAndNewLineWithHeap(IoBufferAllocatorEx<?> allocator, int flags, IoBufferEx decoded, ByteBuffer prefix) { byte[] decodedArray = decoded.array(); final int decodedArrayOffset = decoded.arrayOffset(); int decodedArrayPosition = decodedArrayOffset + decoded.position(); final int decodedArrayInitialPosition = decodedArrayPosition; final int decodedArrayLimit = decodedArrayOffset + decoded.limit(); int[] encodedArrayInsertionCount = new int[1]; byte[] encodedArray = null; encodedArray = doEscapeZeroAndNewline(decodedArray, decodedArrayInitialPosition, decodedArrayInitialPosition, decodedArrayLimit, encodedArray, encodedArrayInsertionCount, prefix); if (encodedArray != null) { return allocator.wrap(ByteBuffer.wrap(encodedArray, decodedArrayInitialPosition, prefix.remaining() + decoded.remaining() + encodedArrayInsertionCount[0])); } else { encodedArray = Arrays.copyOf(prefix.array(), prefix.remaining() + decoded.remaining()); System.arraycopy(decodedArray, decodedArrayInitialPosition, encodedArray, prefix.remaining(), decoded.remaining()); return allocator.wrap(ByteBuffer.wrap(encodedArray)); } } // quick calculate WsebFrame prefix bytes protected ByteBuffer calculatePrefixBytes(int payloadLength, byte opCode) { int totalOffset = 2 + WsUtils.calculateEncodedLengthSize(payloadLength); ByteBuffer binary = ByteBuffer.allocate(totalOffset); binary.put(opCode); WsUtils.encodeLength(binary, payloadLength); //the only possible escaped byte in prefix bytes is the last byte switch(binary.get(binary.position() - 1)) { case 0x00: binary.put(binary.position() - 1,(byte) 0x7f); binary.put((byte) 0x30); break; case 0x0a: binary.put(binary.position() - 1,(byte) 0x7f); binary.put((byte) 0x6e); break; case 0x0d: binary.put(binary.position() - 1,(byte) 0x7f); binary.put((byte) 0x72); break; case 0x7f: binary.put(binary.position() - 1,(byte) 0x7f); binary.put((byte) 0x7f); break; } binary.flip(); return binary; } // insert escape characters into encodedArray, return number of inserted bytes private byte[] doEscapeZeroAndNewline(byte[] decodedArray,int decodedArrayOffset, int decodedArrayPosition,int decodedArrayLimit, byte[] encodedArray, int[] encodedArrayInsertionCount, ByteBuffer prefix) { int prefixLength = prefix.remaining(); for (; decodedArrayPosition < decodedArrayLimit; decodedArrayPosition++) { byte decodedValue = decodedArray[decodedArrayPosition]; switch (decodedValue) { case 0x00: // null byte, requires multi-byte escaped representation encodedArray = supplyEncodedArray(decodedArray,decodedArrayOffset, decodedArrayPosition, decodedArrayLimit, encodedArray, encodedArrayInsertionCount, prefix); // 0x00 -> 0x7f 0x30 ('0') encodedArray[decodedArrayPosition + encodedArrayInsertionCount[0] + prefixLength] = 0x7f; encodedArrayInsertionCount[0]++; encodedArray[decodedArrayPosition + encodedArrayInsertionCount[0] + prefixLength] = 0x30; // advance to next byte continue; case 0x0a: // newline byte, requires multi-byte escaped representation encodedArray = supplyEncodedArray(decodedArray, decodedArrayOffset, decodedArrayPosition, decodedArrayLimit, encodedArray, encodedArrayInsertionCount, prefix); // 0x0a -> 0x7f 0x6e ('n') encodedArray[decodedArrayPosition + encodedArrayInsertionCount[0] + prefixLength] = 0x7f; encodedArrayInsertionCount[0]++; encodedArray[decodedArrayPosition + encodedArrayInsertionCount[0] + prefixLength] = 0x6e; // advance to next byte continue; case 0x0d: // carriage return byte, requires multi-byte escaped // representation encodedArray = supplyEncodedArray(decodedArray, decodedArrayOffset, decodedArrayPosition, decodedArrayLimit, encodedArray, encodedArrayInsertionCount, prefix); // 0x0d -> 0x7f 0x72 ('r') encodedArray[decodedArrayPosition + encodedArrayInsertionCount[0] + prefixLength] = 0x7f; encodedArrayInsertionCount[0]++; encodedArray[decodedArrayPosition + encodedArrayInsertionCount[0] + prefixLength] = 0x72; // advance to next byte continue; case 0x7f: // escape prefix byte, requires multi-byte escaped // representation encodedArray = supplyEncodedArray(decodedArray, decodedArrayOffset, decodedArrayPosition, decodedArrayLimit, encodedArray, encodedArrayInsertionCount, prefix); // 0x7f -> 0x7f 0x7f encodedArray[decodedArrayPosition + encodedArrayInsertionCount[0] + prefixLength] = 0x7f; encodedArrayInsertionCount[0]++; encodedArray[decodedArrayPosition + encodedArrayInsertionCount[0] + prefixLength] = 0x7f; // advance to next byte continue; default: if (encodedArray != null) { // not escaping character, copy this byte to encodedValue encodedArray[decodedArrayPosition + encodedArrayInsertionCount[0] + prefixLength] = decodedValue; } continue; } } return encodedArray; } private static byte[] supplyEncodedArray(byte[] decodedArray, int decodedArrayOffset, int decodedArrayPosition, int decodedArrayLimit, byte[] encodedArray, int[] encodedArrayInsertionCount, ByteBuffer prefix) { if (encodedArray == null) { int decodedRemaining = decodedArrayLimit - decodedArrayPosition; encodedArray = new byte[decodedArrayPosition + decodedRemaining * 2 + prefix.remaining()]; } if (encodedArrayInsertionCount[0] == 0) { //first escaped character encounter, copy read bytes until first escape byte System.arraycopy(prefix.array(), 0, encodedArray, decodedArrayOffset, prefix.remaining()); //copy prefix System.arraycopy(decodedArray, decodedArrayOffset, encodedArray, decodedArrayOffset + prefix.remaining(), decodedArrayPosition - decodedArrayOffset); //copy previous } return encodedArray; } private IoBufferEx doEncode(IoBufferAllocatorEx<?> allocator, int flags, IoBufferEx ioBuf, byte opCode) { ByteBuffer prefix = calculatePrefixBytes(ioBuf.buf().remaining(), opCode); return escapeZeroAndNewLine(allocator, flags, ioBuf, prefix); } @Override protected IoBufferEx doTextEncode(IoBufferAllocatorEx<?> allocator, int flags, WsMessage message) { return doEncode(allocator, flags, message.getBytes(), SPECIFIED_LENGTH_TEXT_TYPE_BYTE); } @Override protected IoBufferEx doBinaryEncode(IoBufferAllocatorEx<?> allocator, int flags, WsMessage message) { return doEncode(allocator, flags, message.getBytes(), BINARY_TYPE_BYTE); } @Override protected IoBufferEx doPingEncode(IoBufferAllocatorEx<?> allocator, int flags, WsMessage message) { WsPingMessage ping = (WsPingMessage)message; assert ping.getBytes().remaining() == 0 : "PING with payload not supported"; ByteBuffer text = allocator.allocate(EMPTY_PING_BYTES.length, flags); int offset = text.position(); text.put(EMPTY_PING_BYTES); text.flip(); text.position(offset); return allocator.wrap(text, flags); } @Override protected IoBufferEx doPongEncode(IoBufferAllocatorEx<?> allocator, int flags, WsMessage message) { WsPongMessage ping = (WsPongMessage)message; assert ping.getBytes().remaining() == 0 : "PONG with payload not supported"; ByteBuffer text = allocator.allocate(EMPTY_PONG_BYTES.length, flags); int offset = text.position(); text.put(EMPTY_PONG_BYTES); text.flip(); text.position(offset); return allocator.wrap(text, flags); } }
/* * JFLAP - Formal Languages and Automata Package * * * Susan H. Rodger * Computer Science Department * Duke University * August 27, 2009 * Copyright (c) 2002-2009 * All rights reserved. * JFLAP is open source software. Please see the LICENSE for terms. * */ package edu.duke.cs.jflap.file.xml; import java.io.Serializable; import java.util.ArrayList; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.google.common.collect.Lists; import edu.duke.cs.jflap.pumping.RegularPumpingLemma; /** * This is the transducer for encoding and decoding * {@link edu.duke.cs.jflap.pumping.RegularPumpingLemma} objects. * * @author Jinghui Lim * @see edu.duke.cs.jflap.gui.pumping.PumpingLemmaChooser * */ public class RegPumpingLemmaTransducer extends PumpingLemmaTransducer { /** * The type of pumping lemma. */ public static String TYPE = "regular pumping lemma"; /** * The tag for the length of <i>x</i>. */ public static String X_NAME = "xLength"; /** * The tag for the length of <i>y</i>. */ public static String Y_NAME = "yLength"; @Override public Serializable fromDOM(final Document document) { final RegularPumpingLemma pl = (RegularPumpingLemma) PumpingLemmaFactory.createPumpingLemma(TYPE, document.getElementsByTagName(LEMMA_NAME).item(0).getTextContent()); // Decode m, w, & i. pl.setM(Integer.parseInt(document.getElementsByTagName(M_NAME).item(0).getTextContent())); pl.setW(document.getElementsByTagName(W_NAME).item(0).getTextContent()); pl.setI(Integer.parseInt(document.getElementsByTagName(I_NAME).item(0).getTextContent())); // Decode the attempts final NodeList attempts = document.getDocumentElement().getElementsByTagName(ATTEMPT); for (int i = 0; i < attempts.getLength(); i++) { pl.addAttempt(attempts.item(i).getTextContent()); } // Decode the first player. pl.setFirstPlayer(document.getElementsByTagName(FIRST_PLAYER).item(0).getTextContent()); // Decode the decomposition. final int xLength = Integer.parseInt(document.getElementsByTagName(X_NAME).item(0).getTextContent()); final int yLength = Integer.parseInt(document.getElementsByTagName(Y_NAME).item(0).getTextContent()); pl.setDecomposition(Lists.newArrayList(xLength, yLength)); return pl; } @Override public String getType() { return TYPE; } @Override public Document toDOM(final Serializable structure) { final RegularPumpingLemma pl = (RegularPumpingLemma) structure; final Document doc = newEmptyDocument(); final Element elem = doc.getDocumentElement(); elem.appendChild(createElement(doc, LEMMA_NAME, null, pl.getTitle())); elem.appendChild(createElement(doc, FIRST_PLAYER, null, pl.getFirstPlayer())); elem.appendChild(createElement(doc, M_NAME, null, "" + pl.getM())); elem.appendChild(createElement(doc, W_NAME, null, "" + pl.getW())); elem.appendChild(createElement(doc, I_NAME, null, "" + pl.getI())); elem.appendChild(createElement(doc, X_NAME, null, "" + pl.getX().length())); elem.appendChild(createElement(doc, Y_NAME, null, "" + pl.getY().length())); // Encode the list of attempts. final ArrayList<?> attempts = pl.getAttempts(); if (attempts != null && attempts.size() > 0) { for (int i = 0; i < attempts.size(); i++) { elem.appendChild(createElement(doc, ATTEMPT, null, (String) attempts.get(i))); } } return doc; } }
/* * 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 hivemall.tools.matrix; import hivemall.utils.hadoop.WritableUtils; import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator; import org.apache.hadoop.hive.ql.udf.generic.SimpleGenericUDAFParameterInfo; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.junit.Assert; import org.junit.Test; public class TransposeAndDotUDAFTest { @Test public void test() throws Exception { final TransposeAndDotUDAF tad = new TransposeAndDotUDAF(); final double[][] matrix0 = new double[][] { {1, -2}, {-1, 3}}; final double[][] matrix1 = new double[][] { {1, 2}, {3, 4}}; final ObjectInspector[] OIs = new ObjectInspector[] { ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.writableDoubleObjectInspector), ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)}; final GenericUDAFEvaluator evaluator = tad.getEvaluator(new SimpleGenericUDAFParameterInfo( OIs, false, false)); evaluator.init(GenericUDAFEvaluator.Mode.PARTIAL1, OIs); TransposeAndDotUDAF.TransposeAndDotUDAFEvaluator.TransposeAndDotAggregationBuffer agg = (TransposeAndDotUDAF.TransposeAndDotUDAFEvaluator.TransposeAndDotAggregationBuffer) evaluator.getNewAggregationBuffer(); evaluator.reset(agg); for (int i = 0; i < matrix0.length; i++) { evaluator.iterate(agg, new Object[] {WritableUtils.toWritableList(matrix0[i]), WritableUtils.toWritableList(matrix1[i])}); } final double[][] answer = new double[][] { {-2.0, -2.0}, {7.0, 8.0}}; for (int i = 0; i < answer.length; i++) { Assert.assertArrayEquals(answer[i], agg.aggMatrix[i], 0.d); } } }
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the “License”). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.client.concurrent; import org.junit.Assert; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * A set of utility methods for testing concurrency. */ public final class ConcurrencyTestUtils { private ConcurrencyTestUtils() {} // prevent instantiation /** * Tests the current operations of a list of runnables. Run all the operations at the same time to * maximize the chances of triggering a multithreading code error. Suggested by junit team at * https://github.com/junit-team/junit/wiki/Multithreaded-code-and-concurrency. * * @param runnables * @param maxTimeoutSeconds * @throws InterruptedException */ public static void assertConcurrent(final List<? extends Runnable> runnables, final int maxTimeoutSeconds) throws InterruptedException { final int numThreads = runnables.size(); final List<Throwable> exceptions = Collections.synchronizedList(new ArrayList<Throwable>()); final ExecutorService threadPool = Executors.newFixedThreadPool(numThreads); try { final CountDownLatch allExecutorThreadsReady = new CountDownLatch(numThreads); final CountDownLatch afterInitBlocker = new CountDownLatch(1); final CountDownLatch allDone = new CountDownLatch(numThreads); for (final Runnable submittedTestRunnable : runnables) { threadPool.submit(new Runnable() { @Override public void run() { allExecutorThreadsReady.countDown(); try { afterInitBlocker.await(); submittedTestRunnable.run(); } catch (final Throwable e) { exceptions.add(e); } finally { allDone.countDown(); } } }); } // wait until all threads are ready Assert.assertTrue("Timeout initializing threads!", allExecutorThreadsReady.await(runnables.size() * 10, TimeUnit.MILLISECONDS)); // start all test runners afterInitBlocker.countDown(); Assert.assertTrue("Timeout! More than " + maxTimeoutSeconds + " seconds", allDone.await(maxTimeoutSeconds, TimeUnit.SECONDS)); } finally { threadPool.shutdownNow(); } Assert.assertTrue("Failed with exception(s) " + exceptions, exceptions.isEmpty()); } }
/* * Copyright 2016 KairosDB 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.kairosdb.datastore.h2.orm; /** This class has been automatically generated by GenORMous. This file is for adding custom code to. This file will not be regenerated once it exists. */ public class MetricNamesData extends MetricNamesQuery.Record { public MetricNamesData(MetricNamesQuery query, java.sql.ResultSet resultSet) throws java.sql.SQLException { query.super(resultSet); } }
package mekanism.common.inventory.container.item; import java.util.List; import javax.annotation.Nonnull; import mekanism.api.inventory.IInventorySlot; import mekanism.common.inventory.InventoryPersonalChest; import mekanism.common.inventory.container.slot.HotBarSlot; import mekanism.common.item.block.ItemBlockPersonalChest; import mekanism.common.registries.MekanismContainerTypes; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.container.ClickType; import net.minecraft.inventory.container.Slot; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketBuffer; import net.minecraft.util.Hand; public class PersonalChestItemContainer extends MekanismItemContainer { private InventoryPersonalChest itemInventory; public PersonalChestItemContainer(int id, PlayerInventory inv, Hand hand, ItemStack stack) { super(MekanismContainerTypes.PERSONAL_CHEST_ITEM, id, inv, hand, stack); } public PersonalChestItemContainer(int id, PlayerInventory inv, PacketBuffer buf) { this(id, inv, buf.readEnumValue(Hand.class), getStackFromBuffer(buf, ItemBlockPersonalChest.class)); } @Override protected void addSlotsAndOpen() { //We have to initialize this before actually adding the slots itemInventory = new InventoryPersonalChest(stack); super.addSlotsAndOpen(); } @Override protected void addSlots() { super.addSlots(); //Get all the inventory slots the tile has List<IInventorySlot> inventorySlots = itemInventory.getInventorySlots(null); for (IInventorySlot inventorySlot : inventorySlots) { Slot containerSlot = inventorySlot.createContainerSlot(); if (containerSlot != null) { addSlot(containerSlot); } } } public Hand getHand() { return hand; } @Override protected int getInventoryYOffset() { return 148; } @Override protected HotBarSlot createHotBarSlot(@Nonnull PlayerInventory inv, int index, int x, int y) { // special handling to prevent removing the personal chest from the player's inventory slot if (index == inv.currentItem && hand == Hand.MAIN_HAND) { return new HotBarSlot(inv, index, x, y) { @Override public boolean canTakeStack(@Nonnull PlayerEntity player) { return false; } }; } return super.createHotBarSlot(inv, index, x, y); } @Nonnull @Override public ItemStack slotClick(int slotId, int dragType, @Nonnull ClickType clickType, @Nonnull PlayerEntity player) { if (clickType == ClickType.SWAP) { if (hand == Hand.OFF_HAND && dragType == 40) { //Block pressing f to swap it when it is in the offhand return ItemStack.EMPTY; } else if (hand == Hand.MAIN_HAND && dragType >= 0 && dragType < PlayerInventory.getHotbarSize()) { //Block taking out of the selected slot (we don't validate we have a hotbar slot as we always should for this container) if (!hotBarSlots.get(dragType).canTakeStack(player)) { return ItemStack.EMPTY; } } } return super.slotClick(slotId, dragType, clickType, player); } }
/** * Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3.0 of the License, or * (at your option) any later version. * * EvoSuite is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.graphs.cfg; import org.objectweb.asm.tree.AbstractInsnNode; public class BytecodeInstructionFactory { /** * <p> * createBytecodeInstruction * </p> * * @param className * a {@link java.lang.String} object. * @param methodName * a {@link java.lang.String} object. * @param instructionId * a int. * @param bytecodeOffset * a int. * @param node * a {@link org.objectweb.asm.tree.AbstractInsnNode} object. * @return a {@link org.evosuite.graphs.cfg.BytecodeInstruction} object. */ public static BytecodeInstruction createBytecodeInstruction(ClassLoader classLoader, String className, String methodName, int instructionId, int bytecodeOffset, AbstractInsnNode node) { BytecodeInstruction instruction = new BytecodeInstruction(classLoader, className, methodName, instructionId, bytecodeOffset, node); return instruction; } }
package com.ruoyi.web.netty.hj212.streamReader.core; import com.ruoyi.web.netty.hj212.streamReader.base.MapEntryStepGenerator; import com.ruoyi.web.netty.hj212.streamReader.base.lambda.RunnableWithThrowable; import com.ruoyi.web.netty.hj212.streamReader.base.lambda.SupplierWithThrowable; import java.io.IOException; import java.io.PushbackReader; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; import java.util.function.Supplier; import static com.ruoyi.web.netty.hj212.streamReader.core.ReaderMatch.*; public class MultipleCharMatch<ParentStream extends ReaderStream> implements ReaderMatch<MultipleCharMatch<ParentStream>,ParentStream,char[]> { private ParentStream parentStream; private PushbackReader reader; private int count; private boolean alwaysRollBack = false; private Map<Predicate<char[]>, SupplierWithThrowable<Optional<Object>,IOException>> map; private MapEntryStepGenerator<Predicate<char[]>,SupplierWithThrowable<Optional<Object>,IOException>> generator; public MultipleCharMatch(ParentStream parentStream, int count) { this.parentStream = parentStream; this.reader = parentStream.reader(); this.count = count; this.map = new LinkedHashMap<>(); MapEntryStepGenerator.Builder<Predicate<char[]>,SupplierWithThrowable<Optional<Object>,IOException>> builder = MapEntryStepGenerator.builder(); this.generator = builder.consumer((k,v) -> map.put(k,v)) .keyDefault(() -> character -> false) .keyMergeOperator(Predicate::or) .valueMergeOperator((thisRunnable,runnable) -> () -> { Optional<Object> o = thisRunnable.get(); if(!o.isPresent()){ o = runnable.get(); } return o; }) .create(); } /** * 当符合条件时 * @param predicate 条件 * @return THIS */ public MultipleCharMatch<ParentStream> when(Predicate<char[]> predicate) { generator.putKey(predicate); return this; } /** * 当字符一致时 * @param characters 字符 * @return THIS */ public MultipleCharMatch<ParentStream> when(char... characters) { generator.putKey((ca) -> Arrays.equals(ca,characters)); return this; } // public ReaderStream<MultipleCharMatch<ParentStream>> when() { // ReaderStream<MultipleCharMatch<ParentStream>> stream = new ReaderStream<>( // this.reader, // this.parentStream.bufSize() -1, // this); // generator.putKey((ca) -> { // try { // return stream.core().isPresent(); // } catch (IOException e) { // e.printStackTrace(); // } // }); // return stream; // } public MultipleCharMatch<ParentStream> then(Supplier<IOException> exceptionSupplier) { generator.putValue(() -> { throw exceptionSupplier.get(); }); return this; } public MultipleCharMatch<ParentStream> then(SupplierWithThrowable<Optional<Object>,IOException> runnable) { generator.putValue(runnable); return this; } public MultipleCharMatch<ParentStream> then(RunnableWithThrowable<IOException> runnable) { generator.putValue(alwaysReturnPresent(runnable)); return this; } public ReaderStream<MultipleCharMatch<ParentStream>> then() { ReaderStream<MultipleCharMatch<ParentStream>> reader = new ReaderStream<>( this.reader, this.parentStream.bufSize() -1, this); then(reader::match); return reader; } /** * * @return */ @Override public ParentStream done() { generator.generate(); return parentStream; } /** * 中断 * @return */ public ParentStream stop(){ return done(); } /** * 回滚 * @return */ public ParentStream back(){ alwaysRollBack = true; return done(); } @Override public Optional<char[]> match() throws IOException { char[] chars = new char[count]; //noinspection ResultOfMethodCallIgnored reader.read(chars); Optional<SupplierWithThrowable<Optional<Object>,IOException>> r = map.entrySet().stream() .filter(kv -> kv.getKey().test(chars)) .map(Map.Entry::getValue) .findAny(); if(r.isPresent()){ if(r.get().get().isPresent() && !alwaysRollBack){ //必须运行成功才不会回滚 return Optional.of(chars); } } // if(r.isPresent()){ // r.get().get(); // return Optional.of(chars); // } //回滚 reader.unread(chars); return Optional.empty(); } @Override public String toString() { return parentStream.toString() + "/" + this.getClass().getSimpleName() + "(" + map.size() + ")"; } }
package cn.edu.hit.spat.system.mapper; import cn.edu.hit.spat.system.entity.UserRole; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * @author MrBird */ public interface UserRoleMapper extends BaseMapper<UserRole> { }
package slimeknights.tconstruct.library.recipe.casting.material; import com.google.gson.JsonObject; import lombok.Getter; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.GsonHelper; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.Level; import net.minecraft.world.level.material.Fluid; import net.minecraftforge.fluids.FluidStack; import slimeknights.mantle.recipe.FluidIngredient; import slimeknights.mantle.recipe.ICustomOutputRecipe; import slimeknights.tconstruct.common.recipe.LoggingRecipeSerializer; import slimeknights.tconstruct.library.MaterialRegistry; import slimeknights.tconstruct.library.materials.IMaterial; import slimeknights.tconstruct.library.materials.MaterialId; import slimeknights.tconstruct.library.recipe.RecipeTypes; import slimeknights.tconstruct.library.tinkering.IMaterialItem; import slimeknights.tconstruct.smeltery.TinkerSmeltery; import slimeknights.tconstruct.smeltery.recipe.ICastingInventory; import javax.annotation.Nullable; import java.util.List; /** Recipe defining casting and composite fluids for a given input */ public class MaterialFluidRecipe implements ICustomOutputRecipe<ICastingInventory> { @Getter private final ResourceLocation id; private final FluidIngredient fluid; @Getter private final int temperature; /** Material base for composite */ @Getter @Nullable private final MaterialId inputId; /** Output material ID */ @Getter private final MaterialId outputId; /** Cached input material */ private IMaterial input; /** Cached output material */ private IMaterial output; public MaterialFluidRecipe(ResourceLocation id, FluidIngredient fluid, int temperature, @Nullable MaterialId inputId, MaterialId outputId) { this.id = id; this.fluid = fluid; this.temperature = temperature; this.inputId = inputId; this.outputId = outputId; MaterialCastingLookup.registerFluid(this); } /** Checks if the recipe matches the given inventory */ public boolean matches(ICastingInventory inv) { if (!fluid.test(inv.getFluid())) { return false; } if (inputId != null) { ItemStack stack = inv.getStack(); return !stack.isEmpty() && IMaterialItem.getMaterialFromStack(stack) == getInput(); } return true; } /** Gets the amount of fluid to cast this recipe */ public int getFluidAmount(Fluid fluid) { return this.fluid.getAmount(fluid); } /** Gets the material output for this recipe */ public IMaterial getOutput() { if (output == null) { output = MaterialRegistry.getMaterial(outputId); } return output; } /** Gets the material input for this recipe */ @Nullable public IMaterial getInput() { if (input == null && inputId != null) { input = MaterialRegistry.getMaterial(inputId); } return input; } /** Gets a list of fluids for display */ public List<FluidStack> getFluids() { return fluid.getFluids(); } @Override public final boolean matches(ICastingInventory inv, Level worldIn) { return matches(inv); } @Override public RecipeSerializer<?> getSerializer() { return TinkerSmeltery.materialFluidRecipe.get(); } @Override public RecipeType<?> getType() { return RecipeTypes.DATA; } public static class Serializer extends LoggingRecipeSerializer<MaterialFluidRecipe> { @Override public MaterialFluidRecipe fromJson(ResourceLocation id, JsonObject json) { FluidIngredient fluid = FluidIngredient.deserialize(json, "fluid"); int temperature = GsonHelper.getAsInt(json, "temperature"); MaterialId input = null; if (json.has("input")) { input = new MaterialId(GsonHelper.getAsString(json, "input")); } MaterialId output = new MaterialId(GsonHelper.getAsString(json, "output")); return new MaterialFluidRecipe(id, fluid, temperature, input, output); } @Nullable @Override protected MaterialFluidRecipe readSafe(ResourceLocation id, FriendlyByteBuf buffer) { FluidIngredient fluid = FluidIngredient.read(buffer); int temperature = buffer.readInt(); MaterialId input = null; if (buffer.readBoolean()) { input = new MaterialId(buffer.readUtf(Short.MAX_VALUE)); } MaterialId output = new MaterialId(buffer.readUtf(Short.MAX_VALUE)); return new MaterialFluidRecipe(id, fluid, temperature, input, output); } @Override protected void writeSafe(FriendlyByteBuf buffer, MaterialFluidRecipe recipe) { recipe.fluid.write(buffer); buffer.writeInt(recipe.temperature); if (recipe.inputId != null) { buffer.writeBoolean(true); buffer.writeUtf(recipe.inputId.toString()); } else { buffer.writeBoolean(false); } buffer.writeUtf(recipe.outputId.toString()); } } }
package com.apachetune.httpserver.ui.updating.impl; import com.apachetune.httpserver.ui.updating.OpenWebPageHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.*; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import static com.apachetune.core.utils.Utils.createRuntimeException; /** * FIXDOC */ public class OpenWebPageHelperImpl implements OpenWebPageHelper { private static final Logger logger = LoggerFactory.getLogger(OpenWebPageHelper.class); @Override public final void openWebPage(URL location) { try { Desktop.getDesktop().browse(location.toURI()); } catch (IOException e) { logger.error("Error during open a web page.", e); //NON-NLS } catch (URISyntaxException e) { throw createRuntimeException(e); } } }
package com.robothand.highqualitybot.command; import com.robothand.highqualitybot.Config; import com.robothand.highqualitybot.music.GuildMusicPlayer; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.MessageChannel; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import java.util.Queue; /** * QueueCommand.java * Lists up to 10 songs in the player's queue, as well as the total number of tracks. */ public class QueueCommand extends Command { @Override public String[] getNames() { return new String[] {"list", "queue"}; } @Override public String getDescription() { return "Prints out a list of all songs currently in the music queue.\n" + "Usage: " + Config.PREFIX + "list"; } @Override public String getShortDesc() { return "List all of the songs currently in the queue."; } @Override public void execute(MessageReceivedEvent event, String[] args) { GuildMusicPlayer musicPlayer; Guild guild = event.getGuild(); MessageChannel channel = event.getChannel(); StringBuilder message = new StringBuilder(); musicPlayer = GuildMusicPlayer.getPlayer(guild); Queue<AudioTrack> queue = musicPlayer.getQueue(); if (queue.isEmpty()) { log.debug("{}: queue is empty, doing nothing", guild.getName()); message.append("The queue is empty!"); } else { message.append("Now Playing: **").append(musicPlayer.getPlayingTrack().getInfo().title).append("**\n"); message.append("Current Queue (").append(queue.size()).append(" tracks):\n"); int currentTrack = 1; for (AudioTrack track : queue) { message.append(currentTrack).append(". ").append(track.getInfo().title).append("\n"); if (currentTrack++ > 10) { break; } } } channel.sendMessage(message.toString()).queue(); } }
/* * Copyright (c) 2011-2018, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.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 boofcv.gui.d3; import boofcv.gui.BoofSwingUtil; import boofcv.visualize.PointCloudViewer; import georegression.struct.ConvertFloatType; import georegression.struct.point.Point3D_F64; import georegression.struct.se.Se3_F32; import georegression.struct.se.Se3_F64; import org.ddogleg.struct.GrowQueue_F32; import org.ddogleg.struct.GrowQueue_I32; import javax.swing.*; import java.util.List; /** * Wrapper around {@link PointCloudViewerPanelSwing} for {@link PointCloudViewer}. * * @author Peter Abeles */ public class PointCloudViewerSwing implements PointCloudViewer { PointCloudViewerPanelSwing panel; public PointCloudViewerSwing() { panel = new PointCloudViewerPanelSwing((float)60,(float)1.0 ); } @Override public void setShowAxis(boolean show) { // Not implemented yet. Doing correctly is a bit of work. Need to compute the 3D location of each rendered // point on a line } @Override public void setTranslationStep(double step) { BoofSwingUtil.invokeNowOrLater(()->panel.stepSize = (float)step); } @Override public void setDotSize(int pixels) { BoofSwingUtil.invokeNowOrLater(()->panel.setDotRadius(pixels)); } @Override public void setClipDistance(double distance) { BoofSwingUtil.invokeNowOrLater(()->panel.maxRenderDistance = (float)distance); } @Override public void setFog(boolean active) { BoofSwingUtil.invokeNowOrLater(()->panel.fog = active); } @Override public void setBackgroundColor(int rgb) { BoofSwingUtil.invokeNowOrLater(()->panel.backgroundColor=rgb); } @Override public void addCloud(List<Point3D_F64> cloudXyz, int[] colorsRgb) { if( cloudXyz.size() > colorsRgb.length ) { throw new IllegalArgumentException("Number of points do not match"); } if( SwingUtilities.isEventDispatchThread() ) { for (int i = 0; i < cloudXyz.size(); i++) { Point3D_F64 p = cloudXyz.get(i); panel.addPoint((float) p.x, (float) p.y, (float) p.z, colorsRgb[i]); } } else { SwingUtilities.invokeLater(() -> { for (int i = 0; i < cloudXyz.size(); i++) { Point3D_F64 p = cloudXyz.get(i); panel.addPoint((float) p.x, (float) p.y, (float) p.z, colorsRgb[i]); } }); } } @Override public void addCloud(List<Point3D_F64> cloud) { if( SwingUtilities.isEventDispatchThread() ) { for (int i = 0; i < cloud.size(); i++) { Point3D_F64 p = cloud.get(i); panel.addPoint((float) p.x, (float) p.y, (float) p.z, 0xFF0000); } } else { SwingUtilities.invokeLater(() -> { for (int i = 0; i < cloud.size(); i++) { Point3D_F64 p = cloud.get(i); panel.addPoint((float) p.x, (float) p.y, (float) p.z, 0xFF0000); } }); } } @Override public void addCloud(GrowQueue_F32 cloudXYZ, GrowQueue_I32 colorRGB) { if( cloudXYZ.size/3 != colorRGB.size ) { throw new IllegalArgumentException("Number of points do not match"); } if( SwingUtilities.isEventDispatchThread() ) { panel.addPoints(cloudXYZ.data, colorRGB.data, cloudXYZ.size / 3); } else { SwingUtilities.invokeLater(() -> { panel.addPoints(cloudXYZ.data, colorRGB.data, cloudXYZ.size / 3); }); } } @Override public void addPoint(double x, double y, double z, int rgb) { if( SwingUtilities.isEventDispatchThread() ) { panel.addPoint((float)x,(float)y,(float)z,rgb); } else { SwingUtilities.invokeLater(() -> { panel.addPoint((float) x, (float) y, (float) z, rgb); }); } } @Override public void clearPoints() { if( SwingUtilities.isEventDispatchThread() ) { panel.clearCloud(); } else { SwingUtilities.invokeLater(() -> { panel.clearCloud(); }); } } @Override public void setCameraHFov(double radians) { BoofSwingUtil.invokeNowOrLater(()->panel.setHorizontalFieldOfView((float)radians)); } @Override public void setCameraToWorld(Se3_F64 cameraToWorld) { Se3_F64 worldToCamera = cameraToWorld.invert(null); Se3_F32 worldToCameraF32 = new Se3_F32(); ConvertFloatType.convert(worldToCamera,worldToCameraF32); BoofSwingUtil.invokeNowOrLater(()->panel.setWorldToCamera(worldToCameraF32)); } @Override public JComponent getComponent() { return panel; } }
import java.util.Set; @FunctionalInterface public interface PartyInfoConsumer { public abstract void process(Set<Hero> party, Hero leader, String pName); }
import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import java.awt.GridLayout; 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.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; public class CalculatorFrame extends JFrame implements ActionListener{ private JPanel contentPane; private JMenu jMenuFile, jMenuHelp; private JPanel jMaster, jplBackSpace, jplControl; private JLabel jLabelOuput; private JButton JbnButtons[]; private boolean firstInput = true; private String numStr1 = ""; private String numStr2 = ""; Font f12 = new Font("Times New Roman", 0, 12); Font f121 = new Font("Times New Roman", 1, 12); private char op; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { CalculatorFrame frame = new CalculatorFrame(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public CalculatorFrame() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); // MEnu File jMenuFile = new JMenu("File"); // MEnu Help jMenuHelp = new JMenu("Help"); // Menu Bar JMenuBar mb = new JMenuBar(); mb.add(jMenuFile); mb.add(jMenuHelp); setJMenuBar(mb); // frame componant jMaster = new JPanel(); jLabelOuput = new JLabel("0"); // add our componante to fram getContentPane().add(jLabelOuput, BorderLayout.NORTH); JbnButtons = new JButton[25]; for(int i = 0; i<= 9; i++) { JbnButtons[i] = new JButton(String.valueOf(i)); } // Create operator Jbuttons JbnButtons[10] = new JButton("+/-"); JbnButtons[11] = new JButton("."); JbnButtons[12] = new JButton("="); JbnButtons[13] = new JButton("/"); JbnButtons[14] = new JButton("*"); JbnButtons[15] = new JButton("-"); JbnButtons[16] = new JButton("+"); JbnButtons[17] = new JButton("sqrt"); JbnButtons[18] = new JButton("1/x"); JbnButtons[19] = new JButton("%"); jplBackSpace = new JPanel(); jplBackSpace.setLayout(new GridLayout(1, 1, 2, 2)); JbnButtons[20] = new JButton("Backspace"); jplBackSpace.add(JbnButtons[20]); jplControl = new JPanel(); jplControl.setLayout(new GridLayout(1,4)); JbnButtons[21] = new JButton("O"); JbnButtons[22] = new JButton("C"); JbnButtons[23] = new JButton("H"); JbnButtons[24] = new JButton("B"); jplControl.add(JbnButtons[21]); jplControl.add(JbnButtons[23]); jplControl.add(JbnButtons[24]); jplControl.add(JbnButtons[22]); // Setting all Numbered JButton's to Blue. The rest to Red for (int i = 0; i < JbnButtons.length; i++) { JbnButtons[i].setFont(f12); if (i < 10) JbnButtons[i].setForeground(Color.blue); else JbnButtons[i].setForeground(Color.red); } JPanel jPLButtons = new JPanel(); jPLButtons.setLayout(new GridLayout(4, 5, 2, 2)); // add button to the jPLButtons for(int i = 7; i<=9; i++) { jPLButtons.add(JbnButtons[i]); } // add button / and sqrt jPLButtons.add(JbnButtons[13]); jPLButtons.add(JbnButtons[17]); // Second row for (int i = 4; i <= 6; i++) { jPLButtons.add(JbnButtons[i]); } // add button * and x^2 jPLButtons.add(JbnButtons[14]); jPLButtons.add(JbnButtons[18]); // Third row for (int i = 1; i <= 3; i++) { jPLButtons.add(JbnButtons[i]); } //adds button - and % jPLButtons.add(JbnButtons[15]); jPLButtons.add(JbnButtons[19]); //Fourth Row // add 0, +/-, ., +, and = jPLButtons.add(JbnButtons[0]); jPLButtons.add(JbnButtons[10]); jPLButtons.add(JbnButtons[11]); jPLButtons.add(JbnButtons[16]); jPLButtons.add(JbnButtons[12]); // JPANEL MASET jMaster.setLayout(new BorderLayout()); jMaster.add(jPLButtons, BorderLayout.SOUTH); jMaster.add(jplBackSpace, BorderLayout.WEST); jMaster.add(jplControl, BorderLayout.EAST); // add componant to frame getContentPane().add(jMaster, BorderLayout.SOUTH); requestFocus(); //add listenner to button for(int i = 0; i< JbnButtons.length; i++) { JbnButtons[i].addActionListener(this); } } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String resultStr; String str = String.valueOf(e.getActionCommand()); char ch = str.charAt(0); switch(ch) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if(firstInput) { numStr1 = numStr1 + ch; jLabelOuput.setText(numStr1); } else { numStr2 = numStr2 + ch; jLabelOuput.setText(numStr2); } break; case '+': case '-': case '*': //Step 4b case '/': op = ch; firstInput = false; break; case '=': resultStr = evaluate(); //Step 4c jLabelOuput.setText(resultStr); numStr1 = resultStr; numStr2 = ""; firstInput = false; break; case 'C': jLabelOuput.setText(""); //Step 4c numStr1 = ""; numStr2 = ""; firstInput = true; case 'O': int deci; deci=new Integer(jLabelOuput.getText()); jLabelOuput.setText(Integer.toOctalString(deci)); case 'H': int dec; dec=new Integer(jLabelOuput.getText()); //Step 4c jLabelOuput.setText(Integer.toHexString(dec)); case 'B': int value=new Integer(jLabelOuput.getText()); String valueBinaire = ""; while(value > 1) { valueBinaire += (value%2); value = value/2; } valueBinaire += value; valueBinaire = new StringBuilder(valueBinaire).reverse().toString(); jLabelOuput.setText(valueBinaire); } } private String evaluate() { int resultat = 0; int x = Integer.parseInt(numStr1); int y = Integer.parseInt(numStr2); switch(op) { case '+': resultat = x + y; break; case '-': resultat = x - y; break; case '*': resultat = x * y; break; case '/': resultat = x / y; break; } return String.valueOf(resultat); } }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.siddhi.extension.eventtable.rdbms; public interface RDBMSEventTableConstants { public static final String EVENT_TABLE_RDBMS_ATTRIBUTE_TABLE_NAME = "$TABLE_NAME"; public static final String EVENT_TABLE_RDBMS_ATTRIBUTE_COLUMN_TYPES = "$COLUMN_TYPES"; public static final String EVENT_TABLE_RDBMS_ATTRIBUTE_COLUMNS = "$COLUMNS"; public static final String EVENT_TABLE_RDBMS_ATTRIBUTE_VALUES = "$VALUES"; public static final String EVENT_TABLE_RDBMS_ATTRIBUTE_COLUMN_VALUES = "$COLUMN_VALUES"; public static final String EVENT_TABLE_RDBMS_ATTRIBUTE_CONDITION = "$CONDITION"; public static final String EVENT_TABLE_RDBMS_COMMA = "comma"; public static final String EVENT_TABLE_RDBMS_INTEGER = "integer"; public static final String EVENT_TABLE_RDBMS_LONG = "long"; public static final String EVENT_TABLE_RDBMS_FLOAT = "float"; public static final String EVENT_TABLE_RDBMS_DOUBLE = "double"; public static final String EVENT_TABLE_RDBMS_STRING = "string"; public static final String EVENT_TABLE_RDBMS_BOOL = "bool"; public static final String EVENT_TABLE_RDBMS_QUESTION_MARK = "questionMark"; public static final String EVENT_TABLE_RDBMS_CREATE_TABLE = "createTable"; public static final String EVENT_TABLE_RDBMS_INSERT_DATA = "insertDataToTable"; public static final String EVENT_TABLE_RDBMS_TABLE_EXIST = "isTableExist"; public static final String EVENT_TABLE_GENERIC_RDBMS_EQUAL = "equal"; public static final String EVENT_TABLE_GENERIC_RDBMS_GREATER_THAN = "greaterThan"; public static final String EVENT_TABLE_GENERIC_RDBMS_GREATER_THAN_EQUAL = "greaterThanEqual"; public static final String EVENT_TABLE_GENERIC_RDBMS_LESS_THAN = "lessThan"; public static final String EVENT_TABLE_GENERIC_RDBMS_LESS_THAN_EQUAL = "lessThanEqual"; public static final String EVENT_TABLE_GENERIC_RDBMS_NOT_EQUAL = "notEqual"; public static final String EVENT_TABLE_GENERIC_RDBMS_AND = "and"; public static final String EVENT_TABLE_GENERIC_RDBMS_OR = "or"; public static final String EVENT_TABLE_GENERIC_RDBMS_UPDATE_TABLE = "updateTableRow"; public static final String EVENT_TABLE_GENERIC_RDBMS_DELETE_TABLE = "deleteTableRow"; public static final String EVENT_TABLE_GENERIC_RDBMS_SELECT_TABLE = "selectTableRow"; public static final String EVENT_TABLE_GENERIC_RDBMS_LIMIT_SELECT_TABLE = "limitSelectRow"; public static final String EVENT_TABLE_GENERIC_RDBMS_TABLE_ROW_EXIST = "isTableRowExist"; public static final String EVENT_TABLE_CONDITION_WHITE_SPACE_CHARACTER = " "; public static final String EVENT_TABLE_GENERIC_RDBMS_IS_NULL = "isNull"; public static final String EVENT_TABLE_GENERIC_RDBMS_NOT = "not"; public static final String ANNOTATION_ELEMENT_DATASOURCE_NAME = "datasource.name"; public static final String ANNOTATION_ELEMENT_TABLE_NAME = "table.name"; public static final String ANNOTATION_ELEMENT_CACHE = "cache"; public static final String ANNOTATION_ELEMENT_CACHE_SIZE = "cache.size"; public static final String ANNOTATION_ELEMENT_CACHE_LOADING = "cache.loading"; public static final String ANNOTATION_ELEMENT_CACHE_VALIDITY_PERIOD = "cache.validity"; public static final String ANNOTATION_ELEMENT_BLOOM_VALIDITY_PERIOD = "bloom.validity"; public static final String EAGER_CACHE_LOADING_ELEMENT = "eager"; public static final String ANNOTATION_ELEMENT_BLOOM_FILTERS = "bloom.filters"; public static final String RDBMS_TABLE_CONFIG_FILE = "rdbms-table-config.xml"; public static final String EVENT_TABLE_RDBMS_TABLE_JDBC_URL = "jdbc.url"; public static final String EVENT_TABLE_RDBMS_TABLE_USERNAME = "username"; public static final String EVENT_TABLE_RDBMS_TABLE_PASSWORD = "password"; public static final String EVENT_TABLE_RDBMS_TABLE_DRIVER_NAME = "driver.name"; public static final String ANNOTATION_ELEMENT_BLOOM_FILTERS_SIZE = "bloom.filters.size"; public static final String ANNOTATION_ELEMENT_BLOOM_FILTERS_HASH = "bloom.filters.hash"; public static final int BLOOM_FILTER_SIZE = 10000; public static final int BLOOM_FILTER_HASH_FUNCTIONS = 4; public static final String ANNOTATION_CONNECTION = "connection"; public static final String BOOLEAN_LITERAL_TRUE = "TRUE"; public static final String BOOLEAN_LITERAL_FALSE = "FALSE"; }
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.endpoint.invoke.reflect; import java.lang.reflect.Method; import org.junit.Test; import org.springframework.lang.Nullable; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link OperationMethodParameter}. * * @author Phillip Webb */ public class OperationMethodParameterTests { private Method method = ReflectionUtils.findMethod(getClass(), "example", String.class, String.class); @Test public void getNameShouldReturnName() { OperationMethodParameter parameter = new OperationMethodParameter("name", this.method.getParameters()[0]); assertThat(parameter.getName()).isEqualTo("name"); } @Test public void getTypeShouldReturnType() { OperationMethodParameter parameter = new OperationMethodParameter("name", this.method.getParameters()[0]); assertThat(parameter.getType()).isEqualTo(String.class); } @Test public void isMandatoryWhenNoAnnotationShouldReturnTrue() { OperationMethodParameter parameter = new OperationMethodParameter("name", this.method.getParameters()[0]); assertThat(parameter.isMandatory()).isTrue(); } @Test public void isMandatoryWhenNullableAnnotationShouldReturnFalse() { OperationMethodParameter parameter = new OperationMethodParameter("name", this.method.getParameters()[1]); assertThat(parameter.isMandatory()).isFalse(); } void example(String one, @Nullable String two) { } }
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache.checker.tasks; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.cache.processor.EntryProcessor; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion; import org.apache.ignite.internal.processors.cache.CacheObject; import org.apache.ignite.internal.processors.cache.CacheObjectImpl; import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.cache.IgniteInternalCache; import org.apache.ignite.internal.processors.cache.KeyCacheObject; import org.apache.ignite.internal.processors.cache.KeyCacheObjectImpl; import org.apache.ignite.internal.processors.cache.checker.objects.ExecutionResult; import org.apache.ignite.internal.processors.cache.checker.objects.VersionedKey; import org.apache.ignite.internal.processors.cache.checker.objects.RepairResult; import org.apache.ignite.internal.processors.cache.checker.objects.VersionedValue; import org.apache.ignite.internal.processors.cache.verify.RepairAlgorithm; import org.apache.ignite.internal.processors.cache.verify.RepairMeta; import org.apache.ignite.internal.processors.cache.version.GridCacheVersion; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.testframework.ConsoleTestLogger; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import static org.apache.ignite.internal.processors.cache.verify.RepairAlgorithm.LATEST; import static org.apache.ignite.internal.processors.cache.verify.RepairAlgorithm.MAJORITY; import static org.apache.ignite.internal.processors.cache.verify.RepairAlgorithm.PRIMARY; import static org.apache.ignite.internal.processors.cache.verify.RepairAlgorithm.REMOVE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Tests {@link RepairRequestTask} with different inputs and repair algorithms. */ @RunWith(Parameterized.class) public class RepairRequestTaskTest { /** * */ private static final String DEFAULT_CACHE_NAME = "default"; /** Node 2. */ private static final UUID NODE_2 = UUID.randomUUID(); /** Node 3. */ private static final UUID NODE_3 = UUID.randomUUID(); /** Node 4. */ private static final UUID NODE_4 = UUID.randomUUID(); /** Node 5. */ private static final UUID NODE_5 = UUID.randomUUID(); /** Node 1. */ private static final UUID NODE_1 = UUID.randomUUID(); /** Key. */ private static final String KEY = "some_key"; /** Repair algorithm. */ @Parameterized.Parameter(0) public RepairAlgorithm repairAlgorithm; /** Repair algorithm. */ @Parameterized.Parameter(1) public boolean fixed; /** * */ @Parameterized.Parameters(name = "repairAlgorithm = {0}, fixed={1}") public static List<Object[]> parameters() { ArrayList<Object[]> params = new ArrayList<>(); RepairAlgorithm[] repairAlgorithms = {LATEST, PRIMARY, MAJORITY, REMOVE}; for (RepairAlgorithm algorithm : repairAlgorithms) { params.add(new Object[] {algorithm, true}); params.add(new Object[] {algorithm, false}); } return params; } /** * Test can't resolve conflict and should use user algorithm. */ @Test public void testNotFullSetOfOldKeysUsesUserRepairAlg() throws IllegalAccessException { Map<VersionedKey, Map<UUID, VersionedValue>> data = new HashMap<>(); VersionedKey key = new VersionedKey(null, new KeyCacheObjectImpl(), null); Map<UUID, VersionedValue> keyVers = new HashMap<>(); keyVers.put(NODE_1, versionedValue("1", 1)); keyVers.put(NODE_2, versionedValue("2", 2)); keyVers.put(NODE_3, versionedValue("2", 2)); keyVers.put(NODE_4, versionedValue("4", 4)); data.put(key, keyVers); IgniteEx igniteMock = igniteMock(true); ExecutionResult<RepairResult> res = injectIgnite(repairJob(data, 5, 1), igniteMock).execute(); assertTrue(res.result().keysToRepair().isEmpty()); assertEquals(1, res.result().repairedKeys().size()); Map.Entry<VersionedKey, RepairMeta> entry = res.result() .repairedKeys().entrySet().iterator().next(); assertEquals(keyVers, entry.getValue().getPreviousValue()); RepairMeta repairMeta = entry.getValue(); assertTrue(repairMeta.fixed()); assertEquals(repairAlgorithm, repairMeta.repairAlg()); switch (repairAlgorithm) { case LATEST: assertCacheObjectEquals(keyVers.get(NODE_4).value(), repairMeta.value()); break; case PRIMARY: assertCacheObjectEquals(keyVers.get(NODE_1).value(), repairMeta.value()); break; case MAJORITY: assertCacheObjectEquals(keyVers.get(NODE_2).value(), repairMeta.value()); break; case REMOVE: assertCacheObjectEquals(null, repairMeta.value()); break; } } /** * This reparation works with GRID_MAX_VERSION and ignores th user algorithm. */ @Test public void testFullOwnerSetNotMaxAttempt() throws IllegalAccessException { Map<VersionedKey, Map<UUID, VersionedValue>> data = new HashMap<>(); VersionedKey key = new VersionedKey(null, new KeyCacheObjectImpl(), null); Map<UUID, VersionedValue> keyVers = new HashMap<>(); keyVers.put(NODE_1, versionedValue("1", 1)); keyVers.put(NODE_2, versionedValue("2", 2)); data.put(key, keyVers); IgniteEx igniteMock = igniteMock(fixed); ExecutionResult<RepairResult> res = injectIgnite(repairJob(data, 2, 1), igniteMock).execute(); if (fixed) { assertTrue(res.result().keysToRepair().isEmpty()); assertEquals(1, res.result().repairedKeys().size()); Map.Entry<VersionedKey, RepairMeta> entry = res.result() .repairedKeys().entrySet().iterator().next(); assertEquals(keyVers, entry.getValue().getPreviousValue()); RepairMeta repairMeta = entry.getValue(); assertTrue(repairMeta.fixed()); assertEquals(LATEST, repairMeta.repairAlg()); } else { assertTrue(res.result().repairedKeys().isEmpty()); assertEquals(1, res.result().keysToRepair().size()); Map.Entry<VersionedKey, Map<UUID, VersionedValue>> entry = res.result() .keysToRepair().entrySet().iterator().next(); assertEquals(keyVers, entry.getValue()); } } /** * Repair reached max attempts, it should use user algorithm. */ @Test public void testFullOwnerSetMaxAttempt() throws IllegalAccessException { Map<VersionedKey, Map<UUID, VersionedValue>> data = new HashMap<>(); VersionedKey key = new VersionedKey(null, new KeyCacheObjectImpl(), null); Map<UUID, VersionedValue> keyVers = new HashMap<>(); keyVers.put(NODE_1, versionedValue("1", 1)); keyVers.put(NODE_2, versionedValue("2", 2)); keyVers.put(NODE_3, versionedValue("2", 2)); keyVers.put(NODE_4, versionedValue("4", 4)); data.put(key, keyVers); IgniteEx igniteMock = igniteMock(true); final int lastAttempt = 3; ExecutionResult<RepairResult> res = injectIgnite(repairJob(data, 4, lastAttempt), igniteMock).execute(); assertTrue(res.result().keysToRepair().isEmpty()); assertEquals(1, res.result().repairedKeys().size()); Map.Entry<VersionedKey, RepairMeta> entry = res.result() .repairedKeys().entrySet().iterator().next(); assertEquals(keyVers, entry.getValue().getPreviousValue()); RepairMeta repairMeta = entry.getValue(); assertTrue(repairMeta.fixed()); assertEquals(repairAlgorithm, repairMeta.repairAlg()); switch (repairAlgorithm) { case LATEST: assertCacheObjectEquals(keyVers.get(NODE_4).value(), repairMeta.value()); break; case PRIMARY: assertCacheObjectEquals(keyVers.get(NODE_1).value(), repairMeta.value()); break; case MAJORITY: assertCacheObjectEquals(keyVers.get(NODE_2).value(), repairMeta.value()); break; case REMOVE: assertCacheObjectEquals(null, repairMeta.value()); break; } } /** * */ private void assertCacheObjectEquals(CacheObject exp, CacheObject actual) { assertEquals(value(exp), value(actual)); } /** * */ private String value(CacheObject cacheObj) { return cacheObj != null ? U.field(cacheObj, "val") : null; } /** * */ private RepairRequestTask.RepairJob repairJob( Map<VersionedKey, Map<UUID, VersionedValue>> data, int owners, int repairAttempt ) { return new RepairRequestTask.RepairJob( data, DEFAULT_CACHE_NAME, repairAlgorithm, repairAttempt, new AffinityTopologyVersion(), 1 ) { @Override protected UUID primaryNodeId(GridCacheContext ctx, Object key) { return NODE_1; } @Override protected int owners(GridCacheContext ctx) { return owners; } @Override protected Object keyValue(GridCacheContext ctx, KeyCacheObject key) throws IgniteCheckedException { return KEY; } }; } /** * @param val Value. * @param ver Version. */ private VersionedValue versionedValue(String val, int ver) { return new VersionedValue( new CacheObjectImpl(val, val.getBytes()), new GridCacheVersion(ver, 1, ver), 1, 1 ); } /** * */ private IgniteEx igniteMock(boolean invokeReturnFixed) { IgniteEx igniteMock = mock(IgniteEx.class); IgniteCache cacheMock = mock(IgniteCache.class); when(igniteMock.cache(DEFAULT_CACHE_NAME)).thenReturn(cacheMock); GridCacheContext ccMock = mock(GridCacheContext.class); IgniteInternalCache internalCacheMock = mock(IgniteInternalCache.class); when(igniteMock.cachex(DEFAULT_CACHE_NAME)).thenReturn(internalCacheMock); when(internalCacheMock.context()).thenReturn(ccMock); when(cacheMock.withKeepBinary()).thenReturn(cacheMock); when(cacheMock.invoke(any(), any(EntryProcessor.class))).thenReturn(invokeReturnFixed ? RepairEntryProcessor.RepairStatus.SUCCESS : RepairEntryProcessor.RepairStatus.FAIL); return igniteMock; } /** * */ private RepairRequestTask.RepairJob injectIgnite(RepairRequestTask.RepairJob job, IgniteEx ignite) throws IllegalAccessException { Field igniteField = U.findField(RepairRequestTask.RepairJob.class, "ignite"); igniteField.set(job, ignite); Field logField = U.findField(RepairRequestTask.RepairJob.class, "log"); logField.set(job, new ConsoleTestLogger(this.getClass().getName())); return job; } }
package com.deavensoft.jiraworklogs.application.csvexporteradapter; import lombok.RequiredArgsConstructor; import org.apache.commons.io.IOUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.time.LocalDate; /** * WEB endpoint for exporting user work logs as CSV file. */ @Controller @RequestMapping("work-logs") @RequiredArgsConstructor public class CsvExportController { private final WorkLogCsvExport workLogCsvExport; @GetMapping(value = "/csv-export", produces = "text/csv") public @ResponseBody byte[] getFile(@RequestParam String userDisplayName, @RequestParam(required = false) String dayOfWeekList, @RequestParam String startDate, @RequestParam String endDate, HttpServletResponse response) throws IOException { File csvFile = workLogCsvExport.exportWorkLogsForUserInPeriod(userDisplayName, dayOfWeekList, LocalDate.parse(startDate), LocalDate.parse(endDate)); if (csvFile.exists()) { try (InputStream in = new FileInputStream(csvFile)) { response.addHeader("Content-Disposition", "attachment; filename=\"" + csvFile.getName() + "\""); return IOUtils.toByteArray(in); } finally { Files.delete(csvFile.toPath()); } } else { throw new IllegalArgumentException("CSV file could not be produced for the given parameters!"); } } }
package entities.ships; /* * Destroyers are the mid sized class of vessels. They each carry * one railgun and twenty missile tubes. */ public class Destroyer extends Ship{ public Destroyer(double X, double Y, double Z, int modifier){ super(X,Y,Z,75,1,0,20,1,modifier); } }
package com.ruoyi.web.controller.monitor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.framework.web.service.CacheService; /** * 缓存监控 * * @author ruoyi */ @Controller @RequestMapping("/monitor/cache") public class CacheController extends BaseController { private String prefix = "monitor/cache"; @Autowired private CacheService cacheService; @GetMapping() public String cache(ModelMap mmap) { mmap.put("cacheNames", cacheService.getCacheNames()); return prefix + "/cache"; } @PostMapping("/getNames") public String getCacheNames(String fragment, ModelMap mmap) { mmap.put("cacheNames", cacheService.getCacheNames()); return prefix + "/cache::" + fragment; } @PostMapping("/getKeys") public String getCacheKeys(String fragment, String cacheName, ModelMap mmap) { mmap.put("cacheName", cacheName); mmap.put("cacheKyes", cacheService.getCacheKeys(cacheName)); return prefix + "/cache::" + fragment; } @PostMapping("/getValue") public String getCacheValue(String fragment, String cacheName, String cacheKey, ModelMap mmap) { mmap.put("cacheName", cacheName); mmap.put("cacheKey", cacheKey); mmap.put("cacheValue", cacheService.getCacheValue(cacheName, cacheKey)); return prefix + "/cache::" + fragment; } @PostMapping("/clearCacheName") @ResponseBody public AjaxResult clearCacheName(String cacheName, ModelMap mmap) { cacheService.clearCacheName(cacheName); return AjaxResult.success(); } @PostMapping("/clearCacheKey") @ResponseBody public AjaxResult clearCacheKey(String cacheName, String cacheKey, ModelMap mmap) { cacheService.clearCacheKey(cacheName, cacheKey); return AjaxResult.success(); } @GetMapping("/clearAll") @ResponseBody public AjaxResult clearAll(ModelMap mmap) { cacheService.clearAll(); return AjaxResult.success(); } }
package com.folioreader.ui.adapter; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.folioreader.Config; import com.folioreader.R; import com.folioreader.ThemeConfig; import com.folioreader.ui.activity.FolioActivity; import javax.security.auth.login.LoginException; public class AdapterLayerSpinner extends BaseAdapter { private final String[] mList; private final LayoutInflater mInflater; public AdapterLayerSpinner(Context context, String[] list, Config config) { mList = list; mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { if(mList != null) return mList.length; else return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { convertView = mInflater.inflate(R.layout.item_setting_spinner_normal, parent, false); } //데이터세팅 TextView fontText = convertView.findViewById(R.id.tvItemSpinner); fontText.setTextColor(ThemeConfig._settingFontCenterTextColor); fontText.setText(mList[position]); return convertView; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { if(convertView == null) { convertView = mInflater.inflate(R.layout.item_setting_spinner_dropdown, parent, false); } //데이터세팅 TextView fontText = convertView.findViewById(R.id.tvItemSpinner); fontText.setTextColor(ThemeConfig._settingFontCenterTextColor); fontText.setBackgroundColor(ThemeConfig._baseBackgroundColor); fontText.setText(mList[position]); return convertView; } @Override public Object getItem(int position) { return mList[position]; } @Override public long getItemId(int position) { return position; } }
/* * #%L * SciJava Common shared library for SciJava software. * %% * Copyright (C) 2009 - 2021 SciJava developers. * %% * Redistribution and use 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. * * 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 HOLDERS 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. * #L% */ package org.scijava.display; /** * An interface used by classes that can draw on demand. Typically used by * things like the Overlay classes. * * @author Barry DeZonia */ public interface Displayable { /** * Render self when called. */ void draw(); }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.pinpointemail.model; import javax.annotation.Generated; /** * <p> * The resource you attempted to access doesn't exist. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class NotFoundException extends com.amazonaws.services.pinpointemail.model.AmazonPinpointEmailException { private static final long serialVersionUID = 1L; /** * Constructs a new NotFoundException with the specified error message. * * @param message * Describes the error encountered. */ public NotFoundException(String message) { super(message); } }
package com.paise.paiseAutomatizado.api.controllers; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Optional; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.BDDMockito; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.paise.paiseAutomatizado.api.dtos.LancamentoDto; import com.paise.paiseAutomatizado.api.entidades.Funcionario; import com.paise.paiseAutomatizado.api.entidades.Lancamento; import com.paise.paiseAutomatizado.api.enums.TipoEnum; import com.paise.paiseAutomatizado.api.servicos.FuncionarioService; import com.paise.paiseAutomatizado.api.servicos.LancamentoService; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") public class LancamentoControllerTest { @Autowired private MockMvc mvc; @MockBean private LancamentoService lancamentoService; @MockBean private FuncionarioService funcionarioService; private static final String URL_BASE = "/api/lancamentos/"; private static final Long ID_FUNCIONARIO = 1L; private static final Long ID_LANCAMENTO = 1L; private static final String TIPO = TipoEnum.INICIO_TRABALHO.name(); private static final Date DATA = new Date(); private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Test @WithMockUser public void testCadastrarLancamento() throws Exception { Lancamento lancamento = obterDadosLancamento(); BDDMockito.given(this.funcionarioService.buscarPorId(Mockito.anyLong())).willReturn(Optional.of(new Funcionario())); BDDMockito.given(this.lancamentoService.persistir(Mockito.any(Lancamento.class))).willReturn(lancamento); mvc.perform(MockMvcRequestBuilders.post(URL_BASE) .content(this.obterJsonRequisicaoPost()) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.data.id").value(ID_LANCAMENTO)) .andExpect(jsonPath("$.data.tipo").value(TIPO)) .andExpect(jsonPath("$.data.data").value(this.dateFormat.format(DATA))) .andExpect(jsonPath("$.data.funcionarioId").value(ID_FUNCIONARIO)) .andExpect(jsonPath("$.errors").isEmpty()); } @Test @WithMockUser public void testCadastrarLancamentoFuncionarioIdInvalido() throws Exception { BDDMockito.given(this.funcionarioService.buscarPorId(Mockito.anyLong())).willReturn(Optional.empty()); mvc.perform(MockMvcRequestBuilders.post(URL_BASE) .content(this.obterJsonRequisicaoPost()) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.errors").value("Funcionário não encontrado. ID inexistente.")) .andExpect(jsonPath("$.data").isEmpty()); } @Test @WithMockUser(username = "admin@admin.com", roles = {"ADMIN"}) public void testRemoverLancamento() throws Exception { BDDMockito.given(this.lancamentoService.buscarPorId(Mockito.anyLong())).willReturn(Optional.of(new Lancamento())); mvc.perform(MockMvcRequestBuilders.delete(URL_BASE + ID_LANCAMENTO) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } @Test @WithMockUser public void testRemoverLancamentoAcessoNegado() throws Exception { BDDMockito.given(this.lancamentoService.buscarPorId(Mockito.anyLong())).willReturn(Optional.of(new Lancamento())); mvc.perform(MockMvcRequestBuilders.delete(URL_BASE + ID_LANCAMENTO) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isForbidden()); } private String obterJsonRequisicaoPost() throws JsonProcessingException { LancamentoDto lancamentoDto = new LancamentoDto(); lancamentoDto.setId(null); lancamentoDto.setData(this.dateFormat.format(DATA)); lancamentoDto.setTipo(TIPO); lancamentoDto.setFuncionarioId(ID_FUNCIONARIO); ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(lancamentoDto); } private Lancamento obterDadosLancamento() { Lancamento lancamento = new Lancamento(); lancamento.setId(ID_LANCAMENTO); lancamento.setData(DATA); lancamento.setTipo(TipoEnum.valueOf(TIPO)); lancamento.setFuncionario(new Funcionario()); lancamento.getFuncionario().setId(ID_FUNCIONARIO); return lancamento; } }
// Targeted by JavaCPP version 1.5.5-SNAPSHOT: DO NOT EDIT THIS FILE package org.bytedeco.arrow; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.arrow.global.arrow.*; /** \brief File selector for filesystem APIs */ @Namespace("arrow::fs") @NoOffset @Properties(inherit = org.bytedeco.arrow.presets.arrow.class) public class FileSelector extends Pointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public FileSelector(Pointer p) { super(p); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public FileSelector(long size) { super((Pointer)null); allocateArray(size); } private native void allocateArray(long size); @Override public FileSelector position(long position) { return (FileSelector)super.position(position); } @Override public FileSelector getPointer(long i) { return new FileSelector((Pointer)this).position(position + i); } /** The directory in which to select files. * If the path exists but doesn't point to a directory, this should be an error. */ public native @StdString String base_dir(); public native FileSelector base_dir(String setter); /** The behavior if {@code base_dir} isn't found in the filesystem. If false, * an error is returned. If true, an empty selection is returned. */ public native @Cast("bool") boolean allow_not_found(); public native FileSelector allow_not_found(boolean setter); /** Whether to recurse into subdirectories. */ public native @Cast("bool") boolean recursive(); public native FileSelector recursive(boolean setter); /** The maximum number of subdirectories to recurse into. */ public native int max_recursion(); public native FileSelector max_recursion(int setter); public FileSelector() { super((Pointer)null); allocate(); } private native void allocate(); }
/* * Copyright (c) 2020, Zoinkwiz * All rights reserved. * * Redistribution and use 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.questhelper.quests.waterfallquest; import com.questhelper.QuestHelperQuest; import com.questhelper.banktab.BankSlotIcons; import com.questhelper.steps.DetailedQuestStep; import com.questhelper.steps.conditional.Conditions; import com.questhelper.steps.conditional.ItemRequirementCondition; import com.questhelper.steps.conditional.VarbitCondition; import com.questhelper.steps.conditional.ZoneCondition; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import net.runelite.api.ItemID; import net.runelite.api.NpcID; import net.runelite.api.ObjectID; import net.runelite.api.coords.WorldPoint; import com.questhelper.requirements.ItemRequirement; import com.questhelper.QuestDescriptor; import com.questhelper.Zone; import com.questhelper.panel.PanelDetails; import com.questhelper.questhelpers.BasicQuestHelper; import com.questhelper.steps.ConditionalStep; import com.questhelper.steps.NpcStep; import com.questhelper.steps.ObjectStep; import com.questhelper.steps.QuestStep; import com.questhelper.steps.conditional.ConditionForStep; @QuestDescriptor( quest = QuestHelperQuest.WATERFALL_QUEST ) public class WaterfallQuest extends BasicQuestHelper { ItemRequirement rope, highlightRope, glarialsPebble, glarialsUrn, glarialsAmulet, unequippedAmulet, book, key, baxKey, airRunes, waterRunes, earthRunes, airRune, waterRune, earthRune, gamesNecklace, food; ConditionForStep inGnomeBasement, inGlarialTomb, inFalls, onHudonIsland, onDeadTreeIsland, onLedge, hasGlarialsPebble, hasGlarialsUrn, hasGlarialsAmulet, hasBook, inUpstairsInHouse, hasKey, hasBaxKey, inGolrieRoom, gotPebble, hasAirRunes, hasEarthRunes, hasWaterRunes, hasRope, inEndRoom, inEnd2; QuestStep talkToAlmera, boardRaft, talkToHudon, useRopeOnRock, useRopeOnTree, getInBarrel, goUpstairsHadley, searchBookcase, readBook, enterGnomeDungeon, searchGnomeCrate, enterGnomeDoor, talkToGolrie, usePebble, searchGlarialChest, searchGlarialCoffin, getFinalItems, boardRaftFinal, useRopeOnRockFinal, useRopeOnTreeFinal, enterFalls, searchFallsCrate, useKeyOnFallsDoor, useRunes, useAmuletOnStatue, useUrnOnChalice; ConditionalStep goGetPebble, getGlarialStuff; Zone gnomeBasement, glarialTomb, falls, endRoom, end2, hudonIsland, deadTreeIsland, ledge, upstairsInHouse, golrieRoom; @Override public Map<Integer, QuestStep> loadSteps() { loadZones(); setupItemRequirements(); setupConditions(); setupSteps(); Map<Integer, QuestStep> steps = new HashMap<>(); steps.put(0, talkToAlmera); ConditionalStep goTalkToHudon = new ConditionalStep(this, boardRaft); goTalkToHudon.addStep(onHudonIsland, talkToHudon); steps.put(1, goTalkToHudon); ConditionalStep goReadBook = new ConditionalStep(this, goUpstairsHadley); goReadBook.addStep(hasBook, readBook); goReadBook.addStep(inUpstairsInHouse, searchBookcase); goReadBook.addStep(onLedge, getInBarrel); goReadBook.addStep(onDeadTreeIsland, useRopeOnTree); goReadBook.addStep(onHudonIsland, useRopeOnRock); steps.put(2, goReadBook); // TODO: Add lines to guide through maze goGetPebble = new ConditionalStep(this, enterGnomeDungeon); goGetPebble.addStep(inGolrieRoom, talkToGolrie); goGetPebble.addStep(new Conditions(inGnomeBasement, hasKey), enterGnomeDoor); goGetPebble.addStep(inGnomeBasement, searchGnomeCrate); goGetPebble.setLockingCondition(gotPebble); getGlarialStuff = new ConditionalStep(this, usePebble); getGlarialStuff.addStep(new Conditions(hasGlarialsAmulet, inGlarialTomb), searchGlarialCoffin); getGlarialStuff.addStep(inGlarialTomb, searchGlarialChest); getGlarialStuff.setLockingCondition(new Conditions(new Conditions(hasGlarialsAmulet, hasGlarialsUrn))); ConditionalStep puttingToRest = new ConditionalStep(this, getFinalItems); puttingToRest.addStep(inEnd2, useUrnOnChalice); puttingToRest.addStep(inEndRoom, useRunes); puttingToRest.addStep(new Conditions(inFalls, hasBaxKey), useKeyOnFallsDoor); puttingToRest.addStep(inFalls, searchFallsCrate); puttingToRest.addStep(onLedge, enterFalls); puttingToRest.addStep(onDeadTreeIsland, useRopeOnTreeFinal); puttingToRest.addStep(onHudonIsland, useRopeOnRockFinal); puttingToRest.addStep(new Conditions(hasGlarialsUrn, hasGlarialsAmulet, hasAirRunes, hasEarthRunes, hasWaterRunes, hasRope), boardRaftFinal); ConditionalStep finishingSteps = new ConditionalStep(this, goGetPebble); finishingSteps.addStep(new Conditions(hasGlarialsUrn, hasGlarialsAmulet), puttingToRest); finishingSteps.addStep(gotPebble, getGlarialStuff); steps.put(3, finishingSteps); steps.put(4, finishingSteps); steps.put(5, puttingToRest); steps.put(6, puttingToRest); steps.put(7, puttingToRest); // 7 didn't occur during testing steps.put(8, puttingToRest); return steps; } public void setupItemRequirements() { highlightRope = new ItemRequirement("Rope", ItemID.ROPE); highlightRope.setHighlightInInventory(true); rope = new ItemRequirement("Rope", ItemID.ROPE); book = new ItemRequirement("Book on baxtorian", ItemID.BOOK_ON_BAXTORIAN); book.setHighlightInInventory(true); glarialsPebble = new ItemRequirement("Glarial's pebble", ItemID.GLARIALS_PEBBLE); glarialsPebble.setHighlightInInventory(true); glarialsPebble.setTip("You can get another from Golrie under the Tree Gnome Village"); glarialsUrn = new ItemRequirement("Glarial's urn", ItemID.GLARIALS_URN); glarialsUrn.setTip("You can get another from the chest in Glarial's tomb"); glarialsAmulet = new ItemRequirement("Glarial's amulet", ItemID.GLARIALS_AMULET, 1, true); glarialsAmulet.setTip("You can get another from the chest in Glarial's tomb"); unequippedAmulet = new ItemRequirement("Glarial's amulet", ItemID.GLARIALS_AMULET); key = new ItemRequirement("Key", ItemID.KEY_293); baxKey = new ItemRequirement("Key", ItemID.KEY_298); airRunes = new ItemRequirement("Air runes", ItemID.AIR_RUNE, 6); airRune = new ItemRequirement("Air rune", ItemID.AIR_RUNE); earthRunes = new ItemRequirement("Earth runes", ItemID.EARTH_RUNE, 6); earthRune = new ItemRequirement("Earth rune", ItemID.EARTH_RUNE); waterRunes = new ItemRequirement("Water runes", ItemID.WATER_RUNE, 6); waterRune = new ItemRequirement("Water rune", ItemID.WATER_RUNE); gamesNecklace = new ItemRequirement("Games necklace", ItemID.GAMES_NECKLACE8); food = new ItemRequirement("Food", -1, -1); food.setDisplayItemId(BankSlotIcons.getFood()); } public void loadZones() { gnomeBasement = new Zone(new WorldPoint(2497, 9552, 0), new WorldPoint(2559, 9593, 0)); glarialTomb = new Zone(new WorldPoint(2524, 9801, 0), new WorldPoint(2557, 9849, 0)); golrieRoom = new Zone(new WorldPoint(2502, 9576, 0), new WorldPoint(2523, 9593, 0)); hudonIsland = new Zone(new WorldPoint(2510, 3476, 0), new WorldPoint(2515, 3482, 0)); deadTreeIsland = new Zone(new WorldPoint(2512, 3465, 0), new WorldPoint(2513, 3475, 0)); ledge = new Zone(new WorldPoint(2510, 3462, 0), new WorldPoint(2513, 3464, 0)); upstairsInHouse = new Zone(new WorldPoint(2516, 3424, 1), new WorldPoint(2520, 3431, 1)); falls = new Zone(new WorldPoint(2556, 9861, 0), new WorldPoint(2595, 9920, 0)); endRoom = new Zone(new WorldPoint(2561, 9902, 0), new WorldPoint(2570, 9917, 0)); end2 = new Zone(new WorldPoint(2599, 9890, 0), new WorldPoint(2608, 9916, 0)); } public void setupConditions() { onDeadTreeIsland = new ZoneCondition(deadTreeIsland); onHudonIsland = new ZoneCondition(hudonIsland); onLedge = new ZoneCondition(ledge); inUpstairsInHouse = new ZoneCondition(upstairsInHouse); hasBook = new ItemRequirementCondition(book); inGnomeBasement = new ZoneCondition(gnomeBasement); inGolrieRoom = new ZoneCondition(golrieRoom); inGlarialTomb = new ZoneCondition(glarialTomb); inFalls = new ZoneCondition(falls); inEndRoom = new ZoneCondition(endRoom); inEnd2 = new ZoneCondition(end2); hasGlarialsAmulet = new ItemRequirementCondition(unequippedAmulet); hasGlarialsPebble = new ItemRequirementCondition(glarialsPebble); hasGlarialsUrn = new ItemRequirementCondition(glarialsUrn); hasKey = new ItemRequirementCondition(key); hasBaxKey = new ItemRequirementCondition(baxKey); gotPebble = new VarbitCondition(9110, 1); hasEarthRunes = new ItemRequirementCondition(earthRunes); hasWaterRunes = new ItemRequirementCondition(waterRunes); hasAirRunes = new ItemRequirementCondition(airRunes); hasRope = new ItemRequirementCondition(highlightRope); } public void setupSteps() { talkToAlmera = new NpcStep(this, NpcID.ALMERA, new WorldPoint(2521, 3495, 0), "Talk to Almera on top of Baxtorian Falls."); talkToAlmera.addDialogStep("How can I help?"); boardRaft = new ObjectStep(this, ObjectID.LOG_RAFT, new WorldPoint(2509, 3494, 0), "Board the log raft west of Almera."); talkToHudon = new NpcStep(this, NpcID.HUDON, new WorldPoint(2511, 3484, 0), "Talk to Hudon."); useRopeOnRock = new ObjectStep(this, ObjectID.ROCK, new WorldPoint(2512, 3468, 0), "Use a rope on the rock to the south", highlightRope); useRopeOnRock.addIcon(ItemID.ROPE); useRopeOnTree = new ObjectStep(this, ObjectID.DEAD_TREE_2020, new WorldPoint(2512, 3465, 0), "Use a rope on the dead tree.", highlightRope); useRopeOnTree.addIcon(ItemID.ROPE); getInBarrel = new ObjectStep(this, ObjectID.BARREL_2022, new WorldPoint(2512, 3463, 0), "Get in the barrel."); goUpstairsHadley = new ObjectStep(this, ObjectID.STAIRCASE_16671, new WorldPoint(2518, 3430, 0), "Go up the stairs in the house south of Almera's house."); searchBookcase = new ObjectStep(this, ObjectID.BOOKCASE_1989, new WorldPoint(2520, 3427, 1), "Search the south east bookcase."); readBook = new DetailedQuestStep(this, "Read the book.", book); enterGnomeDungeon = new ObjectStep(this, ObjectID.LADDER_5250, new WorldPoint(2533, 3155, 0), "Go to the centre of the Tree Gnome Village and go down the ladder at the entrance."); searchGnomeCrate = new ObjectStep(this, ObjectID.CRATE_1990, new WorldPoint(2548, 9565, 0), "Search the off-coloured crate in the east room."); enterGnomeDoor = new ObjectStep(this, ObjectID.DOOR_1991, new WorldPoint(2515, 9575, 0), "Go through the gate in the west room.", key); talkToGolrie = new NpcStep(this, NpcID.GOLRIE_4183, new WorldPoint(2514, 9580, 0), "Talk to Golrie."); usePebble = new ObjectStep(this, ObjectID.GLARIALS_TOMBSTONE, new WorldPoint(2559, 3445, 0), "Bank everything besides the pebble and some food. After, go use Glarial's pebble to Glarial's Tombstone east of Baxtorian Falls.", glarialsPebble); usePebble.addIcon(ItemID.GLARIALS_PEBBLE); searchGlarialChest = new ObjectStep(this, ObjectID.CHEST_1994, new WorldPoint(2530, 9844, 0), "Search the chest in the western room."); searchGlarialCoffin = new ObjectStep(this, ObjectID.GLARIALS_TOMB, new WorldPoint(2542, 9812, 0), "Search Glarial's Tomb in the south room."); getFinalItems = new DetailedQuestStep(this, "Leave Glarial's Tomb and get 6 air, water and earth runes, a rope, glarial's amulet, glarial's urn, a rope, and some food.", airRunes, earthRunes, waterRunes, glarialsAmulet, glarialsUrn, rope); boardRaftFinal = new ObjectStep(this, ObjectID.LOG_RAFT, new WorldPoint(2509, 3494, 0), "Board the log raft west of Almera."); useRopeOnRockFinal = new ObjectStep(this, ObjectID.ROCK, new WorldPoint(2512, 3468, 0), "Use a rope on the rock to the south", highlightRope); useRopeOnRockFinal.addIcon(ItemID.ROPE); useRopeOnTreeFinal = new ObjectStep(this, ObjectID.DEAD_TREE_2020, new WorldPoint(2512, 3465, 0), "Use a rope on the dead tree.", highlightRope); useRopeOnTreeFinal.addIcon(ItemID.ROPE); enterFalls = new ObjectStep(this, ObjectID.DOOR_2010, new WorldPoint(2511, 3464, 0), "EQUIP Glarial's amulet, then enter the falls.", glarialsAmulet); searchFallsCrate = new ObjectStep(this, ObjectID.CRATE_1999, new WorldPoint(2589, 9888, 0), "Search the crate in the east room for a key."); useKeyOnFallsDoor = new ObjectStep(this, ObjectID.DOOR_2002, new WorldPoint(2566, 9901, 0), "Go through the doors from the west room.", baxKey); useRunes = new DetailedQuestStep(this, "Use 1 earth, water and air rune on each of the 6 pillars in the room. Afterwards, use Glarial's amulet on the statue of Glarial.", airRune, waterRune, earthRune); useAmuletOnStatue = new ObjectStep(this, ObjectID.STATUE_OF_GLARIAL, new WorldPoint(2603, 9915, 0), "Use Glarial's amulet on the Statue of Glarial", unequippedAmulet); useAmuletOnStatue.addIcon(ItemID.GLARIALS_AMULET); useUrnOnChalice = new ObjectStep(this, ObjectID.CHALICE, new WorldPoint(2604, 9911, 0), "Use Glarial's urn on the Chalice to finish the quest.", glarialsUrn); useUrnOnChalice.addIcon(ItemID.GLARIALS_URN); } @Override public ArrayList<ItemRequirement> getItemRequirements() { ArrayList<ItemRequirement> reqs = new ArrayList<>(); reqs.add(highlightRope); reqs.add(airRunes); reqs.add(earthRunes); reqs.add(waterRunes); return reqs; } @Override public ArrayList<String> getCombatRequirements() { ArrayList<String> reqs = new ArrayList<>(); reqs.add("Able to survive enemies up to level 86 attacking you"); return reqs; } @Override public ArrayList<ItemRequirement> getItemRecommended() { ArrayList<ItemRequirement> reqs = new ArrayList<>(); reqs.add(gamesNecklace); reqs.add(food); return reqs; } @Override public ArrayList<PanelDetails> getPanels() { ArrayList<PanelDetails> allSteps = new ArrayList<>(); allSteps.add(new PanelDetails("Starting off", new ArrayList<>(Collections.singletonList(talkToAlmera)))); allSteps.add(new PanelDetails("Investigate", new ArrayList<>(Arrays.asList(boardRaft, talkToHudon, useRopeOnRock, useRopeOnTree, getInBarrel, goUpstairsHadley, searchBookcase, readBook)), rope)); PanelDetails getPebblePanel = new PanelDetails("Get Glarial's Pebble", new ArrayList<>(Arrays.asList(enterGnomeDungeon, searchGnomeCrate, enterGnomeDoor, talkToGolrie))); getPebblePanel.setLockingStep(goGetPebble); allSteps.add(getPebblePanel); PanelDetails getGlarialStuffPanel = new PanelDetails("Loot Glarial's tomb", new ArrayList<>(Arrays.asList(usePebble, searchGlarialChest, searchGlarialCoffin))); getGlarialStuffPanel.setLockingStep(getGlarialStuff); allSteps.add(getGlarialStuffPanel); PanelDetails finishOffPanel = new PanelDetails("Put Glarial to rest", new ArrayList<>(Arrays.asList(getFinalItems, boardRaftFinal, useRopeOnRockFinal, useRopeOnTreeFinal, enterFalls, searchFallsCrate, useKeyOnFallsDoor, useRunes, useUrnOnChalice)), rope, airRunes, earthRunes, waterRunes, glarialsUrn, glarialsAmulet); allSteps.add(finishOffPanel); return allSteps; } }
package com.jeesite.modules.common.utils; import java.math.BigDecimal; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellReference; /** * @version 1.0 * @author * @data 2017年6月21日 * @描述: */ public class ExcelHelper { public static String cellValue(Cell cell) { if (cell == null) { return ""; } switch (cell.getCellTypeEnum()) { case STRING: return cell.getRichStringCellValue().getString().trim(); case NUMERIC: String trim = new BigDecimal(Double.toString(cell.getNumericCellValue())).toPlainString().trim(); return trim.endsWith(".0") ? trim.substring(0, trim.length() - 2) : trim; case BOOLEAN: return String.valueOf(cell.getBooleanCellValue()); case FORMULA: return cell.getCellFormula(); case BLANK: default: return ""; } } public static CellStyle align(Workbook wb, HorizontalAlignment align) { CellStyle styleLeft = wb.createCellStyle(); styleLeft.setWrapText(true); styleLeft.setAlignment(align); styleLeft.setVerticalAlignment(VerticalAlignment.CENTER); return styleLeft; } /** * 文本格式 */ public static CellStyle style(Workbook wb, HorizontalAlignment align, boolean... bold) { CellStyle style = wb.createCellStyle(); style.setWrapText(true); style.setAlignment(align); style.setVerticalAlignment(VerticalAlignment.CENTER); if (bold.length > 0 && bold[0]) { Font font = wb.createFont(); font.setBold(true); style.setFont(font); } return style; } /** * 标题格式 */ public static CellStyle styleTitle(Workbook wb) { CellStyle styleTitle = wb.createCellStyle(); Font font = wb.createFont();// 前端ajax导出的时候不会自适应单元格宽度 font.setBold(true); styleTitle.setFont(font); styleTitle.setFillPattern(FillPatternType.SOLID_FOREGROUND); styleTitle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_25_PERCENT.getIndex());// 设置背景色; styleTitle.setAlignment(HorizontalAlignment.CENTER); return styleTitle; } /** * 数值格式 * * @param format * 格式,示例保留4位小数:0.0000 */ public static CellStyle styleNumber(Workbook wb, String format, boolean... bold) { CellStyle style = style(wb, HorizontalAlignment.RIGHT); DataFormat df = wb.createDataFormat(); if (StringUtils.isNotBlank(format)) { style.setDataFormat(df.getFormat(format)); } if (bold.length > 0 && bold[0]) { Font font = wb.createFont(); font.setBold(true); style.setFont(font); } return style; } public static String convertNumToColString(int col) { return CellReference.convertNumToColString(col); } public static int convertColStringToNum(String colString) { if (StringUtils.isBlank(colString) || colString.length() > 2) { return -1; } else { return CellReference.convertColStringToIndex(colString); } } public static void main(String[] args) { System.out.println(convertColStringToNum("A")); } }
package com.wzh.back_template.utils; /** * @author wzh * @date 2020/1/7 - 16:20 */ public class MapperUtils { }
package com.technicise; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for COCT_MT310000UV04.Author complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="COCT_MT310000UV04.Author"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{urn:hl7-org:v3}InfrastructureRootElements"/> * &lt;element name="accommodationRequestorRole" type="{urn:hl7-org:v3}COCT_MT310000UV04.AccommodationRequestorRole"/> * &lt;/sequence> * &lt;attGroup ref="{urn:hl7-org:v3}InfrastructureRootAttributes"/> * &lt;attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" /> * &lt;attribute name="typeCode" use="required" type="{urn:hl7-org:v3}ParticipationType" fixed="AUT" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "COCT_MT310000UV04.Author", propOrder = { "realmCode", "typeId", "templateId", "accommodationRequestorRole" }) public class COCTMT310000UV04Author implements Serializable { private final static long serialVersionUID = 20130510160300L; protected List<CS> realmCode; protected II typeId; protected List<II> templateId; @XmlElement(required = true) protected COCTMT310000UV04AccommodationRequestorRole accommodationRequestorRole; @XmlAttribute(name = "nullFlavor") protected List<String> nullFlavor; @XmlAttribute(name = "typeCode", required = true) protected List<String> typeCode; /** * Gets the value of the realmCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the realmCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRealmCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CS } * * */ public List<CS> getRealmCode() { if (realmCode == null) { realmCode = new ArrayList<CS>(); } return this.realmCode; } /** * Gets the value of the typeId property. * * @return * possible object is * {@link II } * */ public II getTypeId() { return typeId; } /** * Sets the value of the typeId property. * * @param value * allowed object is * {@link II } * */ public void setTypeId(II value) { this.typeId = value; } /** * Gets the value of the templateId property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the templateId property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTemplateId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link II } * * */ public List<II> getTemplateId() { if (templateId == null) { templateId = new ArrayList<II>(); } return this.templateId; } /** * Gets the value of the accommodationRequestorRole property. * * @return * possible object is * {@link COCTMT310000UV04AccommodationRequestorRole } * */ public COCTMT310000UV04AccommodationRequestorRole getAccommodationRequestorRole() { return accommodationRequestorRole; } /** * Sets the value of the accommodationRequestorRole property. * * @param value * allowed object is * {@link COCTMT310000UV04AccommodationRequestorRole } * */ public void setAccommodationRequestorRole(COCTMT310000UV04AccommodationRequestorRole value) { this.accommodationRequestorRole = value; } /** * Gets the value of the nullFlavor property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the nullFlavor property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNullFlavor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getNullFlavor() { if (nullFlavor == null) { nullFlavor = new ArrayList<String>(); } return this.nullFlavor; } /** * Gets the value of the typeCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the typeCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTypeCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getTypeCode() { if (typeCode == null) { typeCode = new ArrayList<String>(); } return this.typeCode; } }
// Copyright 2016 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.remote; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.remote.CacheNotFoundException; import com.google.devtools.build.lib.remote.CasServiceGrpc.CasServiceImplBase; import com.google.devtools.build.lib.remote.ChannelOptions; import com.google.devtools.build.lib.remote.Chunker; import com.google.devtools.build.lib.remote.ContentDigests; import com.google.devtools.build.lib.remote.ContentDigests.ActionKey; import com.google.devtools.build.lib.remote.ExecuteServiceGrpc.ExecuteServiceImplBase; import com.google.devtools.build.lib.remote.ExecutionCacheServiceGrpc.ExecutionCacheServiceImplBase; import com.google.devtools.build.lib.remote.RemoteOptions; import com.google.devtools.build.lib.remote.RemoteProtocol; import com.google.devtools.build.lib.remote.RemoteProtocol.Action; import com.google.devtools.build.lib.remote.RemoteProtocol.ActionResult; import com.google.devtools.build.lib.remote.RemoteProtocol.BlobChunk; import com.google.devtools.build.lib.remote.RemoteProtocol.CasDownloadBlobRequest; import com.google.devtools.build.lib.remote.RemoteProtocol.CasDownloadReply; import com.google.devtools.build.lib.remote.RemoteProtocol.CasLookupReply; import com.google.devtools.build.lib.remote.RemoteProtocol.CasLookupRequest; import com.google.devtools.build.lib.remote.RemoteProtocol.CasStatus; import com.google.devtools.build.lib.remote.RemoteProtocol.CasUploadBlobReply; import com.google.devtools.build.lib.remote.RemoteProtocol.CasUploadBlobRequest; import com.google.devtools.build.lib.remote.RemoteProtocol.CasUploadTreeMetadataReply; import com.google.devtools.build.lib.remote.RemoteProtocol.CasUploadTreeMetadataRequest; import com.google.devtools.build.lib.remote.RemoteProtocol.Command.EnvironmentEntry; import com.google.devtools.build.lib.remote.RemoteProtocol.ContentDigest; import com.google.devtools.build.lib.remote.RemoteProtocol.ExecuteReply; import com.google.devtools.build.lib.remote.RemoteProtocol.ExecuteRequest; import com.google.devtools.build.lib.remote.RemoteProtocol.ExecutionCacheReply; import com.google.devtools.build.lib.remote.RemoteProtocol.ExecutionCacheRequest; import com.google.devtools.build.lib.remote.RemoteProtocol.ExecutionCacheSetReply; import com.google.devtools.build.lib.remote.RemoteProtocol.ExecutionCacheSetRequest; import com.google.devtools.build.lib.remote.RemoteProtocol.ExecutionCacheStatus; import com.google.devtools.build.lib.remote.RemoteProtocol.ExecutionStatus; import com.google.devtools.build.lib.remote.RemoteProtocol.FileNode; import com.google.devtools.build.lib.remote.RemoteProtocol.Platform; import com.google.devtools.build.lib.remote.SimpleBlobStore; import com.google.devtools.build.lib.remote.SimpleBlobStoreActionCache; import com.google.devtools.build.lib.remote.SimpleBlobStoreFactory; import com.google.devtools.build.lib.runtime.AuthAndTLSOptions; import com.google.devtools.build.lib.shell.AbnormalTerminationException; import com.google.devtools.build.lib.shell.Command; import com.google.devtools.build.lib.shell.CommandException; import com.google.devtools.build.lib.shell.TimeoutKillableObserver; import com.google.devtools.build.lib.unix.UnixFileSystem; import com.google.devtools.build.lib.util.OS; import com.google.devtools.build.lib.util.Preconditions; import com.google.devtools.build.lib.util.ProcessUtils; import com.google.devtools.build.lib.vfs.FileSystem; import com.google.devtools.build.lib.vfs.FileSystemUtils; import com.google.devtools.build.lib.vfs.JavaIoFileSystem; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.common.options.Options; import com.google.devtools.common.options.OptionsParser; import com.google.protobuf.Duration; import com.google.protobuf.util.Durations; import io.grpc.Server; import io.grpc.netty.NettyServerBuilder; import io.grpc.stub.StreamObserver; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.FileAlreadyExistsException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; /** * Implements a remote worker that accepts work items as protobufs. The server implementation is * based on grpc. */ public class RemoteWorker { private static final Logger LOG = Logger.getLogger(RemoteWorker.class.getName()); private static final boolean LOG_FINER = LOG.isLoggable(Level.FINER); private final CasServiceImplBase casServer; private final ExecuteServiceImplBase execServer; private final ExecutionCacheServiceImplBase execCacheServer; private final SimpleBlobStoreActionCache cache; private final RemoteWorkerOptions workerOptions; private final RemoteOptions remoteOptions; public RemoteWorker( RemoteWorkerOptions workerOptions, RemoteOptions remoteOptions, SimpleBlobStoreActionCache cache) throws IOException { this.cache = cache; this.workerOptions = workerOptions; this.remoteOptions = remoteOptions; if (workerOptions.workPath != null) { Path workPath = getFileSystem().getPath(workerOptions.workPath); FileSystemUtils.createDirectoryAndParents(workPath); execServer = new ExecutionServer(workPath); } else { execServer = null; } casServer = new CasServer(); execCacheServer = new ExecutionCacheServer(); } public Server startServer() throws IOException { NettyServerBuilder b = NettyServerBuilder.forPort(workerOptions.listenPort) .maxMessageSize(ChannelOptions.create(Options.getDefaults(AuthAndTLSOptions.class), remoteOptions.grpcMaxChunkSizeBytes).maxMessageSize()) .addService(casServer) .addService(execCacheServer); if (execServer != null) { b.addService(execServer); } else { System.out.println("*** Execution disabled, only serving cache requests."); } Server server = b.build(); System.out.println( "*** Starting grpc server on all locally bound IPs on port " + workerOptions.listenPort + "."); server.start(); return server; } class CasServer extends CasServiceImplBase { private static final int MAX_MEMORY_KBYTES = 512 * 1024; @Override public void lookup(CasLookupRequest request, StreamObserver<CasLookupReply> responseObserver) { CasLookupReply.Builder reply = CasLookupReply.newBuilder(); CasStatus.Builder status = reply.getStatusBuilder(); for (ContentDigest digest : request.getDigestList()) { if (!cache.containsKey(digest)) { status.addMissingDigest(digest); } } if (status.getMissingDigestCount() > 0) { status.setSucceeded(false); status.setError(CasStatus.ErrorCode.MISSING_DIGEST); } else { status.setSucceeded(true); } responseObserver.onNext(reply.build()); responseObserver.onCompleted(); } @Override public void uploadTreeMetadata( CasUploadTreeMetadataRequest request, StreamObserver<CasUploadTreeMetadataReply> responseObserver) { try { for (FileNode treeNode : request.getTreeNodeList()) { cache.uploadBlob(treeNode.toByteArray()); } responseObserver.onNext( CasUploadTreeMetadataReply.newBuilder() .setStatus(CasStatus.newBuilder().setSucceeded(true)) .build()); } catch (Exception e) { LOG.warning("Request failed: " + e.toString()); CasUploadTreeMetadataReply.Builder reply = CasUploadTreeMetadataReply.newBuilder(); reply .getStatusBuilder() .setSucceeded(false) .setError(CasStatus.ErrorCode.UNKNOWN) .setErrorDetail(e.toString()); responseObserver.onNext(reply.build()); } finally { responseObserver.onCompleted(); } } @Override public void downloadBlob( CasDownloadBlobRequest request, StreamObserver<CasDownloadReply> responseObserver) { CasDownloadReply.Builder reply = CasDownloadReply.newBuilder(); CasStatus.Builder status = reply.getStatusBuilder(); for (ContentDigest digest : request.getDigestList()) { if (!cache.containsKey(digest)) { status.addMissingDigest(digest); } } if (status.getMissingDigestCount() > 0) { status.setSucceeded(false); status.setError(CasStatus.ErrorCode.MISSING_DIGEST); responseObserver.onNext(reply.build()); responseObserver.onCompleted(); return; } status.setSucceeded(true); try { // This still relies on the total blob size to be small enough to fit in memory // simultaneously! TODO(olaola): refactor to fix this if the need arises. Chunker.Builder b = new Chunker.Builder().chunkSize(remoteOptions.grpcMaxChunkSizeBytes); for (ContentDigest digest : request.getDigestList()) { b.addInput(cache.downloadBlob(digest)); } Chunker c = b.build(); while (c.hasNext()) { reply.setData(c.next()); responseObserver.onNext(reply.build()); if (reply.hasStatus()) { reply.clearStatus(); // Only send status on first chunk. } } } catch (IOException e) { // This cannot happen, as we are chunking in-memory blobs. throw new RuntimeException("Internal error: " + e); } catch (CacheNotFoundException e) { // This can only happen if an item gets evicted right after we check. reply.clearData(); status.setSucceeded(false); status.setError(CasStatus.ErrorCode.MISSING_DIGEST); status.addMissingDigest(e.getMissingDigest()); responseObserver.onNext(reply.build()); } finally { responseObserver.onCompleted(); } } @Override public StreamObserver<CasUploadBlobRequest> uploadBlob( final StreamObserver<CasUploadBlobReply> responseObserver) { return new StreamObserver<CasUploadBlobRequest>() { byte[] blob = null; ContentDigest digest = null; long offset = 0; @Override public void onNext(CasUploadBlobRequest request) { BlobChunk chunk = request.getData(); try { if (chunk.hasDigest()) { // Check if the previous chunk was really done. Preconditions.checkArgument( digest == null || offset == 0, "Missing input chunk for digest %s", digest == null ? "" : ContentDigests.toString(digest)); digest = chunk.getDigest(); // This unconditionally downloads the whole blob into memory! Preconditions.checkArgument((int) (digest.getSizeBytes() / 1024) < MAX_MEMORY_KBYTES); blob = new byte[(int) digest.getSizeBytes()]; } Preconditions.checkArgument(digest != null, "First chunk contains no digest"); Preconditions.checkArgument( offset == chunk.getOffset(), "Missing input chunk for digest %s", ContentDigests.toString(digest)); if (digest.getSizeBytes() > 0) { chunk.getData().copyTo(blob, (int) offset); offset = (offset + chunk.getData().size()) % digest.getSizeBytes(); } if (offset == 0) { ContentDigest uploadedDigest = cache.uploadBlob(blob); Preconditions.checkArgument( uploadedDigest.equals(digest), "Digest mismatch: client sent %s, server computed %s", ContentDigests.toString(digest), ContentDigests.toString(uploadedDigest)); } } catch (Exception e) { LOG.warning("Request failed: " + e.toString()); CasUploadBlobReply.Builder reply = CasUploadBlobReply.newBuilder(); reply .getStatusBuilder() .setSucceeded(false) .setError( e instanceof IllegalArgumentException ? CasStatus.ErrorCode.INVALID_ARGUMENT : CasStatus.ErrorCode.UNKNOWN) .setErrorDetail(e.toString()); responseObserver.onNext(reply.build()); } } @Override public void onError(Throwable t) { LOG.warning("Request errored remotely: " + t); } @Override public void onCompleted() { responseObserver.onCompleted(); } }; } } class ExecutionCacheServer extends ExecutionCacheServiceImplBase { @Override public void getCachedResult( ExecutionCacheRequest request, StreamObserver<ExecutionCacheReply> responseObserver) { try { ActionKey actionKey = ContentDigests.unsafeActionKeyFromDigest(request.getActionDigest()); ExecutionCacheReply.Builder reply = ExecutionCacheReply.newBuilder(); ActionResult result = cache.getCachedActionResult(actionKey); if (result != null) { reply.setResult(result); } reply.getStatusBuilder().setSucceeded(true); responseObserver.onNext(reply.build()); } catch (Exception e) { LOG.warning("getCachedActionResult request failed: " + e.toString()); ExecutionCacheReply.Builder reply = ExecutionCacheReply.newBuilder(); reply .getStatusBuilder() .setSucceeded(false) .setError(ExecutionCacheStatus.ErrorCode.UNKNOWN); responseObserver.onNext(reply.build()); } finally { responseObserver.onCompleted(); } } @Override public void setCachedResult( ExecutionCacheSetRequest request, StreamObserver<ExecutionCacheSetReply> responseObserver) { try { ActionKey actionKey = ContentDigests.unsafeActionKeyFromDigest(request.getActionDigest()); cache.setCachedActionResult(actionKey, request.getResult()); ExecutionCacheSetReply.Builder reply = ExecutionCacheSetReply.newBuilder(); reply.getStatusBuilder().setSucceeded(true); responseObserver.onNext(reply.build()); } catch (Exception e) { LOG.warning("setCachedActionResult request failed: " + e.toString()); ExecutionCacheSetReply.Builder reply = ExecutionCacheSetReply.newBuilder(); reply .getStatusBuilder() .setSucceeded(false) .setError(ExecutionCacheStatus.ErrorCode.UNKNOWN); responseObserver.onNext(reply.build()); } finally { responseObserver.onCompleted(); } } } // How long to wait for the uid command. private static final Duration uidTimeout = Durations.fromMicros(30); class ExecutionServer extends ExecuteServiceImplBase { private final Path workPath; //The name of the container image entry in the Platform proto // (see src/main/protobuf/remote_protocol.proto and // experimental_remote_platform_override in // src/main/java/com/google/devtools/build/lib/remote/RemoteOptions.java) public static final String CONTAINER_IMAGE_ENTRY_NAME = "container-image"; public ExecutionServer(Path workPath) { this.workPath = workPath; } private Map<String, String> getEnvironmentVariables(RemoteProtocol.Command command) { HashMap<String, String> result = new HashMap<>(); for (EnvironmentEntry entry : command.getEnvironmentList()) { result.put(entry.getVariable(), entry.getValue()); } return result; } // Gets the uid of the current user. If uid could not be successfully fetched (e.g., on other // platforms, if for some reason the timeout was not met, if "id -u" returned non-numeric // number, etc), logs a WARNING and return -1. // This is used to set "-u UID" flag for commands running inside Docker containers. There are // only a small handful of cases where uid is vital (e.g., if strict permissions are set on the // output files), so most use cases would work without setting uid. private long getUid() { Command cmd = new Command(new String[] {"id", "-u"}); try { ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); cmd.execute( Command.NO_INPUT, new TimeoutKillableObserver(Durations.toMicros(uidTimeout)), stdout, stderr); return Long.parseLong(stdout.toString().trim()); } catch (CommandException | NumberFormatException e) { LOG.warning("Could not get UID for passing to Docker container. Proceeding without it."); LOG.warning("Error: " + e.toString()); return -1; } } // Checks Action for docker container definition. If no docker container specified, returns // null. Otherwise returns docker container name from the parameters. private String dockerContainer(Action action) throws IllegalArgumentException { String result = null; List<Platform.Property> entries = action.getPlatform().getEntryList(); for (Platform.Property entry : entries) { if (entry.getName().equals(CONTAINER_IMAGE_ENTRY_NAME)) { if (result == null) { result = entry.getValue(); } else { // Multiple container name entries throw new IllegalArgumentException( "Multiple entries for " + CONTAINER_IMAGE_ENTRY_NAME + " in action.Platform"); } } } return result; } // Takes an Action and parameters that can be used to create a Command. Returns the Command. // If no docker container is specified inside Action, creates a Command straight from the // arguments. Otherwise, returns a Command that would run the specified command inside the // specified docker container. private Command getCommand( Action action, String[] commandLineElements, Map<String, String> environmentVariables, String pathString) throws IllegalArgumentException { String container = dockerContainer(action); if (container == null) { // Was not asked to Dokerize. return new Command(commandLineElements, environmentVariables, new File(pathString)); } // Run command inside a docker container. ArrayList<String> newCommandLineElements = new ArrayList<String>(); newCommandLineElements.add("docker"); newCommandLineElements.add("run"); long uid = getUid(); if (uid >= 0) { newCommandLineElements.add("-u"); newCommandLineElements.add(Long.toString(uid)); } final String dockerPathString = pathString + "-docker"; newCommandLineElements.add("-v"); newCommandLineElements.add(pathString + ":" + dockerPathString); newCommandLineElements.add("-w"); newCommandLineElements.add(dockerPathString); for (Map.Entry<String, String> entry : environmentVariables.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); newCommandLineElements.add("-e"); newCommandLineElements.add(key + "=" + value); } newCommandLineElements.add(container); newCommandLineElements.addAll(Arrays.asList(commandLineElements)); return new Command( newCommandLineElements.toArray(new String[newCommandLineElements.size()]), null, new File(pathString)); } public ExecuteReply execute(Action action, Path execRoot) throws IOException, InterruptedException, IllegalArgumentException { ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); try { RemoteProtocol.Command command = RemoteProtocol.Command.parseFrom(cache.downloadBlob(action.getCommandDigest())); cache.downloadTree(action.getInputRootDigest(), execRoot); List<Path> outputs = new ArrayList<>(action.getOutputPathList().size()); for (String output : action.getOutputPathList()) { Path file = execRoot.getRelative(output); if (file.exists()) { throw new FileAlreadyExistsException("Output file already exists: " + file); } FileSystemUtils.createDirectoryAndParents(file.getParentDirectory()); outputs.add(file); } // TODO(olaola): time out after specified server-side deadline. Command cmd = getCommand( action, command.getArgvList().toArray(new String[] {}), getEnvironmentVariables(command), execRoot.getPathString()); cmd.execute(Command.NO_INPUT, Command.NO_OBSERVER, stdout, stderr, true); // Execute throws a CommandException on non-zero return values, so action has succeeded. ImmutableList<ContentDigest> outErrDigests = cache.uploadBlobs(ImmutableList.of(stdout.toByteArray(), stderr.toByteArray())); ActionResult.Builder result = ActionResult.newBuilder() .setReturnCode(0) .setStdoutDigest(outErrDigests.get(0)) .setStderrDigest(outErrDigests.get(1)); cache.uploadAllResults(execRoot, outputs, result); cache.setCachedActionResult(ContentDigests.computeActionKey(action), result.build()); return ExecuteReply.newBuilder() .setResult(result) .setStatus(ExecutionStatus.newBuilder().setExecuted(true).setSucceeded(true)) .build(); } catch (CommandException e) { ImmutableList<ContentDigest> outErrDigests = cache.uploadBlobs(ImmutableList.of(stdout.toByteArray(), stderr.toByteArray())); final int returnCode = e instanceof AbnormalTerminationException ? ((AbnormalTerminationException) e) .getResult() .getTerminationStatus() .getExitCode() : -1; return ExecuteReply.newBuilder() .setResult( ActionResult.newBuilder() .setReturnCode(returnCode) .setStdoutDigest(outErrDigests.get(0)) .setStderrDigest(outErrDigests.get(1))) .setStatus( ExecutionStatus.newBuilder() .setExecuted(true) .setSucceeded(false) .setError(ExecutionStatus.ErrorCode.EXEC_FAILED) .setErrorDetail(e.toString())) .build(); } catch (CacheNotFoundException e) { LOG.warning("Cache miss on " + ContentDigests.toString(e.getMissingDigest())); return ExecuteReply.newBuilder() .setCasError( CasStatus.newBuilder() .setSucceeded(false) .addMissingDigest(e.getMissingDigest()) .setError(CasStatus.ErrorCode.MISSING_DIGEST) .setErrorDetail(e.toString())) .setStatus( ExecutionStatus.newBuilder() .setExecuted(false) .setSucceeded(false) .setError( e.getMissingDigest() == action.getCommandDigest() ? ExecutionStatus.ErrorCode.MISSING_COMMAND : ExecutionStatus.ErrorCode.MISSING_INPUT) .setErrorDetail(e.toString())) .build(); } } @Override public void execute(ExecuteRequest request, StreamObserver<ExecuteReply> responseObserver) { Path tempRoot = workPath.getRelative("build-" + UUID.randomUUID().toString()); try { tempRoot.createDirectory(); if (LOG_FINER) { LOG.fine( "Work received has " + request.getTotalInputFileCount() + " input files and " + request.getAction().getOutputPathCount() + " output files."); } ExecuteReply reply = execute(request.getAction(), tempRoot); responseObserver.onNext(reply); if (workerOptions.debug) { if (!reply.getStatus().getSucceeded()) { LOG.warning("Work failed. Request: " + request.toString() + "."); } else if (LOG_FINER) { LOG.fine("Work completed."); } } if (!workerOptions.debug) { FileSystemUtils.deleteTree(tempRoot); } else { LOG.warning("Preserving work directory " + tempRoot.toString() + "."); } } catch (IOException | InterruptedException e) { ExecuteReply.Builder reply = ExecuteReply.newBuilder(); reply.getStatusBuilder().setSucceeded(false).setErrorDetail(e.toString()); responseObserver.onNext(reply.build()); if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } } finally { responseObserver.onCompleted(); } } } public static void main(String[] args) throws Exception { OptionsParser parser = OptionsParser.newOptionsParser(RemoteOptions.class, RemoteWorkerOptions.class); parser.parseAndExitUponError(args); RemoteOptions remoteOptions = parser.getOptions(RemoteOptions.class); RemoteWorkerOptions remoteWorkerOptions = parser.getOptions(RemoteWorkerOptions.class); System.out.println("*** Initializing in-memory cache server."); boolean remoteCache = SimpleBlobStoreFactory.isRemoteCacheOptions(remoteOptions); if (!remoteCache) { System.out.println("*** Not using remote cache. This should be used for testing only!"); } SimpleBlobStore blobStore = remoteCache ? SimpleBlobStoreFactory.create(remoteOptions) : new SimpleBlobStoreFactory.ConcurrentMapBlobStore( new ConcurrentHashMap<String, byte[]>()); RemoteWorker worker = new RemoteWorker( remoteWorkerOptions, remoteOptions, new SimpleBlobStoreActionCache(blobStore)); final Server server = worker.startServer(); final Path pidFile; if (remoteWorkerOptions.pidFile != null) { pidFile = getFileSystem().getPath(remoteWorkerOptions.pidFile); PrintWriter writer = new PrintWriter(pidFile.getOutputStream()); writer.append(Integer.toString(ProcessUtils.getpid())); writer.append("\n"); writer.close(); } else { pidFile = null; } Runtime.getRuntime() .addShutdownHook( new Thread() { @Override public void run() { System.err.println("*** Shutting down grpc server."); server.shutdown(); if (pidFile != null) { try { pidFile.delete(); } catch (IOException e) { System.err.println("Cannot remove pid file: " + pidFile.toString()); } } System.err.println("*** Server shut down."); } }); server.awaitTermination(); } static FileSystem getFileSystem() { return OS.getCurrent() == OS.WINDOWS ? new JavaIoFileSystem() : new UnixFileSystem(); } }
/* * (C) Copyright 2017-2018 OpenVidu (https://openvidu.io/) * * 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.openvidu.server.core; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.annotation.PreDestroy; import org.apache.commons.lang3.RandomStringUtils; import org.kurento.jsonrpc.message.Request; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import io.openvidu.client.OpenViduException; import io.openvidu.client.OpenViduException.Code; import io.openvidu.client.internal.ProtocolElements; import io.openvidu.java.client.SessionProperties; import io.openvidu.server.OpenViduServer; import io.openvidu.server.cdr.CallDetailRecord; import io.openvidu.server.config.OpenviduConfig; import io.openvidu.server.coturn.CoturnCredentialsService; import io.openvidu.server.coturn.TurnCredentials; import io.openvidu.server.kurento.core.KurentoTokenOptions; import io.openvidu.server.recording.ComposedRecordingService; public abstract class SessionManager { private static final Logger log = LoggerFactory.getLogger(SessionManager.class); @Autowired protected SessionEventsHandler sessionEventsHandler; @Autowired protected ComposedRecordingService recordingService; @Autowired protected CallDetailRecord CDR; @Autowired protected OpenviduConfig openviduConfig; @Autowired protected CoturnCredentialsService coturnCredentialsService; protected ConcurrentMap<String, Session> sessions = new ConcurrentHashMap<>(); protected ConcurrentMap<String, SessionProperties> sessionProperties = new ConcurrentHashMap<>(); protected ConcurrentMap<String, Long> sessionCreationTime = new ConcurrentHashMap<>(); protected ConcurrentMap<String, ConcurrentHashMap<String, Participant>> sessionidParticipantpublicidParticipant = new ConcurrentHashMap<>(); protected ConcurrentMap<String, Boolean> insecureUsers = new ConcurrentHashMap<>(); public ConcurrentMap<String, ConcurrentHashMap<String, Token>> sessionidTokenTokenobj = new ConcurrentHashMap<>(); private volatile boolean closed = false; public abstract void joinRoom(Participant participant, String sessionId, Integer transactionId); public abstract void leaveRoom(Participant participant, Integer transactionId, String reason, boolean closeWebSocket); public abstract void publishVideo(Participant participant, MediaOptions mediaOptions, Integer transactionId); public abstract void unpublishVideo(Participant participant, Participant moderator, Integer transactionId, String reason); public abstract void subscribe(Participant participant, String senderName, String sdpOffer, Integer transactionId); public abstract void unsubscribe(Participant participant, String senderName, Integer transactionId); public abstract void sendMessage(Participant participant, String message, Integer transactionId); public abstract void streamPropertyChanged(Participant participant, Integer transactionId, String streamId, String property, JsonElement newValue, String reason); public abstract void onIceCandidate(Participant participant, String endpointName, String candidate, int sdpMLineIndex, String sdpMid, Integer transactionId); public abstract boolean unpublishStream(Session session, String streamId, Participant moderator, Integer transactionId, String reason); public abstract void evictParticipant(Participant evictedParticipant, Participant moderator, Integer transactionId, String reason); public abstract void applyFilter(Session session, String streamId, String filterType, JsonObject filterOptions, Participant moderator, Integer transactionId, String reason); public abstract void execFilterMethod(Session session, String streamId, String filterMethod, JsonObject filterParams, Participant moderator, Integer transactionId, String reason); public abstract void removeFilter(Session session, String streamId, Participant moderator, Integer transactionId, String reason); public abstract void addFilterEventListener(Session session, Participant subscriber, String streamId, String eventType); public abstract void removeFilterEventListener(Session session, Participant subscriber, String streamId, String eventType); public abstract String getParticipantPrivateIdFromStreamId(String sessionId, String streamId) throws OpenViduException; /** * Returns a Session given its id * * @return Session */ public Session getSession(String sessionId) { return sessions.get(sessionId); } /** * Returns all currently active (opened) sessions. * * @return set of the session's identifiers */ public Set<String> getSessions() { return new HashSet<String>(sessions.keySet()); } /** * Returns all currently active (opened) sessions. * * @return set of the session's identifiers */ public Collection<Session> getSessionObjects() { return sessions.values(); } /** * Returns all the participants inside a session. * * @param sessionId * identifier of the session * @return set of {@link Participant} * @throws OpenViduException * in case the session doesn't exist */ public Set<Participant> getParticipants(String sessionId) throws OpenViduException { Session session = sessions.get(sessionId); if (session == null) { throw new OpenViduException(Code.ROOM_NOT_FOUND_ERROR_CODE, "Session '" + sessionId + "' not found"); } Set<Participant> participants = session.getParticipants(); participants.removeIf(p -> p.isClosed()); return participants; } /** * Returns a participant in a session * * @param sessionId * identifier of the session * @param participantPrivateId * private identifier of the participant * @return {@link Participant} * @throws OpenViduException * in case the session doesn't exist or the participant doesn't * belong to it */ public Participant getParticipant(String sessionId, String participantPrivateId) throws OpenViduException { Session session = sessions.get(sessionId); if (session == null) { throw new OpenViduException(Code.ROOM_NOT_FOUND_ERROR_CODE, "Session '" + sessionId + "' not found"); } Participant participant = session.getParticipantByPrivateId(participantPrivateId); if (participant == null) { throw new OpenViduException(Code.USER_NOT_FOUND_ERROR_CODE, "Participant '" + participantPrivateId + "' not found in session '" + sessionId + "'"); } return participant; } /** * Returns a participant * * @param participantPrivateId * private identifier of the participant * @return {@link Participant} * @throws OpenViduException * in case the participant doesn't exist */ public Participant getParticipant(String participantPrivateId) throws OpenViduException { for (Session session : sessions.values()) { if (!session.isClosed()) { if (session.getParticipantByPrivateId(participantPrivateId) != null) { return session.getParticipantByPrivateId(participantPrivateId); } } } throw new OpenViduException(Code.USER_NOT_FOUND_ERROR_CODE, "No participant with private id '" + participantPrivateId + "' was found"); } public MediaOptions generateMediaOptions(Request<JsonObject> request) { return null; } public void storeSessionId(String sessionId, Long creationTime, SessionProperties sessionProperties) { this.sessionidParticipantpublicidParticipant.putIfAbsent(sessionId, new ConcurrentHashMap<>()); this.sessionProperties.putIfAbsent(sessionId, sessionProperties); this.sessionCreationTime.putIfAbsent(sessionId, creationTime); showTokens(); } public String newToken(String sessionId, ParticipantRole role, String serverMetadata, KurentoTokenOptions kurentoTokenOptions) throws OpenViduException { ConcurrentHashMap<String, Token> map = this.sessionidTokenTokenobj.putIfAbsent(sessionId, new ConcurrentHashMap<>()); if (map != null) { if (!isMetadataFormatCorrect(serverMetadata)) { log.error("Data invalid format. Max length allowed is 10000 chars"); throw new OpenViduException(Code.GENERIC_ERROR_CODE, "Data invalid format. Max length allowed is 10000 chars"); } String token = OpenViduServer.publicUrl; token += "?sessionId=" + sessionId; token += "&token=" + this.generateRandomChain(); token += "&role=" + role.name(); TurnCredentials turnCredentials = null; if (this.coturnCredentialsService.isCoturnAvailable()) { turnCredentials = coturnCredentialsService.createUser(); if (turnCredentials != null) { token += "&turnUsername=" + turnCredentials.getUsername(); token += "&turnCredential=" + turnCredentials.getCredential(); } } Token t = new Token(token, role, serverMetadata, turnCredentials, kurentoTokenOptions); map.putIfAbsent(token, t); showTokens(); return token; } else { this.sessionidTokenTokenobj.remove(sessionId); log.error("sessionId [" + sessionId + "] is not valid"); throw new OpenViduException(Code.ROOM_NOT_FOUND_ERROR_CODE, "sessionId [" + sessionId + "] not found"); } } public boolean isTokenValidInSession(String token, String sessionId, String participanPrivatetId) { if (!this.isInsecureParticipant(participanPrivatetId)) { if (this.sessionidTokenTokenobj.get(sessionId) != null) { return this.sessionidTokenTokenobj.get(sessionId).containsKey(token); } else { return false; } } else { this.sessionidParticipantpublicidParticipant.putIfAbsent(sessionId, new ConcurrentHashMap<>()); this.sessionCreationTime.putIfAbsent(sessionId, System.currentTimeMillis()); this.sessionidTokenTokenobj.putIfAbsent(sessionId, new ConcurrentHashMap<>()); this.sessionidTokenTokenobj.get(sessionId).putIfAbsent(token, new Token(token, ParticipantRole.PUBLISHER, "", this.coturnCredentialsService.isCoturnAvailable() ? this.coturnCredentialsService.createUser() : null, null)); return true; } } public boolean isParticipantInSession(String sessionId, Participant participant) { Session session = this.sessions.get(sessionId); if (session != null) { return (session.getParticipantByPrivateId(participant.getParticipantPrivateId()) != null); } else { throw new OpenViduException(Code.ROOM_NOT_FOUND_ERROR_CODE, "[" + sessionId + "] is not a valid sessionId"); } } public boolean isPublisherInSession(String sessionId, Participant participant) { if (!this.isInsecureParticipant(participant.getParticipantPrivateId())) { if (this.sessionidParticipantpublicidParticipant.get(sessionId) != null) { return (ParticipantRole.PUBLISHER.equals(participant.getToken().getRole()) || ParticipantRole.MODERATOR.equals(participant.getToken().getRole())); } else { return false; } } else { return true; } } public boolean isModeratorInSession(String sessionId, Participant participant) { if (!this.isInsecureParticipant(participant.getParticipantPrivateId())) { if (this.sessionidParticipantpublicidParticipant.get(sessionId) != null) { return ParticipantRole.MODERATOR.equals(participant.getToken().getRole()); } else { return false; } } else { return true; } } public boolean isInsecureParticipant(String participantPrivateId) { if (this.insecureUsers.containsKey(participantPrivateId)) { log.info("The user with private id {} is an INSECURE user", participantPrivateId); return true; } return false; } public boolean isMetadataFormatCorrect(String metadata) { // Max 10000 chars return (metadata.length() <= 10000); } public void newInsecureParticipant(String participantPrivateId) { this.insecureUsers.put(participantPrivateId, true); } public Participant newParticipant(String sessionId, String participantPrivatetId, Token token, String clientMetadata, String location, String platform) { if (this.sessionidParticipantpublicidParticipant.get(sessionId) != null) { String participantPublicId = this.generateRandomChain(); Participant p = new Participant(participantPrivatetId, participantPublicId, token, clientMetadata, location, platform, null); while (this.sessionidParticipantpublicidParticipant.get(sessionId).putIfAbsent(participantPublicId, p) != null) { participantPublicId = this.generateRandomChain(); p.setParticipantPublicId(participantPublicId); } return p; } else { throw new OpenViduException(Code.ROOM_NOT_FOUND_ERROR_CODE, sessionId); } } public Participant newRecorderParticipant(String sessionId, String participantPrivatetId, Token token, String clientMetadata) { if (this.sessionidParticipantpublicidParticipant.get(sessionId) != null) { Participant p = new Participant(participantPrivatetId, ProtocolElements.RECORDER_PARTICIPANT_PUBLICID, token, clientMetadata, null, null, null); this.sessionidParticipantpublicidParticipant.get(sessionId) .put(ProtocolElements.RECORDER_PARTICIPANT_PUBLICID, p); return p; } else { throw new OpenViduException(Code.ROOM_NOT_FOUND_ERROR_CODE, sessionId); } } public Token consumeToken(String sessionId, String participantPrivateId, String token) { if (this.sessionidTokenTokenobj.get(sessionId) != null) { Token t = this.sessionidTokenTokenobj.get(sessionId).remove(token); if (t != null) { return t; } else { throw new OpenViduException(Code.TOKEN_CANNOT_BE_CREATED_ERROR_CODE, sessionId); } } else { throw new OpenViduException(Code.ROOM_NOT_FOUND_ERROR_CODE, sessionId); } } public void showTokens() { log.info("<SESSIONID, TOKENS>: {}", this.sessionidTokenTokenobj.toString()); } public void showInsecureParticipants() { log.info("<INSECURE_PARTICIPANTS>: {}", this.insecureUsers.toString()); } public void showAllParticipants() { log.info("<SESSIONID, PARTICIPANTS>: {}", this.sessionidParticipantpublicidParticipant.toString()); } public String generateRandomChain() { return RandomStringUtils.randomAlphanumeric(16).toLowerCase(); } /** * Closes all resources. This method has been annotated with the @PreDestroy * directive (javax.annotation package) so that it will be automatically called * when the SessionManager instance is container-managed. <br/> * <strong>Dev advice:</strong> Send notifications to all participants to inform * that their session has been forcibly closed. * * @see SessionManmager#closeSession(String) */ @PreDestroy public void close() { closed = true; log.info("Closing all sessions"); for (String sessionId : sessions.keySet()) { try { closeSession(sessionId, "openviduServerStopped"); } catch (Exception e) { log.warn("Error closing session '{}'", sessionId, e); } } } /** * Closes an existing session by releasing all resources that were allocated for * it. Once closed, the session can be reopened (will be empty and it will use * another Media Pipeline). Existing participants will be evicted. <br/> * <strong>Dev advice:</strong> The session event handler should send * notifications to the existing participants in the session to inform that it * was forcibly closed. * * @param sessionId * identifier of the session * @return * @return set of {@link Participant} POJOS representing the session's * participants * @throws OpenViduException * in case the session doesn't exist or has been already closed */ public Set<Participant> closeSession(String sessionId, String reason) { Session session = sessions.get(sessionId); if (session == null) { throw new OpenViduException(Code.ROOM_NOT_FOUND_ERROR_CODE, "Session '" + sessionId + "' not found"); } if (session.isClosed()) { throw new OpenViduException(Code.ROOM_CLOSED_ERROR_CODE, "Session '" + sessionId + "' already closed"); } Set<Participant> participants = getParticipants(sessionId); for (Participant p : participants) { try { this.evictParticipant(p, null, null, reason); } catch (OpenViduException e) { log.warn("Error evicting participant '{}' from session '{}'", p.getParticipantPublicId(), sessionId, e); } } this.closeSessionAndEmptyCollections(session, reason); if (recordingService.sessionIsBeingRecorded(session.getSessionId())) { recordingService.stopRecording(session, null, reason); } return participants; } public void closeSessionAndEmptyCollections(Session session, String reason) { if (session.close(reason)) { sessionEventsHandler.onSessionClosed(session.getSessionId(), reason); } sessions.remove(session.getSessionId()); sessionProperties.remove(session.getSessionId()); sessionCreationTime.remove(session.getSessionId()); sessionidParticipantpublicidParticipant.remove(session.getSessionId()); sessionidTokenTokenobj.remove(session.getSessionId()); log.warn("Session '{}' removed and closed", session.getSessionId()); } }
package net.termat.gtfsviewer.gtfs.model; import androidx.room.Database; import androidx.room.RoomDatabase; @Database(entities = {GTranslation.class}, version = 1, exportSchema = false) public abstract class GTranslationDB extends RoomDatabase { public abstract GtranslationDao getDao(); }
/* * Copyright (C) 2012 Zach Melamed * * Latest version available online at https://github.com/zach-m/jonix * Contact me at zach@tectonica.co.il * * 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.tectonica.jonix.codelist; import java.util.HashMap; import java.util.Map; import com.tectonica.jonix.OnixCodelist; /* * NOTE: THIS IS AN AUTO-GENERATED FILE, DON'T EDIT MANUALLY */ /** * marker interface to assist in IDE navigation to code-list 1 (Notification or update type code) */ interface CodeList1 {} /** * <code>Enum</code> that corresponds to ONIX <b>Codelist 1</b> * <p> * Description: Notification or update type code * * @see <a href="http://www.editeur.org/14/code-lists">About ONIX Codelists</a> * @see <a * href="http://www.editeur.org/files/ONIX%20for%20books%20-%20code%20lists/ONIX_BookProduct_Codelists_Issue_32.html#codelist1">ONIX * Codelist 1 in Reference Guide</a> */ public enum NotificationOrUpdateTypes implements OnixCodelist, CodeList1 { /** * Use for a complete record issued earlier than approximately six months before publication */ Early_notification("01", "Early notification"), // /** * Use for a complete record issued to confirm advance information approximately six months before publication; or * for a complete record issued after that date and before information has been confirmed from the book-in-hand */ Advance_notification_confirmed("02", "Advance notification (confirmed)"), // /** * Use for a complete record issued to confirm advance information at or just before actual publication date; or for * a complete record issued at any later date */ Notification_confirmed_on_publication("03", "Notification confirmed on publication"), // /** * In ONIX 3.0 only, use when sending a 'block update' record. In previous ONIX releases, ONIX updating has * generally been by complete record replacement using code 03, and code 04 is not used */ Update_partial("04", "Update (partial)"), // /** * Use when sending an instruction to delete a record which was previously issued. Note that a Delete instruction * should NOT be used when a product is cancelled, put out of print, or otherwise withdrawn from sale: this should * be handled as a change of Publishing status, leaving the receiver to decide whether to retain or delete the * record. A Delete instruction is only used when there is a particular reason to withdraw a record completely, eg * because it was issued in error */ Delete("05", "Delete"), // /** * Notice of sale of a product, from one publisher to another: sent by the publisher disposing of the product */ Notice_of_sale("08", "Notice of sale"), // /** * Notice of acquisition of a product, by one publisher from another: sent by the acquiring publisher */ Notice_of_acquisition("09", "Notice of acquisition"), // /** * ONIX Books 2.1 supply update - &lt;SupplyDetail&gt; only (not used in ONIX 3.0) */ Update_SupplyDetail_only("12", "Update – SupplyDetail only"), // /** * ONIX Books 2.1 supply update - &lt;MarketRepresentation&gt; only (not used in ONIX 3.0) */ Update_MarketRepresentation_only("13", "Update – MarketRepresentation only"), // /** * ONIX Books 2.1 supply update - both &lt;SupplyDetail&gt; and &lt;MarketRepresentation&gt; (not used in ONIX 3.0) */ Update_SupplyDetail_and_MarketRepresentation("14", "Update – SupplyDetail and MarketRepresentation"), // /** * ONIX 3.0 only. Record may be processed for test purposes, but data should be discarded. Sender must ensure the * &lt;RecordReference&gt; matches a previously-sent Test record */ Test_update_Partial("88", "Test update (Partial)"), // /** * Record may be processed for test purposes, but data should be discarded. Sender must ensure the * &lt;RecordReference&gt; does not match any previously-sent live product record */ Test_record("89", "Test record"); public final String code; public final String description; private NotificationOrUpdateTypes(String code, String description) { this.code = code; this.description = description; } @Override public String getCode() { return code; } @Override public String getDescription() { return description; } private static volatile Map<String, NotificationOrUpdateTypes> map; private static Map<String, NotificationOrUpdateTypes> map() { Map<String, NotificationOrUpdateTypes> result = map; if (result == null) { synchronized (NotificationOrUpdateTypes.class) { result = map; if (result == null) { result = new HashMap<>(); for (NotificationOrUpdateTypes e : values()) result.put(e.code, e); map = result; } } } return result; } public static NotificationOrUpdateTypes byCode(String code) { if (code == null || code.isEmpty()) return null; return map().get(code); } }
package net.whydah.sso.session.baseclasses; import net.whydah.sso.application.mappers.ApplicationMapper; import net.whydah.sso.application.types.Application; import net.whydah.sso.basehelpers.JsonPathHelper; import net.whydah.sso.commands.application.CommandListApplications; import net.whydah.sso.util.LoggerUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.ArrayList; import java.util.List; public class ApplicationModelUtil { public static final String maxSessionTimeoutSeconds = "$.security.maxSessionTimeoutSeconds"; public static final String minDEFCON = "$.security.minDEFCON"; public static final String minSecurityLevel = "$.security.minSecurityLevel"; private static final Logger log = LoggerFactory.getLogger(ApplicationModelUtil.class); private static List<Application> applications = new ArrayList<Application>(); public static List<Application> getApplicationList() { return applications; } public static Application getApplication(String applicationID) { for (Application application : applications) { if (application.getId().equalsIgnoreCase(applicationID)) { return application; } } return null; } // JsonPath query against Application.json to find value, empty string if not found public static String getParameterForApplication(String param, String applicationID) { if (applications == null) { return ""; } try { for (Application application : applications) { if (applicationID.equalsIgnoreCase(application.getId())) { log.debug("Found application, looking for ", param); return JsonPathHelper.findJsonPathValue(ApplicationMapper.toJson(application), param); } } } catch (Exception e) { log.warn("Attempt to find {} from applicationID: {} failed. returning empty string.", param, applicationID); } return ""; } public static void updateApplicationList(URI userAdminServiceUri, String myAppTokenId, String userTokenId) { if (userAdminServiceUri != null) { String applicationsJson = new net.whydah.sso.commands.application.CommandListApplications(userAdminServiceUri, myAppTokenId).execute(); log.trace("AppLications returned:" + LoggerUtil.first50(applicationsJson)); if (applicationsJson != null) { if (applicationsJson.length() > 20) { try { List<Application> newapplications = ApplicationMapper.fromJsonList(applicationsJson); updateApplications(newapplications); } catch (Exception e) { log.warn("Unable to update applicationList"); } } } } } public static void updateApplicationList(URI userAdminServiceUri, String myAppTokenId) { if (userAdminServiceUri != null) { String applicationsJson = new CommandListApplications(userAdminServiceUri, myAppTokenId).execute(); log.trace("AppLications returned:" + LoggerUtil.first50(applicationsJson)); if (applicationsJson != null) { if (applicationsJson.length() > 20) { try { List<Application> newapplications = ApplicationMapper.fromJsonList(applicationsJson); updateApplications(newapplications); } catch (Exception e) { log.warn("Unable to update applicationList"); } } } } } private static synchronized void updateApplications(List<Application> newapplications) { applications = newapplications; } public static boolean shouldUpdate() { int max = 100; return (5 >= ((int) (Math.random() * max))); // update on 5 percent of requests } public static boolean shouldUpdate(int percentage) { int max = 100; return (percentage >= ((int) (Math.random() * max))); // update on 5 percent of requests } }
/* * 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.asterix.api.http.server; import java.io.IOException; import java.util.concurrent.ConcurrentMap; import org.apache.asterix.api.common.ResultMetadata; import org.apache.asterix.app.result.ResponseMetrics; import org.apache.asterix.app.result.ResponsePrinter; import org.apache.asterix.app.result.ResultHandle; import org.apache.asterix.app.result.ResultReader; import org.apache.asterix.app.result.fields.MetricsPrinter; import org.apache.asterix.app.result.fields.ProfilePrinter; import org.apache.asterix.app.result.fields.ResultsPrinter; import org.apache.asterix.common.api.IApplicationContext; import org.apache.asterix.translator.IStatementExecutor.Stats; import org.apache.asterix.translator.SessionConfig; import org.apache.asterix.translator.SessionOutput; import org.apache.hyracks.api.exceptions.ErrorCode; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.api.result.IResultSet; import org.apache.hyracks.api.result.ResultJobRecord; import org.apache.hyracks.http.api.IServletRequest; import org.apache.hyracks.http.api.IServletResponse; import org.apache.hyracks.http.server.utils.HttpUtil; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.netty.handler.codec.http.HttpResponseStatus; public class QueryResultApiServlet extends AbstractQueryApiServlet { private static final Logger LOGGER = LogManager.getLogger(); public QueryResultApiServlet(ConcurrentMap<String, Object> ctx, IApplicationContext appCtx, String... paths) { super(appCtx, ctx, paths); } @Override protected void get(IServletRequest request, IServletResponse response) throws Exception { long elapsedStart = System.nanoTime(); HttpUtil.setContentType(response, HttpUtil.ContentType.TEXT_HTML, request); final String strHandle = localPath(request); final ResultHandle handle = ResultHandle.parse(strHandle); if (handle == null) { response.setStatus(HttpResponseStatus.BAD_REQUEST); return; } IResultSet resultSet = getResultSet(); ResultReader resultReader = new ResultReader(resultSet, handle.getJobId(), handle.getResultSetId()); try { ResultJobRecord.Status status = resultReader.getStatus(); final HttpResponseStatus httpStatus; if (status == null) { httpStatus = HttpResponseStatus.NOT_FOUND; } else { switch (status.getState()) { case SUCCESS: httpStatus = HttpResponseStatus.OK; break; case RUNNING: case IDLE: case FAILED: httpStatus = HttpResponseStatus.NOT_FOUND; break; default: httpStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR; break; } } response.setStatus(httpStatus); if (httpStatus != HttpResponseStatus.OK) { return; } ResultMetadata metadata = (ResultMetadata) resultReader.getMetadata(); SessionOutput sessionOutput = initResponse(request, response, metadata.getFormat()); ResponsePrinter printer = new ResponsePrinter(sessionOutput); if (metadata.getFormat() == SessionConfig.OutputFormat.CLEAN_JSON || metadata.getFormat() == SessionConfig.OutputFormat.LOSSLESS_JSON) { final Stats stats = new Stats(); printer.begin(); printer.addResultPrinter(new ResultsPrinter(appCtx, resultReader, null, stats, sessionOutput)); printer.printResults(); ResponseMetrics metrics = ResponseMetrics.of(System.nanoTime() - elapsedStart, metadata.getJobDuration(), stats.getCount(), stats.getSize(), metadata.getProcessedObjects(), 0, metadata.getTotalWarningsCount()); printer.addFooterPrinter(new MetricsPrinter(metrics, HttpUtil.getPreferredCharset(request))); if (metadata.getJobProfile() != null) { printer.addFooterPrinter(new ProfilePrinter(metadata.getJobProfile())); } printer.printFooters(); printer.end(); } else { ResultUtil.printResults(appCtx, resultReader, sessionOutput, new Stats(), null); } } catch (HyracksDataException e) { if (e.matches(ErrorCode.NO_RESULT_SET)) { LOGGER.log(Level.INFO, "No results for: \"" + strHandle + "\""); response.setStatus(HttpResponseStatus.NOT_FOUND); return; } response.setStatus(HttpResponseStatus.BAD_REQUEST); response.writer().println(e.getMessage()); LOGGER.log(Level.WARN, "Error retrieving result for \"" + strHandle + "\"", e); } catch (Exception e) { response.setStatus(HttpResponseStatus.BAD_REQUEST); LOGGER.log(Level.WARN, "Error retrieving result for \"" + strHandle + "\"", e); } if (response.writer().checkError()) { LOGGER.warn("Error flushing output writer for \"" + strHandle + "\""); } } /** * Initialize the Content-Type of the response, and construct a * SessionConfig with the appropriate output writer and output-format * based on the Accept: header and other servlet parameters. */ static SessionOutput initResponse(IServletRequest request, IServletResponse response, SessionConfig.OutputFormat format) throws IOException { String accept = request.getHeader("Accept"); if (accept == null) { accept = ""; } SessionConfig.PlanFormat planFormat = SessionConfig.PlanFormat.get(request.getParameter("plan-format"), "plan format", SessionConfig.PlanFormat.STRING, LOGGER); SessionOutput.ResultAppender appendHandle = (app, handle) -> app.append("{ \"").append("handle") .append("\":" + " \"").append(handle).append("\" }"); SessionConfig sessionConfig = new SessionConfig(format, planFormat); // If it's JSON or ADM, check for the "wrapper-array" flag. Default is // "true" for JSON and "false" for ADM. (Not applicable for CSV.) boolean wrapperArray = format == SessionConfig.OutputFormat.CLEAN_JSON || format == SessionConfig.OutputFormat.LOSSLESS_JSON; String wrapperParam = request.getParameter("wrapper-array"); if (wrapperParam != null) { wrapperArray = Boolean.valueOf(wrapperParam); } else if (accept.contains("wrap-array=true")) { wrapperArray = true; } else if (accept.contains("wrap-array=false")) { wrapperArray = false; } sessionConfig.set(SessionConfig.FORMAT_WRAPPER_ARRAY, wrapperArray); // Now that format is set, output the content-type SessionOutput.ResultDecorator resultPrefix = null; SessionOutput.ResultDecorator resultPostfix = null; switch (format) { case ADM: HttpUtil.setContentType(response, "application/x-adm", request); break; case CLEAN_JSON: // No need to reflect "clean-ness" in output type; fall through case LOSSLESS_JSON: HttpUtil.setContentType(response, "application/json", request); resultPrefix = ResultUtil.createPreResultDecorator(); resultPostfix = ResultUtil.createPostResultDecorator(); break; case CSV: // Check for header parameter or in Accept:. if ("present".equals(request.getParameter("header")) || accept.contains("header=present")) { HttpUtil.setContentType(response, "text/csv; header=present", request); sessionConfig.set(SessionConfig.FORMAT_CSV_HEADER, true); } else { HttpUtil.setContentType(response, "text/csv; header=absent", request); } break; default: throw new IOException("Unknown format " + format); } return new SessionOutput(sessionConfig, response.writer(), resultPrefix, resultPostfix, appendHandle, null); } }
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.Periodics.Auto.Action; import frc.robot.Subsystems.Drivebase; /** * Add your docs here. */ public class StopAction implements Action { public Drivebase mDrive; @Override public void done() { // TODO Auto-generated method stub } @Override public boolean isFinished() { return false; } @Override public void start() { mDrive = Drivebase.getInstance(); mDrive.stopDrive(); } @Override public void update() { mDrive.stopDrive(); } }
/** * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.api; import java.math.BigDecimal; import org.openapitools.model.Client; import org.openapitools.model.FileSchemaTestClass; import java.time.LocalDate; import java.util.Map; import org.openapitools.model.ModelApiResponse; import java.time.OffsetDateTime; import org.openapitools.model.OuterComposite; import org.openapitools.model.User; import org.openapitools.model.XmlItem; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import springfox.documentation.annotations.ApiIgnore; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; import java.util.Map; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") public interface FakeApi { default FakeApiDelegate getDelegate() { return new FakeApiDelegate() {}; } /** * POST /fake/create_xml_item : creates an XmlItem * this route creates an XmlItem * * @param xmlItem XmlItem Body (required) * @return successful operation (status code 200) */ @ApiOperation(value = "creates an XmlItem", nickname = "createXmlItem", notes = "this route creates an XmlItem", tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @PostMapping( value = "/fake/create_xml_item", consumes = { "application/xml", "application/xml; charset=utf-8", "application/xml; charset=utf-16", "text/xml", "text/xml; charset=utf-8", "text/xml; charset=utf-16" } ) default ResponseEntity<Void> createXmlItem(@ApiParam(value = "XmlItem Body" ,required=true ) @Valid @RequestBody XmlItem xmlItem) { return getDelegate().createXmlItem(xmlItem); } /** * POST /fake/outer/boolean * Test serialization of outer boolean types * * @param body Input boolean as post body (optional) * @return Output boolean (status code 200) */ @ApiOperation(value = "", nickname = "fakeOuterBooleanSerialize", notes = "Test serialization of outer boolean types", response = Boolean.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output boolean", response = Boolean.class) }) @PostMapping( value = "/fake/outer/boolean", produces = { "*/*" } ) default ResponseEntity<Boolean> fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { return getDelegate().fakeOuterBooleanSerialize(body); } /** * POST /fake/outer/composite * Test serialization of object with outer number type * * @param body Input composite as post body (optional) * @return Output composite (status code 200) */ @ApiOperation(value = "", nickname = "fakeOuterCompositeSerialize", notes = "Test serialization of object with outer number type", response = OuterComposite.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output composite", response = OuterComposite.class) }) @PostMapping( value = "/fake/outer/composite", produces = { "*/*" } ) default ResponseEntity<OuterComposite> fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { return getDelegate().fakeOuterCompositeSerialize(body); } /** * POST /fake/outer/number * Test serialization of outer number types * * @param body Input number as post body (optional) * @return Output number (status code 200) */ @ApiOperation(value = "", nickname = "fakeOuterNumberSerialize", notes = "Test serialization of outer number types", response = BigDecimal.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output number", response = BigDecimal.class) }) @PostMapping( value = "/fake/outer/number", produces = { "*/*" } ) default ResponseEntity<BigDecimal> fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { return getDelegate().fakeOuterNumberSerialize(body); } /** * POST /fake/outer/string * Test serialization of outer string types * * @param body Input string as post body (optional) * @return Output string (status code 200) */ @ApiOperation(value = "", nickname = "fakeOuterStringSerialize", notes = "Test serialization of outer string types", response = String.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output string", response = String.class) }) @PostMapping( value = "/fake/outer/string", produces = { "*/*" } ) default ResponseEntity<String> fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { return getDelegate().fakeOuterStringSerialize(body); } /** * PUT /fake/body-with-file-schema * For this test, the body for this request much reference a schema named &#x60;File&#x60;. * * @param body (required) * @return Success (status code 200) */ @ApiOperation(value = "", nickname = "testBodyWithFileSchema", notes = "For this test, the body for this request much reference a schema named `File`.", tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success") }) @PutMapping( value = "/fake/body-with-file-schema", consumes = { "application/json" } ) default ResponseEntity<Void> testBodyWithFileSchema(@ApiParam(value = "" ,required=true ) @Valid @RequestBody FileSchemaTestClass body) { return getDelegate().testBodyWithFileSchema(body); } /** * PUT /fake/body-with-query-params * * @param query (required) * @param body (required) * @return Success (status code 200) */ @ApiOperation(value = "", nickname = "testBodyWithQueryParams", notes = "", tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success") }) @PutMapping( value = "/fake/body-with-query-params", consumes = { "application/json" } ) default ResponseEntity<Void> testBodyWithQueryParams(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "query", required = true) String query,@ApiParam(value = "" ,required=true ) @Valid @RequestBody User body) { return getDelegate().testBodyWithQueryParams(query, body); } /** * PATCH /fake : To test \&quot;client\&quot; model * To test \&quot;client\&quot; model * * @param body client model (required) * @return successful operation (status code 200) */ @ApiOperation(value = "To test \"client\" model", nickname = "testClientModel", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) @PatchMapping( value = "/fake", produces = { "application/json" }, consumes = { "application/json" } ) default ResponseEntity<Client> testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { return getDelegate().testClientModel(body); } /** * POST /fake : Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * * @param number None (required) * @param _double None (required) * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) * @param paramCallback None (optional) * @return Invalid username supplied (status code 400) * or User not found (status code 404) */ @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", nickname = "testEndpointParameters", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", authorizations = { @Authorization(value = "http_basic_test") }, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied"), @ApiResponse(code = 404, message = "User not found") }) @PostMapping( value = "/fake", consumes = { "application/x-www-form-urlencoded" } ) default ResponseEntity<Void> testEndpointParameters(@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "number", required = true) BigDecimal number,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "double", required = true) Double _double,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "pattern_without_delimiter", required = true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "byte", required = true) byte[] _byte,@ApiParam(value = "None") @Valid @RequestPart(value = "integer", required = false) Integer integer,@ApiParam(value = "None") @Valid @RequestPart(value = "int32", required = false) Integer int32,@ApiParam(value = "None") @Valid @RequestPart(value = "int64", required = false) Long int64,@ApiParam(value = "None") @Valid @RequestPart(value = "float", required = false) Float _float,@ApiParam(value = "None") @Valid @RequestPart(value = "string", required = false) String string,@ApiParam(value = "None") @Valid @RequestPart(value = "binary", required = false) MultipartFile binary,@ApiParam(value = "None") @Valid @RequestPart(value = "date", required = false) LocalDate date,@ApiParam(value = "None") @Valid @RequestPart(value = "dateTime", required = false) OffsetDateTime dateTime,@ApiParam(value = "None") @Valid @RequestPart(value = "password", required = false) String password,@ApiParam(value = "None") @Valid @RequestPart(value = "callback", required = false) String paramCallback) { return getDelegate().testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); } /** * GET /fake : To test enum parameters * To test enum parameters * * @param enumHeaderStringArray Header parameter enum test (string array) (optional, default to new ArrayList&lt;&gt;()) * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) * @param enumQueryStringArray Query parameter enum test (string array) (optional, default to new ArrayList&lt;&gt;()) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) * @param enumFormStringArray Form parameter enum test (string array) (optional, default to $) * @param enumFormString Form parameter enum test (string) (optional, default to -efg) * @return Invalid request (status code 400) * or Not found (status code 404) */ @ApiOperation(value = "To test enum parameters", nickname = "testEnumParameters", notes = "To test enum parameters", tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid request"), @ApiResponse(code = 404, message = "Not found") }) @GetMapping( value = "/fake", consumes = { "application/x-www-form-urlencoded" } ) default ResponseEntity<Void> testEnumParameters(@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List<String> enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List<String> enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1.1, -1.2") @Valid @RequestParam(value = "enum_query_double", required = false) Double enumQueryDouble,@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @Valid @RequestPart(value = "enum_form_string_array", required = false) List<String> enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @Valid @RequestPart(value = "enum_form_string", required = false) String enumFormString) { return getDelegate().testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); } /** * DELETE /fake : Fake endpoint to test group parameters (optional) * Fake endpoint to test group parameters (optional) * * @param requiredStringGroup Required String in group parameters (required) * @param requiredBooleanGroup Required Boolean in group parameters (required) * @param requiredInt64Group Required Integer in group parameters (required) * @param stringGroup String in group parameters (optional) * @param booleanGroup Boolean in group parameters (optional) * @param int64Group Integer in group parameters (optional) * @return Someting wrong (status code 400) */ @ApiOperation(value = "Fake endpoint to test group parameters (optional)", nickname = "testGroupParameters", notes = "Fake endpoint to test group parameters (optional)", tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Someting wrong") }) @DeleteMapping( value = "/fake" ) default ResponseEntity<Void> testGroupParameters(@NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup,@ApiParam(value = "Required Boolean in group parameters" ,required=true) @RequestHeader(value="required_boolean_group", required=true) Boolean requiredBooleanGroup,@NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group,@ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup,@ApiParam(value = "Boolean in group parameters" ) @RequestHeader(value="boolean_group", required=false) Boolean booleanGroup,@ApiParam(value = "Integer in group parameters") @Valid @RequestParam(value = "int64_group", required = false) Long int64Group) { return getDelegate().testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); } /** * POST /fake/inline-additionalProperties : test inline additionalProperties * * @param param request body (required) * @return successful operation (status code 200) */ @ApiOperation(value = "test inline additionalProperties", nickname = "testInlineAdditionalProperties", notes = "", tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @PostMapping( value = "/fake/inline-additionalProperties", consumes = { "application/json" } ) default ResponseEntity<Void> testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Map<String, String> param) { return getDelegate().testInlineAdditionalProperties(param); } /** * GET /fake/jsonFormData : test json serialization of form data * * @param param field1 (required) * @param param2 field2 (required) * @return successful operation (status code 200) */ @ApiOperation(value = "test json serialization of form data", nickname = "testJsonFormData", notes = "", tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @GetMapping( value = "/fake/jsonFormData", consumes = { "application/x-www-form-urlencoded" } ) default ResponseEntity<Void> testJsonFormData(@ApiParam(value = "field1", required=true) @Valid @RequestPart(value = "param", required = true) String param,@ApiParam(value = "field2", required=true) @Valid @RequestPart(value = "param2", required = true) String param2) { return getDelegate().testJsonFormData(param, param2); } /** * PUT /fake/test-query-paramters * To test the collection format in query parameters * * @param pipe (required) * @param ioutil (required) * @param http (required) * @param url (required) * @param context (required) * @return Success (status code 200) */ @ApiOperation(value = "", nickname = "testQueryParameterCollectionFormat", notes = "To test the collection format in query parameters", tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success") }) @PutMapping( value = "/fake/test-query-paramters" ) default ResponseEntity<Void> testQueryParameterCollectionFormat(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "pipe", required = true) List<String> pipe,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "ioutil", required = true) List<String> ioutil,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "http", required = true) List<String> http,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "url", required = true) List<String> url,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "context", required = true) List<String> context) { return getDelegate().testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); } /** * POST /fake/{petId}/uploadImageWithRequiredFile : uploads an image (required) * * @param petId ID of pet to update (required) * @param requiredFile file to upload (required) * @param additionalMetadata Additional data to pass to server (optional) * @return successful operation (status code 200) */ @ApiOperation(value = "uploads an image (required)", nickname = "uploadFileWithRequiredFile", notes = "", response = ModelApiResponse.class, authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) @PostMapping( value = "/fake/{petId}/uploadImageWithRequiredFile", produces = { "application/json" }, consumes = { "multipart/form-data" } ) default ResponseEntity<ModelApiResponse> uploadFileWithRequiredFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "requiredFile", required = true) MultipartFile requiredFile,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata) { return getDelegate().uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); } }
package com.datastaxdev.todo; import static org.springframework.web.bind.annotation.RequestMethod.DELETE; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.OPTIONS; import static org.springframework.web.bind.annotation.RequestMethod.PATCH; import static org.springframework.web.bind.annotation.RequestMethod.POST; import static org.springframework.web.bind.annotation.RequestMethod.PUT; import java.net.URI; import java.net.URISyntaxException; import java.util.Optional; import java.util.UUID; import java.util.stream.Stream; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin( methods = {POST, GET, OPTIONS, PUT, DELETE, PATCH}, maxAge = 3600, allowedHeaders = {"x-requested-with", "origin", "content-type", "accept"}, origins = "*" ) @RequestMapping("/api/v1") public class TodoRestController { private TodoItemRepository repo; public TodoRestController(TodoItemRepository todoRepo) { this.repo = todoRepo; } @GetMapping("/{user}/todos/") public Stream<Todo> findAllByUser(HttpServletRequest req, @PathVariable(value = "user") String user) { return repo.findByKeyUserId(user).stream() .map(TodoRestController::mapAsTodo) .map(t -> t.setUrl(req)); } @GetMapping("/{user}/todos/{uid}") public ResponseEntity<Todo> findById(HttpServletRequest req, @PathVariable(value = "user") String user, @PathVariable(value = "uid") String itemId) { Optional<TodoItem> e = repo.findById(new TodoItemKey(user, UUID.fromString(itemId))); if (e.isEmpty()) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(mapAsTodo(e.get()).setUrl(req.getRequestURL().toString())); } @PostMapping("/{user}/todos/") public ResponseEntity<Todo> create(HttpServletRequest req, @PathVariable(value = "user") String user, @RequestBody Todo todoReq) throws URISyntaxException { TodoItem te = mapAsTodoEntity(todoReq, user); repo.save(te); todoReq.setUuid(te.getKey().getItemId()); todoReq.setUrl(req); return ResponseEntity.created(new URI(todoReq.getUrl())).body(todoReq); } @PatchMapping("/{user}/todos/{uid}") public ResponseEntity<Todo> update(HttpServletRequest req, @PathVariable(value = "user") String user, @PathVariable(value = "uid") String uid, @RequestBody Todo todoReq) throws URISyntaxException { // Retrieve existing task Optional<TodoItem> todo = repo.findById(new TodoItemKey(user, UUID.fromString(uid))); if (todo.isEmpty()) return ResponseEntity.notFound().build(); // Update based on provided information TodoItem item = todo.get(); if (null != todoReq.getTitle() && !"".equals(todoReq.getTitle())) { item.setTitle(todoReq.getTitle()); } if (null != todoReq.getOrder()) { item.setOffset(todoReq.getOrder()); } item.setCompleted(todoReq.isCompleted()); // Save repo.save(item); todoReq.setTitle(item.getTitle()); todoReq.setUrl(req.getRequestURL().toString()); todoReq.setUuid(UUID.fromString(uid)); return ResponseEntity.accepted().body(todoReq); } @DeleteMapping("/{user}/todos/{uid}") public ResponseEntity<Void> deleteById( @PathVariable(value = "user") String user, @PathVariable(value = "uid") String uid) { if (!repo.existsById(new TodoItemKey(user, UUID.fromString(uid)))) { return ResponseEntity.notFound().build(); } repo.deleteById(new TodoItemKey(user, UUID.fromString(uid))); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @DeleteMapping("/{user}/todos/") public ResponseEntity<Void> deleteAllByUser(@PathVariable(value = "user") String user) { repo.deleteByKeyUserId(user); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } private static Todo mapAsTodo(TodoItem te) { Todo todo = new Todo(); todo.setTitle(te.getTitle()); todo.setOrder(te.getOffset()); todo.setUuid(te.getKey().getItemId()); todo.setCompleted(te.isCompleted()); return todo; } private TodoItem mapAsTodoEntity(Todo te, String user) { TodoItem todo = new TodoItem(); if (null != te.getUuid()) { todo.getKey().setItemId(te.getUuid()); } todo.getKey().setUserId(user); todo.setTitle(te.getTitle()); todo.setOffset(te.getOrder()); todo.setCompleted(te.isCompleted()); return todo; } }
package uk.gov.cslearning.catalogue.service.upload.processor; import org.apache.tika.metadata.Metadata; import org.springframework.stereotype.Component; @Component public class MetadataFactory { public Metadata create() { return new Metadata(); } }
/* * Copyright (c) 2007-2018 Siemens AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.siemens.ct.exi.core.values; /** * * @author Daniel.Peintner.EXT@siemens.com * @author Richard.Kuntschke@siemens.com * */ public class StringValue extends AbstractValue { protected char[] characters; protected String sValue; public StringValue(char[] ca) { super(ValueType.STRING); this.characters = ca; } public StringValue(String s) { super(ValueType.STRING); // this(s.toCharArray()); sValue = s; } private void checkCharacters() { if (characters == null) { characters = sValue.toCharArray(); } } public int getCharactersLength() { checkCharacters(); return characters.length; } public char[] getCharacters() { checkCharacters(); return characters; } public void getCharacters(char[] cbuffer, int offset) { checkCharacters(); // not optimal, need to copy char data System.arraycopy(characters, 0, cbuffer, offset, characters.length); } @Override public String toString() { if (sValue == null) { sValue = new String(characters); } return sValue; } @Override public String toString(char[] cbuffer, int offset) { return toString(); } @Override public boolean equals(Object o) { if (o == null) { return false; } return this == o ? true : toString().equals(o.toString()); } @Override public int hashCode() { return toString().hashCode(); } }
/* * 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.multimap.impl; import com.hazelcast.config.EntryListenerConfig; import com.hazelcast.core.EntryListener; import com.hazelcast.core.HazelcastException; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.HazelcastInstanceAware; import com.hazelcast.core.ICompletableFuture; import com.hazelcast.core.MultiMap; import com.hazelcast.mapreduce.Collator; import com.hazelcast.mapreduce.CombinerFactory; import com.hazelcast.mapreduce.Job; import com.hazelcast.mapreduce.JobTracker; import com.hazelcast.mapreduce.KeyValueSource; import com.hazelcast.mapreduce.Mapper; import com.hazelcast.mapreduce.MappingJob; import com.hazelcast.mapreduce.ReducerFactory; import com.hazelcast.mapreduce.ReducingSubmittableJob; import com.hazelcast.mapreduce.aggregation.Aggregation; import com.hazelcast.mapreduce.aggregation.Supplier; import com.hazelcast.monitor.LocalMultiMapStats; import com.hazelcast.multimap.impl.operations.EntrySetResponse; import com.hazelcast.multimap.impl.operations.MultiMapResponse; import com.hazelcast.nio.ClassLoaderUtil; import com.hazelcast.nio.serialization.Data; import com.hazelcast.spi.InitializingObject; import com.hazelcast.spi.NodeEngine; import com.hazelcast.util.ExceptionUtil; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import static com.hazelcast.util.Preconditions.checkNotNull; import static com.hazelcast.util.Preconditions.checkPositive; import static com.hazelcast.util.Preconditions.isNotNull; public class ObjectMultiMapProxy<K, V> extends MultiMapProxySupport implements MultiMap<K, V>, InitializingObject { protected static final String NULL_KEY_IS_NOT_ALLOWED = "Null key is not allowed!"; protected static final String NULL_VALUE_IS_NOT_ALLOWED = "Null value is not allowed!"; public ObjectMultiMapProxy(MultiMapService service, NodeEngine nodeEngine, String name) { super(service, nodeEngine, name); } public String getName() { return name; } @Override public void initialize() { final NodeEngine nodeEngine = getNodeEngine(); List<EntryListenerConfig> listenerConfigs = config.getEntryListenerConfigs(); for (EntryListenerConfig listenerConfig : listenerConfigs) { EntryListener listener = null; if (listenerConfig.getImplementation() != null) { listener = listenerConfig.getImplementation(); } else if (listenerConfig.getClassName() != null) { try { listener = ClassLoaderUtil.newInstance(nodeEngine.getConfigClassLoader(), listenerConfig.getClassName()); } catch (Exception e) { throw ExceptionUtil.rethrow(e); } } if (listener != null) { if (listener instanceof HazelcastInstanceAware) { ((HazelcastInstanceAware) listener).setHazelcastInstance(nodeEngine.getHazelcastInstance()); } if (listenerConfig.isLocal()) { addLocalEntryListener(listener); } else { addEntryListener(listener, listenerConfig.isIncludeValue()); } } } } public boolean put(K key, V value) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); final NodeEngine nodeEngine = getNodeEngine(); Data dataKey = nodeEngine.toData(key); Data dataValue = nodeEngine.toData(value); return putInternal(dataKey, dataValue, -1); } public Collection<V> get(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final NodeEngine nodeEngine = getNodeEngine(); Data dataKey = nodeEngine.toData(key); MultiMapResponse result = getAllInternal(dataKey); return result.getObjectCollection(nodeEngine); } public boolean remove(Object key, Object value) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); final NodeEngine nodeEngine = getNodeEngine(); Data dataKey = nodeEngine.toData(key); Data dataValue = nodeEngine.toData(value); return removeInternal(dataKey, dataValue); } public Collection<V> remove(Object key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final NodeEngine nodeEngine = getNodeEngine(); Data dataKey = nodeEngine.toData(key); MultiMapResponse result = removeInternal(dataKey); return result.getObjectCollection(nodeEngine); } public Set<K> localKeySet() { Set<Data> dataKeySet = localKeySetInternal(); return toObjectSet(dataKeySet); } public Set<K> keySet() { Set<Data> dataKeySet = keySetInternal(); return toObjectSet(dataKeySet); } public Collection<V> values() { final NodeEngine nodeEngine = getNodeEngine(); Map map = valuesInternal(); Collection values = new LinkedList(); for (Object obj : map.values()) { if (obj == null) { continue; } MultiMapResponse response = nodeEngine.toObject(obj); values.addAll(response.getObjectCollection(nodeEngine)); } return values; } public Set<Map.Entry<K, V>> entrySet() { final NodeEngine nodeEngine = getNodeEngine(); Map map = entrySetInternal(); Set<Map.Entry<K, V>> entrySet = new HashSet<Map.Entry<K, V>>(); for (Object obj : map.values()) { if (obj == null) { continue; } EntrySetResponse response = nodeEngine.toObject(obj); Set<Map.Entry<K, V>> entries = response.getObjectEntrySet(nodeEngine); entrySet.addAll(entries); } return entrySet; } public boolean containsKey(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final NodeEngine nodeEngine = getNodeEngine(); Data dataKey = nodeEngine.toData(key); return containsInternal(dataKey, null); } public boolean containsValue(Object value) { checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); final NodeEngine nodeEngine = getNodeEngine(); Data valueKey = nodeEngine.toData(value); return containsInternal(null, valueKey); } public boolean containsEntry(K key, V value) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); final NodeEngine nodeEngine = getNodeEngine(); Data dataKey = nodeEngine.toData(key); Data valueKey = nodeEngine.toData(value); return containsInternal(dataKey, valueKey); } public int valueCount(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final NodeEngine nodeEngine = getNodeEngine(); Data dataKey = nodeEngine.toData(key); return countInternal(dataKey); } public String addLocalEntryListener(EntryListener<K, V> listener) { return getService().addListener(name, listener, null, false, true); } public String addEntryListener(EntryListener<K, V> listener, boolean includeValue) { return getService().addListener(name, listener, null, includeValue, false); } public boolean removeEntryListener(String registrationId) { return getService().removeListener(name, registrationId); } public String addEntryListener(EntryListener<K, V> listener, K key, boolean includeValue) { final NodeEngine nodeEngine = getNodeEngine(); Data dataKey = nodeEngine.toData(key); return getService().addListener(name, listener, dataKey, includeValue, false); } public void lock(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final NodeEngine nodeEngine = getNodeEngine(); Data dataKey = nodeEngine.toData(key); lockSupport.lock(nodeEngine, dataKey); } public void lock(K key, long leaseTime, TimeUnit timeUnit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkPositive(leaseTime, "leaseTime should be positive"); final NodeEngine nodeEngine = getNodeEngine(); Data dataKey = nodeEngine.toData(key); lockSupport.lock(nodeEngine, dataKey, timeUnit.toMillis(leaseTime)); } public boolean isLocked(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final NodeEngine nodeEngine = getNodeEngine(); Data dataKey = nodeEngine.toData(key); return lockSupport.isLocked(nodeEngine, dataKey); } public boolean tryLock(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); try { return tryLock(key, 0, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { return false; } } public boolean tryLock(K key, long time, TimeUnit timeunit) throws InterruptedException { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final NodeEngine nodeEngine = getNodeEngine(); Data dataKey = nodeEngine.toData(key); return lockSupport.tryLock(nodeEngine, dataKey, time, timeunit); } public void unlock(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final NodeEngine nodeEngine = getNodeEngine(); Data dataKey = nodeEngine.toData(key); lockSupport.unlock(nodeEngine, dataKey); } public void forceUnlock(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final NodeEngine nodeEngine = getNodeEngine(); Data dataKey = nodeEngine.toData(key); lockSupport.forceUnlock(nodeEngine, dataKey); } public LocalMultiMapStats getLocalMultiMapStats() { return (LocalMultiMapStats) getService().createStats(name); } @Override public <SuppliedValue, Result> Result aggregate(Supplier<K, V, SuppliedValue> supplier, Aggregation<K, SuppliedValue, Result> aggregation) { HazelcastInstance hazelcastInstance = getNodeEngine().getHazelcastInstance(); JobTracker jobTracker = hazelcastInstance.getJobTracker("hz::aggregation-multimap-" + getName()); return aggregate(supplier, aggregation, jobTracker); } @Override public <SuppliedValue, Result> Result aggregate(Supplier<K, V, SuppliedValue> supplier, Aggregation<K, SuppliedValue, Result> aggregation, JobTracker jobTracker) { try { isNotNull(jobTracker, "jobTracker"); KeyValueSource<K, V> keyValueSource = KeyValueSource.fromMultiMap(this); Job<K, V> job = jobTracker.newJob(keyValueSource); Mapper mapper = aggregation.getMapper(supplier); CombinerFactory combinerFactory = aggregation.getCombinerFactory(); ReducerFactory reducerFactory = aggregation.getReducerFactory(); Collator collator = aggregation.getCollator(); MappingJob mappingJob = job.mapper(mapper); ReducingSubmittableJob reducingJob; if (combinerFactory != null) { reducingJob = mappingJob.combiner(combinerFactory).reducer(reducerFactory); } else { reducingJob = mappingJob.reducer(reducerFactory); } ICompletableFuture<Result> future = reducingJob.submit(collator); return future.get(); } catch (Exception e) { throw new HazelcastException(e); } } private Set<K> toObjectSet(Set<Data> dataSet) { final NodeEngine nodeEngine = getNodeEngine(); Set<K> keySet = new HashSet<K>(dataSet.size()); for (Data dataKey : dataSet) { keySet.add((K) nodeEngine.toObject(dataKey)); } return keySet; } @Override public String toString() { final StringBuilder sb = new StringBuilder("MultiMap{"); sb.append("name=").append(getName()); sb.append('}'); return sb.toString(); } }
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 4.0.0 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package xyz.redtorch.gateway.ctp.x64v6v3v16t1v.api; public class CThostFtdcManualSyncBrokerUserOTPField { private transient long swigCPtr; protected transient boolean swigCMemOwn; protected CThostFtdcManualSyncBrokerUserOTPField(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } protected static long getCPtr(CThostFtdcManualSyncBrokerUserOTPField obj) { return (obj == null) ? 0 : obj.swigCPtr; } @SuppressWarnings("deprecation") protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; jctpv6v3v16t1x64apiJNI.delete_CThostFtdcManualSyncBrokerUserOTPField(swigCPtr); } swigCPtr = 0; } } public void setBrokerID(String value) { jctpv6v3v16t1x64apiJNI.CThostFtdcManualSyncBrokerUserOTPField_BrokerID_set(swigCPtr, this, value); } public String getBrokerID() { return jctpv6v3v16t1x64apiJNI.CThostFtdcManualSyncBrokerUserOTPField_BrokerID_get(swigCPtr, this); } public void setUserID(String value) { jctpv6v3v16t1x64apiJNI.CThostFtdcManualSyncBrokerUserOTPField_UserID_set(swigCPtr, this, value); } public String getUserID() { return jctpv6v3v16t1x64apiJNI.CThostFtdcManualSyncBrokerUserOTPField_UserID_get(swigCPtr, this); } public void setOTPType(char value) { jctpv6v3v16t1x64apiJNI.CThostFtdcManualSyncBrokerUserOTPField_OTPType_set(swigCPtr, this, value); } public char getOTPType() { return jctpv6v3v16t1x64apiJNI.CThostFtdcManualSyncBrokerUserOTPField_OTPType_get(swigCPtr, this); } public void setFirstOTP(String value) { jctpv6v3v16t1x64apiJNI.CThostFtdcManualSyncBrokerUserOTPField_FirstOTP_set(swigCPtr, this, value); } public String getFirstOTP() { return jctpv6v3v16t1x64apiJNI.CThostFtdcManualSyncBrokerUserOTPField_FirstOTP_get(swigCPtr, this); } public void setSecondOTP(String value) { jctpv6v3v16t1x64apiJNI.CThostFtdcManualSyncBrokerUserOTPField_SecondOTP_set(swigCPtr, this, value); } public String getSecondOTP() { return jctpv6v3v16t1x64apiJNI.CThostFtdcManualSyncBrokerUserOTPField_SecondOTP_get(swigCPtr, this); } public CThostFtdcManualSyncBrokerUserOTPField() { this(jctpv6v3v16t1x64apiJNI.new_CThostFtdcManualSyncBrokerUserOTPField(), true); } }