repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
sshrdp/mclab
languages/Natlab/src/mclint/analyses/UnreachableCode.java
2181
package mclint.analyses; import java.util.Arrays; import java.util.List; import mclint.AnalysisKit; import mclint.Lint; import mclint.LintAnalysis; import mclint.Message; import natlab.utils.NodeFinder; import nodecases.AbstractNodeCaseHandler; import ast.ASTNode; import ast.BreakStmt; import ast.ContinueStmt; import ast.NameExpr; import ast.ParameterizedExpr; import ast.ReturnStmt; import ast.Stmt; public class UnreachableCode extends AbstractNodeCaseHandler implements LintAnalysis { private static final String WARNING = "This statement (and possibly following ones) cannot be reached."; private static final List<String> THROWS = Arrays.asList("throw", "rethrow", "error", "throwAsCaller"); private ASTNode<?> tree; private Lint lint; public UnreachableCode(AnalysisKit kit) { this.tree = kit.getAST(); } private Message unreachableCode(ASTNode<?> node) { return Message.regarding(node, "DEAD_CODE", WARNING); } @SuppressWarnings("rawtypes") @Override public void caseASTNode(ASTNode node) { for (int i = 0; i < node.getNumChild(); ++i) { node.getChild(i).analyze(this); } } @Override public void analyze(Lint lint) { this.lint = lint; tree.analyze(this); } private void caseAbruptControlFlow(ASTNode<?> node) { @SuppressWarnings("unchecked") ast.List<Stmt> body = (ast.List<Stmt>) node.getParent(); int index = body.getIndexOfChild(node); if (index < body.getNumChild() - 1) { lint.report(unreachableCode(body.getChild(index + 1))); } } @Override public void caseBreakStmt(BreakStmt node) { caseAbruptControlFlow(node); } @Override public void caseContinueStmt(ContinueStmt node) { caseAbruptControlFlow(node); } @Override public void caseReturnStmt(ReturnStmt node) { caseAbruptControlFlow(node); } @Override public void caseParameterizedExpr(ParameterizedExpr node) { if (!(node.getTarget() instanceof NameExpr)) { return; } String name = ((NameExpr)(node.getTarget())).getName().getID(); if (THROWS.contains(name)) { caseAbruptControlFlow(NodeFinder.findParent(node, Stmt.class)); } } }
apache-2.0
MathenJee/NotifymeWebService
NotifyMeWebService/src/main/java/com/sunlegend/mathen/notifymesv/service/AuthorizationService.java
3312
/* * 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 com.sunlegend.mathen.notifymesv.service; import com.google.gson.Gson; import com.sunlegend.mathen.notifymesv.controller.Authorization; import com.sunlegend.mathen.notifymesv.model.Enumable; import com.sunlegend.mathen.notifymesv.model.json.ObjectIdFixedGson; import com.sunlegend.mathen.notifymesv.model.Token; import com.sunlegend.mathen.notifymesv.model.TokenFactory; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * * @author tux */ @Path("/user") public class AuthorizationService { private static final Gson GSON = new ObjectIdFixedGson().getGson(); private volatile static Authorization authorization; public AuthorizationService() { getAuthorization(); } static Authorization getAuthorization() { synchronized (AuthorizationService.class) { if (authorization == null) { authorization = new Authorization(); } } return authorization; } @POST @Path("/login/google") @Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA}) @Produces(MediaType.APPLICATION_JSON) public Response authViaGoogle(@FormParam("clientid") String clientId, @FormParam("tokenid") String tokenId) throws GeneralSecurityException, IOException { Token token = authorization.authViaGoogle(clientId, tokenId); List<Enumable> statuses = token.getStatuses(); if (statuses.contains(TokenFactory.Status.NOT_ACCEPTABLE)) { return Response.status(Response.Status.NOT_ACCEPTABLE).build(); } if (statuses.contains(TokenFactory.Status.UNAUTHORIZED)) { return Response.status(Response.Status.UNAUTHORIZED).build(); } return Response.ok(GSON.toJson(token), MediaType.APPLICATION_JSON).build(); } @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) @Path("/password/create") public Response createPassword(@FormParam("accesstoken") String accessToken, @FormParam("password") String password) { return Response.ok(authorization.createPassword(accessToken, password)).build(); } @POST @Path("/login/email_password") @Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA}) @Produces(MediaType.APPLICATION_JSON) public Response loginByEmail_password(@FormParam("email") String email, @FormParam("password") String password) throws GeneralSecurityException, IOException { Token token = authorization.loginByEmail_password(email, password); List<Enumable> statuses = token.getStatuses(); if (statuses.contains(TokenFactory.Status.UNAUTHORIZED)) { return Response.status(Response.Status.UNAUTHORIZED).build(); } return Response.ok(GSON.toJson(token), MediaType.APPLICATION_JSON).build(); } }
apache-2.0
rmannibucau/diagram-generator-parent
diagram-generator-maven-plugin/src/main/java/com/github/rmannibucau/graph/transformer/VertexShapeTransformer.java
1231
package com.github.rmannibucau.graph.transformer; import com.github.rmannibucau.loader.spi.graph.Node; import org.apache.commons.collections15.Transformer; import javax.swing.Icon; import java.awt.FontMetrics; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; /** * @author Romain Manni-Bucau */ public class VertexShapeTransformer implements Transformer<Node, Shape> { private static final int X_MARGIN = 4; private static final int Y_MARGIN = 2; private FontMetrics metrics; public VertexShapeTransformer(FontMetrics f) { metrics = f; } @Override public Shape transform(Node i) { int w; int h; Icon icon = i.getIcon(); if (icon == null) { w = metrics.stringWidth(i.getText()); h = metrics.getHeight(); } else { w = icon.getIconWidth(); h = icon.getIconHeight(); } h += Y_MARGIN; w += X_MARGIN; // centering AffineTransform transform = AffineTransform.getTranslateInstance(-w / 2.0, -h / 2.0); return transform.createTransformedShape(new Rectangle(0, 0, w, h)); } }
apache-2.0
craigthomas/NLMT
src/main/java/nlmt/datatypes/IdentifierObjectMapper.java
4965
/* * Copyright 2015 Craig Thomas * * 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 nlmt.datatypes; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * The IdentifierObjectMapper associates a numeric identifier with a * specific object. It also maintains the reverse mapping of an object * with a specific identifier. */ public class IdentifierObjectMapper<T extends Serializable> implements Serializable { // Maps an object to a number private Map<T, Integer> objectIndexMap; // The inverse mapping of objectIndexMap private Map<Integer, T> indexObjectMap; // The next number to assign to the next object seen private int nextIndex; public IdentifierObjectMapper() { objectIndexMap = new HashMap<>(); indexObjectMap = new HashMap<>(); } /** * Adds an object to the mapper if it isn't already in it. Returns the * newly generated id for the object. * * @param object the object to add to the mapper * @return the id of the object */ public int addObject(T object) { if (!objectIndexMap.containsKey(object)) { objectIndexMap.put(object, nextIndex); indexObjectMap.put(nextIndex, object); int result = nextIndex; incrementNextIndex(); return result; } return objectIndexMap.get(object); } /** * Gets the object associated with the index number. If the index does * not appear in the mapping, will return null. * * @param index the index to get * @return the object at the specified index */ public T getObjectFromIndex(int index) { if (indexObjectMap.containsKey(index)) { return indexObjectMap.get(index); } return null; } /** * Gets the index for the specified object. If the object is not in the * mapping, will return -1. * * @param object the object to check * @return the index of the object, or -1 if it does not exist */ public int getIndexFromObject(T object) { if (objectIndexMap.containsKey(object)) { return objectIndexMap.get(object); } return -1; } /** * Returns <code>true</code> if the mapper contains the specified * object. * * @param object the object to check for * @return <code>true</code> if the object is in the mapper */ public boolean contains(T object) { return objectIndexMap.containsKey(object); } /** * Returns <code>true</code> if the mapper contains the specified * index. * * @param index the index to check for * @return <code>true</code> if the index is in the mapper */ public boolean containsIndex(int index) { return indexObjectMap.containsKey(index); } /** * Bumps the nextIndex counter up by 1. */ private void incrementNextIndex() { nextIndex++; } /** * Returns the total size of the mapper. This is the number * of unique objects in the mapper. * * @return the number of objects in the mapper */ public int size() { return indexObjectMap.size(); } /** * Returns the set of keys for the mapper. * * @return the set of keys for the mapper */ public Set<Integer> getIndexKeys() { return indexObjectMap.keySet(); } /** * Removes an object based on its index. * * @param index the index of the object to remove */ public void deleteIndex(int index) { if (indexObjectMap.containsKey(index)) { T objectToDelete = indexObjectMap.get(index); objectIndexMap.remove(objectToDelete); indexObjectMap.remove(index); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IdentifierObjectMapper<?> that = (IdentifierObjectMapper<?>) o; return nextIndex == that.nextIndex && objectIndexMap.equals(that.objectIndexMap) && indexObjectMap.equals(that.indexObjectMap); } @Override public int hashCode() { int result = objectIndexMap.hashCode(); result = 31 * result + indexObjectMap.hashCode(); result = 31 * result + nextIndex; return result; } }
apache-2.0
PutraSudaryanto/Pakar-UMBY-Android-Application
app/src/main/java/co/ommu/phonebroke/ResultDetailActivity.java
1551
package co.ommu.phonebroke; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class ResultDetailActivity extends Activity implements View.OnClickListener { TextView tvRusak, tvGejala, tvPencegahan, tvSolusi; Button btnBack; String rusak, gejala, pencegahan, solusi; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result_detail); if (getIntent().getExtras() != null) { rusak = getIntent().getExtras().getString("rusak"); gejala = getIntent().getExtras().getString("gejala"); pencegahan = getIntent().getExtras().getString("pencegahan"); solusi = getIntent().getExtras().getString("solusi"); } tvRusak = (TextView) findViewById(R.id.textRusak); tvRusak.setText(rusak); tvGejala = (TextView) findViewById(R.id.textGejala); tvGejala.setText(gejala); tvPencegahan = (TextView) findViewById(R.id.textPencegahan); tvPencegahan.setText(pencegahan); tvSolusi = (TextView) findViewById(R.id.textSolusi); tvSolusi.setText(solusi); btnBack = (Button) findViewById(R.id.buttonBack); btnBack.setOnClickListener(this); } @Override public void onClick(View arg0) { int id = arg0.getId(); if (id == R.id.buttonBack) { onBackPressed(); } } }
apache-2.0
boneman1231/org.apache.felix
trunk/webconsole/src/main/java/org/apache/felix/webconsole/internal/Util.java
8081
/* * 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.felix.webconsole.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Enumeration; import java.util.Locale; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.osgi.framework.Version; /** * The <code>Util</code> class contains various utility methods used internally * by the web console implementation and the build-in plugins. */ public class Util { // FIXME: from the constants below only PARAM_ACTION is used, consider removeal of others? /** web apps subpage */ public static final String PAGE_WEBAPPS = "/webapps"; /** vm statistics subpage */ public static final String PAGE_VM_STAT = "/vmstat"; /** Logs subpage */ public static final String PAGE_LOGS = "/logs"; /** Parameter name */ public static final String PARAM_ACTION = "action"; /** Parameter name */ public static final String PARAM_CONTENT = "content"; /** Parameter name */ public static final String PARAM_SHUTDOWN = "shutdown"; /** Parameter value */ public static final String VALUE_SHUTDOWN = "shutdown"; /** * Return a display name for the given <code>bundle</code>: * <ol> * <li>If the bundle has a non-empty <code>Bundle-Name</code> manifest * header that value is returned.</li> * <li>Otherwise the symbolic name is returned if set</li> * <li>Otherwise the bundle's location is returned if defined</li> * <li>Finally, as a last resort, the bundles id is returned</li> * </ol> * * @param bundle the bundle which name to retrieve * @param locale the locale, in which the bundle name is requested * @return the bundle name - see the description of the method for more details. */ public static String getName( Bundle bundle, Locale locale ) { final String loc = locale == null ? null : locale.toString(); String name = ( String ) bundle.getHeaders( loc ).get( Constants.BUNDLE_NAME ); if ( name == null || name.length() == 0 ) { name = bundle.getSymbolicName(); if ( name == null ) { name = bundle.getLocation(); if ( name == null ) { name = String.valueOf( bundle.getBundleId() ); } } } return name; } /** * Returns the value of the header or the empty string if the header * is not available. * * @param bundle the bundle which header to retrieve * @param headerName the name of the header to retrieve * @return the header or empty string if it is not set */ public static String getHeaderValue( Bundle bundle, String headerName ) { Object value = bundle.getHeaders().get(headerName); if ( value != null ) { return value.toString(); } return ""; } /** * Orders the bundles according to their name as returned by * {@link #getName(Bundle, Locale)}, with the exception that the system bundle is * always place as the first entry. If two bundles have the same name, they * are ordered according to their version. If they have the same version, * the bundle with the lower bundle id comes before the other. * * @param bundles the bundles to sort * @param locale the locale, used to obtain the localized bundle name */ public static void sort( Bundle[] bundles, Locale locale ) { Arrays.sort( bundles, new BundleNameComparator( locale ) ); } /** * This method is the same as Collections#list(Enumeration). The reason to * duplicate it here, is that it is missing in OSGi/Minimum execution * environment. * * @param e the enumeration which to convert * @return the list containing all enumeration entries. */ public static final ArrayList list( Enumeration e ) { ArrayList l = new ArrayList(); while ( e.hasMoreElements() ) { l.add( e.nextElement() ); } return l; } /** * This method expects a locale string in format language_COUNTRY, or * language. The method will determine which is the correct form of locale * string and construct a <code>Locale</code> object. * * @param locale the locale string, if <code>null</code> - default locale is * returned * @return a locale object * @see Locale */ public static final Locale parseLocaleString(String locale) { if (locale == null) { return Locale.getDefault(); } int idx = locale.indexOf('_'); String language; String country = ""; if (idx < 0) { // "en" language = locale; } else { // "en_US" language = locale.substring(0, idx); // "en" idx++; // "_" int last = locale.indexOf('_', idx); // "US" if (last < 0) { last = locale.length(); } country = locale.substring(idx, last); } return new Locale(language, country); } private static final class BundleNameComparator implements Comparator { private final Locale locale; BundleNameComparator( final Locale locale ) { this.locale = locale; } public int compare( Object o1, Object o2 ) { return compare( ( Bundle ) o1, ( Bundle ) o2 ); } public int compare( Bundle b1, Bundle b2 ) { // the same bundles if ( b1 == b2 || b1.getBundleId() == b2.getBundleId() ) { return 0; } // special case for system bundle, which always is first if ( b1.getBundleId() == 0 ) { return -1; } else if ( b2.getBundleId() == 0 ) { return 1; } // compare the symbolic names int snComp = Util.getName( b1, locale ).compareToIgnoreCase( Util.getName( b2, locale ) ); if ( snComp != 0 ) { return snComp; } // same names, compare versions Version v1 = Version.parseVersion( ( String ) b1.getHeaders().get( Constants.BUNDLE_VERSION ) ); Version v2 = Version.parseVersion( ( String ) b2.getHeaders().get( Constants.BUNDLE_VERSION ) ); int vComp = v1.compareTo( v2 ); if ( vComp != 0 ) { return vComp; } // same version ? Not really, but then, we compare by bundle id if ( b1.getBundleId() < b2.getBundleId() ) { return -1; } // b1 id must be > b2 id because equality is already checked return 1; } } }
apache-2.0
kzubrinic/oop
oop/src/hr/unidu/oop/p04/dod/CdPekac.java
160
package hr.unidu.oop.p04.dod; /** * Primjer rje�enja problema DoD */ public interface CdPekac extends DigitalniPekac { boolean pecenjeDiska(Cd medij ); }
apache-2.0
pyricau/forplay-clone-pyricau
core/src/forplay/html/HtmlGroupLayerDom.java
2844
/** * Copyright 2010 The ForPlay 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 forplay.html; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Node; import java.util.ArrayList; import java.util.List; import forplay.core.GroupLayer; import forplay.core.Layer; class HtmlGroupLayerDom extends HtmlLayerDom implements GroupLayer { private List<HtmlLayerDom> children = new ArrayList<HtmlLayerDom>(); HtmlGroupLayerDom() { super(Document.get().createDivElement()); } HtmlGroupLayerDom(Element elem) { super(elem); } @Override public void add(Layer layer) { assert layer instanceof HtmlLayerDom; HtmlLayerDom hlayer = (HtmlLayerDom) layer; children.add(hlayer); element().appendChild(hlayer.element()); hlayer.setParent(this); hlayer.onAdd(); } @Override public void destroy() { super.destroy(); for (HtmlLayerDom child : children) { child.destroy(); } } @Override public void remove(Layer layer) { assert layer instanceof HtmlLayerDom; HtmlLayerDom hlayer = (HtmlLayerDom) layer; hlayer.onRemove(); children.remove(hlayer); element().removeChild(hlayer.element()); hlayer.setParent(null); } void update() { super.update(); for (HtmlLayerDom child : children) { child.update(); } } @Override public Layer get(int index) { return children.get(index); } @Override public void add(int index, Layer layer) { assert layer instanceof HtmlLayerDom; HtmlLayerDom hlayer = (HtmlLayerDom) layer; if (index == size()) { element().appendChild(hlayer.element()); } else { Node refChild = element().getChild(index); element().insertBefore(hlayer.element(), refChild); } children.add(index, hlayer); hlayer.setParent(this); hlayer.onAdd(); } @Override public void remove(int index) { HtmlLayerDom hlayer = children.get(index); hlayer.onRemove(); children.remove(index); element().removeChild(element().getChild(index)); hlayer.setParent(null); } @Override public void clear() { while (!children.isEmpty()) { remove(children.size() - 1); } } @Override public int size() { return children.size(); } }
apache-2.0
niravkalola007/Foodies
app/src/main/java/yalantis/com/sidemenu/foodies/fragment/HistoryFragment.java
7228
package yalantis.com.sidemenu.foodies.fragment; import android.app.ProgressDialog; import android.content.Context; import android.graphics.Bitmap; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.android.volley.VolleyError; import com.bumptech.glide.Glide; import com.google.gson.GsonBuilder; import java.util.ArrayList; import java.util.List; import yalantis.com.sidemenu.foodies.model.AppConstants; import yalantis.com.sidemenu.foodies.model.HistoryClass; import yalantis.com.sidemenu.foodies.model.Hotel; import yalantis.com.sidemenu.foodies.model.HotelsList; import yalantis.com.sidemenu.foodies.model.UserOrder; import yalantis.com.sidemenu.foodies.utils.CircularImageView; import yalantis.com.sidemenu.foodies.utils.GetServiceCall; import yalantis.com.sidemenu.foodies.utils.PrefUtils; import yalantis.com.sidemenu.interfaces.ScreenShotable; import yalantis.com.sidemenu.sample.R; /** * Created by Konstantin on 22.12.2014. */ public class HistoryFragment extends Fragment implements ScreenShotable { public static final String PAINT = "Paint"; private ListView historyList; private MyAppAdapter customAdapter; private View containerView; protected ImageView mImageView; private ProgressDialog progressDialog; private ArrayList<UserOrder> hotelArrayList; protected int res; private Bitmap bitmap; public static HistoryFragment newInstance() { HistoryFragment contentFragment = new HistoryFragment(); Bundle bundle = new Bundle(); bundle.putInt(Integer.class.getName(),android.R.drawable.screen_background_light_transparent); contentFragment.setArguments(bundle); return contentFragment; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // this.containerView = view.findViewById(R.id.container); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // res = getArguments().getInt(Integer.class.getName()); } private void getHotelList() { progressDialog=new ProgressDialog(getActivity()); progressDialog.setMessage("Loading..."); progressDialog.show(); new GetServiceCall(AppConstants.USER_HISTORY+PrefUtils.getLogin(getActivity()).OwnerId+"",GetServiceCall.TYPE_JSONOBJECT){ @Override public void response(String response) { Log.e("response:", response + ""); progressDialog.dismiss(); HistoryClass hotelsList = new GsonBuilder().create().fromJson(response, HistoryClass.class); hotelArrayList=hotelsList.userOrderArrayList; Log.e("list size", hotelArrayList.size() + ""); customAdapter=new MyAppAdapter(hotelArrayList,getActivity()); historyList.setAdapter(customAdapter); } @Override public void error(VolleyError error) { progressDialog.dismiss(); ; } }.call(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_history, container, false); // mImageView = (ImageView) rootView.findViewById(R.id.image_content); historyList= (ListView) rootView.findViewById(R.id.historyList); if(PrefUtils.getLogin(getActivity()) != null){ getHotelList(); } // mImageView.setClickable(true); // mImageView.setFocusable(true); // mImageView.setImageResource(res); // Toast.makeText(getActivity(), "content fragment 2", Toast.LENGTH_LONG).show(); return rootView; } @Override public void takeScreenShot() { // Thread thread = new Thread() { // @Override // public void run() { // Bitmap bitmap = Bitmap.createBitmap(containerView.getWidth(), // containerView.getHeight(), Bitmap.Config.ARGB_8888); // Canvas canvas = new Canvas(bitmap); // containerView.draw(canvas); // ContentFragment2.this.bitmap = bitmap; // } // }; // // thread.start(); } @Override public Bitmap getBitmap() { return bitmap; } public class MyAppAdapter extends BaseAdapter { public class ViewHolder { public TextView orderId, PriceToPay, Tax, TotalPrice; public TextView Status; } public List<UserOrder> parkingList; public Context context; private MyAppAdapter(List<UserOrder> apps, Context context) { this.parkingList = apps; this.context = context; } @Override public int getCount() { return parkingList.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { View rowView = convertView; ViewHolder viewHolder; if (rowView == null) { LayoutInflater inflater = getActivity().getLayoutInflater(); rowView = inflater.inflate(R.layout.item_history, null); // configure view holder viewHolder = new ViewHolder(); viewHolder.orderId = (TextView) rowView.findViewById(R.id.orderId); viewHolder.PriceToPay = (TextView) rowView.findViewById(R.id.PriceToPay); viewHolder.Tax = (TextView) rowView.findViewById(R.id.Tax); viewHolder.TotalPrice = (TextView) rowView.findViewById(R.id.TotalPrice); viewHolder.Status = (TextView) rowView.findViewById(R.id.Status); rowView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.orderId.setText("Id: "+parkingList.get(position).OrderId + ""); viewHolder.PriceToPay.setText("Price To Pay: "+parkingList.get(position).PriceToPay + ""); viewHolder.Tax.setText("Tax: "+parkingList.get(position).Tax + ""); viewHolder.TotalPrice.setText("Total Price: "+parkingList.get(position).TotalPrice + ""); viewHolder.Status.setText("Status: "+parkingList.get(position).OrderStatus + ""); rowView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); return rowView; } } }
apache-2.0
wcm-io-caravan/caravan-io
json-transform/src/test/java/io/wcm/caravan/io/jsontransform/sink/JacksonStreamSinkTest.java
2003
/* * #%L * wcm.io * %% * Copyright (C) 2014 wcm.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. * #L% */ package io.wcm.caravan.io.jsontransform.sink; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Test; import io.wcm.caravan.io.jsontransform.element.JsonElement; public class JacksonStreamSinkTest { @Test public void test_simple() throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); JacksonStreamSink sink = new JacksonStreamSink(output); assertFalse(sink.hasOutput()); sink.write(JsonElement.DEFAULT_START_OBJECT); sink.write(JsonElement.value("key1", "value1")); sink.write(JsonElement.startObject("key2")); sink.write(JsonElement.value("key3", "value3")); sink.write(JsonElement.DEFAULT_END_OBJECT); sink.write(JsonElement.startArray("key3")); sink.write(JsonElement.value("value4")); sink.write(JsonElement.DEFAULT_START_OBJECT); sink.write(JsonElement.value("key5", "value5")); sink.write(JsonElement.DEFAULT_END_OBJECT); sink.write(JsonElement.DEFAULT_END_ARRAY); sink.write(JsonElement.DEFAULT_END_OBJECT); sink.close(); assertEquals("{\"key1\":\"value1\",\"key2\":{\"key3\":\"value3\"},\"key3\":[\"value4\",{\"key5\":\"value5\"}]}", output.toString()); assertTrue(sink.hasOutput()); } }
apache-2.0
vimaier/conqat
org.conqat.engine.architecture/src/org/conqat/engine/architecture/format/EAssessmentType.java
1761
/*-------------------------------------------------------------------------+ | | | Copyright 2005-2011 The ConQAT Project | | | | Licensed under the Apache License, Version 2.0 (the "License"); | | you may not use this file except in compliance with the License. | | You may obtain a copy of the License at | | | | http://www.apache.org/licenses/LICENSE-2.0 | | | | Unless required by applicable law or agreed to in writing, software | | distributed under the License is distributed on an "AS IS" BASIS, | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | | See the License for the specific language governing permissions and | | limitations under the License. | +-------------------------------------------------------------------------*/ package org.conqat.engine.architecture.format; /** * Assessment result for edges in an architecture graph. * * @author Elmar Juergens * @author $Author: juergens $ * @version $Rev: 35037 $ * @ConQAT.Rating GREEN Hash: 804563901E5803F2515D53B4B70D304B */ public enum EAssessmentType { /** Dependencies underlying this edge are valid w.r.t. policies */ VALID, /** Dependencies underlying this edge are invalid w.r.t. policies */ INVALID, /** No dependencies underly this edge. It is unnecessary. */ UNNECESSARY, }
apache-2.0
RuanXiaoHui/ZxingScan
ZxingScan/zxinglib/src/main/java/cn/jackson/zxinglib/decoding/DecodeThread.java
2574
/* * Copyright (C) 2008 ZXing 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 cn.jackson.zxinglib.decoding; import android.os.Handler; import android.os.Looper; import com.google.zxing.BarcodeFormat; import com.google.zxing.DecodeHintType; import com.google.zxing.ResultPointCallback; import java.util.Hashtable; import java.util.Vector; import java.util.concurrent.CountDownLatch; import cn.jackson.zxinglib.activity.CaptureFragment; final class DecodeThread extends Thread { public static final String BARCODE_BITMAP = "barcode_bitmap"; private final CaptureFragment fragment; private final Hashtable<DecodeHintType, Object> hints; private Handler handler; private final CountDownLatch handlerInitLatch; DecodeThread(CaptureFragment fragment, Vector<BarcodeFormat> decodeFormats, String characterSet, ResultPointCallback resultPointCallback) { this.fragment = fragment; handlerInitLatch = new CountDownLatch(1); hints = new Hashtable<DecodeHintType, Object>(3); if (decodeFormats == null || decodeFormats.isEmpty()) { decodeFormats = new Vector<BarcodeFormat>(); decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS); decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS); decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS); } hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats); if (characterSet != null) { hints.put(DecodeHintType.CHARACTER_SET, characterSet); } hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, resultPointCallback); } Handler getHandler() { try { handlerInitLatch.await(); } catch (InterruptedException ie) { } return handler; } @Override public void run() { Looper.prepare(); handler = new DecodeHandler(fragment, hints); handlerInitLatch.countDown(); Looper.loop(); } }
apache-2.0
freeVM/freeVM
enhanced/archive/classlib/java6/modules/security/src/test/impl/java/org/apache/harmony/security/tests/java/security/MessageDigest_Impl2Test.java
5868
/* * 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. */ /** * @author Boris V. Kuznetsov * @version $Revision$ */ package org.apache.harmony.security.tests.java.security; import java.security.MessageDigest; import java.security.Provider; import java.security.Security; import org.apache.harmony.security.tests.support.MyMessageDigest1; import org.apache.harmony.security.tests.support.MyMessageDigest2; import junit.framework.TestCase; /** * Tests for <code>MessageDigest</code> constructor and methods * */ public class MessageDigest_Impl2Test extends TestCase { /** * Provider */ Provider p; /* * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); p = new MyProvider(); Security.insertProviderAt(p, 1); } /* * @see TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); Security.removeProvider(p.getName()); } /* * Class under test for MessageDigest getInstance(String) */ public void testGetInstanceString1() throws Exception { MessageDigest md1 = MessageDigest.getInstance("ABC"); checkMD1(md1, p); } /* * Class under test for MessageDigest getInstance(String) */ public void testGetInstanceString2() throws Exception { MessageDigest md2 = MessageDigest.getInstance("CBA"); checkMD2(md2, p); } /* * Class under test for MessageDigest getInstance(String, String) */ public void testGetInstanceStringString1() throws Exception { MessageDigest md1 = MessageDigest.getInstance("ABC", "MyProvider"); checkMD1(md1, p); } /* * Class under test for MessageDigest getInstance(String, String) */ public void testGetInstanceStringString2() throws Exception { MessageDigest md2 = MessageDigest.getInstance("CBA", "MyProvider"); checkMD2(md2, p); } /* * Class under test for MessageDigest getInstance(String, Provider) */ public void testGetInstanceStringProvider1() throws Exception { Provider p = new MyProvider(); MessageDigest md1 = MessageDigest.getInstance("ABC", p); checkMD1(md1, p); } /* * Class under test for MessageDigest getInstance(String, Provider) */ public void testGetInstanceStringProvider2() throws Exception { Provider p = new MyProvider(); MessageDigest md2 = MessageDigest.getInstance("CBA", p); checkMD2(md2, p); } /* * Class under test for String toString() */ public void testToString() { MyMessageDigest1 md = new MyMessageDigest1("ABC"); assertEquals("incorrect result", "MESSAGE DIGEST ABC", md.toString()); } private void checkMD1(MessageDigest md1, Provider p) throws Exception { byte[] b = { 1, 2, 3, 4, 5 }; assertTrue("getInstance() failed", md1 instanceof MyMessageDigest1); assertEquals("getProvider() failed", p, md1.getProvider()); assertEquals("getAlgorithm() failed", "ABC", md1.getAlgorithm()); md1.update((byte) 1); md1.update(b, 1, 4); assertTrue("update failed", ((MyMessageDigest1) md1).runEngineUpdate1); assertTrue("update failed", ((MyMessageDigest1) md1).runEngineUpdate2); assertEquals("incorrect digest result", 0, md1.digest().length); assertEquals("getProvider() failed", 0, md1.digest(b, 2, 3)); assertTrue("digest failed", ((MyMessageDigest1) md1).runEngineDigest); md1.reset(); assertTrue("reset failed", ((MyMessageDigest1) md1).runEngineReset); assertEquals("getDigestLength() failed", 0, md1.getDigestLength()); try { md1.clone(); fail("No expected CloneNotSupportedException"); } catch (CloneNotSupportedException e) { } } private void checkMD2(MessageDigest md2, Provider p) throws Exception { byte[] b = { 1, 2, 3, 4, 5 }; assertEquals("getProvider() failed", p, md2.getProvider()); assertEquals("getAlgorithm() failed", "CBA", md2.getAlgorithm()); md2.update((byte) 1); md2.update(b, 1, 3); assertTrue("update failed", MyMessageDigest2.runEngineUpdate1); assertTrue("update failed", MyMessageDigest2.runEngineUpdate2); assertEquals("incorrect digest result", 0, md2.digest().length); assertEquals("getProvider() failed", 0, md2.digest(b, 2, 3)); assertTrue("digest failed", MyMessageDigest2.runEngineDigest); md2.reset(); assertTrue("reset failed", MyMessageDigest2.runEngineReset); assertEquals("getDigestLength() failed", 0, md2.getDigestLength()); try { md2.clone(); fail("No expected CloneNotSupportedException"); } catch (CloneNotSupportedException e) { } } private class MyProvider extends Provider { MyProvider() { super("MyProvider", 1.0, "Provider for testing"); put("MessageDigest.ABC", "org.apache.harmony.security.tests.support.MyMessageDigest1"); put("MessageDigest.CBA", "org.apache.harmony.security.tests.support.MyMessageDigest2"); } MyProvider(String name, double version, String info) { super(name, version, info); } } }
apache-2.0
CodeSmell/camel
components/camel-sjms/src/test/java/org/apache/camel/component/sjms/jms/DefaultDestinationCreationStrategyTest.java
3045
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.sjms.jms; import javax.jms.Queue; import javax.jms.TemporaryQueue; import javax.jms.TemporaryTopic; import javax.jms.Topic; import org.apache.camel.component.sjms.support.JmsTestSupport; import org.junit.Test; public class DefaultDestinationCreationStrategyTest extends JmsTestSupport { private DestinationCreationStrategy strategy = new DefaultDestinationCreationStrategy(); @Test public void testQueueCreation() throws Exception { Queue destination = (Queue)strategy.createDestination(getSession(), "queue://test", false); assertNotNull(destination); assertEquals("test", destination.getQueueName()); destination = (Queue)strategy.createDestination(getSession(), "queue:test", false); assertNotNull(destination); assertEquals("test", destination.getQueueName()); destination = (Queue)strategy.createDestination(getSession(), "test", false); assertNotNull(destination); assertEquals("test", destination.getQueueName()); } @Test public void testTopicCreation() throws Exception { Topic destination = (Topic)strategy.createDestination(getSession(), "topic://test", true); assertNotNull(destination); assertEquals("test", destination.getTopicName()); destination = (Topic)strategy.createDestination(getSession(), "topic:test", true); assertNotNull(destination); assertEquals("test", destination.getTopicName()); destination = (Topic)strategy.createDestination(getSession(), "test", true); assertNotNull(destination); assertEquals("test", destination.getTopicName()); } @Test public void testTemporaryQueueCreation() throws Exception { TemporaryQueue destination = (TemporaryQueue)strategy.createTemporaryDestination(getSession(), false); assertNotNull(destination); assertNotNull(destination.getQueueName()); } @Test public void testTemporaryTopicCreation() throws Exception { TemporaryTopic destination = (TemporaryTopic)strategy.createTemporaryDestination(getSession(), true); assertNotNull(destination); assertNotNull(destination.getTopicName()); } }
apache-2.0
m-m-m/code
base/src/main/java/net/sf/mmm/code/base/type/BaseParameterizedType.java
6528
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.code.base.type; import java.io.IOException; import java.lang.reflect.ParameterizedType; import net.sf.mmm.code.api.copy.CodeCopyMapper; import net.sf.mmm.code.api.copy.CodeCopyType; import net.sf.mmm.code.api.element.CodeElement; import net.sf.mmm.code.api.language.CodeLanguage; import net.sf.mmm.code.api.type.CodeGenericType; import net.sf.mmm.code.api.type.CodeParameterizedType; import net.sf.mmm.code.base.arg.BaseOperationArg; import net.sf.mmm.code.base.element.BaseElement; import net.sf.mmm.code.base.member.BaseOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base implementation of {@link CodeParameterizedType}. * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.0.0 */ public class BaseParameterizedType extends BaseGenericType implements CodeParameterizedType { private static final Logger LOG = LoggerFactory.getLogger(BaseParameterizedType.class); private final BaseElement parent; private final BaseTypeParameters typeVariables; private final ParameterizedType reflectiveObject; private BaseParameterizedType sourceCodeObject; private BaseType type; /** * The constructor. * * @param parent the {@link #getParent() parent}. * @param type the {@link #getType() type} that gets parameterized. Should have the same number of * {@link BaseType#getTypeParameters() type variables} as the {@link #getTypeParameters() type parameters of * this type} when initialized. */ public BaseParameterizedType(BaseElement parent, BaseType type) { this(parent, null, type); } /** * The constructor. * * @param parent the {@link #getParent() parent}. * @param reflectiveObject the {@link #getReflectiveObject() reflective object}. May be {@code null}. */ public BaseParameterizedType(BaseElement parent, ParameterizedType reflectiveObject) { this(parent, reflectiveObject, null); } /** * The constructor. * * @param parent the {@link #getParent() parent}. * @param reflectiveObject the {@link #getReflectiveObject() reflective object}. May be {@code null}. * @param type the {@link #getType() type} that gets parameterized. Should have the same number of * {@link BaseType#getTypeParameters() type variables} as the {@link #getTypeParameters() type parameters of * this type} when initialized. */ public BaseParameterizedType(BaseElement parent, ParameterizedType reflectiveObject, BaseType type) { super(); this.parent = parent; this.typeVariables = new BaseTypeParameters(this); this.reflectiveObject = reflectiveObject; this.type = type; } /** * The copy-constructor. * * @param template the {@link BaseParameterizedType} to copy. * @param mapper the {@link CodeCopyMapper}. */ public BaseParameterizedType(BaseParameterizedType template, CodeCopyMapper mapper) { super(template, mapper); this.parent = mapper.map(template.parent, CodeCopyType.PARENT); this.typeVariables = template.typeVariables.copy(mapper); this.reflectiveObject = null; this.type = mapper.map(template.type, CodeCopyType.REFERENCE); } @Override protected void doInitialize() { super.doInitialize(); getType(); } @Override public BaseElement getParent() { return this.parent; } @Override public BaseTypeParameters getTypeParameters() { return this.typeVariables; } @Override public ParameterizedType getReflectiveObject() { return this.reflectiveObject; } @Override public BaseParameterizedType getSourceCodeObject() { if ((this.sourceCodeObject == null) && !isInitialized()) { CodeElement sourceElement = this.parent.getSourceCodeObject(); if (sourceElement != null) { this.sourceCodeObject = null; // TODO } } return this.sourceCodeObject; } @Override public BaseType getDeclaringType() { return getType(); } @Override public BaseOperation getDeclaringOperation() { return getDeclaringOperation(this.parent); } private BaseOperation getDeclaringOperation(CodeElement parentNode) { if (parentNode instanceof BaseOperationArg) { return ((BaseOperationArg) parentNode).getDeclaringOperation(); } else if (parentNode instanceof BaseParameterizedType) { return ((BaseParameterizedType) parentNode).getDeclaringOperation(); } else if (parentNode instanceof BaseArrayType) { return getDeclaringOperation(((BaseArrayType) parentNode).getParent()); } return null; } @Override public BaseType asType() { return getType().asType(); } @Override public BaseType getType() { if ((this.type == null) && (this.reflectiveObject != null)) { Class<?> rawClass = (Class<?>) this.reflectiveObject.getRawType(); this.type = (BaseType) getContext().getType(rawClass); } return this.type; } @Override public void setType(CodeGenericType type) { verifyMutalbe(); this.type = (BaseType) type; } @Override public BaseTypeVariable asTypeVariable() { return null; } @Override public BaseGenericType resolve(CodeGenericType context) { // TODO Auto-generated method stub return this; } @Override public String getSimpleName() { return getType().getSimpleName(); } @Override public String getQualifiedName() { return getType().getQualifiedName(); } @Override protected void doWrite(Appendable sink, String newline, String defaultIndent, String currentIndent, CodeLanguage language) throws IOException { super.doWrite(sink, newline, null, "", language); writeReference(sink, true); } @Override public BaseParameterizedType copy() { return copy(getDefaultCopyMapper()); } @Override public BaseParameterizedType copy(CodeCopyMapper mapper) { return new BaseParameterizedType(this, mapper); } @Override public void writeReference(Appendable sink, boolean declaration, Boolean qualified) throws IOException { BaseType myType = getType(); if (myType == null) { LOG.warn("Parameterized type with undefined type declared in {}", getDeclaringType().getSimpleName()); sink.append("Undefined"); } else { myType.writeReference(sink, false, qualified); getTypeParameters().write(sink, DEFAULT_NEWLINE, null, ""); } } }
apache-2.0
bbottema/swift-socket-server
demos/clock-worldserver/clock-worldserver-client-java/src/clockworldclient/ClientMessageToServerSetFps.java
491
package clockworldclient; import org.codemonkey.swiftsocketclient.ClientMessageToServer; /** * Message that tells the World Server to adopt a new fps. * * @author Benny Bottema * @since 1.0 */ class ClientMessageToServerSetFps extends ClientMessageToServer { private double framesPerSecond; public ClientMessageToServerSetFps(double fps) { this.framesPerSecond = fps; } @Override public String encode() { return String.valueOf(framesPerSecond); } }
apache-2.0
aQute-os/biz.aQute.openapi
biz.aQute.json.util/src/aQute/json/codec/SpecialHandler.java
1073
package aQute.json.codec; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Map; import java.util.regex.Pattern; public class SpecialHandler extends Handler { @SuppressWarnings("rawtypes") final Class type; final Method valueOf; final Constructor<?> constructor; public SpecialHandler(Class<?> type, Constructor<?> constructor, Method valueOf) { this.type = type; this.constructor = constructor; this.valueOf = valueOf; } @Override public void encode(Encoder app, Object object, Map<Object, Type> visited) throws IOException, Exception { StringHandler.string(app, object.toString()); } @Override public Object decode(Decoder dec, String s) throws Exception { if (type == Pattern.class) return Pattern.compile(s); if (constructor != null) return constructor.newInstance(s); if (valueOf != null) return valueOf.invoke(null, s); throw new IllegalArgumentException("Do not know how to convert a " + type + " from a string"); } }
apache-2.0
consulo/consulo
modules/base/build-ui-impl/src/main/java/com/intellij/build/issue/quickfix/OpenFileQuickFix.java
3529
/* * Copyright 2013-2021 consulo.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 com.intellij.build.issue.quickfix; import com.intellij.build.issue.BuildIssueQuickFix; import com.intellij.codeInsight.highlighting.HighlightManager; import com.intellij.codeInsight.highlighting.HighlightUsagesHandler; import com.intellij.find.FindManager; import com.intellij.find.FindModel; import com.intellij.find.FindResult; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import java.nio.file.Path; import java.util.List; import java.util.concurrent.CompletableFuture; /** * @author VISTALL * @since 17/01/2021 */ public class OpenFileQuickFix implements BuildIssueQuickFix { private final Path myPath; private final String mySearch; public OpenFileQuickFix(Path path, String search) { myPath = path; mySearch = search; } @Override public String getId() { return myPath.toString(); } @Override public CompletableFuture<?> runQuickFix(Project project, DataProvider dataProvider) { CompletableFuture<Object> future = new CompletableFuture<>(); ApplicationManager.getApplication().invokeLater(() -> { try { showFile(project, myPath, mySearch); future.complete(null); } catch (Exception e) { future.completeExceptionally(e); } }); return future; } public static void showFile(Project project, Path path, String search) { ApplicationManager.getApplication().invokeLater(() -> { VirtualFile file = VfsUtil.findFileByIoFile(path.toFile(), false); if (file == null) { return; } Editor editor = FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, file), false); if (search == null || editor == null) return; FindModel findModel = new FindModel(); FindModel.initStringToFind(findModel, search); FindResult findResult = FindManager.getInstance(project).findString(editor.getDocument().getCharsSequence(), 0, findModel, file); HighlightManager highlightManager = HighlightManager.getInstance(project); EditorColorsScheme globalScheme = EditorColorsManager.getInstance().getGlobalScheme(); TextAttributes attributes = globalScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES); HighlightUsagesHandler.highlightRanges(highlightManager, editor, attributes, false, List.of(findResult)); }); } }
apache-2.0
tonyley/SteerableAsyncLoader
steerableasyncloader/src/main/java/com/steerableasyncloader/support/SteerableLoaderManager.java
301
package com.steerableasyncloader.support; import android.support.v4.app.LoaderManager; import com.steerableasyncloader.SteerableAsyncLoaderManager; /** * Created by tony on 2014/12/28. */ public abstract class SteerableLoaderManager extends LoaderManager implements SteerableAsyncLoaderManager{ }
apache-2.0
xtremelabs/xl-image_utils_lib-android
xl_image_utils_lib/src/com/xtremelabs/imageutils/ViewDimensionsUtil.java
2181
/* * Copyright 2013 Xtreme Labs * * 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.xtremelabs.imageutils; import android.graphics.Point; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; class ViewDimensionsUtil { public static Point getImageViewDimensions(ImageView imageView) { Point dimensions = new Point(); dimensions.x = getDimensions(imageView, true); dimensions.y = getDimensions(imageView, false); if (dimensions.x <= 0) { dimensions.x = -1; } if (dimensions.y <= 0) { dimensions.y = -1; } return dimensions; } private static int getDimensions(ImageView imageView, boolean isWidth) { LayoutParams params = imageView.getLayoutParams(); if (params == null) { return -1; } int length = isWidth ? params.width : params.height; if (length == LayoutParams.WRAP_CONTENT) { return -1; } else if (length == LayoutParams.MATCH_PARENT) { try { return getParentDimensions((ViewGroup) imageView.getParent(), isWidth); } catch (ClassCastException e) { return -1; } } else { return length; } } private static int getParentDimensions(ViewGroup parent, boolean isWidth) { LayoutParams params; if (parent == null || (params = parent.getLayoutParams()) == null) { return -1; } int length = isWidth ? params.width : params.height; if (length == LayoutParams.WRAP_CONTENT) { return -1; } else if (length == LayoutParams.MATCH_PARENT) { try { return getParentDimensions((ViewGroup) parent.getParent(), isWidth); } catch (ClassCastException e) { return -1; } } else { return length; } } }
apache-2.0
googleapis/java-compute
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/WaitZoneOperationRequestOrBuilder.java
2485
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto package com.google.cloud.compute.v1; public interface WaitZoneOperationRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.WaitZoneOperationRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Name of the Operations resource to return. * </pre> * * <code>string operation = 52090215 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The operation. */ java.lang.String getOperation(); /** * * * <pre> * Name of the Operations resource to return. * </pre> * * <code>string operation = 52090215 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for operation. */ com.google.protobuf.ByteString getOperationBytes(); /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The project. */ java.lang.String getProject(); /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for project. */ com.google.protobuf.ByteString getProjectBytes(); /** * * * <pre> * Name of the zone for this request. * </pre> * * <code>string zone = 3744684 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The zone. */ java.lang.String getZone(); /** * * * <pre> * Name of the zone for this request. * </pre> * * <code>string zone = 3744684 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for zone. */ com.google.protobuf.ByteString getZoneBytes(); }
apache-2.0
wind-clothes/tendons
tendons-common/src/main/java/org/tendons/common/server/RpcServer.java
996
package org.tendons.common.server; /** * @author: chengweixiong@uworks.cc * @date: 2017年5月10日 下午11:04:09 */ public interface RpcServer { /** * 开启服务器 * * @return void */ void start() throws Throwable; /** * 停止服务 * * @return void */ void stop() throws Throwable; /* *//** * 发布本地所有服务到注册中心. *//* void publishAll(); *//** * 从注册中心把指定服务下线. *//* void unpublish(ServiceWrapper serviceWrapper); *//** * 从注册中心把本地所有服务全部下线. *//* void unpublishAll(); *//** * 注册所有服务到本地容器. *//* List<ServiceWrapper> allRegisteredServices(); *//** * 发布指定服务到注册中心. *//* void publish(ServiceWrapper serviceWrapper); *//** * 发布指定服务列表到注册中心. *//* void publish(ServiceWrapper... serviceWrappers);*/ }
apache-2.0
bit-zyl/Alluxio-Nvdimm
core/common/src/main/java/alluxio/util/CommonUtils.java
11065
/* * 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.util; import alluxio.Constants; import alluxio.security.group.CachedGroupMapping; import alluxio.security.group.GroupMappingService; import alluxio.util.ShellUtils.ExitCodeException; import com.google.common.base.Function; import com.google.common.base.Splitter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.StringTokenizer; import javax.annotation.concurrent.ThreadSafe; /** * Common utilities shared by all components in Alluxio. */ @ThreadSafe public final class CommonUtils { private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE); private static final String ALPHANUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private static final Random RANDOM = new Random(); /** * @return current time in milliseconds */ public static long getCurrentMs() { return System.currentTimeMillis(); } /** * Converts a list of objects to a string. * * @param list list of objects * @param <T> type of the objects * @return space-separated concatenation of the string representation returned by Object#toString * of the individual objects */ public static <T> String listToString(List<T> list) { StringBuilder sb = new StringBuilder(); for (T s : list) { if (sb.length() != 0) { sb.append(" "); } sb.append(s); } return sb.toString(); } /** * Converts varargs of objects to a string. * * @param separator separator string * @param args variable arguments * @param <T> type of the objects * @return concatenation of the string representation returned by Object#toString * of the individual objects */ public static <T> String argsToString(String separator, T... args) { StringBuilder sb = new StringBuilder(); for (T s : args) { if (sb.length() != 0) { sb.append(separator); } sb.append(s); } return sb.toString(); } /** * Parses {@code ArrayList<String>} into {@code String[]}. * * @param src is the ArrayList of strings * @return an array of strings */ public static String[] toStringArray(ArrayList<String> src) { String[] ret = new String[src.size()]; return src.toArray(ret); } /** * Generates a random alphanumeric string of the given length. * * @param length the length * @return a random string */ public static String randomString(int length) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { sb.append(ALPHANUM.charAt(RANDOM.nextInt(ALPHANUM.length()))); } return sb.toString(); } /** * Generates a random byte array of the given length. * * @param length the length * @return a random byte array */ public static byte[] randomBytes(int length) { byte[] result = new byte[length]; RANDOM.nextBytes(result); return result; } /** * Sleeps for the given number of milliseconds. * * @param timeMs sleep duration in milliseconds */ public static void sleepMs(long timeMs) { sleepMs(null, timeMs); } /** * Sleeps for the given number of milliseconds, reporting interruptions using the given logger. * * Unlike Thread.sleep(), this method responds to interrupts by setting the thread interrupt * status. This means that callers must check the interrupt status if they need to handle * interrupts. * * @param logger logger for reporting interruptions; no reporting is done if the logger is null * @param timeMs sleep duration in milliseconds */ public static void sleepMs(Logger logger, long timeMs) { try { Thread.sleep(timeMs); } catch (InterruptedException e) { if (logger != null) { logger.warn(e.getMessage(), e); } Thread.currentThread().interrupt(); } } /** * Common empty loop utility that serves the purpose of warming up the JVM before performance * microbenchmarks. */ public static void warmUpLoop() { for (int k = 0; k < 10000000; k++) {} } /** * Creates new instance of a class by calling a constructor that receives ctorClassArgs arguments. * * @param <T> type of the object * @param cls the class to create * @param ctorClassArgs parameters type list of the constructor to initiate, if null default * constructor will be called * @param ctorArgs the arguments to pass the constructor * @return new class object or null if not successful * @throws InstantiationException if the instantiation fails * @throws IllegalAccessException if the constructor cannot be accessed * @throws NoSuchMethodException if the constructor does not exist * @throws SecurityException if security violation has occurred * @throws InvocationTargetException if the constructor invocation results in an exception */ public static <T> T createNewClassInstance(Class<T> cls, Class<?>[] ctorClassArgs, Object[] ctorArgs) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, InvocationTargetException { if (ctorClassArgs == null) { return cls.newInstance(); } Constructor<T> ctor = cls.getConstructor(ctorClassArgs); return ctor.newInstance(ctorArgs); } /** * Gets the current user's group list from Unix by running the command 'groups' NOTE. For * non-existing user it will return EMPTY list. This method may return duplicate groups. * * @param user user name * @return the groups list that the {@code user} belongs to. The primary group is returned first * @throws IOException if encounter any error when running the command */ public static List<String> getUnixGroups(String user) throws IOException { String result; List<String> groups = new ArrayList<>(); try { result = ShellUtils.execCommand(ShellUtils.getGroupsForUserCommand(user)); } catch (ExitCodeException e) { // if we didn't get the group - just return empty list; LOG.warn("got exception trying to get groups for user " + user + ": " + e.getMessage()); return groups; } StringTokenizer tokenizer = new StringTokenizer(result, ShellUtils.TOKEN_SEPARATOR_REGEX); while (tokenizer.hasMoreTokens()) { groups.add(tokenizer.nextToken()); } return groups; } /** * Waits for a condition to be satisfied until a timeout occurs. * * @param description a description of what causes condition to evaluation to true * @param condition the condition to wait on * @param timeoutMs the number of milliseconds to wait before giving up and throwing an exception */ public static void waitFor(String description, Function<Void, Boolean> condition, int timeoutMs) { long start = System.currentTimeMillis(); while (!condition.apply(null)) { if (System.currentTimeMillis() - start > timeoutMs) { throw new RuntimeException("Timed out waiting for " + description); } CommonUtils.sleepMs(20); } } /** * Gets the primary group name of a user. * * @param userName Alluxio user name * @return primary group name * @throws IOException if getting group failed */ public static String getPrimaryGroupName(String userName) throws IOException { List<String> groups = getGroups(userName); return (groups != null && groups.size() > 0) ? groups.get(0) : ""; } /** * Using {@link CachedGroupMapping} to get the group list of a user. * * @param userName Alluxio user name * @return the group list of the user * @throws IOException if getting group list failed */ public static List<String> getGroups(String userName) throws IOException { GroupMappingService groupMappingService = GroupMappingService.Factory.get(); return groupMappingService.getGroups(userName); } /** * Strips the suffix if it exists. This method will leave keys without a suffix unaltered. * * @param key the key to strip the suffix from * @param suffix suffix to remove * @return the key with the suffix removed, or the key unaltered if the suffix is not present */ public static String stripSuffixIfPresent(final String key, final String suffix) { if (key.endsWith(suffix)) { return key.substring(0, key.length() - suffix.length()); } return key; } /** * Strips the prefix from the key if it is present. For example, for input key * ufs://my-bucket-name/my-key/file and prefix ufs://my-bucket-name/, the output would be * my-key/file. This method will leave keys without a prefix unaltered, ie. my-key/file * returns my-key/file. * * @param key the key to strip * @param prefix prefix to remove * @return the key without the prefix */ public static String stripPrefixIfPresent(final String key, final String prefix) { if (key.startsWith(prefix)) { return key.substring(prefix.length()); } return key; } /** * Returns whether the given ufs address indicates a object storage ufs. * @param ufsAddress the ufs address * @return true if the under file system is a object storage; false otherwise */ public static boolean isUfsObjectStorage(String ufsAddress) { return ufsAddress.startsWith(Constants.HEADER_S3) || ufsAddress.startsWith(Constants.HEADER_S3N) || ufsAddress.startsWith(Constants.HEADER_S3A) || ufsAddress.startsWith(Constants.HEADER_GCS) || ufsAddress.startsWith(Constants.HEADER_SWIFT) || ufsAddress.startsWith(Constants.HEADER_OSS); } /** * Gets the value with a given key from a static key/value mapping in string format. E.g. with * mapping "id1=user1;id2=user2", it returns "user1" with key "id1". It returns null if the given * key does not exist in the mapping. * * @param mapping the "key=value" mapping in string format separated by ";" * @param key the key to query * @return the mapped value if the key exists, otherwise returns "" */ public static String getValueFromStaticMapping(String mapping, String key) { Map<String, String> m = Splitter.on(";") .omitEmptyStrings() .trimResults() .withKeyValueSeparator("=") .split(mapping); return m.get(key); } private CommonUtils() {} // prevent instantiation }
apache-2.0
b2ihealthcare/snow-owl
core/com.b2international.snowowl.core/src/com/b2international/snowowl/core/monitoring/TimedProgressMonitorWrapper.java
5770
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.core.monitoring; import java.lang.ref.WeakReference; import java.text.MessageFormat; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.ProgressMonitorWrapper; import com.google.common.collect.Lists; /** * Progress monitor wrapper that updates the wrapped monitor's subtask every * second with the elapsed time (since {@link #beginTask(String, int)} was * called). * <p> * For proper operation, make sure to call {@link #done()} on this monitor even * if an exception is thrown (preferably in a finally block). */ public final class TimedProgressMonitorWrapper extends ProgressMonitorWrapper { private static final class TimedProgressMonitorThread extends Thread { private final List<WeakReference<TimedProgressMonitorWrapper>> monitorsToUpdate = Collections.synchronizedList( Lists.<WeakReference<TimedProgressMonitorWrapper>>newLinkedList()); public TimedProgressMonitorThread() { super(TimedProgressMonitorThread.class.getSimpleName()); setDaemon(true); } public void addMonitor(final TimedProgressMonitorWrapper monitor) { monitorsToUpdate.add(new WeakReference<TimedProgressMonitorWrapper>(monitor)); } public void removeMonitor(final TimedProgressMonitorWrapper monitor) { synchronized (monitorsToUpdate) { for (final Iterator<WeakReference<TimedProgressMonitorWrapper>> iterator = monitorsToUpdate.iterator(); iterator.hasNext();) { final WeakReference<TimedProgressMonitorWrapper> monitorRef = iterator.next(); final TimedProgressMonitorWrapper monitor2 = monitorRef.get(); if (monitor2 == null || monitor2 == monitor) { iterator.remove(); } } } } @Override public void run() { while (true) { synchronized (monitorsToUpdate) { for (final Iterator<WeakReference<TimedProgressMonitorWrapper>> iterator = monitorsToUpdate.iterator(); iterator.hasNext();) { final WeakReference<TimedProgressMonitorWrapper> monitorRef = iterator.next(); try { final TimedProgressMonitorWrapper monitor = monitorRef.get(); if (monitor != null) { monitor.update(); } else { iterator.remove(); } } catch (final Exception e) { iterator.remove(); } } } try { Thread.sleep(1000); } catch (final InterruptedException e) { // Nothing to do here } } } } private static TimedProgressMonitorThread timeUpdateThread; private synchronized static TimedProgressMonitorThread getTimeUpdateThread() { if (timeUpdateThread == null) { timeUpdateThread = new TimedProgressMonitorThread(); timeUpdateThread.start(); } return timeUpdateThread; } private static final String SUBTASK_TEMPLATE = "Elapsed time: {0}."; private long startTime; private long stopTime; private final AtomicBoolean stopped = new AtomicBoolean(true); private String subTask = ""; public TimedProgressMonitorWrapper(final IProgressMonitor delegate) { super(delegate); } public String getElapsedTime() { final long runningFinishTime = (!stopped.get()) ? System.currentTimeMillis() : stopTime; final long elapsedTimeMillis = (0 == startTime) ? 0 : Math.max(runningFinishTime - startTime, 0); // Check if the timer was ever started final long elapsedMinutes = elapsedTimeMillis / (60L * 1000L); final long remainderMillis = elapsedTimeMillis - (elapsedMinutes * 60L * 1000L); final long elapsedSeconds = remainderMillis / 1000L; return MessageFormat.format("{0} minute{1} {2} second{3}", elapsedMinutes, pluralSuffix(elapsedMinutes), elapsedSeconds, pluralSuffix(elapsedSeconds)); } private String pluralSuffix(long number) { return number > 1 ? "s" : ""; } @Override public void beginTask(final String name, final int totalWork) { super.beginTask(name, totalWork); // Start the wall clock resume(); } @Override public void done() { // Stop the wall clock pause(); super.done(); } @Override public void setCanceled(final boolean value) { // Only stop the wall clock if the progress monitor has been canceled if (value) { pause(); } super.setCanceled(value); } @Override public void subTask(final String name) { subTask = (name == null) ? "" : name; update(); } private void update() { final StringBuilder builder = new StringBuilder(); builder.append(MessageFormat.format(SUBTASK_TEMPLATE, getElapsedTime())); if (!subTask.isEmpty()) { builder.append(" "); builder.append(subTask); } super.subTask(builder.toString()); } public synchronized void pause() { if (stopped.compareAndSet(false, true)) { stopTime = System.currentTimeMillis(); getTimeUpdateThread().removeMonitor(this); } } public synchronized void resume() { if (stopped.compareAndSet(true, false)) { startTime = System.currentTimeMillis() - Math.max((stopTime - startTime), 0); stopTime = 0L; getTimeUpdateThread().addMonitor(this); } } }
apache-2.0
eubrazilcc/leishvl
leishvl-core/src/main/generated-sources/esearch/io/leishvl/core/ncbi/esearch/WebEnv.java
2911
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.11.04 at 10:30:05 PM CET // package io.leishvl.core.ncbi.esearch; import javax.annotation.Generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @XmlRootElement(name = "WebEnv") @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-11-04T10:30:05+01:00", comments = "JAXB RI v2.2.11") public class WebEnv { @XmlValue @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-11-04T10:30:05+01:00", comments = "JAXB RI v2.2.11") protected String value; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-11-04T10:30:05+01:00", comments = "JAXB RI v2.2.11") public String getvalue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-11-04T10:30:05+01:00", comments = "JAXB RI v2.2.11") public void setvalue(String value) { this.value = value; } @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-11-04T10:30:05+01:00", comments = "JAXB RI v2.2.11") public WebEnv withvalue(String value) { setvalue(value); return this; } @Override @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-11-04T10:30:05+01:00", comments = "JAXB RI v2.2.11") public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-11-04T10:30:05+01:00", comments = "JAXB RI v2.2.11") public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-11-04T10:30:05+01:00", comments = "JAXB RI v2.2.11") public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } }
apache-2.0
jonefeewang/armeria
core/src/main/java/com/linecorp/armeria/server/http/encoding/package-info.java
727
/* * Copyright 2016 LINE Corporation * * LINE Corporation 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. */ /** * HTTP content encoding service. */ package com.linecorp.armeria.server.http.encoding;
apache-2.0
D-iii-S/java-ubench-agent
src/test-java/cz/cuni/mff/d3s/perf/JvmUtilsTest.java
2231
/* * Copyright 2018 Charles University in Prague * Copyright 2018 Vojtech Horky * * 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 cz.cuni.mff.d3s.perf; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; import java.util.Set; import java.util.regex.Pattern; import org.junit.*; public class JvmUtilsTest { private static final Pattern NAME_MATCHES_JVMCI_THREAD = Pattern.compile("^Name:.*JVMCI.*", Pattern.CASE_INSENSITIVE); @Test public void jvmciThreadsFound() { Assume.assumeTrue(System.getProperty("java.vm.version", "").contains("jvmci")); Set<Long> tids = JvmUtils.getNativeIdsOfJvmciThreads(); Assert.assertFalse(tids.isEmpty()); } @Test public void jvmciThreadsFoundOnLinux() throws IOException { // Skipping as it does not work this way on all JDKs Assume.assumeTrue(false); Set<Long> tids = JvmUtils.getNativeIdsOfJvmciThreads(); Assume.assumeTrue(System.getProperty("os.name", "").equals("Linux")); for (Long tid : tids) { String path = String.format("/proc/%d/status", tid); Scanner sc = new Scanner(new FileReader(path)); boolean found = false; while (sc.hasNextLine()) { String line = sc.nextLine(); System.out.println(line); if (NAME_MATCHES_JVMCI_THREAD.matcher(line).find()) { found = true; break; } } sc.close(); Assert.assertTrue( String.format("Thread %d seems not to be a JVMCI thread.", tid), found ); } } }
apache-2.0
Shivam101/ManipalNow-Android
src/com/example/nav/HelpFragment5.java
1349
package com.example.nav; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class HelpFragment5 extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.helpfrag, null); ImageView iv1=(ImageView)root.findViewById(R.id.helpimg1); TextView title=(TextView)root.findViewById(R.id.tv2); Typeface robotoLight = Typeface.createFromAsset(getActivity().getAssets(), "Roboto-Light.ttf"); TextView desc=(TextView)root.findViewById(R.id.tv3); LinearLayout lv1=(LinearLayout)root.findViewById(R.id.footer); View v2=new LinearLayout(getActivity()); lv1.setVisibility(v2.GONE); View v=new ImageView(getActivity()); iv1.setImageDrawable(v.getResources().getDrawable(R.drawable.airport)); title.setText("Airports"); title.setTextColor(getResources().getColor(R.color.playred)); desc.setText("Looking to book your tickets ?"); desc.setTypeface(robotoLight); return root; } }
apache-2.0
aspectran/aspectran
shell-jline/src/test/java/com/aspectran/shell/jline/JLineAspectranShellOnlyTest.java
1204
/* * Copyright (c) 2008-2022 The Aspectran Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aspectran.shell.jline; import com.aspectran.core.util.ResourceUtils; import com.aspectran.shell.AspectranShell; import com.aspectran.shell.jline.console.JLineConsole; import java.io.File; import java.io.IOException; /** * <p>Created: 2019. 1. 23.</p> */ class JLineAspectranShellOnlyTest { public static void main(String[] args) throws IOException { File aspectranConfigFile = ResourceUtils.getResourceAsFile("config/shell/jline/aspectran-config-jline-shell-only-test.apon"); AspectranShell.bootstrap(aspectranConfigFile, new JLineConsole()); } }
apache-2.0
aspectran/aspectran
demo/src/main/java/com/aspectran/demo/chat/codec/ChatMessageDecoder.java
1524
/* * Copyright (c) 2008-2022 The Aspectran Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aspectran.demo.chat.codec; import com.aspectran.core.util.apon.JsonToApon; import com.aspectran.demo.chat.model.ChatMessage; import jakarta.websocket.DecodeException; import jakarta.websocket.Decoder; import jakarta.websocket.EndpointConfig; import java.io.IOException; /** * Decoder for {@link ChatMessage}. * * <p>Created: 2019/10/09</p> */ public class ChatMessageDecoder implements Decoder.Text<ChatMessage> { @Override public ChatMessage decode(String s) throws DecodeException { try { return JsonToApon.from(s, ChatMessage.class); } catch (IOException e) { throw new DecodeException(s, "Badly formatted message", e); } } @Override public boolean willDecode(String s) { return true; } @Override public void init(EndpointConfig config) { } @Override public void destroy() { } }
apache-2.0
LevelFourAB/vibe
vibe-api/src/main/java/se/l4/vibe/checks/CheckListener.java
299
package se.l4.vibe.checks; import edu.umd.cs.findbugs.annotations.NonNull; /** * Listener for status of a {@link Check}. * * @see Check */ public interface CheckListener { /** * Status of the check has been updated. * * @param event */ void checkStatus(@NonNull CheckEvent event); }
apache-2.0
cercao/GrafoLib
src/desafios/kruskal/Estado.java
347
package desafios.kruskal; public enum Estado { RO(0), AC(1), AM(2), RR(3), PA(4), AP(5), TO(6), MA(7), PI(8), CE(9), RN(10), PB(11), PE(12), AL(13), SE(14), BA(15), MG(16), ES(17), RJ(18), SP(19), PR(20), SC(21), RS(22), MS(23), MT(24), GO(25), DF(26); public int valor; Estado(int _valor) { valor = _valor; } }
apache-2.0
spring-projects/spring-data-examples
jpa/deferred/src/main/java/example/model/Customer1917.java
628
package example.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Customer1917 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1917() {} public Customer1917(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1917[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } }
apache-2.0
pepperonas/FxIconics
src/main/java/com/pepperonas/fxiconics/oct/FxFontOcticons.java
7915
/* * Copyright (c) 2015 Martin Pfeffer * 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.pepperonas.fxiconics.oct; import com.pepperonas.fxiconics.base.FxFontBase; /** * @author Martin Pfeffer (pepperonas) */ public class FxFontOcticons extends FxFontBase { public enum Icons { oct_alert("\uf02d"), oct_alignment_align("\uf08a"), oct_alignment_aligned_to("\uf08e"), oct_alignment_unalign("\uf08b"), oct_arrow_down("\uf03f"), oct_arrow_left("\uf040"), oct_arrow_right("\uf03e"), oct_arrow_small_down("\uf0a0"), oct_arrow_small_left("\uf0a1"), oct_arrow_small_right("\uf071"), oct_arrow_small_up("\uf09f"), oct_arrow_up("\uf03d"), oct_beer("\uf069"), oct_book("\uf007"), oct_bookmark("\uf07b"), oct_briefcase("\uf0d3"), oct_broadcast("\uf048"), oct_browser("\uf0c5"), oct_bug("\uf091"), oct_calendar("\uf068"), oct_check("\uf03a"), oct_checklist("\uf076"), oct_chevron_down("\uf0a3"), oct_chevron_left("\uf0a4"), oct_chevron_right("\uf078"), oct_chevron_up("\uf0a2"), oct_circle_slash("\uf084"), oct_circuit_board("\uf0d6"), oct_clippy("\uf035"), oct_clock("\uf046"), oct_cloud_download("\uf00b"), oct_cloud_upload("\uf00c"), oct_code("\uf05f"), oct_color_mode("\uf065"), oct_comment_add("\uf02b"), oct_comment("\uf02b"), oct_comment_discussion("\uf04f"), oct_credit_card("\uf045"), oct_dash("\uf0ca"), oct_dashboard("\uf07d"), oct_database("\uf096"), oct_device_camera("\uf056"), oct_device_camera_video("\uf057"), oct_device_desktop("\uf27c"), oct_device_mobile("\uf038"), oct_diff("\uf04d"), oct_diff_added("\uf06b"), oct_diff_ignored("\uf099"), oct_diff_modified("\uf06d"), oct_diff_removed("\uf06c"), oct_diff_renamed("\uf06e"), oct_ellipsis("\uf09a"), oct_eye_unwatch("\uf04e"), oct_eye_watch("\uf04e"), oct_eye("\uf04e"), oct_file_binary("\uf094"), oct_file_code("\uf010"), oct_file_directory("\uf016"), oct_file_media("\uf012"), oct_file_pdf("\uf014"), oct_file_submodule("\uf017"), oct_file_symlink_directory("\uf0b1"), oct_file_symlink_file("\uf0b0"), oct_file_text("\uf011"), oct_file_zip("\uf013"), oct_flame("\uf0d2"), oct_fold("\uf0cc"), oct_gear("\uf02f"), oct_gift("\uf042"), oct_gist("\uf00e"), oct_gist_secret("\uf08c"), oct_git_branch_create("\uf020"), oct_git_branch_delete("\uf020"), oct_git_branch("\uf020"), oct_git_commit("\uf01f"), oct_git_compare("\uf0ac"), oct_git_merge("\uf023"), oct_git_pull_request_abandoned("\uf009"), oct_git_pull_request("\uf009"), oct_globe("\uf0b6"), oct_graph("\uf043"), oct_heart("\u2665"), oct_history("\uf07e"), oct_home("\uf08d"), oct_horizontal_rule("\uf070"), oct_hourglass("\uf09e"), oct_hubot("\uf09d"), oct_inbox("\uf0cf"), oct_info("\uf059"), oct_issue_closed("\uf028"), oct_issue_opened("\uf026"), oct_issue_reopened("\uf027"), oct_jersey("\uf019"), oct_jump_down("\uf072"), oct_jump_left("\uf0a5"), oct_jump_right("\uf0a6"), oct_jump_up("\uf073"), oct_key("\uf049"), oct_keyboard("\uf00d"), oct_law("\uf0d8"), oct_light_bulb("\uf000"), oct_link("\uf05c"), oct_link_external("\uf07f"), oct_list_ordered("\uf062"), oct_list_unordered("\uf061"), oct_location("\uf060"), oct_gist_private("\uf06a"), oct_mirror_private("\uf06a"), oct_git_fork_private("\uf06a"), oct_lock("\uf06a"), oct_logo_github("\uf092"), oct_mail("\uf03b"), oct_mail_read("\uf03c"), oct_mail_reply("\uf051"), oct_mark_github("\uf00a"), oct_markdown("\uf0c9"), oct_megaphone("\uf077"), oct_mention("\uf0be"), oct_microscope("\uf089"), oct_milestone("\uf075"), oct_mirror_public("\uf024"), oct_mirror("\uf024"), oct_mortar_board("\uf0d7"), oct_move_down("\uf0a8"), oct_move_left("\uf074"), oct_move_right("\uf0a9"), oct_move_up("\uf0a7"), oct_mute("\uf080"), oct_no_newline("\uf09c"), oct_octoface("\uf008"), oct_organization("\uf037"), oct_package("\uf0c4"), oct_paintcan("\uf0d1"), oct_pencil("\uf058"), oct_person_add("\uf018"), oct_person_follow("\uf018"), oct_person("\uf018"), oct_pin("\uf041"), oct_playback_fast_forward("\uf0bd"), oct_playback_pause("\uf0bb"), oct_playback_play("\uf0bf"), oct_playback_rewind("\uf0bc"), oct_plug("\uf0d4"), oct_repo_create("\uf05d"), oct_gist_new("\uf05d"), oct_file_directory_create("\uf05d"), oct_file_add("\uf05d"), oct_plus("\uf05d"), oct_podium("\uf0af"), oct_primitive_dot("\uf052"), oct_primitive_square("\uf053"), oct_pulse("\uf085"), oct_puzzle("\uf0c0"), oct_question("\uf02c"), oct_quote("\uf063"), oct_radio_tower("\uf030"), oct_repo_delete("\uf001"), oct_repo("\uf001"), oct_repo_clone("\uf04c"), oct_repo_force_push("\uf04a"), oct_gist_fork("\uf002"), oct_repo_forked("\uf002"), oct_repo_pull("\uf006"), oct_repo_push("\uf005"), oct_rocket("\uf033"), oct_rss("\uf034"), oct_ruby("\uf047"), oct_screen_full("\uf066"), oct_screen_normal("\uf067"), oct_search_save("\uf02e"), oct_search("\uf02e"), oct_server("\uf097"), oct_settings("\uf07c"), oct_log_in("\uf036"), oct_sign_in("\uf036"), oct_log_out("\uf032"), oct_sign_out("\uf032"), oct_split("\uf0c6"), oct_squirrel("\uf0b2"), oct_star_add("\uf02a"), oct_star_delete("\uf02a"), oct_star("\uf02a"), oct_steps("\uf0c7"), oct_stop("\uf08f"), oct_repo_sync("\uf087"), oct_sync("\uf087"), oct_tag_remove("\uf015"), oct_tag_add("\uf015"), oct_tag("\uf015"), oct_telescope("\uf088"), oct_terminal("\uf0c8"), oct_three_bars("\uf05e"), oct_thumbsdown("\uf0db"), oct_thumbsup("\uf0da"), oct_tools("\uf031"), oct_trashcan("\uf0d0"), oct_triangle_down("\uf05b"), oct_triangle_left("\uf044"), oct_triangle_right("\uf05a"), oct_triangle_up("\uf0aa"), oct_unfold("\uf039"), oct_unmute("\uf0ba"), oct_versions("\uf064"), oct_x("\uf081"), oct_zap("\u26A1"); private final String id; Icons(String s) { this.id = s; } public String getName() { return name(); } @Override public String toString() { return id; } } }
apache-2.0
kellan04/IboxApp
IBOX/app/src/main/java/com/iboxapp/ibox/ui/ForgetPasswordActivity.java
2586
package com.iboxapp.ibox.ui; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.iboxapp.ibox.R; public class ForgetPasswordActivity extends AppCompatActivity { private EditText phone; private EditText code; private Button get_code; private Button forget_password; private Toolbar mToolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forget_password); mToolbar = (Toolbar) findViewById(R.id.simple_toolbar); mToolbar.setTitle(getResources().getString(R.string.forget_password)); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); phone = (EditText)findViewById(R.id.edit_forget_phoneNum); code = (EditText)findViewById(R.id.edit_code); get_code = (Button)findViewById(R.id.button_get_code); forget_password = (Button)findViewById(R.id.forget_password_button); get_code.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //调用获取验证码的接口 } }); forget_password.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(phone.getText().toString().equals(null) || code.getText().toString().equals(null)){ Toast toast = Toast.makeText(getApplicationContext(), "手机号或验证码不能为空", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); }else{ //先调用接口判断,验证码是否正确。根据返回信息,toast出不同的信息,并跳转 startActivity(new Intent(ForgetPasswordActivity.this,ForgetPassword2Activity.class)); } } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub if(item.getItemId() == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } }
apache-2.0
linkedin/MTBT
perf-tool-core/src/main/java/com/linkedin/multitenant/workload/Workload.java
2206
/** * Copyright 2014 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.linkedin.multitenant.workload; import java.util.Map; import com.linkedin.multitenant.common.Query; public interface Workload { public enum WorkloadResult { OK, FAIL } /** * Initialize this workload instance. * @param myId ID of the WorkerThread that instantiates this Workload instance.<br> * Should be between [0, numberOfWorkers) * @param numberOfWorkers Number of total workerThreads for this job.<br> * Total workers is numberOfMachines * numberOfThreads for this job. * @param workPlanProperties Properties for the work plan * @param jobProperties Properties for the job * @return init result in WorkloadResult type */ public abstract WorkloadResult init(int myId, int numberOfWorkers, Map<String, String> workPlanProperties, Map<String, String> jobProperties); /** * Generate an insert query that is used in the data loading phase. * @return Returns query instance if succeeded. Null otherwise. */ public abstract Query generateInsertLoad(); /** * Generate a transaction chosen randomly amongst read/write/delete if specified before. * @return Returns query instance if succeeded. Null otherwise. */ public abstract Query generateTransaction(); /** * Close any open connection/file before quitting. * @return close result in WorkloadResult type */ public abstract WorkloadResult close(); /** * Return the number of rows that this Workload instances is responsible for.<br> * Different Workload implementations may have different assignment techniques to each thread. * @return The number of rows that this workload instance (hence, this thread) is responsible for. */ public abstract int getRowsResponsible(); }
apache-2.0
luigi-agosti/seba
src/test/java/com/luigiagosti/seba/utils/MyEvent.java
745
package com.luigiagosti.seba.utils; import com.luigiagosti.seba.Event; public class MyEvent implements Event { private int id; public void setId(int id) { this.id = id; } public int getId() { return id; } @Override public String toString() { return "MyEvent [id=" + id + "]"; } public static class MyEvent1 extends MyEvent { @Override public String toString() { return "MyEvent1 [id=" + getId() + "]"; } } ; public static class MyEvent2 extends MyEvent { @Override public String toString() { return "MyEvent2 [id=" + getId() + "]"; } } ; }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-managedgrafana/src/main/java/com/amazonaws/services/managedgrafana/model/AssociateLicenseRequest.java
5858
/* * 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.managedgrafana.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/grafana-2020-08-18/AssociateLicense" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AssociateLicenseRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The type of license to associate with the workspace. * </p> */ private String licenseType; /** * <p> * The ID of the workspace to associate the license with. * </p> */ private String workspaceId; /** * <p> * The type of license to associate with the workspace. * </p> * * @param licenseType * The type of license to associate with the workspace. * @see LicenseType */ public void setLicenseType(String licenseType) { this.licenseType = licenseType; } /** * <p> * The type of license to associate with the workspace. * </p> * * @return The type of license to associate with the workspace. * @see LicenseType */ public String getLicenseType() { return this.licenseType; } /** * <p> * The type of license to associate with the workspace. * </p> * * @param licenseType * The type of license to associate with the workspace. * @return Returns a reference to this object so that method calls can be chained together. * @see LicenseType */ public AssociateLicenseRequest withLicenseType(String licenseType) { setLicenseType(licenseType); return this; } /** * <p> * The type of license to associate with the workspace. * </p> * * @param licenseType * The type of license to associate with the workspace. * @return Returns a reference to this object so that method calls can be chained together. * @see LicenseType */ public AssociateLicenseRequest withLicenseType(LicenseType licenseType) { this.licenseType = licenseType.toString(); return this; } /** * <p> * The ID of the workspace to associate the license with. * </p> * * @param workspaceId * The ID of the workspace to associate the license with. */ public void setWorkspaceId(String workspaceId) { this.workspaceId = workspaceId; } /** * <p> * The ID of the workspace to associate the license with. * </p> * * @return The ID of the workspace to associate the license with. */ public String getWorkspaceId() { return this.workspaceId; } /** * <p> * The ID of the workspace to associate the license with. * </p> * * @param workspaceId * The ID of the workspace to associate the license with. * @return Returns a reference to this object so that method calls can be chained together. */ public AssociateLicenseRequest withWorkspaceId(String workspaceId) { setWorkspaceId(workspaceId); 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 (getLicenseType() != null) sb.append("LicenseType: ").append(getLicenseType()).append(","); if (getWorkspaceId() != null) sb.append("WorkspaceId: ").append(getWorkspaceId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof AssociateLicenseRequest == false) return false; AssociateLicenseRequest other = (AssociateLicenseRequest) obj; if (other.getLicenseType() == null ^ this.getLicenseType() == null) return false; if (other.getLicenseType() != null && other.getLicenseType().equals(this.getLicenseType()) == false) return false; if (other.getWorkspaceId() == null ^ this.getWorkspaceId() == null) return false; if (other.getWorkspaceId() != null && other.getWorkspaceId().equals(this.getWorkspaceId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getLicenseType() == null) ? 0 : getLicenseType().hashCode()); hashCode = prime * hashCode + ((getWorkspaceId() == null) ? 0 : getWorkspaceId().hashCode()); return hashCode; } @Override public AssociateLicenseRequest clone() { return (AssociateLicenseRequest) super.clone(); } }
apache-2.0
TomGrill/gdx-firebase
desktop/src/de/tomgrill/gdxfirebase/desktop/database/DesktopDatabaseError.java
1398
package de.tomgrill.gdxfirebase.desktop.database; import de.tomgrill.gdxfirebase.core.database.DatabaseError; public class DesktopDatabaseError implements DatabaseError { public static final int DATA_STALE = -1; public static final int OPERATION_FAILED = -2; public static final int PERMISSION_DENIED = -3; public static final int DISCONNECTED = -4; public static final int EXPIRED_TOKEN = -6; public static final int INVALID_TOKEN = -7; public static final int MAX_RETRIES = -8; public static final int OVERRIDDEN_BY_SET = -9; public static final int UNAVAILABLE = -10; public static final int USER_CODE_EXCEPTION = -11; public static final int NETWORK_ERROR = -24; public static final int WRITE_CANCELED = -25; public static final int UNKNOWN_ERROR = -999; private com.google.firebase.database.DatabaseError databaseError; DesktopDatabaseError(com.google.firebase.database.DatabaseError databaseError) { this.databaseError = databaseError; } @Override public int getCode() { return databaseError.getCode(); } @Override public String getMessage() { return databaseError.getMessage(); } @Override public String getDetails() { return databaseError.getDetails(); } @Override public String toString() { return databaseError.toString(); } }
apache-2.0
datalorax/datagrids
coherence-util/src/test/java/org/acc/coherence/test/CountdownMapListener.java
765
package org.acc.coherence.test; import com.tangosol.util.MapEvent; import com.tangosol.util.MultiplexingMapListener; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * @author datalorax - 14/11/2014. */ public class CountdownMapListener extends MultiplexingMapListener { private final CountDownLatch latch; public CountdownMapListener(int count) { this.latch = new CountDownLatch(count); } public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return latch.await(timeout, unit); } @Override protected void onMapEvent(MapEvent mapEvent) { latch.countDown(); } public int getRemaining() { return (int)latch.getCount(); } }
apache-2.0
android-art-intel/Nougat
art-extension/opttests/src/OptimizationTests/ShortMethodsInliningNonVirtualInvokes/InvokeDirectABooleanThrowNullGet_001/Main.java
1577
/* * Copyright (C) 2016 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package OptimizationTests.ShortMethodsInliningNonVirtualInvokes.InvokeDirectABooleanThrowNullGet_001; // The test checks that stack after NullPointerException occurs is correct despite inlining class Main { final static int iterations = 10; // public static int getThingies(int i) { // return thingiesArray[i]; // } // |[000194] Main.getThingies:(I)I // |0000: sget-object v0, LMain;.thingiesArray:[I // field@0001 // |0002: aget v0, v0, v1 // |0004: return v0 public static void main(String[] args) { Test test = new Test(iterations); boolean nextThingy = false; boolean sumArrElements = false; for(int i = 0; i < iterations; i++) { sumArrElements = sumArrElements & test.thingiesArray[i]; } for(int i = 0; i < iterations; i++) { nextThingy = test.gimme(test.thingiesArray, i) || true; test.hereyouare(test.thingiesArray, nextThingy, i); } } }
apache-2.0
emre-aydin/hazelcast
hazelcast/src/test/java/com/hazelcast/client/map/impl/nearcache/ClientMapNearCacheSerializationCountTest.java
11508
/* * Copyright (c) 2008-2021, 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.client.map.impl.nearcache; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.client.impl.clientside.HazelcastClientProxy; import com.hazelcast.client.impl.proxy.ClientMapProxy; import com.hazelcast.client.test.TestHazelcastFactory; import com.hazelcast.config.Config; import com.hazelcast.config.InMemoryFormat; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.internal.adapter.DataStructureAdapter.DataStructureMethods; import com.hazelcast.internal.adapter.DataStructureAdapterMethod; import com.hazelcast.internal.adapter.IMapDataStructureAdapter; import com.hazelcast.internal.nearcache.NearCache; import com.hazelcast.internal.nearcache.NearCacheManager; import com.hazelcast.internal.nearcache.impl.AbstractNearCacheSerializationCountTest; import com.hazelcast.internal.nearcache.impl.NearCacheSerializationCountConfigBuilder; import com.hazelcast.internal.nearcache.impl.NearCacheTestContext; import com.hazelcast.internal.nearcache.impl.NearCacheTestContextBuilder; import com.hazelcast.internal.nearcache.impl.NearCacheTestUtils; import com.hazelcast.internal.serialization.Data; import com.hazelcast.map.IMap; import com.hazelcast.test.HazelcastParallelParametersRunnerFactory; import com.hazelcast.test.annotation.ParallelJVMTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.After; import org.junit.Before; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import org.junit.runners.Parameterized.UseParametersRunnerFactory; import java.util.Collection; import static com.hazelcast.config.InMemoryFormat.BINARY; import static com.hazelcast.config.InMemoryFormat.OBJECT; import static com.hazelcast.internal.adapter.DataStructureAdapter.DataStructureMethods.GET; import static com.hazelcast.internal.adapter.DataStructureAdapter.DataStructureMethods.GET_ALL; import static com.hazelcast.internal.nearcache.impl.NearCacheTestUtils.createNearCacheConfig; import static com.hazelcast.internal.nearcache.impl.NearCacheTestUtils.getBaseConfig; import static com.hazelcast.spi.properties.ClusterProperty.MAP_INVALIDATION_MESSAGE_BATCH_FREQUENCY_SECONDS; import static com.hazelcast.spi.properties.ClusterProperty.MAP_INVALIDATION_MESSAGE_BATCH_SIZE; import static com.hazelcast.spi.properties.ClusterProperty.PARTITION_COUNT; import static com.hazelcast.spi.properties.ClusterProperty.PARTITION_OPERATION_THREAD_COUNT; import static java.util.Arrays.asList; /** * Near Cache serialization count tests for {@link IMap} on Hazelcast clients. */ @RunWith(Parameterized.class) @UseParametersRunnerFactory(HazelcastParallelParametersRunnerFactory.class) @Category({QuickTest.class, ParallelJVMTest.class}) public class ClientMapNearCacheSerializationCountTest extends AbstractNearCacheSerializationCountTest<Data, String> { @Parameter public DataStructureMethods method; @Parameter(value = 1) public int[] keySerializationCounts; @Parameter(value = 2) public int[] keyDeserializationCounts; @Parameter(value = 3) public int[] valueSerializationCounts; @Parameter(value = 4) public int[] valueDeserializationCounts; @Parameter(value = 5) public InMemoryFormat mapInMemoryFormat; @Parameter(value = 6) public InMemoryFormat nearCacheInMemoryFormat; @Parameter(value = 7) public Boolean invalidateOnChange; @Parameter(value = 8) public Boolean serializeKeys; private final TestHazelcastFactory hazelcastFactory = new TestHazelcastFactory(); @Parameters(name = "method:{0} mapFormat:{5} nearCacheFormat:{6} invalidateOnChange:{7} serializeKeys:{8}") public static Collection<Object[]> parameters() { return asList(new Object[][]{ {GET, newInt(1, 1, 1), newInt(0, 0, 0), newInt(1, 0, 0), newInt(0, 1, 1), BINARY, null, null, null}, {GET, newInt(1, 1, 1), newInt(0, 0, 0), newInt(1, 0, 0), newInt(0, 1, 1), BINARY, BINARY, true, true}, {GET, newInt(1, 1, 0), newInt(0, 0, 0), newInt(1, 0, 0), newInt(0, 1, 1), BINARY, BINARY, true, false}, {GET, newInt(1, 1, 1), newInt(0, 0, 0), newInt(1, 0, 0), newInt(0, 1, 1), BINARY, BINARY, false, true}, {GET, newInt(1, 1, 0), newInt(0, 0, 0), newInt(1, 0, 0), newInt(0, 1, 1), BINARY, BINARY, false, false}, {GET, newInt(1, 1, 1), newInt(0, 0, 0), newInt(1, 0, 0), newInt(0, 1, 0), BINARY, OBJECT, true, true}, {GET, newInt(1, 1, 0), newInt(0, 0, 0), newInt(1, 0, 0), newInt(0, 1, 0), BINARY, OBJECT, true, false}, {GET, newInt(1, 1, 1), newInt(0, 0, 0), newInt(1, 0, 0), newInt(0, 1, 0), BINARY, OBJECT, false, true}, {GET, newInt(1, 1, 0), newInt(0, 0, 0), newInt(1, 0, 0), newInt(0, 1, 0), BINARY, OBJECT, false, false}, {GET, newInt(1, 1, 1), newInt(0, 0, 0), newInt(1, 1, 1), newInt(1, 1, 1), OBJECT, null, null, null}, {GET, newInt(1, 1, 1), newInt(0, 0, 0), newInt(1, 1, 0), newInt(1, 1, 1), OBJECT, BINARY, true, true}, {GET, newInt(1, 1, 1), newInt(0, 0, 0), newInt(1, 1, 0), newInt(1, 1, 1), OBJECT, BINARY, true, true}, {GET, newInt(1, 1, 1), newInt(0, 0, 0), newInt(1, 1, 0), newInt(1, 1, 1), OBJECT, BINARY, false, true}, {GET, newInt(1, 1, 1), newInt(0, 0, 0), newInt(1, 1, 0), newInt(1, 1, 1), OBJECT, BINARY, false, true}, {GET, newInt(1, 1, 1), newInt(0, 0, 0), newInt(1, 1, 0), newInt(1, 1, 0), OBJECT, OBJECT, true, true}, {GET, newInt(1, 1, 1), newInt(0, 0, 0), newInt(1, 1, 0), newInt(1, 1, 0), OBJECT, OBJECT, true, true}, {GET, newInt(1, 1, 1), newInt(0, 0, 0), newInt(1, 1, 0), newInt(1, 1, 0), OBJECT, OBJECT, false, true}, {GET, newInt(1, 1, 1), newInt(0, 0, 0), newInt(1, 1, 0), newInt(1, 1, 0), OBJECT, OBJECT, false, true}, {GET_ALL, newInt(1, 1, 1), newInt(0, 1, 1), newInt(1, 0, 0), newInt(0, 1, 1), BINARY, null, null, null}, {GET_ALL, newInt(1, 1, 1), newInt(0, 1, 1), newInt(1, 0, 0), newInt(0, 1, 1), BINARY, BINARY, true, true}, {GET_ALL, newInt(1, 1, 0), newInt(0, 0, 0), newInt(1, 0, 0), newInt(0, 1, 1), BINARY, BINARY, true, false}, {GET_ALL, newInt(1, 1, 1), newInt(0, 1, 1), newInt(1, 1, 1), newInt(1, 1, 1), OBJECT, null, null, null}, {GET_ALL, newInt(1, 1, 1), newInt(0, 1, 1), newInt(1, 1, 0), newInt(1, 1, 0), OBJECT, OBJECT, false, true}, {GET_ALL, newInt(1, 1, 1), newInt(0, 1, 1), newInt(1, 1, 0), newInt(1, 1, 0), OBJECT, OBJECT, false, true}, }); } @Before public void setUp() { testMethod = method; expectedKeySerializationCounts = keySerializationCounts; expectedKeyDeserializationCounts = keyDeserializationCounts; expectedValueSerializationCounts = valueSerializationCounts; expectedValueDeserializationCounts = valueDeserializationCounts; if (nearCacheInMemoryFormat != null) { nearCacheConfig = createNearCacheConfig(nearCacheInMemoryFormat, serializeKeys) .setInvalidateOnChange(invalidateOnChange); } } @After public void tearDown() { hazelcastFactory.shutdownAll(); } @Override protected void addConfiguration(NearCacheSerializationCountConfigBuilder configBuilder) { configBuilder.append(method); configBuilder.append(mapInMemoryFormat); configBuilder.append(nearCacheInMemoryFormat); configBuilder.append(invalidateOnChange); configBuilder.append(serializeKeys); } @Override protected void assumeThatMethodIsAvailable(DataStructureAdapterMethod method) { NearCacheTestUtils.assumeThatMethodIsAvailable(IMapDataStructureAdapter.class, method); } @Override protected <K, V> NearCacheTestContext<K, V, Data, String> createContext() { Config config = getConfig() // we don't want to have the invalidations from the initial population being sent during this test .setProperty(MAP_INVALIDATION_MESSAGE_BATCH_SIZE.getName(), String.valueOf(Integer.MAX_VALUE)) .setProperty(MAP_INVALIDATION_MESSAGE_BATCH_FREQUENCY_SECONDS.getName(), String.valueOf(Integer.MAX_VALUE)) .setProperty(PARTITION_COUNT.getName(), "1") .setProperty(PARTITION_OPERATION_THREAD_COUNT.getName(), "1"); config.getMapConfig(DEFAULT_NEAR_CACHE_NAME) .setInMemoryFormat(mapInMemoryFormat) .setBackupCount(0) .setAsyncBackupCount(0); prepareSerializationConfig(config.getSerializationConfig()); HazelcastInstance member = hazelcastFactory.newHazelcastInstance(config); IMap<K, V> memberMap = member.getMap(DEFAULT_NEAR_CACHE_NAME); NearCacheTestContextBuilder<K, V, Data, String> contextBuilder = createNearCacheContextBuilder(); return contextBuilder .setDataInstance(member) .setDataAdapter(new IMapDataStructureAdapter<K, V>(memberMap)) .build(); } @Override protected <K, V> NearCacheTestContext<K, V, Data, String> createNearCacheContext() { NearCacheTestContextBuilder<K, V, Data, String> contextBuilder = createNearCacheContextBuilder(); return contextBuilder.build(); } @Override protected Config getConfig() { return getBaseConfig(); } protected ClientConfig getClientConfig() { return new ClientConfig(); } private <K, V> NearCacheTestContextBuilder<K, V, Data, String> createNearCacheContextBuilder() { ClientConfig clientConfig = getClientConfig(); if (nearCacheConfig != null) { clientConfig.addNearCacheConfig(nearCacheConfig); } prepareSerializationConfig(clientConfig.getSerializationConfig()); HazelcastClientProxy client = (HazelcastClientProxy) hazelcastFactory.newHazelcastClient(clientConfig); IMap<K, V> clientMap = client.getMap(DEFAULT_NEAR_CACHE_NAME); NearCacheManager nearCacheManager = ((ClientMapProxy) clientMap).getContext() .getNearCacheManager(clientMap.getServiceName()); NearCache<Data, String> nearCache = nearCacheManager.getNearCache(DEFAULT_NEAR_CACHE_NAME); return new NearCacheTestContextBuilder<K, V, Data, String>(nearCacheConfig, client.getSerializationService()) .setNearCacheInstance(client) .setNearCacheAdapter(new IMapDataStructureAdapter<K, V>(clientMap)) .setNearCache(nearCache) .setNearCacheManager(nearCacheManager); } }
apache-2.0
SpannaProject/SpannaAPI
src/main/java/org/spanna/event/Listener.java
115
package org.spanna.event; /** * Simple interface for tagging all EventListeners */ public interface Listener {}
apache-2.0
freeVM/freeVM
enhanced/buildtest/tests/functional/src/test/functional/org/apache/harmony/test/func/api/java/util/jar/share/MultiThreadRunner.java
5064
/* * 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. */ /** */ /* * Created on 01.12.2004 * */ package org.apache.harmony.test.func.api.java.util.jar.share; import org.apache.harmony.share.Result; import org.apache.harmony.share.Test; /** * */ public class MultiThreadRunner { public static int run(IOMultiCase runned, String[] args) { runned.parseArgs(args); // if(!(runned instanceof BufferedInputStreamTest)) { // return Result.PASS; // } if (Utils.THREADS <= 1) { return runned.test(args); } Thread[] children = new Thread[Utils.THREADS]; int results[] = new int[Utils.THREADS]; for (int i = 0; i < Utils.THREADS; ++i) { children[i] = new ThreadTest(runned, args, results, i); children[i].start(); } String failmsg = null; for (int i = 0; i < Utils.THREADS; ++i) { try { children[i].join(); } catch (InterruptedException e) { failmsg = e.getMessage(); } } if (failmsg != null) { return runned.fail(failmsg); } for (int i = 0; i < Utils.THREADS; i++) { if (results[i] != Result.PASS) { return runned.fail("something is wrong"); } } return runned.pass(); } //multi-threaded tests' threads should try to enter (de)serialization // section simultaneously //put a call of this method just before readObject() or writeObject() call. static Object barrier = new Object(); static int threadsAtBarrier = 0; static int threadsLeftBarrier = 0; public static void waitAtBarrier() { waitAtBarrier(Utils.THREADS); } public static void waitAtBarrier(int threads) { if (threads <= 1) return; // System.err.println(Thread.currentThread().getName() // + " waiting at the barrier, total threads to meet : " // + THREADS); synchronized (barrier) { while (threadsLeftBarrier > 0) { // System.err.println(Thread.currentThread().getName() // + " waiting leaving threads"); try { barrier.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } threadsAtBarrier++; if (threadsAtBarrier == threads) { barrier.notifyAll(); } else while (threadsAtBarrier < threads) { // System.err.println(Thread.currentThread().getName() // + " here 1"); try { // System.err.println(Thread.currentThread().getName() // + " here 2"); barrier.wait(); // System.err.println(Thread.currentThread().getName() // + " here 3"); } catch (InterruptedException e) { System.err.println("thread interrupted" + e.getMessage()); } // System.err.println(Thread.currentThread().getName() // + " here 4"); } threadsLeftBarrier++; // System.err.println(Thread.currentThread().getName() // + " here 5"); if (threadsLeftBarrier == threads) { //cleanup for the next barrier // System.err.println(Thread.currentThread().getName() // + " here 6"); threadsLeftBarrier = 0; threadsAtBarrier = 0; barrier.notifyAll(); } } } } class ThreadTest extends Thread { int threadNo; int[] results; Test runned; String[] args; public ThreadTest(Test runned, String[] args, int[] results, int threadNo) { super(); this.runned = runned; this.args = args; this.results = results; this.threadNo = threadNo; } public void run() { results[threadNo] = runned.test(args); } }
apache-2.0
Jukape/NotificationManager
src/net/sepiroth887/brokeit/notificationmanager/NotificationManagerActivity.java
294
package net.sepiroth887.brokeit.notificationmanager; import android.app.Activity; import android.os.Bundle; public class NotificationManagerActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
apache-2.0
javagossip/opendsp
opendsp-engine/src/main/java/mobi/opendsp/engine/service/package-info.java
138
/* * Copyright 2014-2017 f2time.com All right reserved. */ /** * @author wangweiping * */ package mobi.opendsp.engine.service;
apache-2.0
hmlnarik/keycloak
services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientRolesCondition.java
3953
/* * Copyright 2021 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.services.clientpolicy.condition; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.jboss.logging.Logger; import org.keycloak.models.ClientModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RoleModel; import org.keycloak.representations.idm.ClientPolicyConditionConfigurationRepresentation; import org.keycloak.services.clientpolicy.ClientPolicyContext; import org.keycloak.services.clientpolicy.ClientPolicyException; import org.keycloak.services.clientpolicy.ClientPolicyVote; /** * @author <a href="mailto:takashi.norimatsu.ws@hitachi.com">Takashi Norimatsu</a> */ public class ClientRolesCondition extends AbstractClientPolicyConditionProvider<ClientRolesCondition.Configuration> { private static final Logger logger = Logger.getLogger(ClientRolesCondition.class); public ClientRolesCondition(KeycloakSession session) { super(session); } @Override public Class<Configuration> getConditionConfigurationClass() { return Configuration.class; } public static class Configuration extends ClientPolicyConditionConfigurationRepresentation { protected List<String> roles; public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } } @Override public String getProviderId() { return ClientRolesConditionFactory.PROVIDER_ID; } @Override public ClientPolicyVote applyPolicy(ClientPolicyContext context) throws ClientPolicyException { switch (context.getEvent()) { case AUTHORIZATION_REQUEST: case TOKEN_REQUEST: case TOKEN_REFRESH: case TOKEN_REVOKE: case TOKEN_INTROSPECT: case USERINFO_REQUEST: case LOGOUT_REQUEST: case BACKCHANNEL_AUTHENTICATION_REQUEST: case BACKCHANNEL_TOKEN_REQUEST: case PUSHED_AUTHORIZATION_REQUEST: if (isRolesMatched(session.getContext().getClient())) return ClientPolicyVote.YES; return ClientPolicyVote.NO; default: return ClientPolicyVote.ABSTAIN; } } private boolean isRolesMatched(ClientModel client) { if (client == null) return false; Set<String> rolesForMatching = getRolesForMatching(); if (rolesForMatching == null) return false; // client.getRolesStream() never returns null according to {@link RoleProvider.getClientRolesStream} Set<String> clientRoles = client.getRolesStream().map(RoleModel::getName).collect(Collectors.toSet()); if (logger.isTraceEnabled()) { clientRoles.forEach(i -> logger.tracev("client role assigned = {0}", i)); rolesForMatching.forEach(i -> logger.tracev("client role for matching = {0}", i)); } return rolesForMatching.removeAll(clientRoles); // may change rolesForMatching so that it has needed to be instantiated. } private Set<String> getRolesForMatching() { if (configuration.getRoles() == null) return null; return new HashSet<>(configuration.getRoles()); } }
apache-2.0
rapidoid/rapidoid
rapidoid-commons/src/main/java/org/rapidoid/beany/Metadata.java
4931
/*- * #%L * rapidoid-commons * %% * Copyright (C) 2014 - 2020 Nikolche Mihajlovski and contributors * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.rapidoid.beany; import org.rapidoid.RapidoidThing; import org.rapidoid.annotation.Authors; import org.rapidoid.annotation.Since; import org.rapidoid.cls.Cls; import org.rapidoid.u.U; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Collection; import java.util.Map; @Authors("Nikolche Mihajlovski") @Since("2.0.0") public class Metadata extends RapidoidThing { public static Map<Class<?>, Annotation> classAnnotations(Class<?> clazz) { clazz = Cls.unproxy(clazz); Map<Class<?>, Annotation> annotations = U.map(); for (Annotation ann : clazz.getAnnotations()) { annotations.put(ann.annotationType(), ann); } return annotations; } @SuppressWarnings("unchecked") public static <T extends Annotation> T classAnnotation(Class<?> clazz, Class<T> annotationClass) { clazz = Cls.unproxy(clazz); return (T) classAnnotations(clazz).get(annotationClass); } public static Map<Class<?>, Annotation> methodAnnotations(Method method) { Map<Class<?>, Annotation> annotations = U.map(); for (Annotation ann : method.getAnnotations()) { annotations.put(ann.annotationType(), ann); } return annotations; } @SuppressWarnings("unchecked") public static <T extends Annotation> T methodAnnotation(Method method, Class<T> annotationClass) { return (T) methodAnnotations(method).get(annotationClass); } public static Map<Class<?>, Annotation> propAnnotations(Class<?> clazz, String property) { clazz = Cls.unproxy(clazz); Map<Class<?>, Annotation> annotations = U.map(); Prop prop = Beany.property(clazz, property, false); if (prop != null) { for (Annotation ann : prop.getDeclaringType().getAnnotations()) { annotations.put(ann.annotationType(), ann); } for (Annotation ann : prop.getAnnotations()) { annotations.put(ann.annotationType(), ann); } } return annotations; } @SuppressWarnings("unchecked") public static <T extends Annotation> T propAnnotation(Class<?> clazz, String property, Class<T> annotationClass) { clazz = Cls.unproxy(clazz); return (T) propAnnotations(clazz, property).get(annotationClass); } public static boolean isAnnotated(Class<?> clazz, Class<? extends Annotation> annotation) { clazz = Cls.unproxy(clazz); return classAnnotations(clazz).containsKey(annotation); } public static boolean isAnnotatedAny(Class<?> clazz, Collection<Class<? extends Annotation>> annotations) { clazz = Cls.unproxy(clazz); for (Class<? extends Annotation> ann : annotations) { if (clazz.isAnnotationPresent(ann)) { return true; } } return false; } @SuppressWarnings("unchecked") public static <T extends Annotation> T get(Annotation[] annotations, Class<T> annotationClass) { if (annotations != null) { for (Annotation ann : annotations) { if (annotationClass.isAssignableFrom(ann.annotationType())) { return (T) ann; } } } return null; } @SuppressWarnings("unchecked") public static boolean has(Annotation[] annotations, Class<? extends Annotation> annotationClass) { return get(annotations, annotationClass) != null; } @SuppressWarnings("unchecked") public static boolean hasAny(Annotation[] annotations, Iterable<Class<? extends Annotation>> annotationType) { for (Class<? extends Annotation> annType : annotationType) { if (has(annotations, annType)) return true; } return false; } public static <T extends Annotation> T getAnnotationRecursive(Class<?> clazz, Class<T> annotationClass) { clazz = Cls.unproxy(clazz); for (Class<?> c = clazz; c.getSuperclass() != null; c = c.getSuperclass()) { T ann = c.getAnnotation(annotationClass); if (ann != null) { return ann; } } return null; } }
apache-2.0
trasa/aws-sdk-java
aws-java-sdk-waf/src/main/java/com/amazonaws/services/waf/model/Predicate.java
17482
/* * Copyright 2010-2016 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.waf.model; import java.io.Serializable; /** * <p> * Specifies the <a>ByteMatchSet</a>, <a>IPSet</a>, and * <a>SqlInjectionMatchSet</a> objects that you want to add to a * <code>Rule</code> and, for each object, indicates whether you want to negate * the settings, for example, requests that do NOT originate from the IP address * 192.0.2.44. * </p> */ public class Predicate implements Serializable, Cloneable { /** * <p> * Set <code>Negated</code> to <code>False</code> if you want AWS WAF to * allow, block, or count requests based on the settings in the specified * <a>ByteMatchSet</a>, <a>IPSet</a>, or <a>SqlInjectionMatchSet</a>. For * example, if an <code>IPSet</code> includes the IP address * <code>192.0.2.44</code>, AWS WAF will allow or block requests based on * that IP address. * </p> * <p> * Set <code>Negated</code> to <code>True</code> if you want AWS WAF to * allow or block a request based on the negation of the settings in the * <a>ByteMatchSet</a>, <a>IPSet</a>, or <a>SqlInjectionMatchSet</a>. For * example, if an <code>IPSet</code> includes the IP address * <code>192.0.2.44</code>, AWS WAF will allow, block, or count requests * based on all IP addresses <i>except</i> <code>192.0.2.44</code>. * </p> */ private Boolean negated; /** * <p> * The type of predicate in a <code>Rule</code>, such as * <code>ByteMatchSet</code> or <code>IPSet</code>. * </p> */ private String type; /** * <p> * A unique identifier for a predicate in a <code>Rule</code>, such as * <code>ByteMatchSetId</code> or <code>IPSetId</code>. The ID is returned * by the corresponding <code>Create</code> or <code>List</code> command. * </p> */ private String dataId; /** * <p> * Set <code>Negated</code> to <code>False</code> if you want AWS WAF to * allow, block, or count requests based on the settings in the specified * <a>ByteMatchSet</a>, <a>IPSet</a>, or <a>SqlInjectionMatchSet</a>. For * example, if an <code>IPSet</code> includes the IP address * <code>192.0.2.44</code>, AWS WAF will allow or block requests based on * that IP address. * </p> * <p> * Set <code>Negated</code> to <code>True</code> if you want AWS WAF to * allow or block a request based on the negation of the settings in the * <a>ByteMatchSet</a>, <a>IPSet</a>, or <a>SqlInjectionMatchSet</a>. For * example, if an <code>IPSet</code> includes the IP address * <code>192.0.2.44</code>, AWS WAF will allow, block, or count requests * based on all IP addresses <i>except</i> <code>192.0.2.44</code>. * </p> * * @param negated * Set <code>Negated</code> to <code>False</code> if you want AWS WAF * to allow, block, or count requests based on the settings in the * specified <a>ByteMatchSet</a>, <a>IPSet</a>, or * <a>SqlInjectionMatchSet</a>. For example, if an <code>IPSet</code> * includes the IP address <code>192.0.2.44</code>, AWS WAF will * allow or block requests based on that IP address.</p> * <p> * Set <code>Negated</code> to <code>True</code> if you want AWS WAF * to allow or block a request based on the negation of the settings * in the <a>ByteMatchSet</a>, <a>IPSet</a>, or * <a>SqlInjectionMatchSet</a>. For example, if an <code>IPSet</code> * includes the IP address <code>192.0.2.44</code>, AWS WAF will * allow, block, or count requests based on all IP addresses * <i>except</i> <code>192.0.2.44</code>. */ public void setNegated(Boolean negated) { this.negated = negated; } /** * <p> * Set <code>Negated</code> to <code>False</code> if you want AWS WAF to * allow, block, or count requests based on the settings in the specified * <a>ByteMatchSet</a>, <a>IPSet</a>, or <a>SqlInjectionMatchSet</a>. For * example, if an <code>IPSet</code> includes the IP address * <code>192.0.2.44</code>, AWS WAF will allow or block requests based on * that IP address. * </p> * <p> * Set <code>Negated</code> to <code>True</code> if you want AWS WAF to * allow or block a request based on the negation of the settings in the * <a>ByteMatchSet</a>, <a>IPSet</a>, or <a>SqlInjectionMatchSet</a>. For * example, if an <code>IPSet</code> includes the IP address * <code>192.0.2.44</code>, AWS WAF will allow, block, or count requests * based on all IP addresses <i>except</i> <code>192.0.2.44</code>. * </p> * * @return Set <code>Negated</code> to <code>False</code> if you want AWS * WAF to allow, block, or count requests based on the settings in * the specified <a>ByteMatchSet</a>, <a>IPSet</a>, or * <a>SqlInjectionMatchSet</a>. For example, if an * <code>IPSet</code> includes the IP address * <code>192.0.2.44</code>, AWS WAF will allow or block requests * based on that IP address.</p> * <p> * Set <code>Negated</code> to <code>True</code> if you want AWS WAF * to allow or block a request based on the negation of the settings * in the <a>ByteMatchSet</a>, <a>IPSet</a>, or * <a>SqlInjectionMatchSet</a>. For example, if an * <code>IPSet</code> includes the IP address * <code>192.0.2.44</code>, AWS WAF will allow, block, or count * requests based on all IP addresses <i>except</i> * <code>192.0.2.44</code>. */ public Boolean getNegated() { return this.negated; } /** * <p> * Set <code>Negated</code> to <code>False</code> if you want AWS WAF to * allow, block, or count requests based on the settings in the specified * <a>ByteMatchSet</a>, <a>IPSet</a>, or <a>SqlInjectionMatchSet</a>. For * example, if an <code>IPSet</code> includes the IP address * <code>192.0.2.44</code>, AWS WAF will allow or block requests based on * that IP address. * </p> * <p> * Set <code>Negated</code> to <code>True</code> if you want AWS WAF to * allow or block a request based on the negation of the settings in the * <a>ByteMatchSet</a>, <a>IPSet</a>, or <a>SqlInjectionMatchSet</a>. For * example, if an <code>IPSet</code> includes the IP address * <code>192.0.2.44</code>, AWS WAF will allow, block, or count requests * based on all IP addresses <i>except</i> <code>192.0.2.44</code>. * </p> * * @param negated * Set <code>Negated</code> to <code>False</code> if you want AWS WAF * to allow, block, or count requests based on the settings in the * specified <a>ByteMatchSet</a>, <a>IPSet</a>, or * <a>SqlInjectionMatchSet</a>. For example, if an <code>IPSet</code> * includes the IP address <code>192.0.2.44</code>, AWS WAF will * allow or block requests based on that IP address.</p> * <p> * Set <code>Negated</code> to <code>True</code> if you want AWS WAF * to allow or block a request based on the negation of the settings * in the <a>ByteMatchSet</a>, <a>IPSet</a>, or * <a>SqlInjectionMatchSet</a>. For example, if an <code>IPSet</code> * includes the IP address <code>192.0.2.44</code>, AWS WAF will * allow, block, or count requests based on all IP addresses * <i>except</i> <code>192.0.2.44</code>. * @return Returns a reference to this object so that method calls can be * chained together. */ public Predicate withNegated(Boolean negated) { setNegated(negated); return this; } /** * <p> * Set <code>Negated</code> to <code>False</code> if you want AWS WAF to * allow, block, or count requests based on the settings in the specified * <a>ByteMatchSet</a>, <a>IPSet</a>, or <a>SqlInjectionMatchSet</a>. For * example, if an <code>IPSet</code> includes the IP address * <code>192.0.2.44</code>, AWS WAF will allow or block requests based on * that IP address. * </p> * <p> * Set <code>Negated</code> to <code>True</code> if you want AWS WAF to * allow or block a request based on the negation of the settings in the * <a>ByteMatchSet</a>, <a>IPSet</a>, or <a>SqlInjectionMatchSet</a>. For * example, if an <code>IPSet</code> includes the IP address * <code>192.0.2.44</code>, AWS WAF will allow, block, or count requests * based on all IP addresses <i>except</i> <code>192.0.2.44</code>. * </p> * * @return Set <code>Negated</code> to <code>False</code> if you want AWS * WAF to allow, block, or count requests based on the settings in * the specified <a>ByteMatchSet</a>, <a>IPSet</a>, or * <a>SqlInjectionMatchSet</a>. For example, if an * <code>IPSet</code> includes the IP address * <code>192.0.2.44</code>, AWS WAF will allow or block requests * based on that IP address.</p> * <p> * Set <code>Negated</code> to <code>True</code> if you want AWS WAF * to allow or block a request based on the negation of the settings * in the <a>ByteMatchSet</a>, <a>IPSet</a>, or * <a>SqlInjectionMatchSet</a>. For example, if an * <code>IPSet</code> includes the IP address * <code>192.0.2.44</code>, AWS WAF will allow, block, or count * requests based on all IP addresses <i>except</i> * <code>192.0.2.44</code>. */ public Boolean isNegated() { return this.negated; } /** * <p> * The type of predicate in a <code>Rule</code>, such as * <code>ByteMatchSet</code> or <code>IPSet</code>. * </p> * * @param type * The type of predicate in a <code>Rule</code>, such as * <code>ByteMatchSet</code> or <code>IPSet</code>. * @see PredicateType */ public void setType(String type) { this.type = type; } /** * <p> * The type of predicate in a <code>Rule</code>, such as * <code>ByteMatchSet</code> or <code>IPSet</code>. * </p> * * @return The type of predicate in a <code>Rule</code>, such as * <code>ByteMatchSet</code> or <code>IPSet</code>. * @see PredicateType */ public String getType() { return this.type; } /** * <p> * The type of predicate in a <code>Rule</code>, such as * <code>ByteMatchSet</code> or <code>IPSet</code>. * </p> * * @param type * The type of predicate in a <code>Rule</code>, such as * <code>ByteMatchSet</code> or <code>IPSet</code>. * @return Returns a reference to this object so that method calls can be * chained together. * @see PredicateType */ public Predicate withType(String type) { setType(type); return this; } /** * <p> * The type of predicate in a <code>Rule</code>, such as * <code>ByteMatchSet</code> or <code>IPSet</code>. * </p> * * @param type * The type of predicate in a <code>Rule</code>, such as * <code>ByteMatchSet</code> or <code>IPSet</code>. * @return Returns a reference to this object so that method calls can be * chained together. * @see PredicateType */ public void setType(PredicateType type) { this.type = type.toString(); } /** * <p> * The type of predicate in a <code>Rule</code>, such as * <code>ByteMatchSet</code> or <code>IPSet</code>. * </p> * * @param type * The type of predicate in a <code>Rule</code>, such as * <code>ByteMatchSet</code> or <code>IPSet</code>. * @return Returns a reference to this object so that method calls can be * chained together. * @see PredicateType */ public Predicate withType(PredicateType type) { setType(type); return this; } /** * <p> * A unique identifier for a predicate in a <code>Rule</code>, such as * <code>ByteMatchSetId</code> or <code>IPSetId</code>. The ID is returned * by the corresponding <code>Create</code> or <code>List</code> command. * </p> * * @param dataId * A unique identifier for a predicate in a <code>Rule</code>, such * as <code>ByteMatchSetId</code> or <code>IPSetId</code>. The ID is * returned by the corresponding <code>Create</code> or * <code>List</code> command. */ public void setDataId(String dataId) { this.dataId = dataId; } /** * <p> * A unique identifier for a predicate in a <code>Rule</code>, such as * <code>ByteMatchSetId</code> or <code>IPSetId</code>. The ID is returned * by the corresponding <code>Create</code> or <code>List</code> command. * </p> * * @return A unique identifier for a predicate in a <code>Rule</code>, such * as <code>ByteMatchSetId</code> or <code>IPSetId</code>. The ID is * returned by the corresponding <code>Create</code> or * <code>List</code> command. */ public String getDataId() { return this.dataId; } /** * <p> * A unique identifier for a predicate in a <code>Rule</code>, such as * <code>ByteMatchSetId</code> or <code>IPSetId</code>. The ID is returned * by the corresponding <code>Create</code> or <code>List</code> command. * </p> * * @param dataId * A unique identifier for a predicate in a <code>Rule</code>, such * as <code>ByteMatchSetId</code> or <code>IPSetId</code>. The ID is * returned by the corresponding <code>Create</code> or * <code>List</code> command. * @return Returns a reference to this object so that method calls can be * chained together. */ public Predicate withDataId(String dataId) { setDataId(dataId); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getNegated() != null) sb.append("Negated: " + getNegated() + ","); if (getType() != null) sb.append("Type: " + getType() + ","); if (getDataId() != null) sb.append("DataId: " + getDataId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Predicate == false) return false; Predicate other = (Predicate) obj; if (other.getNegated() == null ^ this.getNegated() == null) return false; if (other.getNegated() != null && other.getNegated().equals(this.getNegated()) == false) return false; if (other.getType() == null ^ this.getType() == null) return false; if (other.getType() != null && other.getType().equals(this.getType()) == false) return false; if (other.getDataId() == null ^ this.getDataId() == null) return false; if (other.getDataId() != null && other.getDataId().equals(this.getDataId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getNegated() == null) ? 0 : getNegated().hashCode()); hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode()); hashCode = prime * hashCode + ((getDataId() == null) ? 0 : getDataId().hashCode()); return hashCode; } @Override public Predicate clone() { try { return (Predicate) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
tatemura/congenio
src/main/java/com/nec/congenio/impl/ResourcePointer.java
1088
/******************************************************************************* * Copyright 2015, 2016 Junichi Tatemura * * 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.nec.congenio.impl; public interface ResourcePointer { /** * dereferences the pointer to a config resource. * * @return a config resource identified by this pointer. * @throws ConfigException * when the resource does not exist */ ConfigResource getResource(); }
apache-2.0
Lemon-han/MobilSafe
mobilesafe/src/main/java/com/emma/mobilesafe/acitivity/Setup1Activity.java
722
package com.emma.mobilesafe.acitivity; import android.content.Intent; import android.os.Bundle; import com.emma.mobilesafe.R; public class Setup1Activity extends BaseSetUpAppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setup1); } @Override protected void showPrePage() { } @Override protected void showNextPage() { Intent intent = new Intent(getApplicationContext(), Setup2Activity.class); startActivity(intent); finish(); //开启平移动画 overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim); } }
apache-2.0
bubichain/blockchain
test/testcase/testng/InterfaceTest-1.8/src/cases/SupplyChainTest.java
12046
package cases; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.testng.annotations.Test; import utils.APIUtil; import utils.Result; import utils.SignUtil; import utils.TxUtil; import base.TestBase; import model.Account; import model.Input; import model.InputInfo; import model.Output; @Test public class SupplyChainTest extends TestBase { @SuppressWarnings("rawtypes") Map acc = TxUtil.createAccount(); Object source_address = acc.get("address"); String pri = acc.get("private_key").toString(); Object pub = acc.get("public_key"); String metadata = "1234"; int type = 6; // @Test public void supplyChainCheck(){ //ÑéÖ¤¹©Ó¦Á´´´½¨³É¹¦£¬Ã»ÓÐinput Account srcAcc = TxUtil.createNewAccount(); Account a1 = TxUtil.createNewAccount(); List<Object> inputs = new ArrayList<>(); List<Object> outputs = TxUtil.outputs(a1.getAddress(), metadata); List<Object> opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.tx(opers, srcAcc.getAddress(), fee, metadata, srcAcc.getPri_key(), srcAcc.getPub_key()); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 0, "¹©Ó¦Á´´´½¨Ê§°Ü"); } //¹©Ó¦Á´²Ù×÷typeÀàÐÍУÑé // @Test @SuppressWarnings("rawtypes") public void typeCheck() { Map acc = TxUtil.createAccount(); Object address = acc.get("address"); Object[] types = { 0, 20, -1, "abc", "!@#", "", null }; for (Object type : types) { List inputs = new ArrayList<>(); List outputs = TxUtil.outputs(address, metadata); List opers = TxUtil.operSupplyChain(type, inputs, outputs); String response = SignUtil.unnormal_tx(opers, source_address, fee, metadata, pri, pub); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 2, "¹©Ó¦Á´type[" + type + "]УÑéʧ°Ü"); } } //ÑéÖ¤¶þ¼¶¹©Ó¦Á´´´½¨³É¹¦ // @Test public void inputs_0Check() { InputInfo info = TxUtil.input2(); String response = Result.getTranHisByHash(info.getHash()); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 0, "input²»Îª¿Õ£¬¹©Ó¦Á´´´½¨Ê§°Ü"); } // @Test @SuppressWarnings("rawtypes") public void input_hashCheck(){ Map acc = TxUtil.createAccount(); Object address = acc.get("address"); Object[] hashs = { 0, -1, "abc", "!@#", "", null,"111111111" }; for (Object hash : hashs) { List inputs = TxUtil.inputs(hash, 0); List outputs = TxUtil.outputs(address, metadata); List opers = TxUtil.operSupplyChain(type, inputs, outputs); String response = SignUtil.unnormal_tx(opers, source_address, fee, metadata, pri, pub); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 2, "¹©Ó¦Á´´´½¨hash[" + hash + "]УÑéʧ°Ü"); } } // @Test @SuppressWarnings("rawtypes") public void input_indexCheck(){ Map acc = TxUtil.createAccount(); Object address = acc.get("address"); List inputs = new ArrayList<>(); List outputs = TxUtil.outputs(address, metadata); List opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.tx(opers, source_address, fee, metadata, pri, pub); Object hash = Result.getHash(response); Object[] indexs = {-1,"abc","!@#","",null}; for (Object index : indexs) { List inputs1 = TxUtil.inputs(hash, index); List outputs1 = TxUtil.outputs(address, metadata); List opers1 = TxUtil.operSupplyChain(type,inputs1,outputs1); String response1 = SignUtil.unnormal_tx(opers1, source_address, fee, metadata, pri, pub); int error_code = Result.getErrorCode(response1); check.assertEquals(error_code, 2, "¹©Ó¦Á´´´½¨index[" + index + "]УÑéʧ°Ü"); } } /* * verify metadata in inputs */ // @Test @SuppressWarnings("rawtypes") public void input_metadataCheck(){ String metadata_ = "1234"; Account account = TxUtil.createNewAccount(); List inputs = new ArrayList<>(); List outputs = TxUtil.outputs(account.getAddress(), metadata); List opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.tx(opers, source_address, fee, metadata, pri, pub); Object hash = Result.getHash(response); List outputs1 = TxUtil.outputs(account.getAddress(), metadata); Object[] metadatas = {0,-1,"abc","!@#","pp"}; for (Object metadata : metadatas) { List inputs1 = TxUtil.inputs(hash, 0,metadata); List opers1 = TxUtil.operSupplyChain(type,inputs1,outputs1); String response1 = SignUtil.unnormal_tx(opers1, account.getAddress(), fee, metadata_, account.getPri_key(), account.getPub_key()); int error_code = Result.getErrorCode(response1); check.assertEquals(error_code, 2, "¹©Ó¦Á´´´½¨metadata[" + metadata + "]УÑéʧ°Ü"); } } @SuppressWarnings("rawtypes") // @Test public void outputsCheck(){ Account a1 = TxUtil.createNewAccount(); Account a2 = TxUtil.createNewAccount(); List inputs = new ArrayList<>(); //ÑéÖ¤outputsÁ½¸ö£¬´´½¨³É¹¦ List outputs = TxUtil.outputs(a1.getAddress(), metadata,a2.getAddress(),metadata); List opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.tx(opers, source_address, fee, metadata, pri, pub); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 0, "outputsÁ½¸ö´´½¨Ê§°Ü"); } //ÑéÖ¤Á½¸öoutputÒ»Ñù£¬´´½¨Ê§°Ü // @Test public void outputs_sameCheck(){ Account src = TxUtil.createNewAccount(); Account a1 = TxUtil.createNewAccount(); System.out.println(source_address); System.out.println(pri); System.out.println(pub); List inputs = new ArrayList<>(); //ÑéÖ¤outputsÁ½¸ö£¬´´½¨³É¹¦ List outputs = TxUtil.outputs(a1.getAddress(), metadata,a1.getAddress(),metadata); List opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.tx(opers, src.getAddress(), fee, metadata, src.getPri_key(), src.getPub_key()); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 0, "outputsÁ½¸ö´´½¨Ê§°Ü"); } //¶à¸öoutput // @Test public void few_outputsCheck(){ List<Input> inputs = new ArrayList<>(); List<Output> outputs = TxUtil.createOutput(3); List<Object> opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.tx(opers, source_address, fee, metadata, pri, pub); System.out.println(response); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 0, "outputsÁ½¸ö´´½¨Ê§°Ü"); } /* * verify none outputs */ // @Test @SuppressWarnings("rawtypes") public void outputs_noneCheck(){ List inputs = new ArrayList<>(); List outputs = new ArrayList<>(); List opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.tx(opers, source_address, fee, metadata, pri, pub); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 2, "outputsΪ¿ÕУÑéʧ°Ü"); } // @Test @SuppressWarnings("rawtypes") public void output_addressinvalidCheck(){ List inputs = new ArrayList(); Object[] adds = {0,-1,"",null,"ab","!@"}; for (Object add : adds) { List outputs = TxUtil.outputs(add, metadata); List opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.unnormal_tx(opers, source_address, fee, metadata, pri, pub); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 2, "¹©Ó¦Á´address[" + add + "]УÑéʧ°Ü"); } } // @Test @SuppressWarnings("rawtypes") public void output_addressNotExistCheck(){ List inputs = new ArrayList(); Object addnew = APIUtil.generateAcc().get("address"); List outputs = TxUtil.outputs(addnew, metadata); List opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.unnormal_tx(opers, source_address, fee, metadata, pri, pub); System.out.println(response); int error_code = Result.getErrorCode(response); check.assertEquals(error_code,103, "¹©Ó¦Á´output_address[" + addnew + "]УÑéʧ°Ü"); } // @Test @SuppressWarnings("rawtypes") public void metadataCheck(){ List inputs = new ArrayList(); Object[] metas = {0,-1,"abc","qq"}; for (Object meta : metas) { Map acc = TxUtil.createAccount(); Object address = acc.get("address"); List outputs = TxUtil.outputs(address, meta); List opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.unnormal_tx(opers, source_address, fee, metadata, pri, pub); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 2, "¹©Ó¦Á´metadata[" + meta + "]УÑéʧ°Ü"); } } // @Test @SuppressWarnings("rawtypes") public void feeinvalidCheck(){ Map acc = TxUtil.createAccount(); Object address = acc.get("address"); List inputs = new ArrayList<>(); Object[] fees = {-1,"abc","!@#","",null}; for (Object fee : fees) { List outputs = TxUtil.outputs(address, metadata); List opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.unnormal_tx(opers, source_address, fee, metadata, pri, pub); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 2, "¹©Ó¦Á´fee[" + fee + "]УÑéʧ°Ü"); } } // @Test @SuppressWarnings("rawtypes") public void feeNotEnoughCheck(){ Map acc = TxUtil.createAccount(); Object address = acc.get("address"); List inputs = new ArrayList<>(); Object[] fees = {0,fee-1}; for (Object fee : fees) { List outputs = TxUtil.outputs(address, metadata); List opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.unnormal_tx(opers, source_address, fee, metadata, pri, pub); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 111, "¹©Ó¦Á´fee[" + fee + "]УÑéʧ°Ü"); } } // @Test @SuppressWarnings("rawtypes") public void source_addressinvalidCheck(){ Map acc = TxUtil.createAccount(); Object address = acc.get("address"); List inputs = new ArrayList<>(); Object[] source_adds = {-1,0,"abc","!@#"}; for (Object source_address : source_adds) { List outputs = TxUtil.outputs(address, metadata); List opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.unnormal_tx(opers, source_address, fee, metadata, pri, pub); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 2, "¹©Ó¦Á´source_address[" + source_address + "]УÑéʧ°Ü"); } } // @Test ֮ǰԤÆÚÊÇ103 @SuppressWarnings("rawtypes") public void source_addressCheck(){ Map acc = TxUtil.createAccount(); Object address = acc.get("address"); List inputs = new ArrayList<>(); String addnew = APIUtil.generateAcc().get("address"); List outputs = TxUtil.outputs(address, metadata); List opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.unnormal_tx(opers, addnew, fee, metadata, pri, pub); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 4, "¹©Ó¦Á´source_address[" + source_address + "]УÑéʧ°Ü"); } // @Test //֮ǰԤÆÚÊÇ93£¬Êµ¼ÊÊÇ4 @SuppressWarnings("rawtypes") public void private_keyCheck(){ Map acc = TxUtil.createAccount(); Object address = acc.get("address"); Object pri1 = TxUtil.createAccount().get("private_key"); Object pri2 = APIUtil.generateAcc().get("private_key"); Object[] pri_keys = { pri1, pri2 }; List inputs = new ArrayList(); for (Object pri_key : pri_keys) { String pri = pri_key.toString(); List outputs = TxUtil.outputs(address, metadata); List opers = TxUtil.operSupplyChain(type,inputs,outputs); String response = SignUtil.unnormal_tx(opers, source_address, fee, metadata, pri, pub); int error_code = Result.getErrorCode(response); check.assertEquals(error_code, 4, "¹©Ó¦Á´private_key[" + pri_key + "]УÑéʧ°Ü"); } } }
apache-2.0
InnoFang/Android-Code-Demos
ProcessingDemo/app/src/main/java/io/innofang/processingdemo/CompassSketch.java
3244
package io.innofang.processingdemo; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; /** * Author: Inno Fang * Time: 2017/7/30 13:15 * Description: */ public class CompassSketch extends Sketch { SensorListener listener; SensorManager manager; Sensor accelerometer; Sensor magnetometer; float easing = 0.01F; float azimuth; float pitch; float roll; public CompassSketch(Context context) { super(context); listener = new SensorListener(); manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); accelerometer = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); magnetometer = manager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); manager.registerListener(listener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL); manager.registerListener(listener, magnetometer, SensorManager.SENSOR_DELAY_NORMAL); } public void settings() { fullScreen(P2D); } public void setup() { orientation(PORTRAIT); } public void draw() { background(255); float cx = width * 0.5F; float cy = height * 0.4F; float radius = cx * 0.8F; translate(cx, cy); noFill(); stroke(0); strokeWeight(2); ellipse(0, 0, radius * 2, radius * 2); line(0, -cy, 0, -radius); fill(192, 0, 0); noStroke(); rotate(-azimuth); beginShape(); vertex(-30, 40); vertex(0, 0); vertex(30, 40); vertex(0, -radius); endShape(); } public void resume() { if (manager != null) { manager.registerListener(listener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL); manager.registerListener(listener, magnetometer, SensorManager.SENSOR_DELAY_NORMAL); } } public void pause() { if (manager != null) { manager.unregisterListener(listener); } } class SensorListener implements SensorEventListener { float[] gravity = new float[3]; float[] geomagnetic = new float[3]; float[] I = new float[16]; float[] R = new float[16]; float[] orientation = new float[3]; public void onSensorChanged(SensorEvent event) { if (event.accuracy == SensorManager.SENSOR_STATUS_ACCURACY_LOW) return; if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { arrayCopy(event.values, geomagnetic); } if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { arrayCopy(event.values, gravity); } if (SensorManager.getRotationMatrix(R, I, gravity, geomagnetic)) { SensorManager.getOrientation(R, orientation); azimuth += easing * (orientation[0] - azimuth); pitch += easing * (orientation[1] - pitch); roll += easing * (orientation[2] - roll); } } public void onAccuracyChanged(Sensor sensor, int accuracy) { } } }
apache-2.0
afiantara/apache-wicket-1.5.7
src/wicket-request/src/test/java/org/apache/wicket/request/mapper/parameter/PageParametersEncoderTest.java
3628
/* * 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.wicket.request.mapper.parameter; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.wicket.request.IRequestParameters; import org.apache.wicket.request.Request; import org.apache.wicket.request.Url; import org.apache.wicket.util.string.StringValue; import org.junit.Assert; import org.junit.Test; /** * Tests for PageParametersEncoder */ public class PageParametersEncoderTest extends Assert { /** * Tests that PageParametersEncoder decodes GET parameters, not POST * * @throws Exception */ @Test public void decodeParameters() throws Exception { PageParametersEncoder encoder = new PageParametersEncoder(); Request request = new Request() { @Override public Url getUrl() { return Url.parse("idx1/idx2?named1=value1&named2=value2"); } @Override public Url getClientUrl() { return null; } @Override public Locale getLocale() { return null; } @Override public Charset getCharset() { return null; } @Override public Object getContainerRequest() { return null; } @Override public IRequestParameters getPostParameters() { return new PostParameters(); } }; PageParameters pageParameters = encoder.decodePageParameters(request); assertEquals("idx1", pageParameters.get(0).toOptionalString()); assertEquals("idx2", pageParameters.get(1).toOptionalString()); assertEquals("value1", pageParameters.get("named1").toOptionalString()); assertEquals("value2", pageParameters.get("named2").toOptionalString()); assertEquals(null, pageParameters.get("postOne").toOptionalString()); assertTrue(pageParameters.getValues("postTwo").isEmpty()); assertTrue(pageParameters.getValues("postTwo").isEmpty()); } /** * Mock IRequestParameters that provides static POST parameters */ private static class PostParameters implements IRequestParameters { private final Map<String, List<StringValue>> params = new HashMap<String, List<StringValue>>(); { params.put("postOne", Arrays.asList(StringValue.valueOf("1"))); params.put("postTwo", Arrays.asList(StringValue.valueOf("2"), StringValue.valueOf("2.1"))); } public Set<String> getParameterNames() { return params.keySet(); } public StringValue getParameterValue(String name) { List<StringValue> values = params.get(name); return (values != null && !values.isEmpty()) ? values.get(0) : StringValue.valueOf((String)null); } public List<StringValue> getParameterValues(String name) { List<StringValue> values = params.get(name); return values != null ? Collections.unmodifiableList(values) : null; } } }
apache-2.0
golovnin/undertow
core/src/main/java/io/undertow/UndertowMessages.java
26669
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.undertow; import java.io.IOException; import java.nio.channels.ClosedChannelException; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLPeerUnverifiedException; import io.undertow.server.RequestTooBigException; import io.undertow.server.handlers.form.MultiPartParserDefinition; import org.jboss.logging.Messages; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; import io.undertow.predicate.PredicateBuilder; import io.undertow.protocols.http2.HpackException; import io.undertow.security.api.AuthenticationMechanism; import io.undertow.server.handlers.builder.HandlerBuilder; import io.undertow.util.HttpString; import io.undertow.util.ParameterLimitException; import io.undertow.util.BadRequestException; /** * @author Stuart Douglas */ @MessageBundle(projectCode = "UT") public interface UndertowMessages { UndertowMessages MESSAGES = Messages.getBundle(UndertowMessages.class); @Message(id = 1, value = "Maximum concurrent requests must be larger than zero.") IllegalArgumentException maximumConcurrentRequestsMustBeLargerThanZero(); @Message(id = 2, value = "The response has already been started") IllegalStateException responseAlreadyStarted(); // id = 3 @Message(id = 4, value = "getResponseChannel() has already been called") IllegalStateException responseChannelAlreadyProvided(); @Message(id = 5, value = "getRequestChannel() has already been called") IllegalStateException requestChannelAlreadyProvided(); // id = 6 // id = 7 @Message(id = 8, value = "Handler cannot be null") IllegalArgumentException handlerCannotBeNull(); @Message(id = 9, value = "Path must be specified") IllegalArgumentException pathMustBeSpecified(); @Message(id = 10, value = "Session is invalid %s") IllegalStateException sessionIsInvalid(String sessionId); @Message(id = 11, value = "Session manager must not be null") IllegalStateException sessionManagerMustNotBeNull(); @Message(id = 12, value = "Session manager was not attached to the request. Make sure that the SessionAttachmentHandler is installed in the handler chain") IllegalStateException sessionManagerNotFound(); @Message(id = 13, value = "Argument %s cannot be null") IllegalArgumentException argumentCannotBeNull(final String argument); // @Message(id = 14, value = "close() called with data still to be flushed. Please call shutdownWrites() and then call flush() until it returns true before calling close()") // IOException closeCalledWithDataStillToBeFlushed(); // // @Message(id = 16, value = "Could not add cookie as cookie handler was not present in the handler chain") // IllegalStateException cookieHandlerNotPresent(); @Message(id = 17, value = "Form value is a file, use getFileItem() instead") IllegalStateException formValueIsAFile(); @Message(id = 18, value = "Form value is a String, use getValue() instead") IllegalStateException formValueIsAString(); // // @Message(id = 19, value = "Connection from %s terminated as request entity was larger than %s") // IOException requestEntityWasTooLarge(SocketAddress address, long size); @Message(id = 20, value = "Connection terminated as request was larger than %s") RequestTooBigException requestEntityWasTooLarge(long size); @Message(id = 21, value = "Session already invalidated") IllegalStateException sessionAlreadyInvalidated(); @Message(id = 22, value = "The specified hash algorithm '%s' can not be found.") IllegalArgumentException hashAlgorithmNotFound(String algorithmName); @Message(id = 23, value = "An invalid Base64 token has been received.") IllegalArgumentException invalidBase64Token(@Cause final IOException cause); @Message(id = 24, value = "An invalidly formatted nonce has been received.") IllegalArgumentException invalidNonceReceived(); @Message(id = 25, value = "Unexpected token '%s' within header.") IllegalArgumentException unexpectedTokenInHeader(final String name); @Message(id = 26, value = "Invalid header received.") IllegalArgumentException invalidHeader(); @Message(id = 27, value = "Could not find session cookie config in the request") IllegalStateException couldNotFindSessionCookieConfig(); // // @Message(id = 28, value = "Session %s already exists") // IllegalStateException sessionAlreadyExists(final String id); @Message(id = 29, value = "Channel was closed mid chunk, if you have attempted to write chunked data you cannot shutdown the channel until after it has all been written.") IOException chunkedChannelClosedMidChunk(); @Message(id = 30, value = "User %s successfully authenticated.") String userAuthenticated(final String userName); @Message(id = 31, value = "User %s has logged out.") String userLoggedOut(final String userName); // // @Message(id = 33, value = "Authentication type %s cannot be combined with %s") // IllegalStateException authTypeCannotBeCombined(String type, String existing); @Message(id = 34, value = "Stream is closed") IOException streamIsClosed(); @Message(id = 35, value = "Cannot get stream as startBlocking has not been invoked") IllegalStateException startBlockingHasNotBeenCalled(); @Message(id = 36, value = "Connection terminated parsing multipart data") IOException connectionTerminatedReadingMultiPartData(); @Message(id = 37, value = "Failed to parse path in HTTP request") RuntimeException failedToParsePath(); @Message(id = 38, value = "Authentication failed, requested user name '%s'") String authenticationFailed(final String userName); @Message(id = 39, value = "Too many query parameters, cannot have more than %s query parameters") BadRequestException tooManyQueryParameters(int noParams); @Message(id = 40, value = "Too many headers, cannot have more than %s header") String tooManyHeaders(int noParams); @Message(id = 41, value = "Channel is closed") ClosedChannelException channelIsClosed(); @Message(id = 42, value = "Could not decode trailers in HTTP request") IOException couldNotDecodeTrailers(); @Message(id = 43, value = "Data is already being sent. You must wait for the completion callback to be be invoked before calling send() again") IllegalStateException dataAlreadyQueued(); @Message(id = 44, value = "More than one predicate with name %s. Builder class %s and %s") IllegalStateException moreThanOnePredicateWithName(String name, Class<? extends PredicateBuilder> aClass, Class<? extends PredicateBuilder> existing); @Message(id = 45, value = "Error parsing predicated handler string %s:%n%s") IllegalArgumentException errorParsingPredicateString(String reason, String s); @Message(id = 46, value = "The number of cookies sent exceeded the maximum of %s") IllegalStateException tooManyCookies(int maxCookies); @Message(id = 47, value = "The number of parameters exceeded the maximum of %s") ParameterLimitException tooManyParameters(int maxValues); @Message(id = 48, value = "No request is currently active") IllegalStateException noRequestActive(); @Message(id = 50, value = "AuthenticationMechanism Outcome is null") IllegalStateException authMechanismOutcomeNull(); @Message(id = 51, value = "Not a valid IP pattern %s") IllegalArgumentException notAValidIpPattern(String peer); @Message(id = 52, value = "Session data requested when non session based authentication in use") IllegalStateException noSessionData(); @Message(id = 53, value = "Listener %s already registered") IllegalArgumentException listenerAlreadyRegistered(String name); @Message(id = 54, value = "The maximum size %s for an individual file in a multipart request was exceeded") MultiPartParserDefinition.FileTooLargeException maxFileSizeExceeded(long maxIndividualFileSize); @Message(id = 55, value = "Could not set attribute %s to %s as it is read only") String couldNotSetAttribute(String attributeName, String newValue); @Message(id = 56, value = "Could not parse URI template %s, exception at char %s") RuntimeException couldNotParseUriTemplate(String path, int i); @Message(id = 57, value = "Mismatched braces in attribute string %s") RuntimeException mismatchedBraces(String valueString); @Message(id = 58, value = "More than one handler with name %s. Builder class %s and %s") IllegalStateException moreThanOneHandlerWithName(String name, Class<? extends HandlerBuilder> aClass, Class<? extends HandlerBuilder> existing); // // @Message(id = 59, value = "Invalid syntax %s") // IllegalArgumentException invalidSyntax(String line); // // @Message(id = 60, value = "Error parsing handler string %s:%n%s") // IllegalArgumentException errorParsingHandlerString(String reason, String s); @Message(id = 61, value = "Out of band responses only allowed for 100-continue requests") IllegalArgumentException outOfBandResponseOnlyAllowedFor100Continue(); // // @Message(id = 62, value = "AJP does not support HTTP upgrade") // IllegalStateException ajpDoesNotSupportHTTPUpgrade(); // // @Message(id = 63, value = "File system watcher already started") // IllegalStateException fileSystemWatcherAlreadyStarted(); // // @Message(id = 64, value = "File system watcher not started") // IllegalStateException fileSystemWatcherNotStarted(); @Message(id = 65, value = "SSL must be specified to connect to a https URL") IOException sslWasNull(); @Message(id = 66, value = "Incorrect magic number %s for AJP packet header") IOException wrongMagicNumber(int number); @Message(id = 67, value = "No client cert was provided") SSLPeerUnverifiedException peerUnverified(); @Message(id = 68, value = "Servlet path match failed") IllegalArgumentException servletPathMatchFailed(); @Message(id = 69, value = "Could not parse set cookie header %s") IllegalArgumentException couldNotParseCookie(String headerValue); @Message(id = 70, value = "method can only be called by IO thread") IllegalStateException canOnlyBeCalledByIoThread(); @Message(id = 71, value = "Cannot add path template %s, matcher already contains an equivalent pattern %s") IllegalStateException matcherAlreadyContainsTemplate(String templateString, String templateString1); @Message(id = 72, value = "Failed to decode url %s to charset %s") IllegalArgumentException failedToDecodeURL(String s, String enc, @Cause Exception e); @Message(id = 73, value = "Resource change listeners are not supported") IllegalArgumentException resourceChangeListenerNotSupported(); // // @Message(id = 74, value = "Could not renegotiate SSL connection to require client certificate, as client had sent more data") // IllegalStateException couldNotRenegotiate(); @Message(id = 75, value = "Object was freed") IllegalStateException objectWasFreed(); @Message(id = 76, value = "Handler not shutdown") IllegalStateException handlerNotShutdown(); @Message(id = 77, value = "The underlying transport does not support HTTP upgrade") IllegalStateException upgradeNotSupported(); @Message(id = 78, value = "Renegotiation not supported") IOException renegotiationNotSupported(); // // @Message(id = 79, value = "Not a valid user agent pattern %s") // IllegalArgumentException notAValidUserAgentPattern(String userAgent); @Message(id = 80, value = "Not a valid regular expression pattern %s") IllegalArgumentException notAValidRegularExpressionPattern(String pattern); @Message(id = 81, value = "Bad request") BadRequestException badRequest(); @Message(id = 82, value = "Host %s already registered") RuntimeException hostAlreadyRegistered(Object host); @Message(id = 83, value = "Host %s has not been registered") RuntimeException hostHasNotBeenRegistered(Object host); @Message(id = 84, value = "Attempted to write additional data after the last chunk") IOException extraDataWrittenAfterChunkEnd(); @Message(id = 85, value = "Could not generate unique session id") RuntimeException couldNotGenerateUniqueSessionId(); // // @Message(id = 86, value = "SPDY needs to be provided with a heap buffer pool, for use in compressing and decompressing headers.") // IllegalArgumentException mustProvideHeapBuffer(); // // @Message(id = 87, value = "Unexpected SPDY frame type %s") // IOException unexpectedFrameType(int type); @Message(id = 88, value = "SPDY control frames cannot have body content") IOException controlFrameCannotHaveBodyContent(); // @Message(id = 89, value = "SPDY not supported") //// IOException spdyNotSupported(); // // @Message(id = 90, value = "No ALPN implementation available (tried Jetty ALPN and JDK9)") // IOException alpnNotAvailable(); @Message(id = 91, value = "Buffer has already been freed") IllegalStateException bufferAlreadyFreed(); // // @Message(id = 92, value = "A SPDY header was too large to fit in a response buffer, if you want to support larger headers please increase the buffer size") // IllegalStateException headersTooLargeToFitInHeapBuffer(); // @Message(id = 93, value = "A SPDY stream was reset by the remote endpoint") // IOException spdyStreamWasReset(); @Message(id = 94, value = "Blocking await method called from IO thread. Blocking IO must be dispatched to a worker thread or deadlocks will result.") IOException awaitCalledFromIoThread(); @Message(id = 95, value = "Recursive call to flushSenders()") RuntimeException recursiveCallToFlushingSenders(); @Message(id = 96, value = "More data was written to the channel than specified in the content-length") IllegalStateException fixedLengthOverflow(); @Message(id = 97, value = "AJP request already in progress") IllegalStateException ajpRequestAlreadyInProgress(); @Message(id = 98, value = "HTTP ping data must be 8 bytes in length") String httpPingDataMustBeLength8(); @Message(id = 99, value = "Received a ping of size other than 8") String invalidPingSize(); @Message(id = 100, value = "stream id must be zero for frame type %s") String streamIdMustBeZeroForFrameType(int frameType); @Message(id = 101, value = "stream id must not be zero for frame type %s") String streamIdMustNotBeZeroForFrameType(int frameType); // // @Message(id = 102, value = "RST_STREAM received for idle stream") // String rstStreamReceivedForIdleStream(); @Message(id = 103, value = "Http2 stream was reset") IOException http2StreamWasReset(); @Message(id = 104, value = "Incorrect HTTP2 preface") IOException incorrectHttp2Preface(); @Message(id = 105, value = "HTTP2 frame to large") IOException http2FrameTooLarge(); @Message(id = 106, value = "HTTP2 continuation frame received without a corresponding headers or push promise frame") IOException http2ContinuationFrameNotExpected(); @Message(id = 107, value = "Huffman encoded value in HPACK headers did not end with EOS padding") HpackException huffmanEncodedHpackValueDidNotEndWithEOS(); @Message(id = 108, value = "HPACK variable length integer encoded over too many octects, max is %s") HpackException integerEncodedOverTooManyOctets(int maxIntegerOctets); @Message(id = 109, value = "Zero is not a valid header table index") HpackException zeroNotValidHeaderTableIndex(); @Message(id = 110, value = "Cannot send 100-Continue, getResponseChannel() has already been called") IOException cannotSendContinueResponse(); @Message(id = 111, value = "Parser did not make progress") IOException parserDidNotMakeProgress(); @Message(id = 112, value = "Only client side can call createStream, if you wish to send a PUSH_PROMISE frame use createPushPromiseStream instead") IOException headersStreamCanOnlyBeCreatedByClient(); @Message(id = 113, value = "Only the server side can send a push promise stream") IOException pushPromiseCanOnlyBeCreatedByServer(); @Message(id = 114, value = "Invalid IP access control rule %s. Format is: [ip-match] allow|deny") IllegalArgumentException invalidAclRule(String rule); @Message(id = 115, value = "Server received PUSH_PROMISE frame from client") IOException serverReceivedPushPromise(); @Message(id = 116, value = "CONNECT not supported by this connector") IllegalStateException connectNotSupported(); @Message(id = 117, value = "Request was not a CONNECT request") IllegalStateException notAConnectRequest(); @Message(id = 118, value = "Cannot reset buffer, response has already been commited") IllegalStateException cannotResetBuffer(); @Message(id = 119, value = "HTTP2 via prior knowledge failed") IOException http2PriRequestFailed(); @Message(id = 120, value = "Out of band responses are not allowed for this connector") IllegalStateException outOfBandResponseNotSupported(); @Message(id = 121, value = "Session was rejected as the maximum number of sessions (%s) has been hit") IllegalStateException tooManySessions(int maxSessions); @Message(id = 122, value = "CONNECT attempt failed as target proxy returned %s") IOException proxyConnectionFailed(int responseCode); @Message(id = 123, value = "MCMP message %s rejected due to suspicious characters") RuntimeException mcmpMessageRejectedDueToSuspiciousCharacters(String data); @Message(id = 124, value = "renegotiation timed out") IllegalStateException rengotiationTimedOut(); @Message(id = 125, value = "Request body already read") IllegalStateException requestBodyAlreadyRead(); @Message(id = 126, value = "Attempted to do blocking IO from the IO thread. This is prohibited as it may result in deadlocks") IllegalStateException blockingIoFromIOThread(); @Message(id = 127, value = "Response has already been sent") IllegalStateException responseComplete(); @Message(id = 128, value = "Remote peer closed connection before all data could be read") IOException couldNotReadContentLengthData(); @Message(id = 129, value = "Failed to send after being safe to send") IllegalStateException failedToSendAfterBeingSafe(); @Message(id = 130, value = "HTTP reason phrase was too large for the buffer. Either provide a smaller message or a bigger buffer. Phrase: %s") IllegalStateException reasonPhraseToLargeForBuffer(String phrase); @Message(id = 131, value = "Buffer pool is closed") IllegalStateException poolIsClosed(); @Message(id = 132, value = "HPACK decode failed") HpackException hpackFailed(); @Message(id = 133, value = "Request did not contain an Upgrade header, upgrade is not permitted") IllegalStateException notAnUpgradeRequest(); @Message(id = 134, value = "Authentication mechanism %s requires property %s to be set") IllegalStateException authenticationPropertyNotSet(String name, String header); @Message(id = 135, value = "renegotiation failed") IllegalStateException rengotiationFailed(); @Message(id = 136, value = "User agent charset string must have an even number of items, in the form pattern,charset,pattern,charset,... Instead got: %s") IllegalArgumentException userAgentCharsetMustHaveEvenNumberOfItems(String supplied); @Message(id = 137, value = "Could not find the datasource called %s") IllegalArgumentException datasourceNotFound(String ds); @Message(id = 138, value = "Server not started") IllegalStateException serverNotStarted(); @Message(id = 139, value = "Exchange already complete") IllegalStateException exchangeAlreadyComplete(); @Message(id = 140, value = "Initial SSL/TLS data is not a handshake record") SSLHandshakeException notHandshakeRecord(); @Message(id = 141, value = "Initial SSL/TLS handshake record is invalid") SSLHandshakeException invalidHandshakeRecord(); @Message(id = 142, value = "Initial SSL/TLS handshake spans multiple records") SSLHandshakeException multiRecordSSLHandshake(); @Message(id = 143, value = "Expected \"client hello\" record") SSLHandshakeException expectedClientHello(); @Message(id = 144, value = "Expected server hello") SSLHandshakeException expectedServerHello(); @Message(id = 145, value = "Too many redirects") IOException tooManyRedirects(@Cause IOException exception); @Message(id = 146, value = "HttpServerExchange cannot have both async IO resumed and dispatch() called in the same cycle") IllegalStateException resumedAndDispatched(); @Message(id = 147, value = "No host header in a HTTP/1.1 request") IOException noHostInHttp11Request(); @Message(id = 148, value = "Invalid HPack encoding. First byte: %s") HpackException invalidHpackEncoding(byte b); @Message(id = 149, value = "HttpString is not allowed to contain newlines. value: %s") IllegalArgumentException newlineNotSupportedInHttpString(String value); @Message(id = 150, value = "Pseudo header %s received after receiving normal headers. Pseudo headers must be the first headers in a HTTP/2 header block.") String pseudoHeaderInWrongOrder(HttpString header); @Message(id = 151, value = "Expected to receive a continuation frame") String expectedContinuationFrame(); @Message(id = 152, value = "Incorrect frame size") String incorrectFrameSize(); @Message(id = 153, value = "Stream id not registered") IllegalStateException streamNotRegistered(); @Message(id = 154, value = "Mechanism %s returned a null result from sendChallenge()") NullPointerException sendChallengeReturnedNull(AuthenticationMechanism mechanism); @Message(id = 155, value = "Framed channel body was set when it was not ready for flush") IllegalStateException bodyIsSetAndNotReadyForFlush(); @Message(id = 156, value = "Invalid GZIP header") IOException invalidGzipHeader(); @Message(id = 157, value = "Invalid GZIP footer") IOException invalidGZIPFooter(); @Message(id = 158, value = "Response of length %s is too large to buffer") IllegalStateException responseTooLargeToBuffer(Long length); // // @Message(id = 159, value = "Max size must be larger than one") // IllegalArgumentException maxSizeMustBeLargerThanOne(); @Message(id = 161, value = "HTTP/2 header block is too large") String headerBlockTooLarge(); @Message(id = 162, value = "Same-site attribute %s is invalid. It must be Strict or Lax") IllegalArgumentException invalidSameSiteMode(String mode); @Message(id = 163, value = "Invalid token %s") IllegalArgumentException invalidToken(byte c); @Message(id = 164, value = "Request contained invalid headers") IllegalArgumentException invalidHeaders(); @Message(id = 165, value = "Invalid character %s in request-target") String invalidCharacterInRequestTarget(char next); @Message(id = 166, value = "Pooled object is closed") IllegalStateException objectIsClosed(); @Message(id = 167, value = "More than one host header in request") IOException moreThanOneHostHeader(); @Message(id = 168, value = "An invalid character [ASCII code: %s] was present in the cookie value") IllegalArgumentException invalidCookieValue(String value); @Message(id = 169, value = "An invalid domain [%s] was specified for this cookie") IllegalArgumentException invalidCookieDomain(String value); @Message(id = 170, value = "An invalid path [%s] was specified for this cookie") IllegalArgumentException invalidCookiePath(String value); @Message(id = 173, value = "An invalid control character [%s] was present in the cookie value or attribute") IllegalArgumentException invalidControlCharacter(String value); @Message(id = 174, value = "An invalid escape character in cookie value") IllegalArgumentException invalidEscapeCharacter(); @Message(id = 175, value = "Invalid Hpack index %s") HpackException invalidHpackIndex(int index); @Message(id = 178, value = "Buffer pool is too small, min size is %s") IllegalArgumentException bufferPoolTooSmall(int minSize); @Message(id = 179, value = "Invalid PROXY protocol header") IOException invalidProxyHeader(); @Message(id = 180, value = "PROXY protocol header exceeded max size of 107 bytes") IOException headerSizeToLarge(); @Message(id = 181, value = "HTTP/2 trailers too large for single buffer") RuntimeException http2TrailerToLargeForSingleBuffer(); @Message(id = 182, value = "Ping not supported") IOException pingNotSupported(); @Message(id = 183, value = "Ping timed out") IOException pingTimeout(); @Message(id = 184, value = "Stream limit exceeded") IOException streamLimitExceeded(); @Message(id = 185, value = "Invalid IP address %s") IOException invalidIpAddress(String addressString); @Message(id = 186, value = "Invalid TLS extension") SSLException invalidTlsExt(); @Message(id = 187, value = "Not enough data") SSLException notEnoughData(); @Message(id = 188, value = "Empty host name in SNI extension") SSLException emptyHostNameSni(); @Message(id = 189, value = "Duplicated host name of type %s") SSLException duplicatedSniServerName(int type); @Message(id = 190, value = "No context for SSL connection") SSLException noContextForSslConnection(); @Message(id = 191, value = "Default context cannot be null") IllegalStateException defaultContextCannotBeNull(); @Message(id = 192, value = "Form value is a in-memory file, use getFileItem() instead") IllegalStateException formValueIsInMemoryFile(); }
apache-2.0
consulo/consulo
modules/base/platform-impl/src/main/java/com/intellij/openapi/editor/ex/EditorGutterComponentEx.java
3311
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.editor.ex; import com.intellij.codeInsight.daemon.GutterMark; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorGutter; import com.intellij.openapi.editor.FoldRegion; import com.intellij.openapi.editor.TextAnnotationGutterProvider; import com.intellij.openapi.editor.markup.GutterIconRenderer; import consulo.util.dataholder.Key; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.swing.*; import java.awt.*; import java.util.List; import java.util.function.IntUnaryOperator; public abstract class EditorGutterComponentEx extends JComponent implements EditorGutter { /** * The key to retrieve a logical editor line position of a latest actionable click inside the gutter. * Available to gutter popup actions (see {@link #setGutterPopupGroup(ActionGroup)}, * {@link GutterIconRenderer#getPopupMenuActions()}, {@link TextAnnotationGutterProvider#getPopupActions(int, Editor)}) */ public static final Key<Integer> LOGICAL_LINE_AT_CURSOR = Key.create("EditorGutter.LOGICAL_LINE_AT_CURSOR"); /** * The key to retrieve a editor gutter icon center position of a latest actionable click inside the gutter. * Available to gutter popup actions (see {@link #setGutterPopupGroup(ActionGroup)}, * {@link GutterIconRenderer#getPopupMenuActions()}, {@link TextAnnotationGutterProvider#getPopupActions(int, Editor)}) */ public static final Key<Point> ICON_CENTER_POSITION = Key.create("EditorGutter.ICON_CENTER_POSITION"); @Nullable public abstract FoldRegion findFoldingAnchorAt(int x, int y); @Nonnull public abstract List<GutterMark> getGutterRenderers(int line); public abstract int getWhitespaceSeparatorOffset(); public abstract void revalidateMarkup(); public abstract int getLineMarkerAreaOffset(); public abstract int getIconAreaOffset(); public abstract int getLineMarkerFreePaintersAreaOffset(); public abstract int getIconsAreaWidth(); public abstract int getAnnotationsAreaOffset(); public abstract int getAnnotationsAreaWidth(); @Nullable public abstract Point getCenterPoint(GutterIconRenderer renderer); public abstract void setLineNumberConvertor(@Nullable IntUnaryOperator lineNumberConvertor); public abstract void setLineNumberConvertor(@Nullable IntUnaryOperator lineNumberConvertor1, @Nullable IntUnaryOperator lineNumberConvertor2); public abstract void setShowDefaultGutterPopup(boolean show); /** * When set to false, makes {@link #closeAllAnnotations()} a no-op and hides the corresponding context menu action. */ public abstract void setCanCloseAnnotations(boolean canCloseAnnotations); public abstract void setGutterPopupGroup(@Nullable ActionGroup group); public abstract void setPaintBackground(boolean value); public abstract void setForceShowLeftFreePaintersArea(boolean value); public abstract void setForceShowRightFreePaintersArea(boolean value); public abstract void setInitialIconAreaWidth(int width); @Nullable public GutterMark getGutterRenderer(final Point p) { return null; } }
apache-2.0
kuali/kpme
tk-lm/api/src/main/java/org/kuali/kpme/tklm/api/time/rules/lunch/sys/SystemLunchRuleContract.java
1805
/** * Copyright 2004-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.kpme.tklm.api.time.rules.lunch.sys; import org.kuali.kpme.tklm.api.time.rules.TkRuleContract; /** * <p>SystemLunchRuleContract interface</p> * */ public interface SystemLunchRuleContract extends TkRuleContract { /** * The primary key of a SystemLunchRule entry saved in a database * * <p> * tkSystemLunchRuleId of a SystemLunchRule * <p> * * @return tkSystemLunchRuleId for SystemLunchRule */ public String getTkSystemLunchRuleId(); /** * The history flag of the SystemLunchRule * * <p> * history flag of a SystemLunchRule * <p> * * @return Y if on, N if not */ public boolean isHistory(); /** * The principal id of the user who set up the SystemLunchRule * * <p> * userPrincipalId of a SystemLunchRule * <p> * * @return userPrincipalId for SystemLunchRule */ public String getUserPrincipalId(); /** * The flag to indicate if the lunch buttons will be presented or not * * <p> * showLunchButton of a SystemLunchRule * <p> * * @return Y if presented, N if not */ public Boolean getShowLunchButton(); }
apache-2.0
ageldama/glados-wiki
src/main/java/com/aperture_software/glados_wiki/entities/functions/page/PageToPageResponseFunction.java
877
package com.aperture_software.glados_wiki.entities.functions.page; import com.aperture_software.glados_wiki.entities.Page; import com.aperture_software.glados_wiki.entities.page.PageResponse; import com.google.common.base.Function; /** * Created by jhyun on 14. 3. 15. */ public class PageToPageResponseFunction implements Function<Page, PageResponse> { @Override public PageResponse apply(Page page) { if (page == null) return null; PageResponse pageResponse = new PageResponse(); // id if (page.getId() != null) pageResponse.setId(page.getId().toString()); // pageResponse.setTitle(page.getTitle()); pageResponse.setCtime(page.getCtime()); pageResponse.setMtime(page.getMtime()); pageResponse.setTags(page.getTags()); // return pageResponse; } }
apache-2.0
jonsvien/shiro
src/main/java/com/liuhao/filter/RoleFilter.java
1448
package com.liuhao.filter; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.apache.shiro.web.filter.authz.AuthorizationFilter; import org.springframework.http.HttpStatus; import com.liuhao.util.WebUtils; public class RoleFilter extends AuthorizationFilter { private static final String UNAUTHORIZED = HttpStatus.UNAUTHORIZED.value() + ""; @Override protected boolean isAccessAllowed(ServletRequest arg0, ServletResponse arg1, Object arg2) throws Exception { if (arg2 == null || ((String[]) arg2).length < 1) { return true; } String[] roleStrArray = (String[]) arg2; Subject user = SecurityUtils.getSubject(); for (String roleStr : roleStrArray) { if (user.hasRole(roleStr)) { return true; } } return false; } @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { HttpServletResponse res = (HttpServletResponse) response; HttpServletRequest req = (HttpServletRequest) request; if (WebUtils.isAjax(req)) { res.setHeader(UNAUTHORIZED, "no permission"); } else { res.getWriter().write(WebUtils.getMsgScript("no permission")); } return false; } }
apache-2.0
griffon/griffon
subprojects/griffon-core-impl/src/main/java/org/codehaus/griffon/runtime/core/resources/DefaultResourceResolver.java
2483
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2008-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.griffon.runtime.core.resources; import griffon.annotations.core.Nonnull; import griffon.converter.ConverterRegistry; import griffon.core.bundles.CompositeResourceBundleBuilder; import griffon.core.resources.NoSuchResourceException; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; import static griffon.util.StringUtils.requireNonBlank; import static java.util.Objects.requireNonNull; /** * @author Andres Almiray * @since 2.0.0 */ public class DefaultResourceResolver extends AbstractResourceResolver { private final String basename; private final Map<Locale, ResourceBundle> bundles = new ConcurrentHashMap<>(); private final CompositeResourceBundleBuilder compositeResourceBundleBuilder; public DefaultResourceResolver(@Nonnull ConverterRegistry converterRegistry, @Nonnull CompositeResourceBundleBuilder builder, @Nonnull String basename) { super(converterRegistry); this.compositeResourceBundleBuilder = requireNonNull(builder, "Argument 'builder' must not be null"); this.basename = requireNonBlank(basename, "Argument 'basename' must not be blank"); } @Nonnull public String getBasename() { return basename; } @Nonnull protected Object doResolveResourceValue(@Nonnull String key, @Nonnull Locale locale) throws NoSuchResourceException { requireNonBlank(key, ERROR_KEY_BLANK); requireNonNull(locale, ERROR_LOCALE_NULL); return getBundle(locale).getObject(key); } @Nonnull protected ResourceBundle getBundle(@Nonnull Locale locale) { requireNonNull(locale, ERROR_LOCALE_NULL); return bundles.computeIfAbsent(locale, l -> compositeResourceBundleBuilder.create(basename, l)); } }
apache-2.0
aspectran/aspectran
core/src/main/java/com/aspectran/core/context/expr/TokenEvaluator.java
1911
/* * Copyright (c) 2008-2022 The Aspectran Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aspectran.core.context.expr; import com.aspectran.core.activity.Activity; import com.aspectran.core.context.expr.token.Token; import com.aspectran.core.context.expr.token.TokenParser; import java.io.IOException; import java.io.Writer; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; /** * Evaluates token expressions. * * <p>Created: 2010. 5. 6. AM 1:35:16</p> */ public interface TokenEvaluator { Activity getActivity(); Object evaluate(Token token); Object evaluate(Token[] tokens); void evaluate(Token[] tokens, Writer writer) throws IOException; String evaluateAsString(Token[] tokens); List<Object> evaluateAsList(List<Token[]> tokensList); Set<Object> evaluateAsSet(Set<Token[]> tokensSet); Map<String, Object> evaluateAsMap(Map<String, Token[]> tokensMap); Properties evaluateAsProperties(Properties tokensProp); static Object evaluate(String expression, Activity activity) { if (Token.hasToken(expression)) { Token[] tokens = TokenParser.parse(expression); TokenEvaluator tokenEvaluator = new TokenEvaluation(activity); return tokenEvaluator.evaluate(tokens); } else { return expression; } } }
apache-2.0
Ericsongyl/PullRefreshAndLoadMore
pullrefresh/src/main/java/com/nicksong/refreshAndLoad/widget/layout/BaseHeaderView.java
5091
package com.nicksong.refreshAndLoad.widget.layout; import android.content.Context; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.util.Log; import android.widget.RelativeLayout; import com.nicksong.refreshAndLoad.widget.support.impl.Refreshable; import com.nicksong.refreshAndLoad.widget.support.type.LayoutType; public abstract class BaseHeaderView extends RelativeLayout implements Refreshable { public final static int NONE = 0; public final static int PULLING = 1; public final static int LOOSENT_O_REFRESH = 2; public final static int REFRESHING = 3; public final static int REFRESH_CLONE = 4; private int stateType = NONE; private PullRefreshLayout pullRefreshLayout; private boolean isLockState = false; OnRefreshListener onRefreshListener; private int scrollState = FlingLayout.SCROLL_STATE_IDLE; public BaseHeaderView(Context context) { this(context, null); } public BaseHeaderView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BaseHeaderView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { setFocusable(false); setFocusableInTouchMode(false); } protected boolean isLockState() { return isLockState; } public int getLayoutType() { return LayoutType.LAYOUT_NORMAL; } private void setState(int state) { if (isLockState || stateType == state) { return; } Log.i("BaseHeaderView", "" + state); this.stateType = state; if (state == REFRESHING) { isLockState = true; if (onRefreshListener != null) { onRefreshListener.onRefresh(this); } } onStateChange(state); } public int getType() { return stateType; } private void close() { if (this.pullRefreshLayout != null) { float moveY = pullRefreshLayout.getMoveY(); if (moveY > 0) { pullRefreshLayout.startMoveTo(moveY, 0); setState(NONE); } } } @Override public void setPullRefreshLayout(PullRefreshLayout pullRefreshLayout) { this.pullRefreshLayout = pullRefreshLayout; } @Override public void startRefresh() { if (pullRefreshLayout != null) { float moveY = pullRefreshLayout.getMoveY(); if (moveY == 0) { float headerSpanHeight = getSpanHeight(); pullRefreshLayout.startMoveTo(0, headerSpanHeight); setState(REFRESHING); } } } /** * 自动刷新 */ public void autoRefresh() { if (pullRefreshLayout != null) { float moveY = pullRefreshLayout.getMoveY(); if (moveY == 0) { float headerSpanHeight = 310; pullRefreshLayout.startMoveTo(0, headerSpanHeight); setState(REFRESHING); } } } @Override public void stopRefresh() { isLockState = false; setState(REFRESH_CLONE); postDelayed(new Runnable() { @Override public void run() { close(); } }, 400); } @Override public boolean onScroll(float y) { boolean intercept = false; int layoutType = getLayoutType(); if (layoutType == LayoutType.LAYOUT_SCROLLER) { ViewCompat.setTranslationY(this, getMeasuredHeight()); } else if (layoutType == LayoutType.LAYOUT_DRAWER) { ViewCompat.setTranslationY(this, y); ViewCompat.setTranslationY(pullRefreshLayout.getPullView(), 0); intercept = true; } else { ViewCompat.setTranslationY(this, y); } float headerSpanHeight = getSpanHeight(); if (scrollState == FlingLayout.SCROLL_STATE_TOUCH_SCROLL) { if (y >= headerSpanHeight) { setState(LOOSENT_O_REFRESH); } else { setState(PULLING); } } return intercept; } @Override public void onScrollChange(int state) { scrollState = state; } @Override public boolean onStartFling(float nowY) { float headerSpanHeight = getSpanHeight(); if (nowY >= headerSpanHeight) { pullRefreshLayout.startMoveTo(nowY, headerSpanHeight); setState(REFRESHING); return true; } pullRefreshLayout.startMoveTo(nowY, 0); setState(NONE); return false; } public abstract float getSpanHeight(); protected abstract void onStateChange(int state); public interface OnRefreshListener { void onRefresh(BaseHeaderView baseHeaderView); } public void setOnRefreshListener(OnRefreshListener onRefreshListener) { this.onRefreshListener = onRefreshListener; } }
apache-2.0
everttigchelaar/camel-svn
camel-core/src/main/java/org/apache/camel/util/concurrent/SubmitOrderedCompletionService.java
5415
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.util.concurrent; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.Executor; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * A {@link java.util.concurrent.CompletionService} that orders the completed tasks * in the same order as they where submitted. * * @version */ public class SubmitOrderedCompletionService<V> implements CompletionService<V> { private final Executor executor; // the idea to order the completed task in the same order as they where submitted is to leverage // the delay queue. With the delay queue we can control the order by the getDelay and compareTo methods // where we can order the tasks in the same order as they where submitted. private final DelayQueue<SubmitOrderFutureTask> completionQueue = new DelayQueue<SubmitOrderFutureTask>(); // id is the unique id that determines the order in which tasks was submitted (incrementing) private final AtomicInteger id = new AtomicInteger(); // index is the index of the next id that should expire and thus be ready to take from the delayed queue private final AtomicInteger index = new AtomicInteger(); private class SubmitOrderFutureTask extends FutureTask<V> implements Delayed { // the id this task was assigned private final long id; public SubmitOrderFutureTask(long id, Callable<V> voidCallable) { super(voidCallable); this.id = id; } public SubmitOrderFutureTask(long id, Runnable runnable, V result) { super(runnable, result); this.id = id; } public long getDelay(TimeUnit unit) { // if the answer is 0 then this task is ready to be taken return id - index.get(); } @SuppressWarnings("unchecked") public int compareTo(Delayed o) { SubmitOrderFutureTask other = (SubmitOrderFutureTask) o; return (int) (this.id - other.id); } @Override protected void done() { // when we are done add to the completion queue completionQueue.add(this); } @Override public String toString() { // output using zero-based index return "SubmitOrderedFutureTask[" + (id - 1) + "]"; } } public SubmitOrderedCompletionService(Executor executor) { this.executor = executor; } @SuppressWarnings("unchecked") public Future<V> submit(Callable task) { if (task == null) { throw new IllegalArgumentException("Task must be provided"); } SubmitOrderFutureTask f = new SubmitOrderFutureTask(id.incrementAndGet(), task); executor.execute(f); return f; } public Future<V> submit(Runnable task, Object result) { if (task == null) { throw new IllegalArgumentException("Task must be provided"); } SubmitOrderFutureTask f = new SubmitOrderFutureTask(id.incrementAndGet(), task, null); executor.execute(f); return f; } @SuppressWarnings("unchecked") public Future<V> take() throws InterruptedException { index.incrementAndGet(); return completionQueue.take(); } @SuppressWarnings("unchecked") public Future<V> poll() { index.incrementAndGet(); Future answer = completionQueue.poll(); if (answer == null) { // decrease counter if we didnt get any data index.decrementAndGet(); } return answer; } @SuppressWarnings("unchecked") public Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException { index.incrementAndGet(); Future answer = completionQueue.poll(timeout, unit); if (answer == null) { // decrease counter if we didnt get any data index.decrementAndGet(); } return answer; } /** * Marks the current task as timeout, which allows you to poll the next * tasks which may already have been completed. */ public void timeoutTask() { index.incrementAndGet(); } }
apache-2.0
android-art-intel/Nougat
art-extension/opttests/src/OptimizationTests/ShortMethodsInliningNonVirtualInvokes/InvokeStaticRangeAObjectThrowBoundSet_001/Foo.java
831
/* * Copyright (C) 2016 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package OptimizationTests.ShortMethodsInliningNonVirtualInvokes.InvokeStaticRangeAObjectThrowBoundSet_001; // The test checks that stack after ArrayIndexOutOffBouns Exception occurs is correct despite inlining class Foo { }
apache-2.0
MorpG/Java-course
package_2/chapter_005_pro/generic/src/main/java/ru/agolovin/Base.java
454
package ru.agolovin; /** * @author agolovin (agolovin@list.ru) * @version $Id$ * @since 0.1 */ public class Base { /** * Identification. */ private String id; /** * Get id. * * @return identification String. */ public String getId() { return id; } /** * Set identification. * * @param id String */ public void setId(String id) { this.id = id; } }
apache-2.0
LorenzReinhart/ONOSnew
apps/test/distributed-primitives/src/main/java/org/onosproject/distributedprimitives/cli/LeaderElectorTestCommand.java
2958
/* * Copyright 2016-present Open Networking Laboratory * * 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.onosproject.distributedprimitives.cli; import org.apache.karaf.shell.commands.Argument; import org.apache.karaf.shell.commands.Command; import org.onosproject.cli.AbstractShellCommand; import org.onosproject.cluster.ClusterService; import org.onosproject.cluster.Leadership; import org.onosproject.cluster.NodeId; import org.onosproject.distributedprimitives.DistributedPrimitivesTest; import org.onosproject.store.service.LeaderElector; import com.google.common.base.Joiner; @Command(scope = "onos", name = "leader-test", description = "LeaderElector test cli fixture") public class LeaderElectorTestCommand extends AbstractShellCommand { @Argument(index = 0, name = "name", description = "leader elector name", required = true, multiValued = false) String name = null; @Argument(index = 1, name = "operation", description = "operation", required = true, multiValued = false) String operation = null; @Argument(index = 2, name = "topic", description = "topic name", required = false, multiValued = false) String topic = null; LeaderElector leaderElector; @Override protected void execute() { ClusterService clusterService = get(ClusterService.class); DistributedPrimitivesTest test = get(DistributedPrimitivesTest.class); leaderElector = test.getLeaderElector(name); NodeId localNodeId = clusterService.getLocalNode().id(); if ("run".equals(operation)) { print(leaderElector.run(topic, localNodeId)); } else if ("withdraw".equals(operation)) { leaderElector.withdraw(topic); } else if ("show".equals(operation)) { print(leaderElector.getLeadership(topic)); } } private void print(Leadership leadership) { if (leadership.leader() != null) { print("leader=%s#term=%d#candidates=%s", leadership.leaderNodeId(), leadership.leader().term(), leadership.candidates().isEmpty() ? "none" : Joiner.on(",").join(leadership.candidates())); } else { print("leader=none#candidates=%s", leadership.candidates().isEmpty() ? "none" : Joiner.on(",").join(leadership.candidates())); } } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-directory/src/main/java/com/amazonaws/services/directory/model/transform/GetSnapshotLimitsResultJsonUnmarshaller.java
2874
/* * 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.directory.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.directory.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * GetSnapshotLimitsResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetSnapshotLimitsResultJsonUnmarshaller implements Unmarshaller<GetSnapshotLimitsResult, JsonUnmarshallerContext> { public GetSnapshotLimitsResult unmarshall(JsonUnmarshallerContext context) throws Exception { GetSnapshotLimitsResult getSnapshotLimitsResult = new GetSnapshotLimitsResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return getSnapshotLimitsResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("SnapshotLimits", targetDepth)) { context.nextToken(); getSnapshotLimitsResult.setSnapshotLimits(SnapshotLimitsJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return getSnapshotLimitsResult; } private static GetSnapshotLimitsResultJsonUnmarshaller instance; public static GetSnapshotLimitsResultJsonUnmarshaller getInstance() { if (instance == null) instance = new GetSnapshotLimitsResultJsonUnmarshaller(); return instance; } }
apache-2.0
JDrit/gossip-crdt
src/main/java/net/batchik/crdt/Main.java
5266
package net.batchik.crdt; import co.paralleluniverse.strands.Strand; import com.codahale.metrics.ConsoleReporter; import com.codahale.metrics.MetricRegistry; import net.batchik.crdt.fiber.FiberServer; import net.batchik.crdt.fiber.HttpRouter; import net.batchik.crdt.fiber.handlers.*; import net.batchik.crdt.gossip.GossipServer; import net.batchik.crdt.gossip.ParticipantStates; import net.batchik.crdt.gossip.Peer; import net.batchik.crdt.zookeeper.ZKServiceDiscovery; import org.apache.commons.cli.*; import org.apache.curator.x.discovery.*; import org.apache.log4j.Logger; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.TimeUnit; public class Main { private static final Logger log = Logger.getLogger(Main.class.getName()); private static final Options options = new Options(); private static final HelpFormatter formatter = new HelpFormatter(); private static final CommandLineParser parser = new DefaultParser(); private static final String VERSION = "1.0.0"; private static final int DEFAULT_GOSSIP_PORT = 5000; private static final int DEFAULT_FIBER_PORT = 8080; private static final int DEFAULT_GOSSIP_TIME = 5000; private static final String DEFAULT_SERVICE_NAME = "uvb-server"; public static final MetricRegistry metrics = new MetricRegistry(); static { options.addOption(Option.builder() .argName("zookeeper address") .hasArg() .desc("the address of the zookeeper instance for configuration") .longOpt("zk") .build()); options.addOption(Option.builder() .desc("should the gossip and web ports be random") .longOpt("random") .build()); options.addOption(Option.builder() .desc("print information about the system configuration options, and exit") .longOpt("help") .build()); options.addOption(Option.builder() .desc("print the version information and exit") .longOpt("version") .build()); } public static InetSocketAddress convertAddress(String address) { String[] split = address.split(":"); return new InetSocketAddress(split[0], Integer.parseInt(split[1])); } public static void main(String[] args) throws Exception { CommandLine cmd = parser.parse(options, args); ArrayList<Peer> peers = new ArrayList<>(); if (cmd.hasOption("help")) { formatter.printHelp("uvb-server", "Overview of argument flags", options, "**just remember this is a pre-alpha personal project**", true); System.exit(0); } if (cmd.hasOption("version")) { System.out.println("version: " + VERSION); System.exit(0); } if (!cmd.hasOption("zk")) { log.error("no zookeeper instance given, please specify with '--zk'"); System.exit(1); } int webPort = DEFAULT_FIBER_PORT; int gossipPort = DEFAULT_GOSSIP_PORT; if (cmd.hasOption("random")) { int min = 4000; int max = 5000; gossipPort = new Random().nextInt(max - min + 1) + min; webPort = gossipPort + 1000; } String zk = cmd.getOptionValue("zk"); InetAddress address = InetAddress.getLocalHost(); InetSocketAddress gossipAddress = new InetSocketAddress(address, gossipPort); InetSocketAddress webAddress = new InetSocketAddress("0.0.0.0", webPort); Peer self = new Peer(gossipAddress); ZKServiceDiscovery zkService = new ZKServiceDiscovery(zk, DEFAULT_SERVICE_NAME); zkService.start(); for (ServiceInstance<String> instance : zkService.getInstances()) { InetSocketAddress peerAddress = new InetSocketAddress(instance.getAddress(), instance.getPort()); log.info("adding peer at address: " + peerAddress); peers.add(new Peer(peerAddress)); } ParticipantStates states = new ParticipantStates(self, peers); zkService.register(address, gossipPort); zkService.addListener(states); log.info("instance registered"); log.info("self peer: " + self); log.info("starting peer with " + peers.size() + " other peer(s)"); log.info("gossipping on: " + gossipAddress); log.info("web requests on: " + webAddress); HttpRouter router = HttpRouter.builder() .registerEndpoint("/status", HttpMethod.GET, new StatusRequestHandler(self)) .registerEndpoint("/update/.*", HttpMethod.GET, new UpdateRequestHandler(self)) .registerEndpoint("/health", HttpMethod.GET, new HealthStatusRequestHandler(states)) .registerEndpoint("/ping", HttpMethod.GET, new PingRequestHandler()) .build(); Service fiberServer = new FiberServer(webAddress, router); fiberServer.start(); Service gossipServer = new GossipServer(states, DEFAULT_GOSSIP_TIME); gossipServer.start(); Strand.sleep(Long.MAX_VALUE, TimeUnit.DAYS); } }
apache-2.0
qibin0506/Glin
glinsample/src/main/java/org/loader/glinsample/utils/Net.java
1446
package org.loader.glinsample.utils; import android.os.Environment; import android.util.Log; import org.loader.glin.Glin; import org.loader.glin.cache.DefaultCacheProvider; import org.loader.glin.chan.GlobalChanNode; import org.loader.glin.chan.LogChanNode; import org.loader.glin.helper.LogHelper; import org.loader.okclient.OkClient; public class Net { private static final LogHelper.LogPrinter printer = new LogHelper.LogPrinter() { @Override public void print(String tag, String content) { Log.d(tag, content); } }; private static Glin glin; public static Glin get() { if (glin == null) { String cachePath = Environment.getExternalStorageDirectory() + "/cache"; LogChanNode beforeLog = new LogChanNode(true, printer); LogChanNode afterLog = new LogChanNode(true, printer); GlobalChanNode before = new GlobalChanNode(beforeLog); GlobalChanNode after = new GlobalChanNode(afterLog); glin = new Glin.Builder() .baseUrl("http://103.50.253.220:8891") .client(new OkClient()) .globalChanNode(before, after) .parserFactory(new Parsers()) .cacheProvider(new DefaultCacheProvider(cachePath, 1024*1024L)) .timeout(5000L) .build(); } return glin; } }
apache-2.0
junchenChow/exciting-app
app/src/main/java/me/vociegif/android/mvp/vo/StickerAdapt2Result.java
2131
package me.vociegif.android.mvp.vo; import java.io.Serializable; import java.util.List; public class StickerAdapt2Result implements Serializable { private List<StickerContentFull> list; private List<StickerCreator> adapts; private List<StickerFile> scenes; private List<StickerPaint> stickerlist; private List<EditorBean> fontlist; private String text; private int scenecount; private StickerHeader head; private int framecount; public List<StickerPaint> getStickerlist() { return stickerlist; } public void setStickerlist(List<StickerPaint> stickerlist) { this.stickerlist = stickerlist; } public int getFramecount() { return framecount; } public void setFramecount(int framecount) { this.framecount = framecount; } public List<EditorBean> getFontlist() { return fontlist; } public void setFontlist(List<EditorBean> fontlist) { this.fontlist = fontlist; } public StickerHeader getHead() { return head; } public void setHead(StickerHeader head) { this.head = head; } public List<StickerPaint> getStickerList() { return stickerlist; } public void setStickerList(List<StickerPaint> stickerlist) { this.stickerlist = stickerlist; } public List<StickerContentFull> getList() { return list; } public void setList(List<StickerContentFull> list) { this.list = list; } public List<StickerCreator> getAdapts() { return adapts; } public void setAdapts(List<StickerCreator> adapts) { this.adapts = adapts; } public List<StickerFile> getScenes() { return scenes; } public void setScenes(List<StickerFile> scenes) { this.scenes = scenes; } public String getText() { return text; } public void setText(String text) { this.text = text; } public int getScenecount() { return scenecount; } public void setScenecount(int scenecount) { this.scenecount = scenecount; } }
apache-2.0
JacekAmbroziak/Ambrosoft
src/main/java/com/ambrosoft/exercises/PatternMatching.java
4401
package com.ambrosoft.exercises; import java.util.Arrays; /** * Created by jacek on 4/13/16. */ public class PatternMatching { public static void main(String[] args) { System.out.println(matches("aabab", "catcatgocatgo")); // System.out.println(matches("a", "catcatgocatgo")); // System.out.println(matches("ab", "catcatgocatgo")); System.out.println(matches("aba", "catcatgocatgo")); } /* can substrings of value be assigned to 'a' & 'b' so pattern recreates value? need to see how many repetitions are called for 'catcatcatcat' should be matched by 'aaaa', 'abab', 'abaa' etc. */ static boolean matches(final String pattern, final String value) { System.out.println("pattern = " + pattern); System.out.println("value = " + value); final int plen = pattern.length(); if (plen == 0) { return false; } else if (plen == 1) { return true; // a or b matches entire string } else { final int vlen = value.length(); if (vlen == 0) { return true; // with a, b empty strings } else { final int aCount = letterCount(pattern, 'a'); final int bCount = plen - aCount; if (aCount == 0) { return checkSimple(pattern, value, bCount); } else if (bCount == 0) { return checkSimple(pattern, value, aCount); } else { return pairs(vlen, aCount, bCount, pattern, value); } } } } private static boolean checkSimple(String pattern, String value, int bCount) { if (value.length() % bCount == 0) { int[] lengths = new int[bCount]; Arrays.fill(lengths, value.length() % bCount); return checkMatch(value, lengths); } return false; } private static int[] mapIntoLengths(final String pattern, final int aLen, final int bLen) { final int plen = pattern.length(); final int[] result = new int[plen]; for (int i = 0; i < plen; i++) { result[i] = pattern.charAt(i) == 'a' ? aLen : -bLen; } return result; } private static int letterCount(final String pattern, final char c) { int count = 0; for (int i = pattern.length(); --i >= 0; ) { if (pattern.charAt(i) == c) { ++count; } } return count; } private static boolean pairs(final int vlen, final int aCount, final int bCount, String pattern, String value) { for (int aLen = 0; ; ++aLen) { final int bs = vlen - aCount * aLen; if (bs < 0) { return false; } else { if (bs % bCount == 0) { final int bLen = bs / bCount; System.out.println("aLen = " + aLen + "\tbLen = " + bLen); int[] lengths = mapIntoLengths(pattern, aLen, bLen); if (checkMatch(value, lengths)) { System.out.println("matches "); return true; } } } } } private static boolean checkMatch(final String value, final int[] lengths) { String a = null; String b = null; int start = 0; for (final int length : lengths) { if (length == 0) { // ignore } else if (length > 0) { // a final String sub = value.substring(start, start + length); if (a == null) { a = sub; } else if (a.equals(sub)) { // good } else { return false; } start += length; } else { // b final String sub = value.substring(start, start - length); if (b == null) { b = sub; } else if (b.equals(sub)) { // good } else { return false; } start -= length; } } System.out.println("a = " + a); System.out.println("b = " + b); return true; } }
apache-2.0
ecarm002/incubator-asterixdb
asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/util/FunctionUtil.java
10528
/* * 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.lang.common.util; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import org.apache.asterix.common.exceptions.CompilationException; import org.apache.asterix.common.exceptions.ErrorCode; import org.apache.asterix.common.functions.FunctionConstants; import org.apache.asterix.common.functions.FunctionSignature; import org.apache.asterix.lang.common.base.Expression; import org.apache.asterix.lang.common.base.IQueryRewriter; import org.apache.asterix.lang.common.expression.CallExpr; import org.apache.asterix.lang.common.expression.LiteralExpr; import org.apache.asterix.lang.common.statement.FunctionDecl; import org.apache.asterix.metadata.MetadataManager; import org.apache.asterix.metadata.MetadataTransactionContext; import org.apache.asterix.metadata.declared.MetadataProvider; import org.apache.asterix.metadata.entities.Function; import org.apache.asterix.metadata.utils.DatasetUtil; import org.apache.asterix.om.functions.BuiltinFunctions; import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException; import org.apache.hyracks.algebricks.common.utils.Pair; import org.apache.hyracks.algebricks.core.algebra.functions.AlgebricksBuiltinFunctions; import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier; import org.apache.hyracks.algebricks.core.algebra.functions.IFunctionInfo; import org.apache.hyracks.api.exceptions.SourceLocation; public class FunctionUtil { public static final String IMPORT_PRIVATE_FUNCTIONS = "import-private-functions"; public static IFunctionInfo getFunctionInfo(FunctionIdentifier fi) { return BuiltinFunctions.getAsterixFunctionInfo(fi); } public static IFunctionInfo getFunctionInfo(FunctionSignature fs) { return getFunctionInfo(new FunctionIdentifier(fs.getNamespace(), fs.getName(), fs.getArity())); } @FunctionalInterface public interface IFunctionCollector { Set<CallExpr> getFunctionCalls(Expression expression) throws CompilationException; } @FunctionalInterface public interface IFunctionParser { FunctionDecl getFunctionDecl(Function function) throws CompilationException; } @FunctionalInterface public interface IFunctionNormalizer { FunctionSignature normalizeBuiltinFunctionSignature(FunctionSignature fs, SourceLocation sourceLoc) throws CompilationException; } /** * Retrieve stored functions (from CREATE FUNCTION statements) that have been * used in an expression. * * @param metadataProvider, * the metadata provider * @param expression, * the expression for analysis * @param declaredFunctions, * a set of declared functions in the query, which can potentially * override stored functions. * @param functionCollector, * for collecting function calls in the <code>expression</code> * @param functionParser, * for parsing stored functions in the string represetnation. * @param functionNormalizer, * for normalizing function names. * @throws CompilationException */ public static List<FunctionDecl> retrieveUsedStoredFunctions(MetadataProvider metadataProvider, Expression expression, List<FunctionSignature> declaredFunctions, List<FunctionDecl> inputFunctionDecls, IFunctionCollector functionCollector, IFunctionParser functionParser, IFunctionNormalizer functionNormalizer) throws CompilationException { List<FunctionDecl> functionDecls = inputFunctionDecls == null ? new ArrayList<>() : new ArrayList<>(inputFunctionDecls); if (expression == null) { return functionDecls; } String value = (String) metadataProvider.getConfig().get(FunctionUtil.IMPORT_PRIVATE_FUNCTIONS); boolean includePrivateFunctions = (value != null) ? Boolean.valueOf(value.toLowerCase()) : false; Set<CallExpr> functionCalls = functionCollector.getFunctionCalls(expression); for (CallExpr functionCall : functionCalls) { FunctionSignature signature = functionCall.getFunctionSignature(); if (declaredFunctions != null && declaredFunctions.contains(signature)) { continue; } if (signature.getNamespace() == null) { signature.setNamespace(metadataProvider.getDefaultDataverseName()); } String namespace = signature.getNamespace(); // Checks the existence of the referred dataverse. try { if (!namespace.equals(FunctionConstants.ASTERIX_NS) && !namespace.equals(AlgebricksBuiltinFunctions.ALGEBRICKS_NS) && metadataProvider.findDataverse(namespace) == null) { throw new CompilationException(ErrorCode.COMPILATION_ERROR, functionCall.getSourceLocation(), "In function call \"" + namespace + "." + signature.getName() + "(...)\", the dataverse \"" + namespace + "\" cannot be found!"); } } catch (AlgebricksException e) { throw new CompilationException(e); } Function function; try { function = lookupUserDefinedFunctionDecl(metadataProvider.getMetadataTxnContext(), signature); } catch (AlgebricksException e) { throw new CompilationException(e); } if (function == null) { FunctionSignature normalizedSignature = functionNormalizer == null ? signature : functionNormalizer.normalizeBuiltinFunctionSignature(signature, functionCall.getSourceLocation()); if (BuiltinFunctions.isBuiltinCompilerFunction(normalizedSignature, includePrivateFunctions)) { continue; } StringBuilder messageBuilder = new StringBuilder(); if (!functionDecls.isEmpty()) { messageBuilder.append("function " + functionDecls.get(functionDecls.size() - 1).getSignature() + " depends upon function " + signature + " which is undefined"); } else { messageBuilder.append("function " + signature + " is not defined"); } throw new CompilationException(ErrorCode.COMPILATION_ERROR, functionCall.getSourceLocation(), messageBuilder.toString()); } if (function.getLanguage().equalsIgnoreCase(Function.LANGUAGE_AQL) || function.getLanguage().equalsIgnoreCase(Function.LANGUAGE_SQLPP)) { FunctionDecl functionDecl = functionParser.getFunctionDecl(function); if (functionDecl != null) { if (functionDecls.contains(functionDecl)) { throw new CompilationException(ErrorCode.COMPILATION_ERROR, functionCall.getSourceLocation(), "Recursive invocation " + functionDecls.get(functionDecls.size() - 1).getSignature() + " <==> " + functionDecl.getSignature()); } functionDecls.add(functionDecl); functionDecls = retrieveUsedStoredFunctions(metadataProvider, functionDecl.getFuncBody(), declaredFunctions, functionDecls, functionCollector, functionParser, functionNormalizer); } } } return functionDecls; } public static List<List<List<String>>> getFunctionDependencies(IQueryRewriter rewriter, Expression expression, MetadataProvider metadataProvider) throws CompilationException { Set<CallExpr> functionCalls = rewriter.getFunctionCalls(expression); //Get the List of used functions and used datasets List<List<String>> datasourceDependencies = new ArrayList<>(); List<List<String>> functionDependencies = new ArrayList<>(); for (CallExpr functionCall : functionCalls) { FunctionSignature signature = functionCall.getFunctionSignature(); FunctionIdentifier fid = new FunctionIdentifier(signature.getNamespace(), signature.getName(), signature.getArity()); if (fid.equals(BuiltinFunctions.DATASET)) { Pair<String, String> path = DatasetUtil.getDatasetInfo(metadataProvider, ((LiteralExpr) functionCall.getExprList().get(0)).getValue().getStringValue()); datasourceDependencies.add(Arrays.asList(path.first, path.second)); } else if (BuiltinFunctions.isBuiltinCompilerFunction(signature, false)) { continue; } else { functionDependencies.add(Arrays.asList(signature.getNamespace(), signature.getName(), Integer.toString(signature.getArity()))); } } List<List<List<String>>> dependencies = new ArrayList<>(); dependencies.add(datasourceDependencies); dependencies.add(functionDependencies); return dependencies; } private static Function lookupUserDefinedFunctionDecl(MetadataTransactionContext mdTxnCtx, FunctionSignature signature) throws AlgebricksException { if (signature.getNamespace() == null) { return null; } return MetadataManager.INSTANCE.getFunction(mdTxnCtx, signature); } }
apache-2.0
termMed/rf2-to-owl
src/com/termmed/owl/OWLFunctionalSyntaxRefsetRenderer.java
1543
/* * * * Copyright (C) 2014 termMed IT * * www.termmed.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.termmed.owl; import org.semanticweb.owlapi.io.AbstractOWLRenderer; import org.semanticweb.owlapi.io.OWLRendererException; import org.semanticweb.owlapi.io.OWLRendererIOException; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLRuntimeException; import java.io.PrintWriter; /** * Created by alo on 4/17/17. */ public class OWLFunctionalSyntaxRefsetRenderer extends AbstractOWLRenderer { @Override public void render(OWLOntology ontology, PrintWriter writer) throws OWLRendererException { try { OWLFuncionalSyntaxRefsetObjectRenderer ren = new OWLFuncionalSyntaxRefsetObjectRenderer(ontology, writer); ontology.accept(ren); writer.flush(); } catch (OWLRuntimeException e) { throw new OWLRendererIOException(e); } } }
apache-2.0
fivesmallq/diffbot-java
src/main/java/im/nll/data/diffbot/processor/ArticleProcessor.java
695
package im.nll.data.diffbot.processor; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import im.nll.data.diffbot.model.Article; /** * @author <a href="mailto:fivesmallq@gmail.com">fivesmallq</a> * @version Revision: 1.0 * @date 16/6/28 下午6:09 */ public class ArticleProcessor implements Processor<Article> { @Override public Article process(String html) { JSONObject jsonObject = JSON.parseObject(html); JSONArray jsonArray = jsonObject.getJSONArray("objects"); if (!jsonArray.isEmpty()) { return jsonArray.getObject(0, Article.class); } return null; } }
apache-2.0
ModernMT/MMT
src/commons/src/main/java/eu/modernmt/lang/LanguageRule.java
551
package eu.modernmt.lang; class LanguageRule { private final LanguagePattern pattern; private final Language outputLanguage; public LanguageRule(LanguagePattern pattern, Language outputLanguage) { this.pattern = pattern; this.outputLanguage = outputLanguage; } public String getLanguage() { return pattern.getLanguage(); } public boolean match(Language language) { return pattern.match(language); } public Language getOutputLanguage() { return outputLanguage; } }
apache-2.0
vzhukovskyi/kaa
examples/robotrun/robotrun-shared/src/test/java/org/kaaproject/kaa/examples/robotrun/labyrinth/BasicLabyrinthGeneratorTest.java
2490
/* * Copyright 2014 CyberVision, 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. */ /** * Copyright 2014 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaaproject.kaa.examples.robotrun.labyrinth; import org.junit.Assert; import org.junit.Test; import org.kaaproject.kaa.examples.robotrun.labyrinth.impl.BasicLabyrinthGenerator; public class BasicLabyrinthGeneratorTest { @Test public void testLabyrinthGeneration() { int height = 4; int width = 3; LabyrinthGenerator generator = new BasicLabyrinthGenerator(width, height); Labyrinth labyrinth = generator.generate(0, 0, width - 1, height - 1); Cell startCell = labyrinth.getCell(0, 0); Assert.assertTrue(startCell.getBorder(Direction.WEST) == BorderType.SOLID); Assert.assertTrue(startCell.getBorder(Direction.NORTH) == BorderType.SOLID); Assert.assertTrue(startCell.getBorder(Direction.SOUTH) == BorderType.FREE || startCell.getBorder(Direction.EAST) == BorderType.FREE); Cell finishCell = labyrinth.getCell(width - 1, height - 1); Assert.assertTrue(finishCell.getBorder(Direction.EAST) == BorderType.FREE); Assert.assertTrue(finishCell.getBorder(Direction.SOUTH) == BorderType.SOLID); Assert.assertTrue(finishCell.getBorder(Direction.NORTH) == BorderType.FREE || finishCell.getBorder(Direction.WEST) == BorderType.FREE); } }
apache-2.0
kevinearls/camel
components/camel-aws/src/main/java/org/apache/camel/component/aws/lambda/LambdaProducer.java
22803
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.aws.lambda; import java.io.File; import java.io.FileInputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.lambda.AWSLambda; import com.amazonaws.services.lambda.model.CreateEventSourceMappingRequest; import com.amazonaws.services.lambda.model.CreateEventSourceMappingResult; import com.amazonaws.services.lambda.model.CreateFunctionRequest; import com.amazonaws.services.lambda.model.CreateFunctionResult; import com.amazonaws.services.lambda.model.DeadLetterConfig; import com.amazonaws.services.lambda.model.DeleteEventSourceMappingRequest; import com.amazonaws.services.lambda.model.DeleteEventSourceMappingResult; import com.amazonaws.services.lambda.model.DeleteFunctionRequest; import com.amazonaws.services.lambda.model.DeleteFunctionResult; import com.amazonaws.services.lambda.model.Environment; import com.amazonaws.services.lambda.model.FunctionCode; import com.amazonaws.services.lambda.model.GetFunctionRequest; import com.amazonaws.services.lambda.model.GetFunctionResult; import com.amazonaws.services.lambda.model.InvokeRequest; import com.amazonaws.services.lambda.model.InvokeResult; import com.amazonaws.services.lambda.model.ListEventSourceMappingsRequest; import com.amazonaws.services.lambda.model.ListEventSourceMappingsResult; import com.amazonaws.services.lambda.model.ListFunctionsResult; import com.amazonaws.services.lambda.model.TracingConfig; import com.amazonaws.services.lambda.model.UpdateFunctionCodeRequest; import com.amazonaws.services.lambda.model.UpdateFunctionCodeResult; import com.amazonaws.services.lambda.model.VpcConfig; import com.amazonaws.util.IOUtils; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.support.DefaultProducer; import org.apache.camel.util.CastUtils; import org.apache.camel.util.ObjectHelper; import static org.apache.camel.component.aws.common.AwsExchangeUtil.getMessageForResponse; /** * A Producer which sends messages to the Amazon Web Service Lambda <a * href="https://aws.amazon.com/lambda/">AWS Lambda</a> */ public class LambdaProducer extends DefaultProducer { public LambdaProducer(final Endpoint endpoint) { super(endpoint); } @Override public void process(final Exchange exchange) throws Exception { switch (determineOperation(exchange)) { case getFunction: getFunction(getEndpoint().getAwsLambdaClient(), exchange); break; case createFunction: createFunction(getEndpoint().getAwsLambdaClient(), exchange); break; case deleteFunction: deleteFunction(getEndpoint().getAwsLambdaClient(), exchange); break; case invokeFunction: invokeFunction(getEndpoint().getAwsLambdaClient(), exchange); break; case listFunctions: listFunctions(getEndpoint().getAwsLambdaClient(), exchange); break; case updateFunction: updateFunction(getEndpoint().getAwsLambdaClient(), exchange); break; case createEventSourceMapping: createEventSourceMapping(getEndpoint().getAwsLambdaClient(), exchange); break; case deleteEventSourceMapping: deleteEventSourceMapping(getEndpoint().getAwsLambdaClient(), exchange); break; case listEventSourceMapping: listEventSourceMapping(getEndpoint().getAwsLambdaClient(), exchange); break; default: throw new IllegalArgumentException("Unsupported operation"); } } private void getFunction(AWSLambda lambdaClient, Exchange exchange) { GetFunctionResult result; try { result = lambdaClient.getFunction(new GetFunctionRequest().withFunctionName(getConfiguration().getFunction())); } catch (AmazonServiceException ase) { log.trace("getFunction command returned the error code {}", ase.getErrorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } private void deleteFunction(AWSLambda lambdaClient, Exchange exchange) { DeleteFunctionResult result; try { result = lambdaClient.deleteFunction(new DeleteFunctionRequest().withFunctionName(getConfiguration().getFunction())); } catch (AmazonServiceException ase) { log.trace("deleteFunction command returned the error code {}", ase.getErrorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } private void listFunctions(AWSLambda lambdaClient, Exchange exchange) { ListFunctionsResult result; try { result = lambdaClient.listFunctions(); } catch (AmazonServiceException ase) { log.trace("listFunctions command returned the error code {}", ase.getErrorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } private void invokeFunction(AWSLambda lambdaClient, Exchange exchange) { InvokeResult result; try { InvokeRequest request = new InvokeRequest() .withFunctionName(getConfiguration().getFunction()) .withPayload(exchange.getIn().getBody(String.class)); result = lambdaClient.invoke(request); } catch (AmazonServiceException ase) { log.trace("invokeFunction command returned the error code {}", ase.getErrorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(StandardCharsets.UTF_8.decode(result.getPayload()).toString()); } private void createFunction(AWSLambda lambdaClient, Exchange exchange) throws Exception { CreateFunctionResult result; try { CreateFunctionRequest request = new CreateFunctionRequest() .withFunctionName(getConfiguration().getFunction()); FunctionCode functionCode = new FunctionCode(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.S3_BUCKET))) { String s3Bucket = exchange.getIn().getHeader(LambdaConstants.S3_BUCKET, String.class); functionCode.withS3Bucket(s3Bucket); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.S3_KEY))) { String s3Key = exchange.getIn().getHeader(LambdaConstants.S3_KEY, String.class); functionCode.withS3Key(s3Key); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.S3_OBJECT_VERSION))) { String s3ObjectVersion = exchange.getIn().getHeader(LambdaConstants.S3_OBJECT_VERSION, String.class); functionCode.withS3ObjectVersion(s3ObjectVersion); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.ZIP_FILE))) { String zipFile = exchange.getIn().getHeader(LambdaConstants.ZIP_FILE, String.class); File fileLocalPath = new File(zipFile); FileInputStream inputStream = new FileInputStream(fileLocalPath); functionCode.withZipFile(ByteBuffer.wrap(IOUtils.toByteArray(inputStream))); } if (ObjectHelper.isNotEmpty(exchange.getIn().getBody())) { functionCode.withZipFile(exchange.getIn().getBody(ByteBuffer.class)); } if (ObjectHelper.isNotEmpty(exchange.getIn().getBody()) || (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.S3_BUCKET)) && ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.S3_KEY)))) { request.withCode(functionCode); } else { throw new IllegalArgumentException("At least S3 bucket/S3 key or zip file must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.ROLE))) { request.withRole(exchange.getIn().getHeader(LambdaConstants.ROLE, String.class)); } else { throw new IllegalArgumentException("Role must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.RUNTIME))) { request.withRuntime(exchange.getIn().getHeader(LambdaConstants.RUNTIME, String.class)); } else { throw new IllegalArgumentException("Runtime must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.HANDLER))) { request.withHandler(exchange.getIn().getHeader(LambdaConstants.HANDLER, String.class)); } else { throw new IllegalArgumentException("Handler must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.DESCRIPTION))) { String description = exchange.getIn().getHeader(LambdaConstants.DESCRIPTION, String.class); request.withDescription(description); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.TARGET_ARN))) { String targetArn = exchange.getIn().getHeader(LambdaConstants.TARGET_ARN, String.class); request.withDeadLetterConfig(new DeadLetterConfig().withTargetArn(targetArn)); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.MEMORY_SIZE))) { Integer memorySize = exchange.getIn().getHeader(LambdaConstants.MEMORY_SIZE, Integer.class); request.withMemorySize(memorySize); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.KMS_KEY_ARN))) { String kmsKeyARN = exchange.getIn().getHeader(LambdaConstants.KMS_KEY_ARN, String.class); request.withKMSKeyArn(kmsKeyARN); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.PUBLISH))) { Boolean publish = exchange.getIn().getHeader(LambdaConstants.PUBLISH, Boolean.class); request.withPublish(publish); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.TIMEOUT))) { Integer timeout = exchange.getIn().getHeader(LambdaConstants.TIMEOUT, Integer.class); request.withTimeout(timeout); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.TRACING_CONFIG))) { String tracingConfigMode = exchange.getIn().getHeader(LambdaConstants.TRACING_CONFIG, String.class); request.withTracingConfig(new TracingConfig().withMode(tracingConfigMode)); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.SDK_CLIENT_EXECUTION_TIMEOUT))) { Integer timeout = exchange.getIn().getHeader(LambdaConstants.SDK_CLIENT_EXECUTION_TIMEOUT, Integer.class); request.withSdkClientExecutionTimeout(timeout); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.SDK_REQUEST_TIMEOUT))) { Integer timeout = exchange.getIn().getHeader(LambdaConstants.SDK_REQUEST_TIMEOUT, Integer.class); request.withSdkRequestTimeout(timeout); } Map<String, String> environmentVariables = CastUtils.cast(exchange.getIn().getHeader(LambdaConstants.ENVIRONMENT_VARIABLES, Map.class)); if (environmentVariables != null) { request.withEnvironment(new Environment().withVariables(environmentVariables)); } Map<String, String> tags = CastUtils.cast(exchange.getIn().getHeader(LambdaConstants.TAGS, Map.class)); if (tags != null) { request.withTags(tags); } List<String> securityGroupIds = CastUtils.cast(exchange.getIn().getHeader(LambdaConstants.SECURITY_GROUP_IDS, (Class<List<String>>) (Object) List.class)); List<String> subnetIds = CastUtils.cast(exchange.getIn().getHeader(LambdaConstants.SUBNET_IDS, (Class<List<String>>) (Object) List.class)); if (securityGroupIds != null || subnetIds != null) { VpcConfig vpcConfig = new VpcConfig(); if (securityGroupIds != null) { vpcConfig.withSecurityGroupIds(securityGroupIds); } if (subnetIds != null) { vpcConfig.withSubnetIds(subnetIds); } request.withVpcConfig(vpcConfig); } result = lambdaClient.createFunction(request); } catch (AmazonServiceException ase) { log.trace("createFunction command returned the error code {}", ase.getErrorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } private void updateFunction(AWSLambda lambdaClient, Exchange exchange) throws Exception { UpdateFunctionCodeResult result; try { UpdateFunctionCodeRequest request = new UpdateFunctionCodeRequest() .withFunctionName(getConfiguration().getFunction()); FunctionCode functionCode = new FunctionCode(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.S3_BUCKET))) { String s3Bucket = exchange.getIn().getHeader(LambdaConstants.S3_BUCKET, String.class); functionCode.withS3Bucket(s3Bucket); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.S3_KEY))) { String s3Key = exchange.getIn().getHeader(LambdaConstants.S3_KEY, String.class); functionCode.withS3Key(s3Key); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.S3_OBJECT_VERSION))) { String s3ObjectVersion = exchange.getIn().getHeader(LambdaConstants.S3_OBJECT_VERSION, String.class); functionCode.withS3ObjectVersion(s3ObjectVersion); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.ZIP_FILE))) { String zipFile = exchange.getIn().getHeader(LambdaConstants.ZIP_FILE, String.class); File fileLocalPath = new File(zipFile); FileInputStream inputStream = new FileInputStream(fileLocalPath); functionCode.withZipFile(ByteBuffer.wrap(IOUtils.toByteArray(inputStream))); } if (ObjectHelper.isNotEmpty(exchange.getIn().getBody())) { functionCode.withZipFile(exchange.getIn().getBody(ByteBuffer.class)); } if (ObjectHelper.isEmpty(exchange.getIn().getBody()) && (ObjectHelper.isEmpty(exchange.getIn().getHeader(LambdaConstants.S3_BUCKET)) && ObjectHelper.isEmpty(exchange.getIn().getHeader(LambdaConstants.S3_KEY)))) { throw new IllegalArgumentException("At least S3 bucket/S3 key or zip file must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.PUBLISH))) { Boolean publish = exchange.getIn().getHeader(LambdaConstants.PUBLISH, Boolean.class); request.withPublish(publish); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.SDK_CLIENT_EXECUTION_TIMEOUT))) { Integer timeout = exchange.getIn().getHeader(LambdaConstants.SDK_CLIENT_EXECUTION_TIMEOUT, Integer.class); request.withSdkClientExecutionTimeout(timeout); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.SDK_REQUEST_TIMEOUT))) { Integer timeout = exchange.getIn().getHeader(LambdaConstants.SDK_REQUEST_TIMEOUT, Integer.class); request.withSdkRequestTimeout(timeout); } result = lambdaClient.updateFunctionCode(request); } catch (AmazonServiceException ase) { log.trace("updateFunction command returned the error code {}", ase.getErrorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } private void createEventSourceMapping(AWSLambda lambdaClient, Exchange exchange) { CreateEventSourceMappingResult result; try { CreateEventSourceMappingRequest request = new CreateEventSourceMappingRequest().withFunctionName(getConfiguration().getFunction()); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.EVENT_SOURCE_ARN))) { request.withEventSourceArn(exchange.getIn().getHeader(LambdaConstants.EVENT_SOURCE_ARN, String.class)); } else { throw new IllegalArgumentException("Event Source Arn must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.EVENT_SOURCE_BATCH_SIZE))) { Integer batchSize = exchange.getIn().getHeader(LambdaConstants.EVENT_SOURCE_BATCH_SIZE, Integer.class); request.withBatchSize(batchSize); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.SDK_CLIENT_EXECUTION_TIMEOUT))) { Integer timeout = exchange.getIn().getHeader(LambdaConstants.SDK_CLIENT_EXECUTION_TIMEOUT, Integer.class); request.withSdkClientExecutionTimeout(timeout); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.SDK_REQUEST_TIMEOUT))) { Integer timeout = exchange.getIn().getHeader(LambdaConstants.SDK_REQUEST_TIMEOUT, Integer.class); request.withSdkRequestTimeout(timeout); } result = lambdaClient.createEventSourceMapping(request); } catch (AmazonServiceException ase) { log.trace("createEventSourceMapping command returned the error code {}", ase.getErrorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } private void deleteEventSourceMapping(AWSLambda lambdaClient, Exchange exchange) { DeleteEventSourceMappingResult result; try { DeleteEventSourceMappingRequest request = new DeleteEventSourceMappingRequest(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.EVENT_SOURCE_UUID))) { request.withUUID(exchange.getIn().getHeader(LambdaConstants.EVENT_SOURCE_UUID, String.class)); } else { throw new IllegalArgumentException("Event Source Arn must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.SDK_CLIENT_EXECUTION_TIMEOUT))) { Integer timeout = exchange.getIn().getHeader(LambdaConstants.SDK_CLIENT_EXECUTION_TIMEOUT, Integer.class); request.withSdkClientExecutionTimeout(timeout); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.SDK_REQUEST_TIMEOUT))) { Integer timeout = exchange.getIn().getHeader(LambdaConstants.SDK_REQUEST_TIMEOUT, Integer.class); request.withSdkRequestTimeout(timeout); } result = lambdaClient.deleteEventSourceMapping(request); } catch (AmazonServiceException ase) { log.trace("deleteEventSourceMapping command returned the error code {}", ase.getErrorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } private void listEventSourceMapping(AWSLambda lambdaClient, Exchange exchange) { ListEventSourceMappingsResult result; try { ListEventSourceMappingsRequest request = new ListEventSourceMappingsRequest().withFunctionName(getConfiguration().getFunction()); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.SDK_CLIENT_EXECUTION_TIMEOUT))) { Integer timeout = exchange.getIn().getHeader(LambdaConstants.SDK_CLIENT_EXECUTION_TIMEOUT, Integer.class); request.withSdkClientExecutionTimeout(timeout); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(LambdaConstants.SDK_REQUEST_TIMEOUT))) { Integer timeout = exchange.getIn().getHeader(LambdaConstants.SDK_REQUEST_TIMEOUT, Integer.class); request.withSdkRequestTimeout(timeout); } result = lambdaClient.listEventSourceMappings(request); } catch (AmazonServiceException ase) { log.trace("listEventSourceMapping command returned the error code {}", ase.getErrorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } private LambdaOperations determineOperation(Exchange exchange) { LambdaOperations operation = exchange.getIn().getHeader(LambdaConstants.OPERATION, LambdaOperations.class); if (operation == null) { operation = getConfiguration().getOperation(); } return operation; } protected LambdaConfiguration getConfiguration() { return getEndpoint().getConfiguration(); } @Override public LambdaEndpoint getEndpoint() { return (LambdaEndpoint) super.getEndpoint(); } }
apache-2.0
google/vr180
java/com/google/vr180/api/camerainterfaces/FileChecksumProvider.java
1174
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.vr180.api.camerainterfaces; import com.google.vr180.CameraApi.FileChecksum; import java.io.IOException; /** * Interface that helps computing file checksums. */ public interface FileChecksumProvider { /** * Gets the checksum of a file. * If possible, the checksum should be precomputed for media items. If precomputation isn't * possible, the checksum should be cached. * @throws IOException If there is an error accessing the file (it's not found or cannot be * opened). */ FileChecksum getFileChecksum(String path) throws IOException; }
apache-2.0
adam-roughton/Concentus
Core/src/test/java/com/adamroughton/concentus/data/TestChunkContent.java
943
package com.adamroughton.concentus.data; import org.junit.Test; public abstract class TestChunkContent { @Test public void empty() { testWith(); } @Test public void singleChunk() { testWith(chunk(100)); } @Test public void singleZeroLengthChunk() { testWith(chunk(0)); } @Test public void multiChunk() { testWith(chunk(25), chunk(16), chunk(8)); } @Test public void multiChunkWithZeroContentSegments() { testWith(chunk(90), chunk(0), chunk(5)); } @Test public void multiChunkWithZeroAtEnd() { testWith(chunk(100), chunk(8), chunk(0)); } protected abstract void testWith(Chunk...chunks); protected Chunk chunk(int length) { return chunk(length, new byte[length]); } protected Chunk chunk(int length, byte[] content) { Chunk c = new Chunk(); c.length = length; c.content = content; return c; } protected static class Chunk { public int length; public byte[] content; } }
apache-2.0
phac-nml/irida
src/main/java/ca/corefacility/bioinformatics/irida/config/security/IridaOauthSecurityConfig.java
10244
package ca.corefacility.bioinformatics.irida.config.security; import ca.corefacility.bioinformatics.irida.web.controller.api.exception.CustomOAuth2ExceptionTranslator; import ca.corefacility.bioinformatics.irida.web.filter.UnauthenticatedAnonymousAuthenticationFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.*; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.ClientDetailsService; import org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService; import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices; import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices; import org.springframework.security.oauth2.provider.error.AbstractOAuth2SecurityExceptionHandler; import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint; import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.web.context.SecurityContextPersistenceFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; /** * Configuration for REST API security using OAuth2 */ @Configuration public class IridaOauthSecurityConfig { private static final Logger logger = LoggerFactory.getLogger(IridaOauthSecurityConfig.class); @Bean @Primary public ResourceServerTokenServices tokenServices(@Qualifier("clientDetails") ClientDetailsService clientDetails, @Qualifier("iridaTokenStore") TokenStore tokenStore) { DefaultTokenServices services = new DefaultTokenServices(); services.setTokenStore(tokenStore); services.setSupportRefreshToken(true); services.setClientDetailsService(clientDetails); return services; } @Bean public ClientDetailsUserDetailsService clientDetailsUserDetailsService( @Qualifier("clientDetails") ClientDetailsService clientDetails) { ClientDetailsUserDetailsService clientDetailsUserDetailsService = new ClientDetailsUserDetailsService( clientDetails); return clientDetailsUserDetailsService; } @Bean public WebResponseExceptionTranslator<OAuth2Exception> exceptionTranslator() { return new CustomOAuth2ExceptionTranslator(); } /** * Class for configuring the OAuth resource server security */ @Configuration @EnableResourceServer @ComponentScan(basePackages = "ca.corefacility.bioinformatics.irida.repositories.remote") @Order(Ordered.HIGHEST_PRECEDENCE + 2) protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { @Autowired private ResourceServerTokenServices tokenServices; @Autowired private WebResponseExceptionTranslator<OAuth2Exception> exceptionTranslator; @Override public void configure(final ResourceServerSecurityConfigurer resources) { resources.resourceId("NmlIrida").tokenServices(tokenServices); forceExceptionTranslator(resources, exceptionTranslator); } @Override public void configure(final HttpSecurity httpSecurity) throws Exception { httpSecurity.antMatcher("/api/**").authorizeRequests().regexMatchers(HttpMethod.GET, "/api.*") .access("#oauth2.hasScope('read')").regexMatchers("/api.*") .access("#oauth2.hasScope('read') and #oauth2.hasScope('write')"); httpSecurity.antMatcher("/api/**").headers().frameOptions().disable(); httpSecurity.antMatcher("/api/**").csrf() .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/api/oauth/authorize")).disable(); httpSecurity.antMatcher("/api/**").csrf().disable(); // SecurityContextPersistenceFilter appears pretty high up (well // before any OAuth related filters), so we'll put our anonymous // user filter into the filter chain after that. httpSecurity.antMatcher("/api/**").addFilterAfter( new UnauthenticatedAnonymousAuthenticationFilter("anonymousTokenAuthProvider"), SecurityContextPersistenceFilter.class); } } /** * Class for configuring the OAuth authorization server */ @Configuration @EnableAuthorizationServer protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Autowired @Qualifier("clientDetails") private ClientDetailsService clientDetailsService; @Autowired @Qualifier("iridaTokenStore") private TokenStore tokenStore; @Autowired @Qualifier("userAuthenticationManager") private AuthenticationManager authenticationManager; @Autowired private WebResponseExceptionTranslator<OAuth2Exception> exceptionTranslator; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.withClientDetails(clientDetailsService); } @Autowired private ResourceServerTokenServices tokenServices; @Override public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(tokenStore); endpoints.authenticationManager(authenticationManager); endpoints.authorizationCodeServices(authorizationCodeServices()); endpoints.pathMapping("/oauth/token", "/api/oauth/token").allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); endpoints.pathMapping("/oauth/check_token", "/api/oauth/check_token"); endpoints.pathMapping("/oauth/confirm_access", "/api/oauth/confirm_access"); endpoints.pathMapping("/oauth/error", "/api/oauth/error"); endpoints.pathMapping("/oauth/authorize", "/api/oauth/authorize"); endpoints.tokenServices((DefaultTokenServices) tokenServices); endpoints.exceptionTranslator(exceptionTranslator); } @Override public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()") .allowFormAuthenticationForClients(); oauthServer.passwordEncoder(new PasswordEncoder() { @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return rawPassword.equals(encodedPassword); } @Override public String encode(CharSequence rawPassword) { return rawPassword.toString(); } }); } @Bean public AuthorizationCodeServices authorizationCodeServices() { return new InMemoryAuthorizationCodeServices(); } } /** * This adds our own custom filter before the OAuth2 filters are run to put * an anonymous authentication object into the security context *before* * {@link ClientDetailsService#loadClientByClientId(String)} is called. */ @Configuration @Order(Ordered.HIGHEST_PRECEDENCE) protected static class AuthorizationServerConfigurer extends AuthorizationServerSecurityConfiguration { @Autowired @Qualifier("clientDetails") private ClientDetailsService clientDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http); // SecurityContextPersistenceFilter appears pretty high up (well // before any OAuth related filters), so we'll put our anonymous // user filter into the filter chain after that. http.addFilterAfter(new UnauthenticatedAnonymousAuthenticationFilter("anonymousTokenAuthProvider"), SecurityContextPersistenceFilter.class); } } /** * Forcibly set the exception translator on the `authenticationEntryPoint` * so that we can supply our own errors on authentication failure. The * `authenticationEntryPoint` field on * {@link AbstractOAuth2SecurityExceptionHandler} is marked `private`, and * is not accessible for customizing. * * @param configurer * the instance of the configurer that we're customizing * @param exceptionTranslator * the {@link WebResponseExceptionTranslator} that we want to * set. * @param <T> * The type of security configurer */ private static <T> void forceExceptionTranslator(final T configurer, final WebResponseExceptionTranslator<OAuth2Exception> exceptionTranslator) { try { final Field authenticationEntryPointField = ReflectionUtils.findField(configurer.getClass(), "authenticationEntryPoint"); ReflectionUtils.makeAccessible(authenticationEntryPointField); final OAuth2AuthenticationEntryPoint authenticationEntryPoint = (OAuth2AuthenticationEntryPoint) authenticationEntryPointField .get(configurer); logger.debug("Customizing the authentication entry point by brute force."); authenticationEntryPoint.setExceptionTranslator(exceptionTranslator); } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { logger.error("Failed to configure the authenticationEntryPoint on ResourceServerSecurityConfigurer.", e); } } }
apache-2.0
VirtualGamer/SnowEngine
Dependencies/opengles/src/org/lwjgl/opengles/OESStencil4.java
612
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opengles; /** * Native bindings to the <a href="https://www.khronos.org/registry/gles/extensions/OES/OES_stencil4.txt">OES_stencil4</a> extension. * * <p>This extension enables 4-bit stencil component as a valid render buffer storage format.</p> */ public final class OESStencil4 { /** Accepted by the {@code internalformat} parameter of RenderbufferStorageOES. */ public static final int GL_STENCIL_INDEX4_OES = 0x8D47; private OESStencil4() {} }
apache-2.0
rwinston/netling
src/main/java/org/netling/ssh/transport/digest/Digest.java
1886
/* * Copyright 2010 netling project <http://netling.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. * * This file may incorporate work covered by the following copyright and * permission notice: * * 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.netling.ssh.transport.digest; /** Interface used to compute digests, based on algorithms such as MD5 or SHA1. */ public interface Digest { byte[] digest(); int getBlockSize(); void init(); void update(byte[] foo); void update(byte[] foo, int start, int len); }
apache-2.0
happyrainyday/bbs_news
src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/rest/resources/NewsEntryResource.java
7364
package net.dontdrinkandroot.example.angularrestspringsecurity.rest.resources; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; 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.MediaType; import org.apache.commons.lang3.StringUtils; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import net.dontdrinkandroot.example.angularrestspringsecurity.BaseResult; import net.dontdrinkandroot.example.angularrestspringsecurity.Constant; import net.dontdrinkandroot.example.angularrestspringsecurity.ErrorCodeEnum; import net.dontdrinkandroot.example.angularrestspringsecurity.FormatUtils; import net.dontdrinkandroot.example.angularrestspringsecurity.JsonViews; import net.dontdrinkandroot.example.angularrestspringsecurity.UserUtils; import net.dontdrinkandroot.example.angularrestspringsecurity.dao.newsentry.CommentDao; import net.dontdrinkandroot.example.angularrestspringsecurity.dao.newsentry.NewsEntryDao; import net.dontdrinkandroot.example.angularrestspringsecurity.model.NewsEntry; import net.dontdrinkandroot.example.angularrestspringsecurity.model.NewsEntryUser; import net.dontdrinkandroot.example.angularrestspringsecurity.transfer.NewsEntryUserVo; import net.dontdrinkandroot.example.angularrestspringsecurity.transfer.Pagination; @Component @Path("/news") public class NewsEntryResource { // private static Logger logger = Logger.getLogger(CommentResource.class); private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private NewsEntryDao newsEntryDao; @Autowired private CommentDao commentDao; @Autowired private ObjectMapper mapper; @GET @Produces(MediaType.APPLICATION_JSON) public String list() throws JsonGenerationException, JsonMappingException, IOException { ObjectWriter viewWriter; if (UserUtils.isAdmin()) { viewWriter = this.mapper.writerWithView(JsonViews.Admin.class); } else { viewWriter = this.mapper.writerWithView(JsonViews.User.class); } // List<NewsEntry> allEntries = this.newsEntryDao.findAll(); List<NewsEntryUser> allEntries = this.newsEntryDao.getNewEntryUserList(); return viewWriter.writeValueAsString(allEntries); } @GET @Path("/pager") @Produces(MediaType.APPLICATION_JSON) public BaseResult<?> getNewsPageList(@QueryParam("pageIndex") String pageIndex, @QueryParam("pageSize") String pageSize){ int index = 0; int size = 0; if (-1 == FormatUtils.checkIsInteger(pageIndex)) { index = Constant.DEFAULT_PAGE_INDEX; } else { index = Integer.parseInt(pageIndex); } if (-1 == FormatUtils.checkIsInteger(pageSize)) { size = Constant.DEFAULT_PAGE_SIZE; } else { size = Integer.parseInt(pageSize); } Pagination<NewsEntryUserVo> pagination = new Pagination<NewsEntryUserVo>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("pageIndex", (index - 1) * size); map.put("pageSize", size); List<NewsEntryUserVo> list = new ArrayList<NewsEntryUserVo>(); NewsEntryUserVo nev = null; List<NewsEntryUser> newsPageList = this.newsEntryDao.getNewsPageList(map); for (NewsEntryUser newsEntryUser : newsPageList) { nev = new NewsEntryUserVo(); nev.setCommentsNum(this.commentDao.getCommentNum(newsEntryUser.getId())); nev.setContent(newsEntryUser.getContent()); nev.setDate(newsEntryUser.getDate()); nev.setDownVotes(newsEntryUser.getDownVotes()); nev.setUpVotes(newsEntryUser.getUpVotes()); nev.setId(newsEntryUser.getId()); nev.setPageViews(newsEntryUser.getPageViews()); nev.setUser(newsEntryUser.getUser()); nev.setUserId(newsEntryUser.getUserId()); nev.setWeight(newsEntryUser.getWeight()); list.add(nev); } pagination.setContent(list); pagination.setCurrentPage(index); pagination.setPageSize(size); pagination.setTotalPage(this.newsEntryDao.getNewsNum()); return new BaseResult<>(pagination); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("{id}") public NewsEntry read(@PathParam("id") Long id) { this.logger.info("view the topic " + id); NewsEntry newsEntry = this.newsEntryDao.find(id); if (newsEntry == null) { this.logger.info("view the topic failed " + id); throw new WebApplicationException(404); } return newsEntry; } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public NewsEntry create(NewsEntry newsEntry) { this.logger.info("publish the topic --> " + newsEntry.getContent()); newsEntry.setDate(new Date()); return this.newsEntryDao.save(newsEntry); } @PUT @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("{id}") public BaseResult<?> update(@PathParam("id") Long id, NewsEntry newsEntry) { int status = this.newsEntryDao.updateNewsEntry(newsEntry); if (status < 1){ return new BaseResult<>("50000", "更新失败"); } return new BaseResult<>(); } @PUT @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("{id}/stick") public BaseResult<?> stick(@PathParam("id") Long id, @QueryParam("oper")String stickType) { NewsEntry newsEntry = new NewsEntry(); newsEntry.setId(id); if ("1".equals(stickType)){ newsEntry.setWeight(100L); this.logger.info("stick the topic -> id"); } else { newsEntry.setWeight(0L); this.logger.info("cancel sticking the topic -> id"); } int status = this.newsEntryDao.updateNewsEntry(newsEntry); if (status < 1){ return new BaseResult<>("50000", "更新失败"); } return new BaseResult<>(); } @PUT @Produces(MediaType.APPLICATION_JSON) @Path("{id}/{param}") public BaseResult<?> updateVoter(@PathParam("id") Long id, @PathParam("param")String param) { if (StringUtils.isBlank(param)){ return new BaseResult<>(ErrorCodeEnum.PARAMETERS_IS_NULL_1); } if ("up".equals(param)){ this.logger.info("up vote the topic " + id); int status = this.newsEntryDao.updateUpVotes(id); if (status < 1){ return new BaseResult<>("50000", "更新失败"); } } if ("down".equals(param)){ this.logger.info("down vote the topic " + id); int status = this.newsEntryDao.updateDownVotes(id); if (status < 1){ return new BaseResult<>("50000", "更新失败"); } } if ("pageViews".equals(param)) { this.logger.info("view the topic " + id); int status = this.newsEntryDao.updatePageViews(id); if (status < 1){ return new BaseResult<>("50000", "更新失败"); } } return new BaseResult<>(); } @DELETE @Produces(MediaType.APPLICATION_JSON) @Path("{id}") public BaseResult<?> delete(@PathParam("id") Long id) { this.logger.info("admin delete the topic"); this.newsEntryDao.delete(id); return new BaseResult<>(); } }
apache-2.0
pdxrunner/geode
geode-core/src/main/java/org/apache/geode/distributed/internal/locks/ElderInitProcessor.java
10908
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.distributed.internal.locks; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.apache.logging.log4j.Logger; import org.apache.geode.DataSerializer; import org.apache.geode.distributed.internal.ClusterDistributionManager; import org.apache.geode.distributed.internal.DistributionManager; import org.apache.geode.distributed.internal.DistributionMessage; import org.apache.geode.distributed.internal.MessageWithReply; import org.apache.geode.distributed.internal.PooledDistributionMessage; import org.apache.geode.distributed.internal.ReplyException; import org.apache.geode.distributed.internal.ReplyMessage; import org.apache.geode.distributed.internal.ReplyProcessor21; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.Assert; import org.apache.geode.internal.logging.LogService; import org.apache.geode.internal.logging.log4j.LogMarker; /** * A processor for initializing the ElderState. This may involve sending a message to every existing * member to discover what services they have. * * @since GemFire 4.0 */ public class ElderInitProcessor extends ReplyProcessor21 { private static final Logger logger = LogService.getLogger(); private final HashMap grantors; private final HashSet crashedGrantors; ////////// Public static entry point ///////// /** * Initializes ElderState map by recovering all existing grantors and crashed grantors in the * current ds. */ static void init(DistributionManager dm, HashMap<String, GrantorInfo> map) { HashSet<String> crashedGrantors = new HashSet<>(); Set others = dm.getOtherDistributionManagerIds(); if (!others.isEmpty()) { ElderInitProcessor processor = new ElderInitProcessor(dm, others, map, crashedGrantors); ElderInitMessage.send(others, dm, processor); try { processor.waitForRepliesUninterruptibly(); } catch (ReplyException e) { e.handleCause(); } } // always recover from ourself GrantorRequestProcessor.readyForElderRecovery(dm.getSystem(), null, null); DLockService.recoverLocalElder(dm, map, crashedGrantors); for (String crashedGrantor : crashedGrantors) { map.put(crashedGrantor, new GrantorInfo(null, 0, 0, true)); } } //////////// Instance methods ////////////// /** * Creates a new instance of ElderInitProcessor */ private ElderInitProcessor(DistributionManager dm, Set others, HashMap grantors, HashSet crashedGrantors) { super(dm/* fix bug 33297 */, others); this.grantors = grantors; this.crashedGrantors = crashedGrantors; } /** * Note the synchronization; we can only process one response at a time. */ private synchronized void processData(ArrayList rmtGrantors, ArrayList rmtGrantorVersions, ArrayList rmtGrantorSerialNumbers, ArrayList rmtNonGrantors, InternalDistributedMember rmtId) { { Iterator iterGrantorServices = rmtGrantors.iterator(); Iterator iterGrantorVersions = rmtGrantorVersions.iterator(); Iterator iterGrantorSerialNumbers = rmtGrantorSerialNumbers.iterator(); while (iterGrantorServices.hasNext()) { String serviceName = (String) iterGrantorServices.next(); long versionId = ((Long) iterGrantorVersions.next()).longValue(); int serialNumber = ((Integer) iterGrantorSerialNumbers.next()).intValue(); GrantorInfo oldgi = (GrantorInfo) this.grantors.get(serviceName); if (oldgi == null || oldgi.getVersionId() < versionId) { this.grantors.put(serviceName, new GrantorInfo(rmtId, versionId, serialNumber, false)); this.crashedGrantors.remove(serviceName); } } } { Iterator it = rmtNonGrantors.iterator(); while (it.hasNext()) { String serviceName = (String) it.next(); if (!this.grantors.containsKey(serviceName)) { this.crashedGrantors.add(serviceName); } } } } @Override public void process(DistributionMessage msg) { if (msg instanceof ElderInitReplyMessage) { ElderInitReplyMessage eiMsg = (ElderInitReplyMessage) msg; processData(eiMsg.getGrantors(), eiMsg.getGrantorVersions(), eiMsg.getGrantorSerialNumbers(), eiMsg.getNonGrantors(), eiMsg.getSender()); } else { Assert.assertTrue(false, "Expected instance of ElderInitReplyMessage but got " + msg.getClass()); } super.process(msg); } /////////////// Inner message classes ////////////////// public static class ElderInitMessage extends PooledDistributionMessage implements MessageWithReply { private int processorId; protected static void send(Set others, DistributionManager dm, ReplyProcessor21 proc) { ElderInitMessage msg = new ElderInitMessage(); msg.processorId = proc.getProcessorId(); msg.setRecipients(others); if (logger.isTraceEnabled(LogMarker.DLS_VERBOSE)) { logger.trace(LogMarker.DLS_VERBOSE, "ElderInitMessage sending {} to {}", msg, others); } dm.putOutgoing(msg); } @Override public int getProcessorId() { return this.processorId; } private void reply(DistributionManager dm, ArrayList grantors, ArrayList grantorVersions, ArrayList grantorSerialNumbers, ArrayList nonGrantors) { ElderInitReplyMessage.send(this, dm, grantors, grantorVersions, grantorSerialNumbers, nonGrantors); } @Override protected void process(ClusterDistributionManager dm) { ArrayList grantors = new ArrayList(); // svc names grantor for ArrayList grantorVersions = new ArrayList(); // grantor versions ArrayList grantorSerialNumbers = new ArrayList(); // serial numbers of grantor svcs ArrayList nonGrantors = new ArrayList(); // svc names non-grantor for if (dm.waitForElder(this.getSender())) { GrantorRequestProcessor.readyForElderRecovery(dm.getSystem(), this.getSender(), null); DLockService.recoverRmtElder(grantors, grantorVersions, grantorSerialNumbers, nonGrantors); reply(dm, grantors, grantorVersions, grantorSerialNumbers, nonGrantors); } else if (dm.getOtherNormalDistributionManagerIds().isEmpty()) { // Either we're alone (and received a message from an unknown member) or else we haven't // yet processed a view. In either case, we clearly don't have any grantors, // so we return empty lists. logger.info(LogMarker.DLS_MARKER, "{}: returning empty lists because I know of no other members.", this); reply(dm, grantors, grantorVersions, grantorSerialNumbers, nonGrantors); } else { logger.info(LogMarker.DLS_MARKER, "{}: disregarding request from departed member.", this); } } public int getDSFID() { return ELDER_INIT_MESSAGE; } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); this.processorId = in.readInt(); } @Override public void toData(DataOutput out) throws IOException { super.toData(out); out.writeInt(this.processorId); } @Override public String toString() { StringBuffer buff = new StringBuffer(); buff.append("ElderInitMessage (processorId='").append(this.processorId).append(")"); return buff.toString(); } } public static class ElderInitReplyMessage extends ReplyMessage { private ArrayList grantors; // svc names private ArrayList grantorVersions; // grantor version longs private ArrayList grantorSerialNumbers; // grantor dls serial number ints private ArrayList nonGrantors; // svc names public static void send(MessageWithReply reqMsg, DistributionManager dm, ArrayList grantors, ArrayList grantorVersions, ArrayList grantorSerialNumbers, ArrayList nonGrantors) { ElderInitReplyMessage m = new ElderInitReplyMessage(); m.grantors = grantors; m.grantorVersions = grantorVersions; m.grantorSerialNumbers = grantorSerialNumbers; m.nonGrantors = nonGrantors; m.processorId = reqMsg.getProcessorId(); m.setRecipient(reqMsg.getSender()); dm.putOutgoing(m); } public ArrayList getGrantors() { return this.grantors; } public ArrayList getGrantorVersions() { return this.grantorVersions; } public ArrayList getGrantorSerialNumbers() { return this.grantorSerialNumbers; } public ArrayList getNonGrantors() { return this.nonGrantors; } @Override public int getDSFID() { return ELDER_INIT_REPLY_MESSAGE; } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); this.grantors = DataSerializer.readArrayList(in); this.grantorVersions = DataSerializer.readArrayList(in); this.grantorSerialNumbers = DataSerializer.readArrayList(in); this.nonGrantors = DataSerializer.readArrayList(in); } @Override public void toData(DataOutput out) throws IOException { super.toData(out); DataSerializer.writeArrayList(this.grantors, out); DataSerializer.writeArrayList(this.grantorVersions, out); DataSerializer.writeArrayList(this.grantorSerialNumbers, out); DataSerializer.writeArrayList(this.nonGrantors, out); } @Override public String toString() { StringBuffer buff = new StringBuffer(); buff.append("ElderInitReplyMessage").append("; sender=").append(getSender()) .append("; processorId=").append(super.processorId).append("; grantors=") .append(this.grantors).append("; grantorVersions=").append(this.grantorVersions) .append("; grantorSerialNumbers=").append(this.grantorSerialNumbers) .append("; nonGrantors=").append(this.nonGrantors).append(")"); return buff.toString(); } } }
apache-2.0
AssafMashiah/assafmashiah-yaml
src/test/java/org/yaml/snakeyaml/recursive/generics/AbstractHumanGen.java
2260
/** * Copyright (c) 2008-2011, http://www.snakeyaml.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.yaml.snakeyaml.recursive.generics; import java.util.Date; public abstract class AbstractHumanGen<T, K extends AbstractHumanGen<T, ?>> { private String name; private Date birthday; private String birthPlace; private K father; private K mother; private K partner; private K bankAccountOwner; protected T children; public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getBirthPlace() { return birthPlace; } public K getFather() { return father; } public void setFather(K father) { this.father = father; } public K getMother() { return mother; } public void setMother(K mother) { this.mother = mother; } public void setBirthPlace(String birthPlace) { this.birthPlace = birthPlace; } public T getChildren() { return children; } public void setChildren(T children) { this.children = children; } public K getPartner() { return partner; } public void setPartner(K partner) { this.partner = partner; } public K getBankAccountOwner() { return bankAccountOwner; } public void setBankAccountOwner(K bankAccountOwner) { this.bankAccountOwner = bankAccountOwner; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-servicediscovery/src/main/java/com/amazonaws/services/servicediscovery/model/transform/NamespaceSummaryMarshaller.java
4135
/* * 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.servicediscovery.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.servicediscovery.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * NamespaceSummaryMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class NamespaceSummaryMarshaller { private static final MarshallingInfo<String> ID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Id").build(); private static final MarshallingInfo<String> ARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Arn").build(); private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Name").build(); private static final MarshallingInfo<String> TYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Type").build(); private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Description").build(); private static final MarshallingInfo<Integer> SERVICECOUNT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ServiceCount").build(); private static final MarshallingInfo<StructuredPojo> PROPERTIES_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Properties").build(); private static final MarshallingInfo<java.util.Date> CREATEDATE_BINDING = MarshallingInfo.builder(MarshallingType.DATE) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CreateDate").timestampFormat("unixTimestamp").build(); private static final NamespaceSummaryMarshaller instance = new NamespaceSummaryMarshaller(); public static NamespaceSummaryMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(NamespaceSummary namespaceSummary, ProtocolMarshaller protocolMarshaller) { if (namespaceSummary == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(namespaceSummary.getId(), ID_BINDING); protocolMarshaller.marshall(namespaceSummary.getArn(), ARN_BINDING); protocolMarshaller.marshall(namespaceSummary.getName(), NAME_BINDING); protocolMarshaller.marshall(namespaceSummary.getType(), TYPE_BINDING); protocolMarshaller.marshall(namespaceSummary.getDescription(), DESCRIPTION_BINDING); protocolMarshaller.marshall(namespaceSummary.getServiceCount(), SERVICECOUNT_BINDING); protocolMarshaller.marshall(namespaceSummary.getProperties(), PROPERTIES_BINDING); protocolMarshaller.marshall(namespaceSummary.getCreateDate(), CREATEDATE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
Watson-Von/DesignPatternsTest
src/com/xiaofong/prototype/pattern/ShapeCache.java
923
package com.xiaofong.prototype.pattern; import java.util.Hashtable; import com.xiaofong.prototype.pattern.abst.Shape; import com.xiaofong.prototype.pattern.abst.impl.Circle; import com.xiaofong.prototype.pattern.abst.impl.Rectangle; import com.xiaofong.prototype.pattern.abst.impl.Square; public class ShapeCache { private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>(); public static Shape getShape(String shapeId) { Shape cacheShape = shapeMap.get(shapeId); return (Shape) cacheShape.clone(); } // ¶ÔÿÖÖÐÎ×´¶¼ÔËÐÐÊý¾Ý¿â²éѯ, ²¢´´½¨¸ÃÐÎ×´ public static void loadCache() { Circle circle = new Circle(); circle.setId("1"); shapeMap.put(circle.getId(), circle); Rectangle rectangle = new Rectangle(); rectangle.setId("2"); shapeMap.put(rectangle.getId(), rectangle); Square square = new Square(); square.setId("3"); shapeMap.put(square.getId(), square); } }
apache-2.0
googleads/googleads-java-lib
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201809/cm/ReportDefinitionService.java
1311
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * ReportDefinitionService.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.adwords.axis.v201809.cm; public interface ReportDefinitionService extends javax.xml.rpc.Service { public java.lang.String getReportDefinitionServiceInterfacePortAddress(); public com.google.api.ads.adwords.axis.v201809.cm.ReportDefinitionServiceInterface getReportDefinitionServiceInterfacePort() throws javax.xml.rpc.ServiceException; public com.google.api.ads.adwords.axis.v201809.cm.ReportDefinitionServiceInterface getReportDefinitionServiceInterfacePort(java.net.URL portAddress) throws javax.xml.rpc.ServiceException; }
apache-2.0
googleads/google-ads-java
google-ads-stubs-v9/src/main/java/com/google/ads/googleads/v9/common/HotelCountryRegionInfoOrBuilder.java
1129
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/common/criteria.proto package com.google.ads.googleads.v9.common; public interface HotelCountryRegionInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v9.common.HotelCountryRegionInfo) com.google.protobuf.MessageOrBuilder { /** * <pre> * The Geo Target Constant resource name. * </pre> * * <code>optional string country_region_criterion = 2;</code> * @return Whether the countryRegionCriterion field is set. */ boolean hasCountryRegionCriterion(); /** * <pre> * The Geo Target Constant resource name. * </pre> * * <code>optional string country_region_criterion = 2;</code> * @return The countryRegionCriterion. */ java.lang.String getCountryRegionCriterion(); /** * <pre> * The Geo Target Constant resource name. * </pre> * * <code>optional string country_region_criterion = 2;</code> * @return The bytes for countryRegionCriterion. */ com.google.protobuf.ByteString getCountryRegionCriterionBytes(); }
apache-2.0
svn2github/commons-vfs2
commons-vfs2/src/main/java/org/apache/commons/vfs2/provider/UriParser.java
16038
/* * 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.commons.vfs2.provider; import org.apache.commons.vfs2.FileName; import org.apache.commons.vfs2.FileSystemException; import org.apache.commons.vfs2.FileType; import org.apache.commons.vfs2.VFS; import org.apache.commons.vfs2.util.Os; /** * Utilities for dealing with URIs. See RFC 2396 for details. * * 2005) $ */ public final class UriParser { /** * The set of valid separators. These are all converted to the normalized one. Does <i>not</i> contain the * normalized separator */ // public static final char[] separators = {'\\'}; public static final char TRANS_SEPARATOR = '\\'; /** * The normalised separator to use. */ private static final char SEPARATOR_CHAR = FileName.SEPARATOR_CHAR; private static final int HEX_BASE = 16; private static final int BITS_IN_HALF_BYTE = 4; private static final char LOW_MASK = 0x0F; private UriParser() { } /** * Extracts the first element of a path. * * @param name StringBuilder containing the path. * @return The first element of the path. */ public static String extractFirstElement(final StringBuilder name) { final int len = name.length(); if (len < 1) { return null; } int startPos = 0; if (name.charAt(0) == SEPARATOR_CHAR) { startPos = 1; } for (int pos = startPos; pos < len; pos++) { if (name.charAt(pos) == SEPARATOR_CHAR) { // Found a separator final String elem = name.substring(startPos, pos); name.delete(startPos, pos + 1); return elem; } } // No separator final String elem = name.substring(startPos); name.setLength(0); return elem; } /** * Normalises a path. Does the following: * <ul> * <li>Removes empty path elements. * <li>Handles '.' and '..' elements. * <li>Removes trailing separator. * </ul> * * Its assumed that the separators are already fixed. * * @param path The path to normalize. * @return The FileType. * @throws FileSystemException if an error occurs. * * @see #fixSeparators */ public static FileType normalisePath(final StringBuilder path) throws FileSystemException { FileType fileType = FileType.FOLDER; if (path.length() == 0) { return fileType; } if (path.charAt(path.length() - 1) != '/') { fileType = FileType.FILE; } // Adjust separators // fixSeparators(path); // Determine the start of the first element int startFirstElem = 0; if (path.charAt(0) == SEPARATOR_CHAR) { if (path.length() == 1) { return fileType; } startFirstElem = 1; } // Iterate over each element int startElem = startFirstElem; int maxlen = path.length(); while (startElem < maxlen) { // Find the end of the element int endElem = startElem; for (; endElem < maxlen && path.charAt(endElem) != SEPARATOR_CHAR; endElem++) { } final int elemLen = endElem - startElem; if (elemLen == 0) { // An empty element - axe it path.delete(endElem, endElem + 1); maxlen = path.length(); continue; } if (elemLen == 1 && path.charAt(startElem) == '.') { // A '.' element - axe it path.delete(startElem, endElem + 1); maxlen = path.length(); continue; } if (elemLen == 2 && path.charAt(startElem) == '.' && path.charAt(startElem + 1) == '.') { // A '..' element - remove the previous element if (startElem == startFirstElem) { // Previous element is missing throw new FileSystemException("vfs.provider/invalid-relative-path.error"); } // Find start of previous element int pos = startElem - 2; for (; pos >= 0 && path.charAt(pos) != SEPARATOR_CHAR; pos--) { } startElem = pos + 1; path.delete(startElem, endElem + 1); maxlen = path.length(); continue; } // A regular element startElem = endElem + 1; } // Remove trailing separator if (!VFS.isUriStyle() && maxlen > 1 && path.charAt(maxlen - 1) == SEPARATOR_CHAR) { path.delete(maxlen - 1, maxlen); } return fileType; } /** * Normalises the separators in a name. * * @param name The StringBuilder containing the name * @return true if the StringBuilder was modified. */ public static boolean fixSeparators(final StringBuilder name) { boolean changed = false; final int maxlen = name.length(); for (int i = 0; i < maxlen; i++) { final char ch = name.charAt(i); if (ch == TRANS_SEPARATOR) { name.setCharAt(i, SEPARATOR_CHAR); changed = true; } } return changed; } /** * Extracts the scheme from a URI. * * @param uri The URI. * @return The scheme name. Returns null if there is no scheme. */ public static String extractScheme(final String uri) { return extractScheme(uri, null); } /** * Extracts the scheme from a URI. Removes the scheme and ':' delimiter from the front of the URI. * * @param uri The URI. * @param buffer Returns the remainder of the URI. * @return The scheme name. Returns null if there is no scheme. */ public static String extractScheme(final String uri, final StringBuilder buffer) { if (buffer != null) { buffer.setLength(0); buffer.append(uri); } final int maxPos = uri.length(); for (int pos = 0; pos < maxPos; pos++) { final char ch = uri.charAt(pos); if (ch == ':') { // Found the end of the scheme final String scheme = uri.substring(0, pos); if (scheme.length() <= 1 && Os.isFamily(Os.OS_FAMILY_WINDOWS)) { // This is not a scheme, but a Windows drive letter return null; } if (buffer != null) { buffer.delete(0, pos + 1); } return scheme.intern(); } if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { // A scheme character continue; } if (pos > 0 && ((ch >= '0' && ch <= '9') || ch == '+' || ch == '-' || ch == '.')) { // A scheme character (these are not allowed as the first // character of the scheme, but can be used as subsequent // characters. continue; } // Not a scheme character break; } // No scheme in URI return null; } /** * Removes %nn encodings from a string. * * @param encodedStr The encoded String. * @return The decoded String. * @throws FileSystemException if an error occurs. */ public static String decode(final String encodedStr) throws FileSystemException { if (encodedStr == null) { return null; } if (encodedStr.indexOf('%') < 0) { return encodedStr; } final StringBuilder buffer = new StringBuilder(encodedStr); decode(buffer, 0, buffer.length()); return buffer.toString(); } /** * Removes %nn encodings from a string. * * @param buffer StringBuilder containing the string to decode. * @param offset The position in the string to start decoding. * @param length The number of characters to decode. * @throws FileSystemException if an error occurs. */ public static void decode(final StringBuilder buffer, final int offset, final int length) throws FileSystemException { int index = offset; int count = length; for (; count > 0; count--, index++) { final char ch = buffer.charAt(index); if (ch != '%') { continue; } if (count < 3) { throw new FileSystemException("vfs.provider/invalid-escape-sequence.error", buffer.substring(index, index + count)); } // Decode final int dig1 = Character.digit(buffer.charAt(index + 1), HEX_BASE); final int dig2 = Character.digit(buffer.charAt(index + 2), HEX_BASE); if (dig1 == -1 || dig2 == -1) { throw new FileSystemException("vfs.provider/invalid-escape-sequence.error", buffer.substring(index, index + 3)); } final char value = (char) (dig1 << BITS_IN_HALF_BYTE | dig2); // Replace buffer.setCharAt(index, value); buffer.delete(index + 1, index + 3); count -= 2; } } /** * Encodes and appends a string to a StringBuilder. * * @param buffer The StringBuilder to append to. * @param unencodedValue The String to encode and append. * @param reserved characters to encode. */ public static void appendEncoded(final StringBuilder buffer, final String unencodedValue, final char[] reserved) { final int offset = buffer.length(); buffer.append(unencodedValue); encode(buffer, offset, unencodedValue.length(), reserved); } /** * Encodes a set of reserved characters in a StringBuilder, using the URI %nn encoding. Always encodes % characters. * * @param buffer The StringBuilder to append to. * @param offset The position in the buffer to start encoding at. * @param length The number of characters to encode. * @param reserved characters to encode. */ public static void encode(final StringBuilder buffer, final int offset, final int length, final char[] reserved) { int index = offset; int count = length; for (; count > 0; index++, count--) { final char ch = buffer.charAt(index); boolean match = ch == '%'; if (reserved != null) { for (int i = 0; !match && i < reserved.length; i++) { if (ch == reserved[i]) { match = true; } } } if (match) { // Encode final char[] digits = { Character.forDigit((ch >> BITS_IN_HALF_BYTE) & LOW_MASK, HEX_BASE), Character.forDigit(ch & LOW_MASK, HEX_BASE) }; buffer.setCharAt(index, '%'); buffer.insert(index + 1, digits); index += 2; } } } /** * Removes %nn encodings from a string. * * @param decodedStr The decoded String. * @return The encoded String. */ public static String encode(final String decodedStr) { return encode(decodedStr, null); } /** * Converts "special" characters to their %nn value. * * @param decodedStr The decoded String. * @param reserved Characters to encode. * @return The encoded String */ public static String encode(final String decodedStr, final char[] reserved) { if (decodedStr == null) { return null; } final StringBuilder buffer = new StringBuilder(decodedStr); encode(buffer, 0, buffer.length(), reserved); return buffer.toString(); } /** * Encode an array of Strings. * * @param strings The array of Strings to encode. * @return An array of encoded Strings. */ public static String[] encode(final String[] strings) { if (strings == null) { return null; } for (int i = 0; i < strings.length; i++) { strings[i] = encode(strings[i]); } return strings; } /** * Decodes the String. * * @param uri The String to decode. * @throws FileSystemException if an error occurs. */ public static void checkUriEncoding(final String uri) throws FileSystemException { decode(uri); } public static void canonicalizePath(final StringBuilder buffer, final int offset, final int length, final FileNameParser fileNameParser) throws FileSystemException { int index = offset; int count = length; for (; count > 0; count--, index++) { final char ch = buffer.charAt(index); if (ch == '%') { if (count < 3) { throw new FileSystemException("vfs.provider/invalid-escape-sequence.error", buffer.substring(index, index + count)); } // Decode final int dig1 = Character.digit(buffer.charAt(index + 1), HEX_BASE); final int dig2 = Character.digit(buffer.charAt(index + 2), HEX_BASE); if (dig1 == -1 || dig2 == -1) { throw new FileSystemException("vfs.provider/invalid-escape-sequence.error", buffer.substring(index, index + 3)); } final char value = (char) (dig1 << BITS_IN_HALF_BYTE | dig2); final boolean match = value == '%' || fileNameParser.encodeCharacter(value); if (match) { // this is a reserved character, not allowed to decode index += 2; count -= 2; continue; } // Replace buffer.setCharAt(index, value); buffer.delete(index + 1, index + 3); count -= 2; } else if (fileNameParser.encodeCharacter(ch)) { // Encode final char[] digits = { Character.forDigit((ch >> BITS_IN_HALF_BYTE) & LOW_MASK, HEX_BASE), Character.forDigit(ch & LOW_MASK, HEX_BASE) }; buffer.setCharAt(index, '%'); buffer.insert(index + 1, digits); index += 2; } } } /** * Extract the query String from the URI. * * @param name StringBuilder containing the URI. * @return The query string, if any. null otherwise. */ public static String extractQueryString(final StringBuilder name) { for (int pos = 0; pos < name.length(); pos++) { if (name.charAt(pos) == '?') { final String queryString = name.substring(pos + 1); name.delete(pos, name.length()); return queryString; } } return null; } }
apache-2.0
MarukoZ/FaceRecognition
app/src/main/java/com/jason/facerecognition/helper/DBHelper.java
2845
package com.jason.facerecognition.helper; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { private final static int VERSION = 1; private final static String DB_NAME = "phones.db"; private final static String TABLE_NAME = "phone"; private final static String CREATE_TBL = "create table phone(_id integer primary key autoincrement, name text, sex text, number text, desc text)"; private SQLiteDatabase db; //SQLiteOpenHelper子类必须要的一个构造函数 public DBHelper(Context context, String name, CursorFactory factory, int version) { //必须通过super 调用父类的构造函数 super(context, name, factory, version); } //数据库的构造函数,传递三个参数的 public DBHelper(Context context, String name, int version){ this(context, name, null, version); } //数据库的构造函数,传递一个参数的, 数据库名字和版本号都写死了 public DBHelper(Context context){ this(context, DB_NAME, null, VERSION); } // 回调函数,第一次创建时才会调用此函数,创建一个数据库 @Override public void onCreate(SQLiteDatabase db) { this.db = db; System.out.println("Create Database"); db.execSQL(CREATE_TBL); } //回调函数,当你构造DBHelper的传递的Version与之前的Version调用此函数 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { System.out.println("update Database"); } //插入方法 public void insert(ContentValues values){ //获取SQLiteDatabase实例 SQLiteDatabase db = getWritableDatabase(); //插入数据库中 db.insert(TABLE_NAME, null, values); db.close(); } //查询方法 public Cursor query(){ SQLiteDatabase db = getReadableDatabase(); //获取Cursor Cursor c = db.query(TABLE_NAME, null, null, null, null, null, null, null); return c; } //根据唯一标识_id 来删除数据 public void delete(int id){ SQLiteDatabase db = getWritableDatabase(); db.delete(TABLE_NAME, "_id=?", new String[]{String.valueOf(id)}); } //更新数据库的内容 public void update(ContentValues values, String whereClause, String[]whereArgs){ SQLiteDatabase db = getWritableDatabase(); db.update(TABLE_NAME, values, whereClause, whereArgs); } //关闭数据库 public void close(){ if(db != null){ db.close(); } } }
apache-2.0
grusso14/eprot
src/it/finsiel/siged/mvc/presentation/tag/CalendarTag.java
2163
package it.finsiel.siged.mvc.presentation.tag; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; public class CalendarTag extends TagSupport { private String textField; private boolean hasTime; public String getTextField() { return textField; } public void setTextField(String textField) { this.textField = textField; } public boolean isHasTime() { return hasTime; } public void setHasTime(boolean hasTime) { this.hasTime = hasTime; } public int doStartTag() throws JspException { JspWriter out = pageContext.getOut(); HttpServletRequest req = (HttpServletRequest) pageContext.getRequest(); try { out.print(" <img id='"); out.print(getTextField()); out.print("Button' alt='' src='"); out.print(req.getContextPath()); out.print("/images/calendar/calendar.png' "); if(isHasTime()){ out.println("title='Seleziona la data e l&#39; ora' />"); }else{ out.println("title='Seleziona la data' />"); } out.println("<script type='text/javascript'>"); out.println("<!--"); out.println("$().ready(function(){"); out.println("$(\"#" + getTextField() + "\").dynDateTime({"); if(isHasTime()){ out.println("showsTime: true,"); out.println("ifFormat: \"%d/%m/%Y - %H:%M\","); }else{ out.println("ifFormat: \"%d/%m/%Y\","); } out.println("align: \"TL\","); out.println("electric: true,"); out.println("button: \".next()\""); out.println("});"); out.println("});"); out.println("// -->"); out.println("</script>"); } catch (IOException e) { } return 0; } public int doEndTag() throws JspException { return 0; } }
apache-2.0
McLeodMoores/starling
projects/financial/src/main/java/com/mcleodmoores/financial/function/rates/functions/RatesDiscountingMethodFunctions.java
2534
/** * Copyright (C) 2017 - present McLeod Moores Software Limited. All rights reserved. */ package com.mcleodmoores.financial.function.rates.functions; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.InitializingBean; import com.mcleodmoores.financial.function.defaults.LinearRatesPerCurrencyDefaults; import com.opengamma.engine.function.config.AbstractFunctionConfigurationBean; import com.opengamma.engine.function.config.FunctionConfiguration; import com.opengamma.engine.function.config.FunctionConfigurationSource; import com.opengamma.financial.analytics.model.discounting.DiscountingPricingFunctions; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.money.Currency; /** * */ public class RatesDiscountingMethodFunctions extends AbstractFunctionConfigurationBean { public static FunctionConfigurationSource instance() { return new DiscountingPricingFunctions().getObjectCreating(); } @Override protected void addAllConfigurations(final List<FunctionConfiguration> functions) { } public static class LinearRatesDefaults extends AbstractFunctionConfigurationBean { public static class CurrencyInfo implements InitializingBean { private String _curveExposuresName; public void setCurveExposuresName(final String curveExposuresName) { _curveExposuresName = curveExposuresName; } public String getCurveExposuresName() { return _curveExposuresName; } @Override public void afterPropertiesSet() { ArgumentChecker.notNullInjected(getCurveExposuresName(), "curveExposuresName"); } } private final Map<Currency, CurrencyInfo> _info = new HashMap<>(); public void setCurrencyInfo(final Map<Currency, CurrencyInfo> info) { _info.clear(); _info.putAll(info); } protected void addDefaults(final List<FunctionConfiguration> functions) { for (final Map.Entry<Currency, CurrencyInfo> entry : _info.entrySet()) { final Currency key = entry.getKey(); final CurrencyInfo value = entry.getValue(); final String[] args = { key.getCode(), value.getCurveExposuresName() }; functions.add(functionConfiguration(LinearRatesPerCurrencyDefaults.class, args)); } } @Override protected void addAllConfigurations(final List<FunctionConfiguration> functions) { if (!_info.isEmpty()) { addDefaults(functions); } } } }
apache-2.0
balazssimon/meta-java
src/metadslx.compiler/src/generated/java/metadslx/compiler/AnnotatedAntlr4ParserListener.java
27976
// Generated from AnnotatedAntlr4Parser.g4 by ANTLR 4.5.1 package metadslx.compiler; import org.antlr.v4.runtime.tree.ParseTreeListener; /** * This interface defines a complete listener for a parse tree produced by * {@link AnnotatedAntlr4Parser}. */ public interface AnnotatedAntlr4ParserListener extends ParseTreeListener { /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#grammarSpec}. * @param ctx the parse tree */ void enterGrammarSpec(AnnotatedAntlr4Parser.GrammarSpecContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#grammarSpec}. * @param ctx the parse tree */ void exitGrammarSpec(AnnotatedAntlr4Parser.GrammarSpecContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#grammarType}. * @param ctx the parse tree */ void enterGrammarType(AnnotatedAntlr4Parser.GrammarTypeContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#grammarType}. * @param ctx the parse tree */ void exitGrammarType(AnnotatedAntlr4Parser.GrammarTypeContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#prequelConstruct}. * @param ctx the parse tree */ void enterPrequelConstruct(AnnotatedAntlr4Parser.PrequelConstructContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#prequelConstruct}. * @param ctx the parse tree */ void exitPrequelConstruct(AnnotatedAntlr4Parser.PrequelConstructContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#optionsSpec}. * @param ctx the parse tree */ void enterOptionsSpec(AnnotatedAntlr4Parser.OptionsSpecContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#optionsSpec}. * @param ctx the parse tree */ void exitOptionsSpec(AnnotatedAntlr4Parser.OptionsSpecContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#option}. * @param ctx the parse tree */ void enterOption(AnnotatedAntlr4Parser.OptionContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#option}. * @param ctx the parse tree */ void exitOption(AnnotatedAntlr4Parser.OptionContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#optionValue}. * @param ctx the parse tree */ void enterOptionValue(AnnotatedAntlr4Parser.OptionValueContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#optionValue}. * @param ctx the parse tree */ void exitOptionValue(AnnotatedAntlr4Parser.OptionValueContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#delegateGrammars}. * @param ctx the parse tree */ void enterDelegateGrammars(AnnotatedAntlr4Parser.DelegateGrammarsContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#delegateGrammars}. * @param ctx the parse tree */ void exitDelegateGrammars(AnnotatedAntlr4Parser.DelegateGrammarsContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#delegateGrammar}. * @param ctx the parse tree */ void enterDelegateGrammar(AnnotatedAntlr4Parser.DelegateGrammarContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#delegateGrammar}. * @param ctx the parse tree */ void exitDelegateGrammar(AnnotatedAntlr4Parser.DelegateGrammarContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#tokensSpec}. * @param ctx the parse tree */ void enterTokensSpec(AnnotatedAntlr4Parser.TokensSpecContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#tokensSpec}. * @param ctx the parse tree */ void exitTokensSpec(AnnotatedAntlr4Parser.TokensSpecContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#annotatedId}. * @param ctx the parse tree */ void enterAnnotatedId(AnnotatedAntlr4Parser.AnnotatedIdContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#annotatedId}. * @param ctx the parse tree */ void exitAnnotatedId(AnnotatedAntlr4Parser.AnnotatedIdContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#action}. * @param ctx the parse tree */ void enterAction(AnnotatedAntlr4Parser.ActionContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#action}. * @param ctx the parse tree */ void exitAction(AnnotatedAntlr4Parser.ActionContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#actionScopeName}. * @param ctx the parse tree */ void enterActionScopeName(AnnotatedAntlr4Parser.ActionScopeNameContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#actionScopeName}. * @param ctx the parse tree */ void exitActionScopeName(AnnotatedAntlr4Parser.ActionScopeNameContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#modeSpec}. * @param ctx the parse tree */ void enterModeSpec(AnnotatedAntlr4Parser.ModeSpecContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#modeSpec}. * @param ctx the parse tree */ void exitModeSpec(AnnotatedAntlr4Parser.ModeSpecContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#rules}. * @param ctx the parse tree */ void enterRules(AnnotatedAntlr4Parser.RulesContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#rules}. * @param ctx the parse tree */ void exitRules(AnnotatedAntlr4Parser.RulesContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#ruleSpec}. * @param ctx the parse tree */ void enterRuleSpec(AnnotatedAntlr4Parser.RuleSpecContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#ruleSpec}. * @param ctx the parse tree */ void exitRuleSpec(AnnotatedAntlr4Parser.RuleSpecContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#parserRuleSpec}. * @param ctx the parse tree */ void enterParserRuleSpec(AnnotatedAntlr4Parser.ParserRuleSpecContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#parserRuleSpec}. * @param ctx the parse tree */ void exitParserRuleSpec(AnnotatedAntlr4Parser.ParserRuleSpecContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#exceptionGroup}. * @param ctx the parse tree */ void enterExceptionGroup(AnnotatedAntlr4Parser.ExceptionGroupContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#exceptionGroup}. * @param ctx the parse tree */ void exitExceptionGroup(AnnotatedAntlr4Parser.ExceptionGroupContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#exceptionHandler}. * @param ctx the parse tree */ void enterExceptionHandler(AnnotatedAntlr4Parser.ExceptionHandlerContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#exceptionHandler}. * @param ctx the parse tree */ void exitExceptionHandler(AnnotatedAntlr4Parser.ExceptionHandlerContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#finallyClause}. * @param ctx the parse tree */ void enterFinallyClause(AnnotatedAntlr4Parser.FinallyClauseContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#finallyClause}. * @param ctx the parse tree */ void exitFinallyClause(AnnotatedAntlr4Parser.FinallyClauseContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#rulePrequel}. * @param ctx the parse tree */ void enterRulePrequel(AnnotatedAntlr4Parser.RulePrequelContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#rulePrequel}. * @param ctx the parse tree */ void exitRulePrequel(AnnotatedAntlr4Parser.RulePrequelContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#ruleReturns}. * @param ctx the parse tree */ void enterRuleReturns(AnnotatedAntlr4Parser.RuleReturnsContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#ruleReturns}. * @param ctx the parse tree */ void exitRuleReturns(AnnotatedAntlr4Parser.RuleReturnsContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#throwsSpec}. * @param ctx the parse tree */ void enterThrowsSpec(AnnotatedAntlr4Parser.ThrowsSpecContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#throwsSpec}. * @param ctx the parse tree */ void exitThrowsSpec(AnnotatedAntlr4Parser.ThrowsSpecContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#localsSpec}. * @param ctx the parse tree */ void enterLocalsSpec(AnnotatedAntlr4Parser.LocalsSpecContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#localsSpec}. * @param ctx the parse tree */ void exitLocalsSpec(AnnotatedAntlr4Parser.LocalsSpecContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#ruleAction}. * @param ctx the parse tree */ void enterRuleAction(AnnotatedAntlr4Parser.RuleActionContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#ruleAction}. * @param ctx the parse tree */ void exitRuleAction(AnnotatedAntlr4Parser.RuleActionContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#ruleModifiers}. * @param ctx the parse tree */ void enterRuleModifiers(AnnotatedAntlr4Parser.RuleModifiersContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#ruleModifiers}. * @param ctx the parse tree */ void exitRuleModifiers(AnnotatedAntlr4Parser.RuleModifiersContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#ruleModifier}. * @param ctx the parse tree */ void enterRuleModifier(AnnotatedAntlr4Parser.RuleModifierContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#ruleModifier}. * @param ctx the parse tree */ void exitRuleModifier(AnnotatedAntlr4Parser.RuleModifierContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#ruleBlock}. * @param ctx the parse tree */ void enterRuleBlock(AnnotatedAntlr4Parser.RuleBlockContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#ruleBlock}. * @param ctx the parse tree */ void exitRuleBlock(AnnotatedAntlr4Parser.RuleBlockContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#ruleAltList}. * @param ctx the parse tree */ void enterRuleAltList(AnnotatedAntlr4Parser.RuleAltListContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#ruleAltList}. * @param ctx the parse tree */ void exitRuleAltList(AnnotatedAntlr4Parser.RuleAltListContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#labeledAlt}. * @param ctx the parse tree */ void enterLabeledAlt(AnnotatedAntlr4Parser.LabeledAltContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#labeledAlt}. * @param ctx the parse tree */ void exitLabeledAlt(AnnotatedAntlr4Parser.LabeledAltContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#propertiesBlock}. * @param ctx the parse tree */ void enterPropertiesBlock(AnnotatedAntlr4Parser.PropertiesBlockContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#propertiesBlock}. * @param ctx the parse tree */ void exitPropertiesBlock(AnnotatedAntlr4Parser.PropertiesBlockContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#lexerRule}. * @param ctx the parse tree */ void enterLexerRule(AnnotatedAntlr4Parser.LexerRuleContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#lexerRule}. * @param ctx the parse tree */ void exitLexerRule(AnnotatedAntlr4Parser.LexerRuleContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#lexerRuleBlock}. * @param ctx the parse tree */ void enterLexerRuleBlock(AnnotatedAntlr4Parser.LexerRuleBlockContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#lexerRuleBlock}. * @param ctx the parse tree */ void exitLexerRuleBlock(AnnotatedAntlr4Parser.LexerRuleBlockContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#lexerAltList}. * @param ctx the parse tree */ void enterLexerAltList(AnnotatedAntlr4Parser.LexerAltListContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#lexerAltList}. * @param ctx the parse tree */ void exitLexerAltList(AnnotatedAntlr4Parser.LexerAltListContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#lexerAlt}. * @param ctx the parse tree */ void enterLexerAlt(AnnotatedAntlr4Parser.LexerAltContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#lexerAlt}. * @param ctx the parse tree */ void exitLexerAlt(AnnotatedAntlr4Parser.LexerAltContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#lexerElements}. * @param ctx the parse tree */ void enterLexerElements(AnnotatedAntlr4Parser.LexerElementsContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#lexerElements}. * @param ctx the parse tree */ void exitLexerElements(AnnotatedAntlr4Parser.LexerElementsContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#lexerElement}. * @param ctx the parse tree */ void enterLexerElement(AnnotatedAntlr4Parser.LexerElementContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#lexerElement}. * @param ctx the parse tree */ void exitLexerElement(AnnotatedAntlr4Parser.LexerElementContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#labeledLexerElement}. * @param ctx the parse tree */ void enterLabeledLexerElement(AnnotatedAntlr4Parser.LabeledLexerElementContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#labeledLexerElement}. * @param ctx the parse tree */ void exitLabeledLexerElement(AnnotatedAntlr4Parser.LabeledLexerElementContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#lexerBlock}. * @param ctx the parse tree */ void enterLexerBlock(AnnotatedAntlr4Parser.LexerBlockContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#lexerBlock}. * @param ctx the parse tree */ void exitLexerBlock(AnnotatedAntlr4Parser.LexerBlockContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#lexerCommands}. * @param ctx the parse tree */ void enterLexerCommands(AnnotatedAntlr4Parser.LexerCommandsContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#lexerCommands}. * @param ctx the parse tree */ void exitLexerCommands(AnnotatedAntlr4Parser.LexerCommandsContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#lexerCommand}. * @param ctx the parse tree */ void enterLexerCommand(AnnotatedAntlr4Parser.LexerCommandContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#lexerCommand}. * @param ctx the parse tree */ void exitLexerCommand(AnnotatedAntlr4Parser.LexerCommandContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#lexerCommandName}. * @param ctx the parse tree */ void enterLexerCommandName(AnnotatedAntlr4Parser.LexerCommandNameContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#lexerCommandName}. * @param ctx the parse tree */ void exitLexerCommandName(AnnotatedAntlr4Parser.LexerCommandNameContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#lexerCommandExpr}. * @param ctx the parse tree */ void enterLexerCommandExpr(AnnotatedAntlr4Parser.LexerCommandExprContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#lexerCommandExpr}. * @param ctx the parse tree */ void exitLexerCommandExpr(AnnotatedAntlr4Parser.LexerCommandExprContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#altList}. * @param ctx the parse tree */ void enterAltList(AnnotatedAntlr4Parser.AltListContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#altList}. * @param ctx the parse tree */ void exitAltList(AnnotatedAntlr4Parser.AltListContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#alternative}. * @param ctx the parse tree */ void enterAlternative(AnnotatedAntlr4Parser.AlternativeContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#alternative}. * @param ctx the parse tree */ void exitAlternative(AnnotatedAntlr4Parser.AlternativeContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#element}. * @param ctx the parse tree */ void enterElement(AnnotatedAntlr4Parser.ElementContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#element}. * @param ctx the parse tree */ void exitElement(AnnotatedAntlr4Parser.ElementContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#labeledElement}. * @param ctx the parse tree */ void enterLabeledElement(AnnotatedAntlr4Parser.LabeledElementContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#labeledElement}. * @param ctx the parse tree */ void exitLabeledElement(AnnotatedAntlr4Parser.LabeledElementContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#ebnf}. * @param ctx the parse tree */ void enterEbnf(AnnotatedAntlr4Parser.EbnfContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#ebnf}. * @param ctx the parse tree */ void exitEbnf(AnnotatedAntlr4Parser.EbnfContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#blockSuffix}. * @param ctx the parse tree */ void enterBlockSuffix(AnnotatedAntlr4Parser.BlockSuffixContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#blockSuffix}. * @param ctx the parse tree */ void exitBlockSuffix(AnnotatedAntlr4Parser.BlockSuffixContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#ebnfSuffix}. * @param ctx the parse tree */ void enterEbnfSuffix(AnnotatedAntlr4Parser.EbnfSuffixContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#ebnfSuffix}. * @param ctx the parse tree */ void exitEbnfSuffix(AnnotatedAntlr4Parser.EbnfSuffixContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#lexerAtom}. * @param ctx the parse tree */ void enterLexerAtom(AnnotatedAntlr4Parser.LexerAtomContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#lexerAtom}. * @param ctx the parse tree */ void exitLexerAtom(AnnotatedAntlr4Parser.LexerAtomContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#atom}. * @param ctx the parse tree */ void enterAtom(AnnotatedAntlr4Parser.AtomContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#atom}. * @param ctx the parse tree */ void exitAtom(AnnotatedAntlr4Parser.AtomContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#notSet}. * @param ctx the parse tree */ void enterNotSet(AnnotatedAntlr4Parser.NotSetContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#notSet}. * @param ctx the parse tree */ void exitNotSet(AnnotatedAntlr4Parser.NotSetContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#blockSet}. * @param ctx the parse tree */ void enterBlockSet(AnnotatedAntlr4Parser.BlockSetContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#blockSet}. * @param ctx the parse tree */ void exitBlockSet(AnnotatedAntlr4Parser.BlockSetContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#setElement}. * @param ctx the parse tree */ void enterSetElement(AnnotatedAntlr4Parser.SetElementContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#setElement}. * @param ctx the parse tree */ void exitSetElement(AnnotatedAntlr4Parser.SetElementContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#block}. * @param ctx the parse tree */ void enterBlock(AnnotatedAntlr4Parser.BlockContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#block}. * @param ctx the parse tree */ void exitBlock(AnnotatedAntlr4Parser.BlockContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#ruleref}. * @param ctx the parse tree */ void enterRuleref(AnnotatedAntlr4Parser.RulerefContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#ruleref}. * @param ctx the parse tree */ void exitRuleref(AnnotatedAntlr4Parser.RulerefContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#range}. * @param ctx the parse tree */ void enterRange(AnnotatedAntlr4Parser.RangeContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#range}. * @param ctx the parse tree */ void exitRange(AnnotatedAntlr4Parser.RangeContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#terminal}. * @param ctx the parse tree */ void enterTerminal(AnnotatedAntlr4Parser.TerminalContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#terminal}. * @param ctx the parse tree */ void exitTerminal(AnnotatedAntlr4Parser.TerminalContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#elementOptions}. * @param ctx the parse tree */ void enterElementOptions(AnnotatedAntlr4Parser.ElementOptionsContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#elementOptions}. * @param ctx the parse tree */ void exitElementOptions(AnnotatedAntlr4Parser.ElementOptionsContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#elementOption}. * @param ctx the parse tree */ void enterElementOption(AnnotatedAntlr4Parser.ElementOptionContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#elementOption}. * @param ctx the parse tree */ void exitElementOption(AnnotatedAntlr4Parser.ElementOptionContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#id}. * @param ctx the parse tree */ void enterId(AnnotatedAntlr4Parser.IdContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#id}. * @param ctx the parse tree */ void exitId(AnnotatedAntlr4Parser.IdContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#annotation}. * @param ctx the parse tree */ void enterAnnotation(AnnotatedAntlr4Parser.AnnotationContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#annotation}. * @param ctx the parse tree */ void exitAnnotation(AnnotatedAntlr4Parser.AnnotationContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#annotationBody}. * @param ctx the parse tree */ void enterAnnotationBody(AnnotatedAntlr4Parser.AnnotationBodyContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#annotationBody}. * @param ctx the parse tree */ void exitAnnotationBody(AnnotatedAntlr4Parser.AnnotationBodyContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#annotationAttributeList}. * @param ctx the parse tree */ void enterAnnotationAttributeList(AnnotatedAntlr4Parser.AnnotationAttributeListContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#annotationAttributeList}. * @param ctx the parse tree */ void exitAnnotationAttributeList(AnnotatedAntlr4Parser.AnnotationAttributeListContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#annotationAttribute}. * @param ctx the parse tree */ void enterAnnotationAttribute(AnnotatedAntlr4Parser.AnnotationAttributeContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#annotationAttribute}. * @param ctx the parse tree */ void exitAnnotationAttribute(AnnotatedAntlr4Parser.AnnotationAttributeContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#expressionList}. * @param ctx the parse tree */ void enterExpressionList(AnnotatedAntlr4Parser.ExpressionListContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#expressionList}. * @param ctx the parse tree */ void exitExpressionList(AnnotatedAntlr4Parser.ExpressionListContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#qualifiedName}. * @param ctx the parse tree */ void enterQualifiedName(AnnotatedAntlr4Parser.QualifiedNameContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#qualifiedName}. * @param ctx the parse tree */ void exitQualifiedName(AnnotatedAntlr4Parser.QualifiedNameContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#expression}. * @param ctx the parse tree */ void enterExpression(AnnotatedAntlr4Parser.ExpressionContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#expression}. * @param ctx the parse tree */ void exitExpression(AnnotatedAntlr4Parser.ExpressionContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#literal}. * @param ctx the parse tree */ void enterLiteral(AnnotatedAntlr4Parser.LiteralContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#literal}. * @param ctx the parse tree */ void exitLiteral(AnnotatedAntlr4Parser.LiteralContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#identifier}. * @param ctx the parse tree */ void enterIdentifier(AnnotatedAntlr4Parser.IdentifierContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#identifier}. * @param ctx the parse tree */ void exitIdentifier(AnnotatedAntlr4Parser.IdentifierContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#boolLiteral}. * @param ctx the parse tree */ void enterBoolLiteral(AnnotatedAntlr4Parser.BoolLiteralContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#boolLiteral}. * @param ctx the parse tree */ void exitBoolLiteral(AnnotatedAntlr4Parser.BoolLiteralContext ctx); /** * Enter a parse tree produced by {@link AnnotatedAntlr4Parser#nullLiteral}. * @param ctx the parse tree */ void enterNullLiteral(AnnotatedAntlr4Parser.NullLiteralContext ctx); /** * Exit a parse tree produced by {@link AnnotatedAntlr4Parser#nullLiteral}. * @param ctx the parse tree */ void exitNullLiteral(AnnotatedAntlr4Parser.NullLiteralContext ctx); }
apache-2.0
brettwooldridge/buck
test/com/facebook/buck/features/apple/project/ProjectIntegrationTest.java
20120
/* * Copyright 2018-present Facebook, 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.facebook.buck.features.apple.project; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assume.assumeTrue; import com.facebook.buck.apple.AppleNativeIntegrationTestUtils; import com.facebook.buck.apple.toolchain.ApplePlatform; import com.facebook.buck.testutil.ProcessResult; import com.facebook.buck.testutil.TemporaryPaths; import com.facebook.buck.testutil.integration.BuckBuildLog; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.util.ProcessExecutor; import com.facebook.buck.util.environment.Platform; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import org.junit.Before; import org.junit.Rule; import org.junit.Test; public class ProjectIntegrationTest { @Rule public TemporaryPaths temporaryFolder = new TemporaryPaths(); @Before public void setUp() { assumeTrue(Platform.detect() == Platform.MACOS || Platform.detect() == Platform.LINUX); } @Test public void testBuckProjectGeneratedSchemeOnlyIncludesDependenciesWithoutTests() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_generated_scheme_only_includes_dependencies", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "--without-tests", "//Apps:workspace"); result.assertSuccess(); workspace.verify(); } @Test public void testBuckProjectGeneratedSchemeIncludesTestsAndDependencies() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_generated_scheme_includes_tests_and_dependencies", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "//Apps:workspace"); result.assertSuccess(); workspace.verify(); } @Test public void testBuckProjectGeneratedSchemeIncludesTestsAndDependenciesInADifferentBuckFile() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_generated_scheme_includes_tests_and_dependencies_in_a_different_buck_file", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "//Apps:workspace"); result.assertSuccess(); workspace.verify(); } @Test public void testBuckProjectGeneratedSchemesDoNotIncludeOtherTests() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_generated_schemes_do_not_include_other_tests", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project"); result.assertSuccess(); workspace.verify(); } @Test public void generatingAllWorkspacesWillNotIncludeAllProjectsInEachOfThem() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "generating_all_workspaces_will_not_include_all_projects_in_each_of_them", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project"); result.assertSuccess(); workspace.verify(); } @Test public void schemeWithActionConfigNames() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "scheme_with_action_config_names", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project"); result.assertSuccess(); workspace.verify(); } @Test public void schemeWithExtraTests() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "scheme_with_extra_tests", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project"); result.assertSuccess(); workspace.verify(); } @Test public void schemeWithExtraTestsWithoutSrcTarget() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "scheme_with_extra_tests_without_src_target", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project"); result.assertSuccess(); workspace.verify(); } @Test public void generatingCombinedProject() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "generating_combined_project", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand( "project", "--combined-project", "--without-tests", "//Apps:workspace"); result.assertSuccess(); workspace.verify(); } @Test public void generatingRootDirectoryProject() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "generating_root_directory_project", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "//:bundle"); result.assertSuccess(); workspace.verify(); } @Test public void generatingCombinedProjectWithTests() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "generating_combined_project_with_tests", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "--combined-project", "//Apps:workspace"); result.assertSuccess(); workspace.verify(); } @Test public void testGeneratesWorkspaceFromBundle() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_implicit_workspace_generation", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "//bin:app"); result.assertSuccess(); Files.exists(workspace.resolve("bin/app.xcworkspace/contents.xcworkspacedata")); Files.exists(workspace.resolve("bin/bin.xcodeproj/project.pbxproj")); } @Test public void testGeneratesWorkspaceFromLibrary() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_implicit_workspace_generation", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "//lib:lib"); result.assertSuccess(); Files.exists(workspace.resolve("lib/lib.xcworkspace/contents.xcworkspacedata")); Files.exists(workspace.resolve("lib/lib.xcodeproj/project.pbxproj")); } @Test public void testGeneratesWorkspaceFromBinary() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_implicit_workspace_generation", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "//bin:bin"); result.assertSuccess(); Files.exists(workspace.resolve("bin/bin.xcworkspace/contents.xcworkspacedata")); Files.exists(workspace.resolve("bin/bin.xcodeproj/project.pbxproj")); } @Test public void testAttemptingToGenerateWorkspaceFromResourceTargetIsABuildError() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_implicit_workspace_generation", temporaryFolder); workspace.setUp(); ProcessResult processResult = workspace.runBuckCommand("project", "//res:res"); processResult.assertFailure(); assertThat( processResult.getStderr(), containsString( "//res:res must be a xcode_workspace_config, apple_binary, apple_bundle, or apple_library")); } @Test public void testGeneratingProjectWithTargetUsingGenruleSourceBuildsGenrule() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "target_using_genrule_source", temporaryFolder); workspace.setUp(); workspace.runBuckCommand("project", "//lib:lib"); BuckBuildLog buildLog = workspace.getBuildLog(); buildLog.assertTargetBuiltLocally("//lib:gen"); buildLog.assertTargetBuiltLocally("other_cell//:gen"); } @Test public void testGeneratingProjectWithGenruleResourceBuildsGenrule() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "target_using_genrule_resource", temporaryFolder); workspace.setUp(); workspace.runBuckCommand("project", "//app:TestApp"); BuckBuildLog buildLog = workspace.getBuildLog(); buildLog.assertTargetBuiltLocally("//app:GenResource"); } @Test public void testBuckProjectBuckConfigWithoutTestsGenerate() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_buckconfig_without_tests_generate", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "//Apps:workspace"); result.assertSuccess(); workspace.verify(); } @Test public void testBuckProjectBuckConfigWithoutTestsGenerateWithTests() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_buckconfig_without_tests_generate_with_tests", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "--with-tests", "//Apps:workspace"); result.assertSuccess(); workspace.verify(); } @Test public void testBuckProjectFocus() throws IOException { assumeTrue(Platform.detect() == Platform.MACOS); assumeTrue( AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.IPHONESIMULATOR)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "project_focus", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand( "project", "--focus", "//Libraries/Dep1:Dep1_1#iphonesimulator-x86_64 //Libraries/Dep2:Dep2", "//Apps:TestApp#iphonesimulator-x86_64"); result.assertSuccess(); workspace.verify(); } @Test public void testBuckProjectFocusPattern() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_focus_pattern", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "--focus", "//Libraries/Dep1:", "//Apps:workspace"); result.assertSuccess(); workspace.verify(); } @Test public void testBuckProjectFocusPatternCell() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_focus_pattern_cell", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "--focus", "bar//Dep2:", "//Apps:workspace"); result.assertSuccess(); workspace.verify(); } @Test public void testBuckProjectFocusWithTests() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_focus_with_tests", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand( "project", "--config", "project.ide=xcode", "--with-tests", "--focus", "//Tests:", "//Apps:TestApp"); result.assertSuccess(); } @Test public void testGeneratingProjectMetadataWithGenrule() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "target_using_genrule_source", temporaryFolder); workspace.setUp(); workspace.runBuckCommand("project", "//lib:lib"); workspace.verify(); } @Test public void testBuckProjectWithUniqueLibraryNames() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_with_unique_library_names", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand( "project", "-c", "cxx.unique_library_name_enabled=true", "//Apps:workspace"); result.assertSuccess(); workspace.verify(); } @Test public void testBuckProjectShowsFullOutput() throws Exception { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "target_using_genrule_source", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "--show-full-output", "//lib:lib"); workspace.verify(); assertEquals( "//lib:lib#default,static " + workspace.getDestPath().resolve("lib").resolve("lib.xcworkspace") + System.lineSeparator(), result.getStdout()); } @Test public void testBuckProjectShowsOutput() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "target_using_genrule_source", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "--show-output", "//lib:lib"); workspace.verify(); assertEquals( "//lib:lib#default,static " + Paths.get("lib", "lib.xcworkspace") + System.lineSeparator(), result.getStdout()); } @Test public void testBuckProjectWithCell() throws IOException, InterruptedException { assumeTrue(Platform.detect() == Platform.MACOS); assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_with_cell", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "//Apps:workspace"); result.assertSuccess(); runXcodebuild(workspace, "Apps/TestApp.xcworkspace", "TestApp"); } @Test public void testBuckProjectWithEmbeddedCellBuckout() throws IOException, InterruptedException { assumeTrue(Platform.detect() == Platform.MACOS); assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_with_cell", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand( "project", "--config", "project.embedded_cell_buck_out_enabled=true", "//Apps:workspace"); result.assertSuccess(); runXcodebuild(workspace, "Apps/TestApp.xcworkspace", "TestApp"); } @Test public void testBuckProjectWithCellAndMergedHeaderMap() throws IOException, InterruptedException { assumeTrue(Platform.detect() == Platform.MACOS); assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_with_cell", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand( "project", "--config", "apple.merge_header_maps_in_xcode=true", "//Apps:workspace"); result.assertSuccess(); runXcodebuild(workspace, "Apps/TestApp.xcworkspace", "TestApp"); } @Test(timeout = 180000) public void testBuckProjectWithAppleBundleTests() throws IOException, InterruptedException { assumeTrue(Platform.detect() == Platform.MACOS); assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_with_apple_bundle_test", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "//app:bundle"); result.assertSuccess(); ProcessExecutor.Result xcodeTestResult = workspace.runCommand( "xcodebuild", "-workspace", "app/bundle.xcworkspace", "-scheme", "bundle", "-destination 'platform=OS X,arch=x86_64'", "clean", "test"); xcodeTestResult.getStderr().ifPresent(System.err::print); assertEquals("xcodebuild should succeed", 0, xcodeTestResult.getExitCode()); } @Test public void testBuckProjectWithEmbeddedCellBuckoutAndMergedHeaderMap() throws IOException, InterruptedException { assumeTrue(Platform.detect() == Platform.MACOS); assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_with_cell", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand( "project", "--config", "project.embedded_cell_buck_out_enabled=true", "--config", "apple.merge_header_maps_in_xcode=true", "//Apps:workspace"); result.assertSuccess(); runXcodebuild(workspace, "Apps/TestApp.xcworkspace", "TestApp"); } @Test public void testBuckProjectWithSwiftDependencyOnModularObjectiveCLibrary() throws IOException, InterruptedException { assumeTrue(Platform.detect() == Platform.MACOS); assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_with_swift_dependency_on_modular_objective_c_library", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project", "//Apps:App"); result.assertSuccess(); runXcodebuild(workspace, "Apps/App.xcworkspace", "App"); } private void runXcodebuild(ProjectWorkspace workspace, String workspacePath, String schemeName) throws IOException, InterruptedException { ProcessExecutor.Result processResult = workspace.runCommand( "xcodebuild", // "json" output. "-json", // Make sure the output stays in the temp folder. "-derivedDataPath", "xcode-out/", // Build the project that we just generated "-workspace", workspacePath, "-scheme", schemeName, // Build for iphonesimulator "-arch", "x86_64", "-sdk", "iphonesimulator"); processResult.getStderr().ifPresent(System.err::print); assertEquals("xcodebuild should succeed", 0, processResult.getExitCode()); } }
apache-2.0
bozimmerman/CoffeeMud
com/planet_ink/coffee_mud/Abilities/Druid/Chant_MetalMold.java
5233
package com.planet_ink.coffee_mud.Abilities.Druid; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2003-2022 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Chant_MetalMold extends Chant { @Override public String ID() { return "Chant_MetalMold"; } private final static String localizedName = CMLib.lang().L("Metal Mold"); @Override public String name() { return localizedName; } @Override protected int canTargetCode() { return CAN_MOBS|CAN_ITEMS; } @Override public int classificationCode() { return Ability.ACODE_CHANT|Ability.DOMAIN_PLANTGROWTH; } @Override public int abstractQuality() { return Ability.QUALITY_MALICIOUS; } private Item findMobTargetItem(final MOB mobTarget) { final List<Item> goodPossibilities=new ArrayList<Item>(); final List<Item> possibilities=new ArrayList<Item>(); for(int i=0;i<mobTarget.numItems();i++) { final Item item=mobTarget.getItem(i); if((item!=null) && (item.subjectToWearAndTear()) && (CMLib.flags().isMetal(item))) { if(item.amWearingAt(Wearable.IN_INVENTORY)) possibilities.add(item); else goodPossibilities.add(item); } } if(goodPossibilities.size()>0) return goodPossibilities.get(CMLib.dice().roll(1,goodPossibilities.size(),-1)); else if(possibilities.size()>0) return possibilities.get(CMLib.dice().roll(1,possibilities.size(),-1)); return null; } @Override public int castingQuality(final MOB mob, final Physical target) { if(mob!=null) { if((target instanceof MOB)&&(target!=mob)) { if(findMobTargetItem((MOB)target)==null) return Ability.QUALITY_INDIFFERENT; } } return super.castingQuality(mob,target); } @Override public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel) { final MOB mobTarget=getTarget(mob,commands,givenTarget,true,false); Item target=null; if(mobTarget!=null) target=findMobTargetItem(mobTarget); if(target==null) target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_ANY); if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success && (target!=null) && CMLib.flags().isMetal(target) && target.subjectToWearAndTear()) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> grow(s) moldy!"):L("^S<S-NAME> chant(s), causing <T-NAMESELF> to get eaten by mold.^?")); final CMMsg msg2=CMClass.getMsg(mob,mobTarget,this,verbalCastCode(mob,mobTarget,auto),null); if((mob.location().okMessage(mob,msg))&&((mobTarget==null)||(mob.location().okMessage(mob,msg2)))) { mob.location().send(mob,msg); if(mobTarget!=null) mob.location().send(mob,msg2); if(msg.value()<=0) { int damage=2; final int num=(mob.phyStats().level()+super.getX1Level(mob)+(2*getXLEVELLevel(mob)))/2; for(int i=0;i<num;i++) damage+=CMLib.dice().roll(1,2,2); if(CMLib.flags().isABonusItems(target)) damage=(int)Math.round(CMath.div(damage,2.0)); if(target.phyStats().ability()>0) damage=(int)Math.round(CMath.div(damage,1+target.phyStats().ability())); CMLib.combat().postItemDamage(mob, target, null, damage, CMMsg.TYP_ACID, null); } } } else if(mobTarget!=null) return maliciousFizzle(mob,mobTarget,L("<S-NAME> chant(s) at <T-NAME> for mold, but nothing happens.")); else if(target!=null) return maliciousFizzle(mob,target,L("<S-NAME> chant(s) at <T-NAME> for mold, but nothing happens.")); else return maliciousFizzle(mob,null,L("<S-NAME> chant(s) for mold, but nothing happens.")); // return whether it worked return success; } }
apache-2.0
gravitee-io/graviteeio-access-management
gravitee-am-gateway/gravitee-am-gateway-policy/src/main/java/io/gravitee/am/gateway/policy/PolicyException.java
1132
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.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.gravitee.am.gateway.policy; /** * @author David BRASSELY (david.brassely at graviteesource.com) * @author GraviteeSource Team */ public class PolicyException extends Exception { public PolicyException() { super(); } public PolicyException(String message) { super(message); } public PolicyException(String message, Throwable cause) { super(message, cause); } public PolicyException(Throwable cause) { super(cause); } }
apache-2.0
googleads/google-ads-java
google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/common/FeedItemSetFilterTypeInfosProto.java
4986
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/common/feed_item_set_filter_type_infos.proto package com.google.ads.googleads.v10.common; public final class FeedItemSetFilterTypeInfosProto { private FeedItemSetFilterTypeInfosProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_common_DynamicLocationSetFilter_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_common_DynamicLocationSetFilter_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_common_BusinessNameFilter_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_common_BusinessNameFilter_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_common_DynamicAffiliateLocationSetFilter_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_common_DynamicAffiliateLocationSetFilter_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\nEgoogle/ads/googleads/v10/common/feed_i" + "tem_set_filter_type_infos.proto\022\037google." + "ads.googleads.v10.common\032Egoogle/ads/goo" + "gleads/v10/enums/feed_item_set_string_fi" + "lter_type.proto\032\034google/api/annotations." + "proto\"}\n\030DynamicLocationSetFilter\022\016\n\006lab" + "els\030\001 \003(\t\022Q\n\024business_name_filter\030\002 \001(\0132" + "3.google.ads.googleads.v10.common.Busine" + "ssNameFilter\"\235\001\n\022BusinessNameFilter\022\025\n\rb" + "usiness_name\030\001 \001(\t\022p\n\013filter_type\030\002 \001(\0162" + "[.google.ads.googleads.v10.enums.FeedIte" + "mSetStringFilterTypeEnum.FeedItemSetStri" + "ngFilterType\"6\n!DynamicAffiliateLocation" + "SetFilter\022\021\n\tchain_ids\030\001 \003(\003B\377\001\n#com.goo" + "gle.ads.googleads.v10.commonB\037FeedItemSe" + "tFilterTypeInfosProtoP\001ZEgoogle.golang.o" + "rg/genproto/googleapis/ads/googleads/v10" + "/common;common\242\002\003GAA\252\002\037Google.Ads.Google" + "Ads.V10.Common\312\002\037Google\\Ads\\GoogleAds\\V1" + "0\\Common\352\002#Google::Ads::GoogleAds::V10::" + "Commonb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.ads.googleads.v10.enums.FeedItemSetStringFilterTypeProto.getDescriptor(), com.google.api.AnnotationsProto.getDescriptor(), }); internal_static_google_ads_googleads_v10_common_DynamicLocationSetFilter_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_ads_googleads_v10_common_DynamicLocationSetFilter_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_common_DynamicLocationSetFilter_descriptor, new java.lang.String[] { "Labels", "BusinessNameFilter", }); internal_static_google_ads_googleads_v10_common_BusinessNameFilter_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_ads_googleads_v10_common_BusinessNameFilter_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_common_BusinessNameFilter_descriptor, new java.lang.String[] { "BusinessName", "FilterType", }); internal_static_google_ads_googleads_v10_common_DynamicAffiliateLocationSetFilter_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_ads_googleads_v10_common_DynamicAffiliateLocationSetFilter_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_common_DynamicAffiliateLocationSetFilter_descriptor, new java.lang.String[] { "ChainIds", }); com.google.ads.googleads.v10.enums.FeedItemSetStringFilterTypeProto.getDescriptor(); com.google.api.AnnotationsProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-cognitoidentity/src/main/java/com/amazonaws/services/cognitoidentity/model/GetPrincipalTagAttributeMapRequest.java
5980
/* * 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.cognitoidentity.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetPrincipalTagAttributeMap" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetPrincipalTagAttributeMapRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * You can use this operation to get the ID of the Identity Pool you setup attribute mappings for. * </p> */ private String identityPoolId; /** * <p> * You can use this operation to get the provider name. * </p> */ private String identityProviderName; /** * <p> * You can use this operation to get the ID of the Identity Pool you setup attribute mappings for. * </p> * * @param identityPoolId * You can use this operation to get the ID of the Identity Pool you setup attribute mappings for. */ public void setIdentityPoolId(String identityPoolId) { this.identityPoolId = identityPoolId; } /** * <p> * You can use this operation to get the ID of the Identity Pool you setup attribute mappings for. * </p> * * @return You can use this operation to get the ID of the Identity Pool you setup attribute mappings for. */ public String getIdentityPoolId() { return this.identityPoolId; } /** * <p> * You can use this operation to get the ID of the Identity Pool you setup attribute mappings for. * </p> * * @param identityPoolId * You can use this operation to get the ID of the Identity Pool you setup attribute mappings for. * @return Returns a reference to this object so that method calls can be chained together. */ public GetPrincipalTagAttributeMapRequest withIdentityPoolId(String identityPoolId) { setIdentityPoolId(identityPoolId); return this; } /** * <p> * You can use this operation to get the provider name. * </p> * * @param identityProviderName * You can use this operation to get the provider name. */ public void setIdentityProviderName(String identityProviderName) { this.identityProviderName = identityProviderName; } /** * <p> * You can use this operation to get the provider name. * </p> * * @return You can use this operation to get the provider name. */ public String getIdentityProviderName() { return this.identityProviderName; } /** * <p> * You can use this operation to get the provider name. * </p> * * @param identityProviderName * You can use this operation to get the provider name. * @return Returns a reference to this object so that method calls can be chained together. */ public GetPrincipalTagAttributeMapRequest withIdentityProviderName(String identityProviderName) { setIdentityProviderName(identityProviderName); 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 (getIdentityPoolId() != null) sb.append("IdentityPoolId: ").append(getIdentityPoolId()).append(","); if (getIdentityProviderName() != null) sb.append("IdentityProviderName: ").append(getIdentityProviderName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetPrincipalTagAttributeMapRequest == false) return false; GetPrincipalTagAttributeMapRequest other = (GetPrincipalTagAttributeMapRequest) obj; if (other.getIdentityPoolId() == null ^ this.getIdentityPoolId() == null) return false; if (other.getIdentityPoolId() != null && other.getIdentityPoolId().equals(this.getIdentityPoolId()) == false) return false; if (other.getIdentityProviderName() == null ^ this.getIdentityProviderName() == null) return false; if (other.getIdentityProviderName() != null && other.getIdentityProviderName().equals(this.getIdentityProviderName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getIdentityPoolId() == null) ? 0 : getIdentityPoolId().hashCode()); hashCode = prime * hashCode + ((getIdentityProviderName() == null) ? 0 : getIdentityProviderName().hashCode()); return hashCode; } @Override public GetPrincipalTagAttributeMapRequest clone() { return (GetPrincipalTagAttributeMapRequest) super.clone(); } }
apache-2.0
eSDK/esdk_cloud_fm_r3_native_java
source/FM/V1R3/esdk_fm_native_java/src/main/java/com/huawei/esdk/fusionmanager/local/bean/vm/DeleteVMBackupPolicyResp.java
446
package com.huawei.esdk.fusionmanager.local.bean.vm; /** * 删除虚拟机备份生成策略返回信息。 * @since eSDK Cloud V100R003C20 */ public class DeleteVMBackupPolicyResp { /** * 异常信息。 */ private String faultString; public String getFaultString() { return faultString; } public void setFaultString(String value) { this.faultString = value; } }
apache-2.0