gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * ServeStream: A HTTP stream browser/player for Android * Copyright 2012 William Seemann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sourceforge.servestream.utils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.sourceforge.servestream.bean.UriBean; import net.sourceforge.servestream.dbutils.StreamDatabase; import net.sourceforge.servestream.transport.TransportFactory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Environment; public class BackupUtils { private static final String BACKUP_FILE = "backup.json"; private static final String ROOT_JSON_ELEMENT = "backup"; private static final String BACKUP_DIRECTORY_PATH = "/ServeStream/backup/"; private static void showBackupDialog(final Context context, String message) { AlertDialog.Builder builder; AlertDialog alertDialog; builder = new AlertDialog.Builder(context); builder.setMessage(message) .setCancelable(true) .setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); alertDialog = builder.create(); alertDialog.show(); } public synchronized static void backup(Context context) { boolean success = true; String message = "Backup failed"; File backupFile = getBackupFile(); if (backupFile == null) { success = false; } else { BufferedWriter out = null; StreamDatabase streamdb = new StreamDatabase(context); List<UriBean> uris = streamdb.getUris(); streamdb.close(); if (uris.size() > 0) { try { String json = writeJSON(uris); out = new BufferedWriter(new FileWriter(backupFile)); out.write(json); } catch (FileNotFoundException e) { success = false; } catch (IOException e) { success = false; } catch (JSONException e) { success = false; } finally { try { out.close(); } catch (IOException e) { } } } else { success = false; message = "No data available to backup."; } } if (success) { message = "Backup was successful, file is: \"" + backupFile + "\""; } showBackupDialog(context, message); } public synchronized static void restore(Context context) { boolean success = true; String message = "Restore failed"; StreamDatabase streamdb = new StreamDatabase(context); File backupFile = getBackupFile(); if (backupFile == null || !backupFile.exists()) { success = false; message = "Restore failed, make sure \"" + Environment.getExternalStorageDirectory() + BACKUP_DIRECTORY_PATH + BACKUP_FILE + "\" exists."; } else { try { List<UriBean> uris = parseBackupFile(backupFile); for (int i = 0; i < uris.size(); i++) { if (TransportFactory.findUri(streamdb, uris.get(i).getUri()) == null) { streamdb.saveUri(uris.get(i)); } } } catch (IOException e) { e.printStackTrace(); success = false; } catch (JSONException e) { e.printStackTrace(); success = false; } } if (success) { message = "Restore was successful"; } streamdb.close(); showBackupDialog(context, message); } private static File getBackupFile() { File file = new File(Environment.getExternalStorageDirectory() + BACKUP_DIRECTORY_PATH); if (!file.exists() && !file.mkdirs()) { return null; } file = new File(Environment.getExternalStorageDirectory() + BACKUP_DIRECTORY_PATH, BACKUP_FILE); return file; } private static String writeJSON(List<UriBean> uris) throws JSONException { JSONObject root = new JSONObject(); JSONArray array = new JSONArray(); JSONObject js = new JSONObject(); for (int i = 0; i < uris.size(); i++) { UriBean uriBean = uris.get(i); js = new JSONObject(); js.put(StreamDatabase.FIELD_STREAM_NICKNAME, uriBean.getNickname()); js.put(StreamDatabase.FIELD_STREAM_PROTOCOL, uriBean.getProtocol()); js.put(StreamDatabase.FIELD_STREAM_USERNAME, uriBean.getUsername()); js.put(StreamDatabase.FIELD_STREAM_PASSWORD, uriBean.getPassword()); js.put(StreamDatabase.FIELD_STREAM_HOSTNAME, uriBean.getHostname()); js.put(StreamDatabase.FIELD_STREAM_PORT, uriBean.getPort()); js.put(StreamDatabase.FIELD_STREAM_PATH, uriBean.getPath()); js.put(StreamDatabase.FIELD_STREAM_QUERY, uriBean.getQuery()); js.put(StreamDatabase.FIELD_STREAM_REFERENCE, uriBean.getReference()); js.put(StreamDatabase.FIELD_STREAM_LASTCONNECT, uriBean.getLastConnect()); array.put(js); } js = new JSONObject(); js.put(UriBean.BEAN_NAME, array); root.put(ROOT_JSON_ELEMENT, js); return root.toString(); } private static List<UriBean> parseBackupFile(File backupFile) throws IOException, JSONException { BufferedReader br = null; String line; StringBuffer buffer = new StringBuffer(); List<UriBean> uris = new ArrayList<UriBean>(); try { br = new BufferedReader(new FileReader(backupFile)); while ((line = br.readLine()) != null) { buffer.append(line); } JSONObject js = new JSONObject(buffer.toString()); JSONArray tableRows = js.getJSONObject(ROOT_JSON_ELEMENT).getJSONArray(UriBean.BEAN_NAME); for (int i = 0; i < tableRows.length(); i++) { JSONObject row = tableRows.getJSONObject(i); UriBean uriBean = new UriBean(); @SuppressWarnings("unchecked") Iterator<String> iterator = row.keys(); while (iterator.hasNext()) { String name = iterator.next(); if (name.equalsIgnoreCase(StreamDatabase.FIELD_STREAM_NICKNAME)) { uriBean.setNickname(row.getString(StreamDatabase.FIELD_STREAM_NICKNAME)); } else if (name.equalsIgnoreCase(StreamDatabase.FIELD_STREAM_PROTOCOL)) { uriBean.setProtocol(row.getString(StreamDatabase.FIELD_STREAM_PROTOCOL)); } else if (name.equalsIgnoreCase(StreamDatabase.FIELD_STREAM_USERNAME)) { uriBean.setUsername(row.getString(StreamDatabase.FIELD_STREAM_USERNAME)); } else if (name.equalsIgnoreCase(StreamDatabase.FIELD_STREAM_PASSWORD)) { uriBean.setPassword(row.getString(StreamDatabase.FIELD_STREAM_PASSWORD)); } else if (name.equalsIgnoreCase(StreamDatabase.FIELD_STREAM_HOSTNAME)) { uriBean.setHostname(row.getString(StreamDatabase.FIELD_STREAM_HOSTNAME)); } else if (name.equalsIgnoreCase(StreamDatabase.FIELD_STREAM_PORT)) { uriBean.setPort(row.getInt(StreamDatabase.FIELD_STREAM_PORT)); } else if (name.equalsIgnoreCase(StreamDatabase.FIELD_STREAM_PATH)) { uriBean.setPath(row.getString(StreamDatabase.FIELD_STREAM_PATH)); } else if (name.equalsIgnoreCase(StreamDatabase.FIELD_STREAM_QUERY)) { uriBean.setQuery(row.getString(StreamDatabase.FIELD_STREAM_QUERY)); } else if (name.equalsIgnoreCase(StreamDatabase.FIELD_STREAM_REFERENCE)) { uriBean.setReference(row.getString(StreamDatabase.FIELD_STREAM_REFERENCE)); } else if (name.equalsIgnoreCase(StreamDatabase.FIELD_STREAM_LASTCONNECT)) { uriBean.setLastConnect(row.getLong(StreamDatabase.FIELD_STREAM_LASTCONNECT)); } } uris.add(uriBean); } } finally { Utils.closeBufferedReader(br); } return uris; } }
package com.zr.dao.impl; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.json.JsonObject; import com.mysql.jdbc.PreparedStatement; import com.zr.connection.DBConnection; import com.zr.dao.TeacherDao; import com.zr.model.Staff; import com.mysql.jdbc.PreparedStatement; import com.zr.connection.DBConnection; import com.zr.dao.TeacherDao; import com.zr.model.Paper; import com.zr.model.Reply; import com.zr.model.Student; import com.zr.service.TeacherService; import net.sf.json.JSONObject; public class TeacherDaoImpl implements TeacherDao { @Override public JSONObject selectAllScores(int eid, int page, int pageSize) { JSONObject json = new JSONObject(); List<Student> list = new ArrayList<Student>(); StringBuffer sql = new StringBuffer(); Connection con = DBConnection.getConnection(); sql.append("select s.s_num,s.s_id,s.s_name,s.score "); sql.append("from student s "); sql.append("join sub b "); sql.append("on b.sub_id = s.sub_id "); sql.append("where b.e_id = ? limit ?,?"); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); pst.setInt(1, eid); pst.setInt(2, (page-1)*pageSize); pst.setInt(3, pageSize); ResultSet rst = pst.executeQuery(); while (rst.next()) { Student stu = new Student(); stu.setSid(rst.getInt("s_id")); stu.setSname(rst.getString("s_name")); stu.setNum(rst.getInt("s_num")); stu.setScore(rst.getInt("score")); list.add(stu); json.put("rows", list); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return json; } @Override public void insertStudentScore(int sid, int score) { JSONObject json = new JSONObject(); StringBuffer sql = new StringBuffer(); Connection con = DBConnection.getConnection(); sql.append("update student set score = ? "); sql.append("where s_id = ?"); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); pst.setInt(1, score); pst.setInt(2, sid); pst.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public List<Staff> selectTeacher() { // TODO Auto-generated method stub StringBuffer sql = new StringBuffer(); sql.append("select a.e_id,a.e_name,a.e_col,b.c_name,a.e_num,a.e_psw "); sql.append("from staff a,college b,staff_role c "); sql.append("where a.e_col = b.c_id and a.e_id = c.e_id and c.r_id = 3"); List<Staff> list = new ArrayList<Staff>(); Connection con = DBConnection.getConnection(); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); ResultSet res = pst.executeQuery(); while (res.next()) { Staff sta = new Staff(); sta.setEcol(res.getInt("e_col")); sta.setEcolname(res.getString("c_name")); sta.setEname(res.getString("e_name")); sta.setEid(res.getInt("e_id")); sta.setEmnum(res.getInt("e_num")); sta.setEpsw(res.getString("e_psw")); list.add(sta); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; } @Override public int selectTeacherCount() { // TODO Auto-generated method stub StringBuffer sql = new StringBuffer(); sql.append("select count(a.e_id)as t_count "); sql.append("from staff a,college b,staff_role c "); sql.append("where a.e_col = b.c_id and a.e_id = c.e_id and c.r_id = 3"); Connection con = DBConnection.getConnection(); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); ResultSet res = pst.executeQuery(); if (res.next()) { int count = res.getInt("t_count"); return count; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } @Override public int deleteTeacher(int eid) { // TODO Auto-generated method stub StringBuffer sql = new StringBuffer(); sql.append("delete from staff "); sql.append("where e_id=? "); Connection con = DBConnection.getConnection(); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); pst.setInt(1, eid); int i = pst.executeUpdate(); return i; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } @Override public int deleteTeacherRole(int eid) { // TODO Auto-generated method stub StringBuffer sql = new StringBuffer(); sql.append("delete from staff_role "); sql.append("where e_id=? "); Connection con = DBConnection.getConnection(); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); pst.setInt(1, eid); int i = pst.executeUpdate(); return i; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } @Override public int updateTeacher(int eid, String ename, int colid, int emnum) { // TODO Auto-generated method stub StringBuffer sql = new StringBuffer(); int i = 0; sql.append("update staff "); sql.append("set e_name=?,e_col=?,e_num=? "); sql.append("where e_id=? "); Connection con = DBConnection.getConnection(); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); pst.setString(1, ename); pst.setInt(2, colid); pst.setInt(3, emnum); pst.setInt(4, eid); i = pst.executeUpdate(); return i; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return i; } @Override public JSONObject checkReplyMisson() { JSONObject json = new JSONObject(); List<Reply> list = new ArrayList<Reply>(); StringBuffer sql = new StringBuffer(); Connection con = DBConnection.getConnection(); sql.append("select r.reply_site,b.sub_name,r.reply_start "); sql.append("from reply r "); sql.append("join sub b "); sql.append("on b.sub_id = r.sub_id "); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); ResultSet rst = pst.executeQuery(); while (rst.next()) { Reply re = new Reply(); re.setReplysite(rst.getString("reply_site")); re.setSubname(rst.getString("sub_name")); re.setReplystart(rst.getString("reply_start")); list.add(re); json.put("rows", list); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return json; } @Override public int insertTeacher(String ename, int colid, int emnum, String epsw) { // TODO Auto-generated method stub int i = 0; StringBuffer sql = new StringBuffer(); sql.append("insert into staff (e_name,e_col,e_num,e_psw) "); sql.append("value (?,?,?,?) "); Connection con = DBConnection.getConnection(); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); pst.setString(1, ename); pst.setInt(2, colid); pst.setInt(3, emnum); pst.setString(4, epsw); i = pst.executeUpdate(); return i; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return i; } @Override public String getSnumBySid(int id) { StringBuffer sql = new StringBuffer(); Connection con = DBConnection.getConnection(); String s = ""; int num; sql.append("select s_num from student "); sql.append("where s_id = ?"); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); pst.setInt(1, id); ResultSet st = pst.executeQuery(); while (st.next()) { num = (st.getInt("s_num")); s = "" + num; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return s; } @Override public int selectTeacherEidByEnum(int e_num) { // TODO Auto-generated method stub StringBuffer sql = new StringBuffer(); sql.append("select e_id from staff where e_num=? "); Connection con = DBConnection.getConnection(); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); pst.setInt(1, e_num); ResultSet res = pst.executeQuery(); if (res.next()) { int eid = res.getInt("e_id"); return eid; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } @Override public int getstudentcount(int eid) { // TODO Auto-generated method stub StringBuffer sql = new StringBuffer(); int count; sql.append("select count(s_id) from student "); sql.append("inner join sub b "); sql.append("where b.e_id = ? "); Connection con = DBConnection.getConnection(); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); pst.setInt(1, eid); ResultSet res = pst.executeQuery(); if (res.next()) { count = res.getInt("count(s_id)"); return count; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } @Override public int[] selectSidsByEid(int eid) { StringBuffer sql = new StringBuffer(); Connection con = DBConnection.getConnection(); int[] sids = new int[] {}; String s = ""; int sid; sql.append("select s.s_id from student s "); sql.append("inner join sub b "); sql.append("where b.e_id = ?"); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); pst.setInt(1, eid); ResultSet st = pst.executeQuery(); while (st.next()) { sid = (st.getInt("s_id")); for (int i = 0; i < sids.length; i++) { sids[i] = sid; } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sids; } @Override public void getStudentPapers() { StringBuffer sql = new StringBuffer(); Connection con = DBConnection.getConnection(); sql.append("insert into paper(lw_name, s_id) "); sql.append("select wx_name,s_id from literature l "); sql.append("where l.wxlx_id = 7 "); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); pst.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public List<JSONObject> getAllPapersOfStudent(int eid, int page, int pageSize) { StringBuffer sql = new StringBuffer(); Connection con = DBConnection.getConnection(); List<JSONObject> list = new ArrayList<JSONObject>(); sql.append("select p.lw_id, p.lw_name,p.s_id,s.s_num,s.s_name,p.lw_state,p.lw_operate,p.lw_backload from paper p "); sql.append("join student s "); sql.append("on s.s_id = p.s_id "); sql.append("join sub b "); sql.append("on b.sub_id= s.sub_id "); sql.append("where b.e_id = ? limit ?,?" ); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); pst.setInt(1, eid); pst.setInt(2, (page-1)*pageSize); pst.setInt(3,pageSize); ResultSet st = pst.executeQuery(); while (st.next()) { JSONObject json = new JSONObject(); int snum = st.getInt("s_num"); String lwname =st.getString("lw_name"); System.out.println(lwname); //Paper p= new Paper(); json.put("lwid", st.getInt("lw_id")); json.put("lwname","<a href ="+"\""+"/graduation_project/downloadfile?path1="+snum+"&path2="+lwname+"\""+">"+lwname+"</a>"); json.put("sid", st.getInt("s_id")); json.put("snum", snum); json.put("sname",st.getString("s_name")); json.put("lwstate",st.getString("lw_state")); json.put("lwoperate", st.getString("lw_operate")); json.put("lwbackload",st.getString("lw_backload")); list.add(json); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; } @Override public int getPapersCount(int eid) { // TODO Auto-generated method stub StringBuffer sql = new StringBuffer(); int count; sql.append("select count(p.lw_id) from paper p "); sql.append("join student s "); sql.append("on s.s_id = p.s_id "); sql.append("join sub b "); sql.append("on b.sub_id= s.sub_id "); sql.append("where b.e_id = ? " ); Connection con = DBConnection.getConnection(); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); pst.setInt(1, eid); ResultSet res = pst.executeQuery(); if (res.next()) { count = res.getInt("count(p.lw_id)"); return count; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } @Override public int checkPapersOfStudent(int lwid, String state) { StringBuffer sql = new StringBuffer(); Connection con = DBConnection.getConnection(); sql.append("update paper set lw_state =? "); sql.append("where lw_id = ? "); try { PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString()); pst.setString(1, state); pst.setInt(2, lwid); int i = pst.executeUpdate(); return i; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } }
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.vision.v1p2beta1.stub; import com.google.api.core.ApiFunction; import com.google.api.core.BetaApi; import com.google.api.gax.core.GaxProperties; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.grpc.GaxGrpcProperties; import com.google.api.gax.grpc.GrpcTransportChannel; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.grpc.ProtoOperationTransformers; import com.google.api.gax.longrunning.OperationSnapshot; import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.OperationCallSettings; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.StubSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.cloud.vision.v1p2beta1.AsyncBatchAnnotateFilesRequest; import com.google.cloud.vision.v1p2beta1.AsyncBatchAnnotateFilesResponse; import com.google.cloud.vision.v1p2beta1.BatchAnnotateImagesRequest; import com.google.cloud.vision.v1p2beta1.BatchAnnotateImagesResponse; import com.google.cloud.vision.v1p2beta1.OperationMetadata; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.longrunning.Operation; import java.io.IOException; import java.util.List; import javax.annotation.Generated; import org.threeten.bp.Duration; // AUTO-GENERATED DOCUMENTATION AND CLASS /** * Settings class to configure an instance of {@link ImageAnnotatorStub}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (vision.googleapis.com) and default port (443) are used. * <li>Credentials are acquired automatically through Application Default Credentials. * <li>Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. For * example, to set the total timeout of batchAnnotateImages to 30 seconds: * * <pre> * <code> * ImageAnnotatorStubSettings.Builder imageAnnotatorSettingsBuilder = * ImageAnnotatorStubSettings.newBuilder(); * imageAnnotatorSettingsBuilder.batchAnnotateImagesSettings().getRetrySettings().toBuilder() * .setTotalTimeout(Duration.ofSeconds(30)); * ImageAnnotatorStubSettings imageAnnotatorSettings = imageAnnotatorSettingsBuilder.build(); * </code> * </pre> */ @Generated("by gapic-generator") @BetaApi public class ImageAnnotatorStubSettings extends StubSettings<ImageAnnotatorStubSettings> { /** The default scopes of the service. */ private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES = ImmutableList.<String>builder() .add("https://www.googleapis.com/auth/cloud-platform") .add("https://www.googleapis.com/auth/cloud-vision") .build(); private final UnaryCallSettings<BatchAnnotateImagesRequest, BatchAnnotateImagesResponse> batchAnnotateImagesSettings; private final UnaryCallSettings<AsyncBatchAnnotateFilesRequest, Operation> asyncBatchAnnotateFilesSettings; private final OperationCallSettings< AsyncBatchAnnotateFilesRequest, AsyncBatchAnnotateFilesResponse, OperationMetadata> asyncBatchAnnotateFilesOperationSettings; /** Returns the object with the settings used for calls to batchAnnotateImages. */ public UnaryCallSettings<BatchAnnotateImagesRequest, BatchAnnotateImagesResponse> batchAnnotateImagesSettings() { return batchAnnotateImagesSettings; } /** Returns the object with the settings used for calls to asyncBatchAnnotateFiles. */ public UnaryCallSettings<AsyncBatchAnnotateFilesRequest, Operation> asyncBatchAnnotateFilesSettings() { return asyncBatchAnnotateFilesSettings; } /** Returns the object with the settings used for calls to asyncBatchAnnotateFiles. */ @BetaApi("The surface for use by generated code is not stable yet and may change in the future.") public OperationCallSettings< AsyncBatchAnnotateFilesRequest, AsyncBatchAnnotateFilesResponse, OperationMetadata> asyncBatchAnnotateFilesOperationSettings() { return asyncBatchAnnotateFilesOperationSettings; } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public ImageAnnotatorStub createStub() throws IOException { if (getTransportChannelProvider() .getTransportName() .equals(GrpcTransportChannel.getGrpcTransportName())) { return GrpcImageAnnotatorStub.create(this); } else { throw new UnsupportedOperationException( "Transport not supported: " + getTransportChannelProvider().getTransportName()); } } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return InstantiatingExecutorProvider.newBuilder(); } /** Returns the default service endpoint. */ public static String getDefaultEndpoint() { return "vision.googleapis.com:443"; } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return DEFAULT_SERVICE_SCOPES; } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return InstantiatingGrpcChannelProvider.newBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return defaultGrpcTransportProviderBuilder().build(); } @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken( "gapic", GaxProperties.getLibraryVersion(ImageAnnotatorStubSettings.class)) .setTransportToken( GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); } /** Returns a new builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected ImageAnnotatorStubSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); batchAnnotateImagesSettings = settingsBuilder.batchAnnotateImagesSettings().build(); asyncBatchAnnotateFilesSettings = settingsBuilder.asyncBatchAnnotateFilesSettings().build(); asyncBatchAnnotateFilesOperationSettings = settingsBuilder.asyncBatchAnnotateFilesOperationSettings().build(); } /** Builder for ImageAnnotatorStubSettings. */ public static class Builder extends StubSettings.Builder<ImageAnnotatorStubSettings, Builder> { private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders; private final UnaryCallSettings.Builder<BatchAnnotateImagesRequest, BatchAnnotateImagesResponse> batchAnnotateImagesSettings; private final UnaryCallSettings.Builder<AsyncBatchAnnotateFilesRequest, Operation> asyncBatchAnnotateFilesSettings; private final OperationCallSettings.Builder< AsyncBatchAnnotateFilesRequest, AsyncBatchAnnotateFilesResponse, OperationMetadata> asyncBatchAnnotateFilesOperationSettings; private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>> RETRYABLE_CODE_DEFINITIONS; static { ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions = ImmutableMap.builder(); definitions.put( "idempotent", ImmutableSet.copyOf( Lists.<StatusCode.Code>newArrayList( StatusCode.Code.DEADLINE_EXCEEDED, StatusCode.Code.UNAVAILABLE))); definitions.put("non_idempotent", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList())); RETRYABLE_CODE_DEFINITIONS = definitions.build(); } private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS; static { ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder(); RetrySettings settings = null; settings = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(100L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelay(Duration.ofMillis(60000L)) .setInitialRpcTimeout(Duration.ofMillis(60000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(60000L)) .setTotalTimeout(Duration.ofMillis(600000L)) .build(); definitions.put("default", settings); RETRY_PARAM_DEFINITIONS = definitions.build(); } protected Builder() { this((ClientContext) null); } protected Builder(ClientContext clientContext) { super(clientContext); batchAnnotateImagesSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); asyncBatchAnnotateFilesSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); asyncBatchAnnotateFilesOperationSettings = OperationCallSettings.newBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( batchAnnotateImagesSettings, asyncBatchAnnotateFilesSettings); initDefaults(this); } private static Builder createDefault() { Builder builder = new Builder((ClientContext) null); builder.setTransportChannelProvider(defaultTransportChannelProvider()); builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); builder.setEndpoint(getDefaultEndpoint()); return initDefaults(builder); } private static Builder initDefaults(Builder builder) { builder .batchAnnotateImagesSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default")); builder .asyncBatchAnnotateFilesSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default")); builder .asyncBatchAnnotateFilesOperationSettings() .setInitialCallSettings( UnaryCallSettings .<AsyncBatchAnnotateFilesRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create( AsyncBatchAnnotateFilesResponse.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(OperationMetadata.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(20000L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelay(Duration.ofMillis(45000L)) .setInitialRpcTimeout(Duration.ZERO) // ignored .setRpcTimeoutMultiplier(1.0) // ignored .setMaxRpcTimeout(Duration.ZERO) // ignored .setTotalTimeout(Duration.ofMillis(86400000L)) .build())); return builder; } protected Builder(ImageAnnotatorStubSettings settings) { super(settings); batchAnnotateImagesSettings = settings.batchAnnotateImagesSettings.toBuilder(); asyncBatchAnnotateFilesSettings = settings.asyncBatchAnnotateFilesSettings.toBuilder(); asyncBatchAnnotateFilesOperationSettings = settings.asyncBatchAnnotateFilesOperationSettings.toBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( batchAnnotateImagesSettings, asyncBatchAnnotateFilesSettings); } // NEXT_MAJOR_VER: remove 'throws Exception' /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) throws Exception { super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); return this; } public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() { return unaryMethodSettingsBuilders; } /** Returns the builder for the settings used for calls to batchAnnotateImages. */ public UnaryCallSettings.Builder<BatchAnnotateImagesRequest, BatchAnnotateImagesResponse> batchAnnotateImagesSettings() { return batchAnnotateImagesSettings; } /** Returns the builder for the settings used for calls to asyncBatchAnnotateFiles. */ public UnaryCallSettings.Builder<AsyncBatchAnnotateFilesRequest, Operation> asyncBatchAnnotateFilesSettings() { return asyncBatchAnnotateFilesSettings; } /** Returns the builder for the settings used for calls to asyncBatchAnnotateFiles. */ @BetaApi( "The surface for use by generated code is not stable yet and may change in the future.") public OperationCallSettings.Builder< AsyncBatchAnnotateFilesRequest, AsyncBatchAnnotateFilesResponse, OperationMetadata> asyncBatchAnnotateFilesOperationSettings() { return asyncBatchAnnotateFilesOperationSettings; } @Override public ImageAnnotatorStubSettings build() throws IOException { return new ImageAnnotatorStubSettings(this); } } }
/* * ModeShape (http://www.modeshape.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.modeshape.jcr; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.IntStream; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.lock.Lock; import javax.jcr.lock.LockManager; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; import javax.jcr.security.AccessControlManager; import javax.jcr.security.Privilege; import javax.jcr.version.VersionException; import javax.jcr.version.VersionManager; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.InvalidTransactionException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.junit.Ignore; import org.junit.Test; import org.modeshape.common.FixFor; import org.modeshape.common.util.FileUtil; import org.modeshape.jcr.security.SimplePrincipal; import org.modeshape.jcr.security.acl.JcrAccessControlList; import org.modeshape.jcr.security.acl.Privileges; public class TransactionsTest extends SingleUseAbstractTest { @FixFor( "MODE-1819" ) @Test public void shouldBeAbleToMoveNodeWithinUserTransaction() throws Exception { startTransaction(); moveDocument("childX"); commitTransaction(); } @FixFor( "MODE-1819" ) @Test public void shouldBeAbleToMoveNodeOutsideOfUserTransaction() throws Exception { moveDocument("childX"); } @FixFor( "MODE-1819" ) @Test public void shouldBeAbleToUseSeparateSessionsWithinSingleUserTransaction() throws Exception { // We'll use separate threads, but we want to have them both do something specific at a given time, // so we'll use a barrier ... final CyclicBarrier barrier1 = new CyclicBarrier(2); final CyclicBarrier barrier2 = new CyclicBarrier(2); // The path at which we expect to find a node ... final String path = "/childY/grandChildZ"; // Create a runnable to obtain a session and look for a particular node ... final AtomicReference<Exception> separateThreadException = new AtomicReference<Exception>(); final AtomicReference<Node> separateThreadNode = new AtomicReference<Node>(); Runnable runnable = () -> { // Wait till we both get to the barrier ... Session session1 = null; try { barrier1.await(20, TimeUnit.SECONDS); // Create a second session, which should NOT see the persisted-but-not-committed changes ... session1 = newSession(); Node grandChild2 = session1.getNode(path); separateThreadNode.set(grandChild2); } catch (Exception err) { separateThreadException.set(err); } finally { try { barrier2.await(); } catch (Exception e) { throw new RuntimeException(e); } } }; // Start another session in a separate thread that won't participate in our transaction ... new Thread(runnable).start(); // Now start a transaction ... startTransaction(); // Create first session and make some changes ... Node node = session.getRootNode().addNode("childY"); node.setProperty("foo", "bar"); Node grandChild = node.addNode("grandChildZ"); grandChild.setProperty("foo", "bar"); assertThat(grandChild.getPath(), is(path)); session.save(); // persisted but not committed ... session.getNode("/childY/grandChildZ").setProperty("bar", "baz"); session.save(); // Use the same session to find the node ... Node grandChild1 = session.getNode(path); assertThat(grandChild.isSame(grandChild1), is(true)); assertEquals("bar", grandChild1.getProperty("foo").getString()); assertEquals("baz", grandChild1.getProperty("bar").getString()); // Create a second session, which should see the persisted-but-not-committed changes ... Session session2 = newSession(); Node grandChild2 = session2.getNode(path); assertThat(grandChild.isSame(grandChild2), is(true)); assertEquals("bar", grandChild2.getProperty("foo").getString()); assertEquals("baz", grandChild2.getProperty("bar").getString()); session2.logout(); // Sync up with the other thread ... barrier1.await(); // Await while the other thread does its work and looks for the node ... barrier2.await(20, TimeUnit.SECONDS); // Commit the transaction ... commitTransaction(); // Our other session should not have seen the node and should have gotten a PathNotFoundException ... assertThat(separateThreadNode.get(), is(nullValue())); assertThat(separateThreadException.get(), is(instanceOf(PathNotFoundException.class))); // It should now be visible outside of the transaction ... Session session3 = newSession(); Node grandChild3 = session3.getNode(path); assertThat(grandChild.isSame(grandChild3), is(true)); assertEquals("bar", grandChild3.getProperty("foo").getString()); assertEquals("baz", grandChild3.getProperty("bar").getString()); session3.logout(); } @Test public void shouldBeAbleToVersionOutsideOfUserTransaction() throws Exception { VersionManager vm = session.getWorkspace().getVersionManager(); Node node = session.getRootNode().addNode("Test3"); node.addMixin("mix:versionable"); node.setProperty("name", "lalalal"); node.setProperty("code", "lalalal"); session.save(); vm.checkin(node.getPath()); } @Test @FixFor( "MODE-2642" ) public void shouldBeAbleToVersionWithinUserTransactionAndDefaultTransactionManager() throws Exception { startTransaction(); VersionManager vm = session.getWorkspace().getVersionManager(); Node node = session.getRootNode().addNode("Test3"); node.addMixin("mix:versionable"); node.setProperty("name", "lalalal"); node.setProperty("code", "lalalal"); session.save(); vm.checkin(node.getPath()); assertFalse(node.isCheckedOut()); try { node.addMixin("mix:lockable"); fail("Expected a version exception because the node is checked in"); } catch (VersionException e) { //expected } commitTransaction(); } @FixFor( "MODE-1822" ) @Test public void shouldBeAbleToVersionWithinUserTransaction() throws Exception { // Start the repository using the JBoss Transactions transaction manager ... startRepositoryWithConfigurationFrom("config/repo-config-inmemory-txn.json"); // print = true; startTransaction(); VersionManager vm = session.getWorkspace().getVersionManager(); printMessage("Looking for root node"); Node node = session.getRootNode().addNode("Test3"); node.addMixin("mix:versionable"); node.setProperty("name", "lalalal"); node.setProperty("code", "lalalal"); printMessage("Saving new node at " + node.getPath()); session.save(); vm.checkin(node.getPath()); printMessage("Checked in " + node.getPath()); for (int i = 0; i != 2; ++i) { // Check it back out before we commit ... node = session.getRootNode().getNode("Test3"); printMessage("Checking out " + node.getPath()); vm.checkout(node.getPath()); // Make some more changes ... node.setProperty("code", "fa-lalalal"); printMessage("Saving changes to " + node.getPath()); session.save(); // Check it back in ... printMessage("Checking in " + node.getPath()); vm.checkin(node.getPath()); } commitTransaction(); } @FixFor( "MODE-1822" ) @Test public void shouldBeAbleToVersionWithinSequentialUserTransactions() throws Exception { startRepositoryWithConfigurationFrom("config/repo-config-inmemory-txn.json"); // print = true; startTransaction(); VersionManager vm = session.getWorkspace().getVersionManager(); printMessage("Looking for root node"); Node node = session.getRootNode().addNode("Test3"); node.addMixin("mix:versionable"); node.setProperty("name", "lalalal"); node.setProperty("code", "lalalal"); printMessage("Saving new node at " + node.getPath()); session.save(); vm.checkin(node.getPath()); commitTransaction(); printMessage("Checked in " + node.getPath()); for (int i = 0; i != 2; ++i) { // Check it back out before we commit ... node = session.getRootNode().getNode("Test3"); printMessage("Checking out " + node.getPath()); vm.checkout(node.getPath()); // Make some more changes ... startTransaction(); node.setProperty("code", "fa-lalalal"); printMessage("Saving changes to " + node.getPath()); session.save(); // Check it back in ... printMessage("Checking in " + node.getPath()); vm.checkin(node.getPath()); commitTransaction(); } } @FixFor( "MODE-1822" ) @Test public void shouldBeAbleToVersionWithinImmediatelySequentialUserTransactions() throws Exception { startRepositoryWithConfigurationFrom("config/repo-config-inmemory-txn.json"); // print = true; startTransaction(); VersionManager vm = session.getWorkspace().getVersionManager(); printMessage("Looking for root node"); Node node = session.getRootNode().addNode("Test3"); node.addMixin("mix:versionable"); node.setProperty("name", "lalalal"); node.setProperty("code", "lalalal"); printMessage("Saving new node at " + node.getPath()); session.save(); vm.checkin(node.getPath()); commitTransaction(); printMessage("Checked in " + node.getPath()); for (int i = 0; i != 2; ++i) { startTransaction(); // Check it back out before we change anything ... printMessage("Checking out " + node.getPath()); vm.checkout(node.getPath()); printMessage("Checked out " + node.getPath()); // Make some more changes ... node = session.getRootNode().getNode("Test3"); node.setProperty("code", "fa-lalalal"); printMessage("Saving changes to " + node.getPath()); session.save(); // Check it back in ... printMessage("Checking in " + node.getPath()); vm.checkin(node.getPath()); commitTransaction(); } } @FixFor( "MODE-1822" ) @Test public void shouldBeAbleToVersionWithinUserTransactionAndAtomikosTransactionManager() throws Exception { startRepositoryWithConfigurationFrom("config/repo-config-inmemory-atomikos.json"); startTransaction(); VersionManager vm = session.getWorkspace().getVersionManager(); Node node = session.getRootNode().addNode("Test3"); node.addMixin("mix:versionable"); node.setProperty("name", "lalalal"); node.setProperty("code", "lalalal"); session.save(); vm.checkin(node.getPath()); commitTransaction(); } @Test @FixFor( "MODE-2050" ) public void shouldBeAbleToUseNoClientTransactionsInMultithreadedEnvironment() throws Exception { startRepositoryWithConfigurationFrom("config/repo-config-inmemory-txn.json"); int threadsCount = 2; ExecutorService executorService = Executors.newFixedThreadPool(threadsCount); List<Future<Void>> results = new ArrayList<Future<Void>>(threadsCount); final int nodesCount = 5; for (int i = 0; i < threadsCount; i++) { Future<Void> result = executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { Session session = repository.login(); try { String threadName = Thread.currentThread().getName(); for (int i = 0; i < nodesCount; i++) { session.getRootNode().addNode("test_" + threadName); session.save(); } return null; } finally { session.logout(); } } }); results.add(result); } try { for (Future<Void> result : results) { result.get(10, TimeUnit.SECONDS); result.cancel(true); } } finally { executorService.shutdownNow(); } } @Test @FixFor( "MODE-2352 " ) public void shouldSupportConcurrentWritersUpdatingTheSameNodeWithSeparateUserTransactions() throws Exception { FileUtil.delete("target/persistent_repository"); startRepositoryWithConfigurationFrom("config/repo-config-new-workspaces.json"); int threadsCount = 10; ExecutorService executorService = Executors.newFixedThreadPool(threadsCount); List<Future<Void>> results = new ArrayList<>(threadsCount); final AtomicInteger counter = new AtomicInteger(1); for (int i = 0; i < threadsCount; i++) { Future<Void> result = executorService.submit(() -> { startTransaction(); Session session1 = repository.login(); session1.getRootNode().addNode("test_" + counter.incrementAndGet()); session1.save(); session1.logout(); commitTransaction(); return null; }); results.add(result); } try { for (Future<Void> result : results) { result.get(10, TimeUnit.SECONDS); } Session session = repository.login(); // don't count jcr:system assertEquals(threadsCount, session.getNode("/").getNodes().getSize() - 1); session.logout(); } finally { executorService.shutdownNow(); } } @FixFor( "MODE-2371" ) @Test public void shouldInitializeWorkspacesWithOngoingUserTransaction() throws Exception { startRepositoryWithConfigurationFrom("config/repo-config-inmemory-txn.json"); startTransaction(); // the active tx should be suspended for the next call Session otherSession = repository.login("otherWorkspace"); otherSession.logout(); commitTransaction(); startTransaction(); session.getWorkspace().createWorkspace("newWS"); session.logout(); commitTransaction(); otherSession = repository.login("newWS"); otherSession.logout(); startTransaction(); session = repository.login(); session.getWorkspace().createWorkspace("newWS1"); session.logout(); otherSession = repository.login("newWS1"); otherSession.logout(); commitTransaction(); } @Test @FixFor( "MODE-2395 " ) public void shouldSupportMultipleUpdatesFromTheSameSessionWithUserTransactions() throws Exception { startRepositoryWithConfigurationFrom("config/repo-config-inmemory-txn.json"); final JcrSession mainSession = repository.login(); startTransaction(); Node node1 = mainSession.getRootNode().addNode("node1"); node1.setProperty("prop", "foo"); mainSession.save(); commitTransaction(); startTransaction(); Node node2 = mainSession.getRootNode().addNode("node2"); node2.setProperty("prop", "foo"); mainSession.save(); commitTransaction(); // re-read the node to make sure it's in the cache node2 = mainSession.getNode("/node2"); ExecutorService executorService = Executors.newFixedThreadPool(1); try { Future<Void> updaterResult = executorService.submit((Callable<Void>) () -> { JcrSession updater = repository.login(); startTransaction(); AbstractJcrNode node21 = updater.getNode("/node2"); node21.setProperty("prop", "bar"); updater.save(); commitTransaction(); updater.logout(); return null; }); updaterResult.get(); node2 = mainSession.getNode("/node2"); assertEquals("bar", node2.getProperty("prop").getString()); mainSession.logout(); } finally { executorService.shutdownNow(); } } @Test @FixFor( "MODE-2495" ) @Ignore( "ModeShape 5 requires thread confinement, otherwise locking will not work correctly" ) public void shouldSupportMultipleThreadsChangingTheSameUserTransaction() throws Exception { startRepositoryWithConfigurationFrom("config/repo-config-inmemory-txn.json"); // STEP 1: create and checkin parent nodes Node root = session.getRootNode(); Node parent = root.addNode("parent"); parent.addMixin("mix:versionable"); parent.addNode("nested"); session.save(); VersionManager vm = session.getWorkspace().getVersionManager(); vm.checkin("/parent"); // STEP 2: checkout, create child and checkin vm = session.getWorkspace().getVersionManager(); vm.checkout("/parent"); Node nested = session.getNode("/parent/nested"); nested.addNode("child"); session.save(); vm.checkin("/parent"); // long transaction final Transaction longTx = startTransaction(); // STEP 3: resume, checkout, suspend vm = session.getWorkspace().getVersionManager(); vm.checkout("/parent"); session.removeItem("/parent/nested/child"); session.save(); suspendTransaction(); // STEP 4: check if child is still exists outside of longTx Session s = repository.login(); s.getNode("/parent/nested/child"); s.logout(); // STEP 5: resume, checkin, commit Thread t5 = new Thread() { @Override public void run() { try { resumeTransaction(longTx); VersionManager vm = session.getWorkspace().getVersionManager(); vm.checkin("/parent"); commitTransaction(); } catch (Exception e) { throw new RuntimeException(e); } } }; t5.start(); t5.join(); // STEP 6: check if child is gone try { Session s1 = repository.login(); s1.getNode("/parent/nested/child"); fail("should fail"); } catch (PathNotFoundException e) { // expected } } @Test @FixFor( "MODE-2558" ) public void shouldNotCorruptDataWhenConcurrentlyWritingAndQuerying() throws Exception { int threadCount = 150; IntStream.range(0, threadCount).parallel().forEach(this::insertAndQueryNodes); } @Test @FixFor( "MODE-2607" ) public void shouldUpdateParentAndRemoveChildWithDifferentTransactions1() throws Exception { final String parentPath = "/parent"; final String childPath = "/parent/child"; //create parent and child node with some properties in a tx startTransaction(); Session session = newSession(); Node parent = session.getRootNode().addNode("parent"); parent.setProperty("foo", "parent"); Node child = parent.addNode("child"); child.setProperty("foo", "child"); session.save(); commitTransaction(); //edit the parent and remove the child in a new tx startTransaction(); session = newSession(); parent = session.getNode(parentPath); parent.setProperty("foo", "bar2"); session.save(); child = session.getNode(childPath); child.remove(); session.save(); commitTransaction(); //check that the editing worked in a new tx startTransaction(); parent = session.getNode(parentPath); assertEquals("bar2", parent.getProperty("foo").getString()); assertNoNode("/parent/child"); commitTransaction(); } @Test @FixFor( "MODE-2610" ) public void shouldUpdateParentAndRemoveChildWithDifferentTransactions2() throws Exception { final String parentPath = "/parent"; final String childPath = "/parent/child"; startTransaction(); Node parent = session.getRootNode().addNode("parent"); parent.setProperty("foo", "parent"); Node child = parent.addNode("child"); child.setProperty("foo", "child"); session.save(); commitTransaction(); startTransaction(); child = session.getNode(childPath); parent = session.getNode(parentPath); parent.setProperty("foo", "bar2"); session.save(); child.remove(); session.save(); commitTransaction(); startTransaction(); parent = session.getNode(parentPath); assertEquals("bar2", parent.getProperty("foo").getString()); assertNoNode("/parent/child"); session.logout(); commitTransaction(); } @FixFor( "MODE-2623" ) @Test public void shouldAllowLockUnlockWithinTransaction() throws Exception { final String path = "/test"; Node parent = session.getRootNode().addNode("test"); parent.addMixin("mix:lockable"); session.save(); startTransaction(); LockManager lockMgr = session.getWorkspace().getLockManager(); lockMgr.lock(path, true, true, Long.MAX_VALUE, session.getUserID()); lockMgr.unlock(path); commitTransaction(); assertFalse(session.getNode(path).isLocked()); } @FixFor("MODE-2627") @Test public void shouldUpdateACLOnMovedNode() throws Exception { AccessControlManager acm = session.getAccessControlManager(); final String childPath2 = "/parent/child2"; final String childDestinationNode = "/parent/child/child2"; JcrAccessControlList acl = new JcrAccessControlList(childDestinationNode); Privileges privileges = new Privileges(session); Privilege[] privilegeArray = new Privilege[] { privileges.forName(Privilege.JCR_READ), privileges.forName(Privilege.JCR_WRITE), privileges.forName(Privilege.JCR_READ_ACCESS_CONTROL) }; acl.addAccessControlEntry(SimplePrincipal.newInstance("anonymous"), privilegeArray); startTransaction(); Node parent = session.getRootNode().addNode("parent"); parent.addNode("child"); parent.addNode("child2"); session.save(); commitTransaction(); startTransaction(); session.getWorkspace().move(childPath2, childDestinationNode); session.save(); commitTransaction(); startTransaction(); acm.setPolicy(childDestinationNode, acl); session.save(); Node movedNode = session.getNode(childDestinationNode); assertEquals(childDestinationNode, movedNode.getPath()); assertEquals(1, acm.getPolicies(childDestinationNode).length); assertEquals(acm.getPolicies(childDestinationNode)[0], acl); assertNoNode(childPath2); session.logout(); commitTransaction(); } @Test @FixFor( "MODE-2642" ) public void shouldLockNodeWithinTransaction() throws Exception { Node node = session.getRootNode().addNode("test"); node.addMixin("mix:lockable"); session.save(); startTransaction(); JcrLockManager lockManager = session.getWorkspace().getLockManager(); Lock lock = lockManager.lock(node.getPath(), false, false, Long.MAX_VALUE, null); assertTrue(lock.isLive()); assertTrue("Node should be locked", node.isLocked()); commitTransaction(); assertTrue(node.isLocked()); } private void insertAndQueryNodes(int i) { Session session = null; try { startTransaction(); session = repository.login(); createNode("/", UUID.randomUUID().toString(), session); commitTransaction(); session = repository.login(); QueryManager queryManager = session.getWorkspace().getQueryManager(); Query query = queryManager.createQuery("SELECT node.* FROM [mix:title] AS node", Query.JCR_SQL2); QueryResult result = query.execute(); assertTrue(result.getNodes().getSize() > 0); session.logout(); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException)e; } else { throw new RuntimeException(e); } } finally { if (session != null) { session.logout(); session = null; } } } private Node createNode(String parentNodePath, String uuid, Session session) throws RepositoryException { String nodeLevelOneName = uuid.substring(0, 2); String nodeLevelOnePath = parentNodePath + "/" + nodeLevelOneName; String nodeLevelTwoName = uuid.substring(2, 4); String nodeLevelTwoPath = nodeLevelOnePath + "/" + nodeLevelTwoName; String nodeLevelThreeName = uuid.substring(4, 6); String nodeLevelThreePath = nodeLevelTwoPath + "/" + nodeLevelThreeName; addLevel(parentNodePath, nodeLevelOneName, nodeLevelOnePath, session); addLevel(nodeLevelOnePath, nodeLevelTwoName, nodeLevelTwoPath, session); addLevel(nodeLevelTwoPath, nodeLevelThreeName, nodeLevelThreePath, session); session.save(); Node parent = session.getNode(parentNodePath); Node node = parent.addNode(uuid); node.addMixin("mix:title"); node.setProperty("jcr:title", "test"); session.save(); return node; } private void addLevel(String currentNodeLevelPath, String nextNodeLevelName, String nextNodeLevelPath, Session session) throws RepositoryException { if (!session.nodeExists(nextNodeLevelPath)) { Node parentNode = session.getNode(currentNodeLevelPath); parentNode.addNode(nextNodeLevelName); } } protected Transaction suspendTransaction() throws SystemException { TransactionManager txnMgr = transactionManager(); return txnMgr.suspend(); } protected void resumeTransaction(Transaction t) throws InvalidTransactionException, IllegalStateException, SystemException { TransactionManager txnMgr = transactionManager(); txnMgr.resume(t); } protected Transaction startTransaction() throws NotSupportedException, SystemException { TransactionManager txnMgr = transactionManager(); // Change this to true if/when debugging ... try { txnMgr.setTransactionTimeout(1000); } catch (Exception e) { // ignore } txnMgr.begin(); return txnMgr.getTransaction(); } protected void commitTransaction() throws SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException { TransactionManager txnMgr = transactionManager(); txnMgr.commit(); } protected TransactionManager transactionManager() { return session.getRepository().transactionManager(); } private void moveDocument(String nodeName) throws Exception { Node section = session.getRootNode().addNode(nodeName); section.setProperty("name", nodeName); section.addNode("temppath"); session.save(); String srcAbsPath = "/" + nodeName + "/temppath"; String destAbsPath = "/" + nodeName + "/20130104"; session.move(srcAbsPath, destAbsPath); session.save(); NodeIterator nitr = section.getNodes(); if (print) { System.err.println("Child Nodes of " + nodeName + " are:"); while (nitr.hasNext()) { Node n = nitr.nextNode(); System.err.println(" Node: " + n.getName()); } } } }
/* * Copyright 2009-2013 by The Regents of the University of California * 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 from * * 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 edu.uci.ics.asterix.runtime.evaluators.functions.temporal; import java.io.DataOutput; import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADateTimeSerializerDeserializer; import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADurationSerializerDeserializer; import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider; import edu.uci.ics.asterix.om.base.ADuration; import edu.uci.ics.asterix.om.base.AMutableDuration; import edu.uci.ics.asterix.om.base.ANull; import edu.uci.ics.asterix.om.base.temporal.DurationArithmeticOperations; import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem; import edu.uci.ics.asterix.om.functions.AsterixBuiltinFunctions; import edu.uci.ics.asterix.om.functions.IFunctionDescriptor; import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory; import edu.uci.ics.asterix.om.types.ATypeTag; import edu.uci.ics.asterix.om.types.BuiltinType; import edu.uci.ics.asterix.om.types.EnumDeserializer; import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor; import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException; import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier; import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator; import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory; import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer; import edu.uci.ics.hyracks.api.exceptions.HyracksDataException; import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider; import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage; import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference; /** * This function converts a given duration into a "human-readable" duration containing both year-month and day-time * duration parts, by re-organizing values between the duration fields from the given reference time point. * <p/> * The basic algorithm for this convert is simple: <br/> * 1. Calculate the time point by adding the given duration to the given time point;<br/> * 2. Calculate the differences by fields between two different time points;<br/> * 3. Re-format the duration into a human-readable one. * <p/> * Here "human-readable" means the value of each field of the duration is within the value range of the field in the calendar system. For example, month would be in [0, 12), and hour would be in [0, 24). * <p/> * The result can be considered as a "field-based" difference between the two datetime value, but all negative values would be converted to be non-negative. * <p/> * In the implementation, we always do the subtraction from the later time point, resulting a positive duration always. * <p/> */ public class CalendarDurationFromDateTimeDescriptor extends AbstractScalarFunctionDynamicDescriptor { private final static long serialVersionUID = 1L; public final static FunctionIdentifier FID = AsterixBuiltinFunctions.CALENDAR_DURATION_FROM_DATETIME; // allowed input types private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize(); private final static byte SER_DATETIME_TYPE_TAG = ATypeTag.DATETIME.serialize(); private final static byte SER_DURATION_TYPE_TAG = ATypeTag.DURATION.serialize(); public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() { @Override public IFunctionDescriptor createFunctionDescriptor() { return new CalendarDurationFromDateTimeDescriptor(); } }; /* (non-Javadoc) * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[]) */ @Override public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException { return new ICopyEvaluatorFactory() { private static final long serialVersionUID = 1L; @Override public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException { return new ICopyEvaluator() { private DataOutput out = output.getDataOutput(); private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage(); private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage(); private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0); private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1); // possible output types @SuppressWarnings("unchecked") private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE .getSerializerDeserializer(BuiltinType.ANULL); @SuppressWarnings("unchecked") private ISerializerDeserializer<ADuration> durationSerde = AqlSerializerDeserializerProvider.INSTANCE .getSerializerDeserializer(BuiltinType.ADURATION); private AMutableDuration aDuration = new AMutableDuration(0, 0); private GregorianCalendarSystem calInstanct = GregorianCalendarSystem.getInstance(); @Override public void evaluate(IFrameTupleReference tuple) throws AlgebricksException { argOut0.reset(); eval0.evaluate(tuple); argOut1.reset(); eval1.evaluate(tuple); try { if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) { nullSerde.serialize(ANull.NULL, out); return; } if (argOut0.getByteArray()[0] != SER_DATETIME_TYPE_TAG) { throw new AlgebricksException(FID.getName() + ": expects type DATETIME/NULL for parameter 0 but got " + EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(argOut0.getByteArray()[0])); } if (argOut1.getByteArray()[0] != SER_DURATION_TYPE_TAG) { throw new AlgebricksException(FID.getName() + ": expects type DURATION/NULL for parameter 1 but got " + EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(argOut1.getByteArray()[0])); } int yearMonthDurationInMonths = ADurationSerializerDeserializer.getYearMonth( argOut1.getByteArray(), 1); long dayTimeDurationInMs = ADurationSerializerDeserializer.getDayTime( argOut1.getByteArray(), 1); long startingTimePoint = ADateTimeSerializerDeserializer.getChronon(argOut0.getByteArray(), 1); long endingTimePoint = DurationArithmeticOperations.addDuration(startingTimePoint, yearMonthDurationInMonths, dayTimeDurationInMs, false); if (startingTimePoint == endingTimePoint) { aDuration.setValue(0, 0); } else { boolean negative = false; if (endingTimePoint < startingTimePoint) { negative = true; // swap the starting and ending time, so that ending time is always larger than the starting time. long tmpTime = endingTimePoint; endingTimePoint = startingTimePoint; startingTimePoint = tmpTime; } int year0 = calInstanct.getYear(startingTimePoint); int month0 = calInstanct.getMonthOfYear(startingTimePoint, year0); int year1 = calInstanct.getYear(endingTimePoint); int month1 = calInstanct.getMonthOfYear(endingTimePoint, year1); int year = year1 - year0; int month = month1 - month0; int day = calInstanct.getDayOfMonthYear(endingTimePoint, year1, month1) - calInstanct.getDayOfMonthYear(startingTimePoint, year0, month0); int hour = calInstanct.getHourOfDay(endingTimePoint) - calInstanct.getHourOfDay(startingTimePoint); int min = calInstanct.getMinOfHour(endingTimePoint) - calInstanct.getMinOfHour(startingTimePoint); int sec = calInstanct.getSecOfMin(endingTimePoint) - calInstanct.getSecOfMin(startingTimePoint); int ms = calInstanct.getMillisOfSec(endingTimePoint) - calInstanct.getMillisOfSec(startingTimePoint); if (ms < 0) { ms += GregorianCalendarSystem.CHRONON_OF_SECOND; sec -= 1; } if (sec < 0) { sec += GregorianCalendarSystem.CHRONON_OF_MINUTE / GregorianCalendarSystem.CHRONON_OF_SECOND; min -= 1; } if (min < 0) { min += GregorianCalendarSystem.CHRONON_OF_HOUR / GregorianCalendarSystem.CHRONON_OF_MINUTE; hour -= 1; } if (hour < 0) { hour += GregorianCalendarSystem.CHRONON_OF_DAY / GregorianCalendarSystem.CHRONON_OF_HOUR; day -= 1; } if (day < 0) { boolean isLeapYear = calInstanct.isLeapYear(year1); // need to "borrow" the days in previous month to make the day positive; when month is 1 (Jan), Dec will be borrowed day += (isLeapYear) ? (GregorianCalendarSystem.DAYS_OF_MONTH_LEAP[(12 + month1 - 2) % 12]) : (GregorianCalendarSystem.DAYS_OF_MONTH_ORDI[(12 + month1 - 2) % 12]); month -= 1; } if (month < 0) { month += GregorianCalendarSystem.MONTHS_IN_A_YEAR; year -= 1; } if (negative) { aDuration.setValue(-1 * (year * GregorianCalendarSystem.MONTHS_IN_A_YEAR + month), -1 * (day * GregorianCalendarSystem.CHRONON_OF_DAY + hour * GregorianCalendarSystem.CHRONON_OF_HOUR + min * GregorianCalendarSystem.CHRONON_OF_MINUTE + sec * GregorianCalendarSystem.CHRONON_OF_SECOND + ms)); } else { aDuration.setValue(year * GregorianCalendarSystem.MONTHS_IN_A_YEAR + month, day * GregorianCalendarSystem.CHRONON_OF_DAY + hour * GregorianCalendarSystem.CHRONON_OF_HOUR + min * GregorianCalendarSystem.CHRONON_OF_MINUTE + sec * GregorianCalendarSystem.CHRONON_OF_SECOND + ms); } } durationSerde.serialize(aDuration, out); } catch (HyracksDataException hex) { throw new AlgebricksException(hex); } } }; } }; } /* (non-Javadoc) * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier() */ @Override public FunctionIdentifier getIdentifier() { return FID; } }
/* * Copyright LWJGL. All rights reserved. * License terms: http://lwjgl.org/license.php * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opengles; import java.nio.*; import org.lwjgl.system.*; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.JNI.*; import static org.lwjgl.system.MemoryStack.*; import static org.lwjgl.system.MemoryUtil.*; /** * Native bindings to the <a href="https://www.khronos.org/registry/gles/extensions/EXT/EXT_occlusion_query_boolean.txt">EXT_occlusion_query_boolean</a> extension. * * <p>This extension defines a mechanism whereby an application can query whether any pixels (or, more precisely, samples) are drawn by a primitive or group * of primitives.</p> * * <p>The primary purpose of such a query (hereafter referred to as an "occlusion query") is to determine the visibility of an object. Typically, the * application will render the major occluders in the scene, then perform an occlusion query for each detail object in the scene. On subsequent frames, * the previous results of the occlusion queries can be used to decide whether to draw an object or not.</p> */ public class EXTOcclusionQueryBoolean { /** Accepted by the {@code target} parameter of BeginQueryEXT, EndQueryEXT, and GetQueryivEXT. */ public static final int GL_ANY_SAMPLES_PASSED_EXT = 0x8C2F, GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT = 0x8D6A; /** Accepted by the {@code pname} parameter of GetQueryivEXT. */ public static final int GL_CURRENT_QUERY_EXT = 0x8865; /** Accepted by the {@code pname} parameter of GetQueryObjectivEXT and GetQueryObjectuivEXT. */ public static final int GL_QUERY_RESULT_EXT = 0x8866, GL_QUERY_RESULT_AVAILABLE_EXT = 0x8867; protected EXTOcclusionQueryBoolean() { throw new UnsupportedOperationException(); } static boolean isAvailable(GLESCapabilities caps) { return checkFunctions( caps.glGenQueriesEXT, caps.glDeleteQueriesEXT, caps.glIsQueryEXT, caps.glBeginQueryEXT, caps.glEndQueryEXT, caps.glGetQueryivEXT, caps.glGetQueryObjectuivEXT ); } // --- [ glGenQueriesEXT ] --- public static void nglGenQueriesEXT(int n, long ids) { long __functionAddress = GLES.getCapabilities().glGenQueriesEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, n, ids); } public static void glGenQueriesEXT(IntBuffer ids) { nglGenQueriesEXT(ids.remaining(), memAddress(ids)); } public static int glGenQueriesEXT() { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { IntBuffer ids = stack.callocInt(1); nglGenQueriesEXT(1, memAddress(ids)); return ids.get(0); } finally { stack.setPointer(stackPointer); } } // --- [ glDeleteQueriesEXT ] --- public static void nglDeleteQueriesEXT(int n, long ids) { long __functionAddress = GLES.getCapabilities().glDeleteQueriesEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, n, ids); } public static void glDeleteQueriesEXT(IntBuffer ids) { nglDeleteQueriesEXT(ids.remaining(), memAddress(ids)); } public static void glDeleteQueriesEXT(int id) { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { IntBuffer ids = stack.ints(id); nglDeleteQueriesEXT(1, memAddress(ids)); } finally { stack.setPointer(stackPointer); } } // --- [ glIsQueryEXT ] --- public static boolean glIsQueryEXT(int id) { long __functionAddress = GLES.getCapabilities().glIsQueryEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); return callZ(__functionAddress, id); } // --- [ glBeginQueryEXT ] --- public static void glBeginQueryEXT(int target, int id) { long __functionAddress = GLES.getCapabilities().glBeginQueryEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, target, id); } // --- [ glEndQueryEXT ] --- public static void glEndQueryEXT(int target) { long __functionAddress = GLES.getCapabilities().glEndQueryEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, target); } // --- [ glGetQueryivEXT ] --- public static void nglGetQueryivEXT(int target, int pname, long params) { long __functionAddress = GLES.getCapabilities().glGetQueryivEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, target, pname, params); } public static void glGetQueryivEXT(int target, int pname, IntBuffer params) { if ( CHECKS ) checkBuffer(params, 1); nglGetQueryivEXT(target, pname, memAddress(params)); } public static int glGetQueryiEXT(int target, int pname) { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { IntBuffer params = stack.callocInt(1); nglGetQueryivEXT(target, pname, memAddress(params)); return params.get(0); } finally { stack.setPointer(stackPointer); } } // --- [ glGetQueryObjectuivEXT ] --- public static void nglGetQueryObjectuivEXT(int id, int pname, long params) { long __functionAddress = GLES.getCapabilities().glGetQueryObjectuivEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, id, pname, params); } public static void glGetQueryObjectuivEXT(int id, int pname, IntBuffer params) { if ( CHECKS ) checkBuffer(params, 1); nglGetQueryObjectuivEXT(id, pname, memAddress(params)); } public static int glGetQueryObjectuiEXT(int id, int pname) { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { IntBuffer params = stack.callocInt(1); nglGetQueryObjectuivEXT(id, pname, memAddress(params)); return params.get(0); } finally { stack.setPointer(stackPointer); } } /** Array version of: {@link #glGenQueriesEXT GenQueriesEXT} */ public static void glGenQueriesEXT(int[] ids) { long __functionAddress = GLES.getCapabilities().glGenQueriesEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, ids.length, ids); } /** Array version of: {@link #glDeleteQueriesEXT DeleteQueriesEXT} */ public static void glDeleteQueriesEXT(int[] ids) { long __functionAddress = GLES.getCapabilities().glDeleteQueriesEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, ids.length, ids); } /** Array version of: {@link #glGetQueryivEXT GetQueryivEXT} */ public static void glGetQueryivEXT(int target, int pname, int[] params) { long __functionAddress = GLES.getCapabilities().glGetQueryivEXT; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBuffer(params, 1); } callPV(__functionAddress, target, pname, params); } /** Array version of: {@link #glGetQueryObjectuivEXT GetQueryObjectuivEXT} */ public static void glGetQueryObjectuivEXT(int id, int pname, int[] params) { long __functionAddress = GLES.getCapabilities().glGetQueryObjectuivEXT; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBuffer(params, 1); } callPV(__functionAddress, id, pname, params); } }
package org.usfirst.frc.team3070.robot; import java.util.TimerTask; import edu.wpi.first.wpilibj.I2C; import edu.wpi.first.wpilibj.Timer; /** * BNO055 IMU for the FIRST Robotics Competition. * References throughout the code are to the following sensor documentation: * http://git.io/vuOl1 * * To use the sensor, wire up to it over I2C on the roboRIO. * Creating an instance of this class will cause communications with the sensor * to being.All communications with the sensor occur in a separate thread * from your robot code to avoid blocking the main robot program execution. * * Example: * private static BNO055 imu; * * public Robot() { * imu = BNO055.getInstance(BNO055.opmode_t.OPERATION_MODE_IMUPLUS, * BNO055.vector_type_t.VECTOR_EULER); * } * * You can check the status of the sensor by using the following methods: * isSensorPresent(); //Checks if the code can talk to the sensor over I2C * // If this returns false, check your wiring. * isInitialized(); //Checks if the sensor initialization has completed. * // Initialization takes about 3 seconds. You won't get * // position data back from the sensor until its init'd. * isCalibrated(); //The BNO055 will return position data after its init'd, * // but the position data may be inaccurate until all * // required sensors report they are calibrated. Some * // Calibration sequences require you to move the BNO055 * // around. See the method comments for more info. * * Once the sensor calibration is complete , you can get position data by * by using the getVector() method. See this method definiton for usage info. * * This code was originally ported from arduino source developed by Adafruit. * See the original comment header below. * * @author [email protected] * * *ORIGINAL ADAFRUIT HEADER - https://github.com/adafruit/Adafruit_BNO055/ *======================================================================= *This is a library for the BNO055 orientation sensor * *Designed specifically to work with the Adafruit BNO055 Breakout. * *Pick one up today in the adafruit shop! *------> http://www.adafruit.com/products * *These sensors use I2C to communicate, 2 pins are required to interface. * *Adafruit invests time and resources providing this open source code, *please support Adafruit and open-source hardware by purchasing products *from Adafruit! * *Written by KTOWN for Adafruit Industries. * *MIT license, all text above must be included in any redistribution * */ public class BNO055 { //Tread variables private java.util.Timer executor; private static final long THREAD_PERIOD = 20; //ms - max poll rate on sensor. public static final byte BNO055_ADDRESS_A = 0x28; public static final byte BNO055_ADDRESS_B = 0x29; public static final int BNO055_ID = 0xA0; private static BNO055 instance; private static I2C imu; private static int _mode; private static opmode_t requestedMode; //user requested mode of operation. private static vector_type_t requestedVectorType; //State machine variables private volatile int state = 0; private volatile boolean sensorPresent = false; private volatile boolean initialized = false; private volatile double currentTime; //seconds private volatile double nextTime; //seconds private volatile byte[] positionVector = new byte[6]; private volatile long turns = 0; private volatile double[] xyz = new double[3]; public class SystemStatus { public int system_status; public int self_test_result; public int system_error; } public enum reg_t { /* Page id register definition */ BNO055_PAGE_ID_ADDR (0X07), /* PAGE0 REGISTER DEFINITION START*/ BNO055_CHIP_ID_ADDR (0x00), BNO055_ACCEL_REV_ID_ADDR (0x01), BNO055_MAG_REV_ID_ADDR (0x02), BNO055_GYRO_REV_ID_ADDR (0x03), BNO055_SW_REV_ID_LSB_ADDR (0x04), BNO055_SW_REV_ID_MSB_ADDR (0x05), BNO055_BL_REV_ID_ADDR (0X06), /* Accel data register */ BNO055_ACCEL_DATA_X_LSB_ADDR (0X08), BNO055_ACCEL_DATA_X_MSB_ADDR (0X09), BNO055_ACCEL_DATA_Y_LSB_ADDR (0X0A), BNO055_ACCEL_DATA_Y_MSB_ADDR (0X0B), BNO055_ACCEL_DATA_Z_LSB_ADDR (0X0C), BNO055_ACCEL_DATA_Z_MSB_ADDR (0X0D), /* Mag data register */ BNO055_MAG_DATA_X_LSB_ADDR (0X0E), BNO055_MAG_DATA_X_MSB_ADDR (0X0F), BNO055_MAG_DATA_Y_LSB_ADDR (0X10), BNO055_MAG_DATA_Y_MSB_ADDR (0X11), BNO055_MAG_DATA_Z_LSB_ADDR (0X12), BNO055_MAG_DATA_Z_MSB_ADDR (0X13), /* Gyro data registers */ BNO055_GYRO_DATA_X_LSB_ADDR (0X14), BNO055_GYRO_DATA_X_MSB_ADDR (0X15), BNO055_GYRO_DATA_Y_LSB_ADDR (0X16), BNO055_GYRO_DATA_Y_MSB_ADDR (0X17), BNO055_GYRO_DATA_Z_LSB_ADDR (0X18), BNO055_GYRO_DATA_Z_MSB_ADDR (0X19), /* Euler data registers */ BNO055_EULER_H_LSB_ADDR (0X1A), BNO055_EULER_H_MSB_ADDR (0X1B), BNO055_EULER_R_LSB_ADDR (0X1C), BNO055_EULER_R_MSB_ADDR (0X1D), BNO055_EULER_P_LSB_ADDR (0X1E), BNO055_EULER_P_MSB_ADDR (0X1F), /* Quaternion data registers */ BNO055_QUATERNION_DATA_W_LSB_ADDR (0X20), BNO055_QUATERNION_DATA_W_MSB_ADDR (0X21), BNO055_QUATERNION_DATA_X_LSB_ADDR (0X22), BNO055_QUATERNION_DATA_X_MSB_ADDR (0X23), BNO055_QUATERNION_DATA_Y_LSB_ADDR (0X24), BNO055_QUATERNION_DATA_Y_MSB_ADDR (0X25), BNO055_QUATERNION_DATA_Z_LSB_ADDR (0X26), BNO055_QUATERNION_DATA_Z_MSB_ADDR (0X27), /* Linear acceleration data registers */ BNO055_LINEAR_ACCEL_DATA_X_LSB_ADDR (0X28), BNO055_LINEAR_ACCEL_DATA_X_MSB_ADDR (0X29), BNO055_LINEAR_ACCEL_DATA_Y_LSB_ADDR (0X2A), BNO055_LINEAR_ACCEL_DATA_Y_MSB_ADDR (0X2B), BNO055_LINEAR_ACCEL_DATA_Z_LSB_ADDR (0X2C), BNO055_LINEAR_ACCEL_DATA_Z_MSB_ADDR (0X2D), /* Gravity data registers */ BNO055_GRAVITY_DATA_X_LSB_ADDR (0X2E), BNO055_GRAVITY_DATA_X_MSB_ADDR (0X2F), BNO055_GRAVITY_DATA_Y_LSB_ADDR (0X30), BNO055_GRAVITY_DATA_Y_MSB_ADDR (0X31), BNO055_GRAVITY_DATA_Z_LSB_ADDR (0X32), BNO055_GRAVITY_DATA_Z_MSB_ADDR (0X33), /* Temperature data register */ BNO055_TEMP_ADDR (0X34), /* Status registers */ BNO055_CALIB_STAT_ADDR (0X35), BNO055_SELFTEST_RESULT_ADDR (0X36), BNO055_INTR_STAT_ADDR (0X37), BNO055_SYS_CLK_STAT_ADDR (0X38), BNO055_SYS_STAT_ADDR (0X39), BNO055_SYS_ERR_ADDR (0X3A), /* Unit selection register */ BNO055_UNIT_SEL_ADDR (0X3B), BNO055_DATA_SELECT_ADDR (0X3C), /* Mode registers */ BNO055_OPR_MODE_ADDR (0X3D), BNO055_PWR_MODE_ADDR (0X3E), BNO055_SYS_TRIGGER_ADDR (0X3F), BNO055_TEMP_SOURCE_ADDR (0X40), /* Axis remap registers */ BNO055_AXIS_MAP_CONFIG_ADDR (0X41), BNO055_AXIS_MAP_SIGN_ADDR (0X42), /* SIC registers */ BNO055_SIC_MATRIX_0_LSB_ADDR (0X43), BNO055_SIC_MATRIX_0_MSB_ADDR (0X44), BNO055_SIC_MATRIX_1_LSB_ADDR (0X45), BNO055_SIC_MATRIX_1_MSB_ADDR (0X46), BNO055_SIC_MATRIX_2_LSB_ADDR (0X47), BNO055_SIC_MATRIX_2_MSB_ADDR (0X48), BNO055_SIC_MATRIX_3_LSB_ADDR (0X49), BNO055_SIC_MATRIX_3_MSB_ADDR (0X4A), BNO055_SIC_MATRIX_4_LSB_ADDR (0X4B), BNO055_SIC_MATRIX_4_MSB_ADDR (0X4C), BNO055_SIC_MATRIX_5_LSB_ADDR (0X4D), BNO055_SIC_MATRIX_5_MSB_ADDR (0X4E), BNO055_SIC_MATRIX_6_LSB_ADDR (0X4F), BNO055_SIC_MATRIX_6_MSB_ADDR (0X50), BNO055_SIC_MATRIX_7_LSB_ADDR (0X51), BNO055_SIC_MATRIX_7_MSB_ADDR (0X52), BNO055_SIC_MATRIX_8_LSB_ADDR (0X53), BNO055_SIC_MATRIX_8_MSB_ADDR (0X54), /* Accelerometer Offset registers */ ACCEL_OFFSET_X_LSB_ADDR (0X55), ACCEL_OFFSET_X_MSB_ADDR (0X56), ACCEL_OFFSET_Y_LSB_ADDR (0X57), ACCEL_OFFSET_Y_MSB_ADDR (0X58), ACCEL_OFFSET_Z_LSB_ADDR (0X59), ACCEL_OFFSET_Z_MSB_ADDR (0X5A), /* Magnetometer Offset registers */ MAG_OFFSET_X_LSB_ADDR (0X5B), MAG_OFFSET_X_MSB_ADDR (0X5C), MAG_OFFSET_Y_LSB_ADDR (0X5D), MAG_OFFSET_Y_MSB_ADDR (0X5E), MAG_OFFSET_Z_LSB_ADDR (0X5F), MAG_OFFSET_Z_MSB_ADDR (0X60), /* Gyroscope Offset register s*/ GYRO_OFFSET_X_LSB_ADDR (0X61), GYRO_OFFSET_X_MSB_ADDR (0X62), GYRO_OFFSET_Y_LSB_ADDR (0X63), GYRO_OFFSET_Y_MSB_ADDR (0X64), GYRO_OFFSET_Z_LSB_ADDR (0X65), GYRO_OFFSET_Z_MSB_ADDR (0X66), /* Radius registers */ ACCEL_RADIUS_LSB_ADDR (0X67), ACCEL_RADIUS_MSB_ADDR (0X68), MAG_RADIUS_LSB_ADDR (0X69), MAG_RADIUS_MSB_ADDR (0X6A); private final int val; reg_t(int val) { this.val = val; } public int getVal() { return val; } }; public enum powermode_t { POWER_MODE_NORMAL (0X00), POWER_MODE_LOWPOWER (0X01), POWER_MODE_SUSPEND (0X02); private final int val; powermode_t(int val) { this.val = val; } public int getVal() { return val; } }; public enum opmode_t { /* Operation mode settings*/ OPERATION_MODE_CONFIG (0X00), OPERATION_MODE_ACCONLY (0X01), OPERATION_MODE_MAGONLY (0X02), OPERATION_MODE_GYRONLY (0X03), OPERATION_MODE_ACCMAG (0X04), OPERATION_MODE_ACCGYRO (0X05), OPERATION_MODE_MAGGYRO (0X06), OPERATION_MODE_AMG (0X07), OPERATION_MODE_IMUPLUS (0X08), OPERATION_MODE_COMPASS (0X09), OPERATION_MODE_M4G (0X0A), OPERATION_MODE_NDOF_FMC_OFF (0X0B), OPERATION_MODE_NDOF (0X0C); private final int val; opmode_t(int val) { this.val = val; } public int getVal() { return val; } } public class RevInfo { public byte accel_rev; public byte mag_rev; public byte gyro_rev; public short sw_rev; public byte bl_rev; } public class CalData { public byte sys; public byte gyro; public byte accel; public byte mag; } public enum vector_type_t { VECTOR_ACCELEROMETER (reg_t.BNO055_ACCEL_DATA_X_LSB_ADDR.getVal()), VECTOR_MAGNETOMETER (reg_t.BNO055_MAG_DATA_X_LSB_ADDR.getVal()), VECTOR_GYROSCOPE (reg_t.BNO055_GYRO_DATA_X_LSB_ADDR.getVal()), VECTOR_EULER (reg_t.BNO055_EULER_H_LSB_ADDR.getVal()), VECTOR_LINEARACCEL (reg_t.BNO055_LINEAR_ACCEL_DATA_X_LSB_ADDR.getVal()), VECTOR_GRAVITY (reg_t.BNO055_GRAVITY_DATA_X_LSB_ADDR.getVal()); private final int val; vector_type_t(int val) { this.val = val; } public int getVal() { return val; } }; /** * Instantiates a new BNO055 class. * * @param port the physical port the sensor is plugged into on the roboRio * @param address the address the sensor is at (0x28 or 0x29) */ private BNO055(I2C.Port port, byte address) { imu = new I2C(port, address); executor = new java.util.Timer(); executor.schedule(new BNO055UpdateTask(this), 0L, THREAD_PERIOD); } /** * Get an instance of the IMU object. * * @param mode the operating mode to run the sensor in. * @param port the physical port the sensor is plugged into on the roboRio * @param address the address the sensor is at (0x28 or 0x29) * @return the instantiated BNO055 object */ public static BNO055 getInstance(opmode_t mode, vector_type_t vectorType, I2C.Port port, byte address) { if(instance == null) { instance = new BNO055(port, address); } requestedMode = mode; requestedVectorType = vectorType; return instance; } /** * Get an instance of the IMU object plugged into the onboard I2C header. * Using the default address (0x28) * * @param mode the operating mode to run the sensor in. * @param vectorType the format the position vector data should be returned * in (if you don't know use VECTOR_EULER). * @return the instantiated BNO055 object */ public static BNO055 getInstance(opmode_t mode, vector_type_t vectorType) { return getInstance(mode, vectorType, I2C.Port.kOnboard, BNO055_ADDRESS_A); } /** * Called periodically. Communicates with the sensor, and checks its state. */ private void update() { currentTime = Timer.getFPGATimestamp(); //seconds if(!initialized) { // System.out.println("State: " + state + ". curr: " + currentTime // + ", next: " + nextTime); //Step through process of initializing the sensor in a non- // blocking manner. This sequence of events follows the process // defined in the original adafruit source as closely as possible. // XXX: It's likely some of these delays can be optimized out. switch(state) { case 0: //Wait for the sensor to be present if((0xFF & read8(reg_t.BNO055_CHIP_ID_ADDR)) != BNO055_ID) { //Sensor not present, keep trying sensorPresent = false; } else { //Sensor present, go to next state sensorPresent = true; state++; nextTime = Timer.getFPGATimestamp() + 0.050; } break; case 1: if(currentTime >= nextTime) { //Switch to config mode (just in case since this is the default) setMode(opmode_t.OPERATION_MODE_CONFIG.getVal()); nextTime = Timer.getFPGATimestamp() + 0.050; state++; } break; case 2: // Reset if(currentTime >= nextTime){ write8(reg_t.BNO055_SYS_TRIGGER_ADDR, (byte) 0x20); state++; } break; case 3: //Wait for the sensor to be present if((0xFF & read8(reg_t.BNO055_CHIP_ID_ADDR)) == BNO055_ID) { //Sensor present, go to next state state++; //Log current time nextTime = Timer.getFPGATimestamp() + 0.050; } break; case 4: //Wait at least 50ms if(currentTime >= nextTime) { /* Set to normal power mode */ write8(reg_t.BNO055_PWR_MODE_ADDR, (byte) powermode_t.POWER_MODE_NORMAL.getVal()); nextTime = Timer.getFPGATimestamp() + 0.050; state++; } break; case 5: //Use external crystal - 32.768 kHz if(currentTime >= nextTime) { write8(reg_t.BNO055_PAGE_ID_ADDR, (byte) 0x00); nextTime = Timer.getFPGATimestamp() + 0.050; state++; } break; case 6: if(currentTime >= nextTime) { write8(reg_t.BNO055_SYS_TRIGGER_ADDR, (byte) 0x80); nextTime = Timer.getFPGATimestamp() + 0.500; state++; } break; case 7: //Set operating mode to mode requested at instantiation if(currentTime >= nextTime) { setMode(requestedMode); nextTime = Timer.getFPGATimestamp() + 1.05; state++; } break; case 8: if(currentTime >= nextTime) { state++; } case 9: initialized = true; break; default: //Should never get here - Fail safe initialized = false; } } else { //Sensor is initialized, periodically query position data calculateVector(); } } /** * Query the sensor for position data. */ private void calculateVector() { double[] pos = new double[3]; short x = 0, y = 0, z = 0; double headingDiff = 0.0; // Read vector data (6 bytes) readLen(requestedVectorType.getVal(), positionVector); x = (short)((positionVector[0] & 0xFF) | ((positionVector[1] << 8) & 0xFF00)); y = (short)((positionVector[2] & 0xFF) | ((positionVector[3] << 8) & 0xFF00)); z = (short)((positionVector[4] & 0xFF) | ((positionVector[5] << 8) & 0xFF00)); /* Convert the value to an appropriate range (section 3.6.4) */ /* and assign the value to the Vector type */ switch(requestedVectorType) { case VECTOR_MAGNETOMETER: /* 1uT = 16 LSB */ pos[0] = ((double)x)/16.0; pos[1] = ((double)y)/16.0; pos[2] = ((double)z)/16.0; break; case VECTOR_GYROSCOPE: /* 1rps = 900 LSB */ pos[0] = ((double)x)/900.0; pos[1] = ((double)y)/900.0; pos[2] = ((double)z)/900.0; break; case VECTOR_EULER: /* 1 degree = 16 LSB */ pos[0] = ((double)x)/16.0; pos[1] = ((double)y)/16.0; pos[2] = ((double)z)/16.0; break; case VECTOR_ACCELEROMETER: case VECTOR_LINEARACCEL: case VECTOR_GRAVITY: /* 1m/s^2 = 100 LSB */ pos[0] = ((double)x)/100.0; pos[1] = ((double)y)/100.0; pos[2] = ((double)z)/100.0; break; } //calculate turns headingDiff = xyz[0] - pos[0]; if(Math.abs(headingDiff) >= 350) { //We've traveled past the zero heading position if(headingDiff > 0) { turns++; } else { turns--; } } //Update position vectors xyz = pos; } /** * Puts the chip in the specified operating mode * @param mode */ public void setMode(opmode_t mode) { setMode(mode.getVal()); } private void setMode(int mode) { _mode = mode; write8(reg_t.BNO055_OPR_MODE_ADDR, (byte) _mode); } /** * Gets the latest system status info * @return */ public SystemStatus getSystemStatus() { SystemStatus status = new SystemStatus(); write8(reg_t.BNO055_PAGE_ID_ADDR, (byte) 0x00); /* System Status (see section 4.3.58) --------------------------------- 0 = Idle 1 = System Error 2 = Initializing Peripherals 3 = System Initalization 4 = Executing Self-Test 5 = Sensor fusion algorithm running 6 = System running without fusion algorithms */ status.system_status = read8(reg_t.BNO055_SYS_STAT_ADDR); /* Self Test Results (see section ) -------------------------------- 1 = test passed, 0 = test failed Bit 0 = Accelerometer self test Bit 1 = Magnetometer self test Bit 2 = Gyroscope self test Bit 3 = MCU self test 0x0F = all good! */ status.self_test_result = read8(reg_t.BNO055_SELFTEST_RESULT_ADDR); /* System Error (see section 4.3.59) --------------------------------- 0 = No error 1 = Peripheral initialization error 2 = System initialization error 3 = Self test result failed 4 = Register map value out of range 5 = Register map address out of range 6 = Register map write error 7 = BNO low power mode not available for selected operation mode 8 = Accelerometer power mode not available 9 = Fusion algorithm configuration error A = Sensor configuration error */ status.system_error = read8(reg_t.BNO055_SYS_ERR_ADDR); return status; } /** * Gets the chip revision numbers * * @return the chips revision information */ public RevInfo getRevInfo() { int a = 0, b = 0; RevInfo info = new RevInfo(); /* Check the accelerometer revision */ info.accel_rev = read8(reg_t.BNO055_ACCEL_REV_ID_ADDR); /* Check the magnetometer revision */ info.mag_rev = read8(reg_t.BNO055_MAG_REV_ID_ADDR); /* Check the gyroscope revision */ info.gyro_rev = read8(reg_t.BNO055_GYRO_REV_ID_ADDR); /* Check the SW revision */ info.bl_rev = read8(reg_t.BNO055_BL_REV_ID_ADDR); a = read8(reg_t.BNO055_SW_REV_ID_LSB_ADDR); b = read8(reg_t.BNO055_SW_REV_ID_MSB_ADDR); info.sw_rev = (short) ((b << 8) | a); return info; } /** * Diagnostic method to determine if communications with the sensor are active. * Note this method returns true after first establishing communications * with the sensor. * Communications are not actively monitored once sensor initialization * has started. * @return true if the sensor is found on the I2C bus */ public boolean isSensorPresent() { return sensorPresent; } /** * After power is applied, the sensor needs to be configured for use. * During this initialization period the sensor will not return position * vector data. Once initialization is complete, data can be read, * although the sensor may not have completed calibration. * See isCalibrated. * @return true when the sensor is initialized. */ public boolean isInitialized() { return initialized; } /** * Gets current calibration state. * @return each value will be set to 0 if not calibrated, 3 if fully * calibrated. */ public CalData getCalibration() { CalData data = new CalData(); int rawCalData = read8(reg_t.BNO055_CALIB_STAT_ADDR); data.sys = (byte) ((rawCalData >> 6) & 0x03); data.gyro = (byte) ((rawCalData >> 4) & 0x03); data.accel = (byte) ((rawCalData >> 2) & 0x03); data.mag = (byte) (rawCalData & 0x03); return data; } /** * Returns true if all required sensors (accelerometer, magnetometer, * gyroscope) have completed their respective calibration sequence. * Only sensors required by the current operating mode are checked. * See Section 3.3. * @return true if calibration is complete for all sensors required for the * mode the sensor is currently operating in. */ public boolean isCalibrated() { boolean retVal = true; //Per Table 3-3 boolean[][] sensorModeMap = new boolean[][]{ //{accel, mag, gyro} {false, false, false}, // OPERATION_MODE_CONFIG { true, false, false}, // OPERATION_MODE_ACCONLY {false, true, false}, // OPERATION_MODE_MAGONLY {false, false, true}, // OPERATION_MODE_GYRONLY { true, true, false}, // OPERATION_MODE_ACCMAG { true, false, true}, // OPERATION_MODE_ACCGYRO {false, true, true}, // OPERATION_MODE_MAGGYRO { true, true, true}, // OPERATION_MODE_AMG { true, false, true}, // OPERATION_MODE_IMUPLUS { true, true, false}, // OPERATION_MODE_COMPASS { true, true, false}, // OPERATION_MODE_M4G { true, true, true}, // OPERATION_MODE_NDOF_FMC_OFF { true, true, true} // OPERATION_MODE_NDOF }; CalData data = getCalibration(); if(sensorModeMap[_mode][0]) //Accelerometer used retVal = retVal && (data.accel >= 3); if(sensorModeMap[_mode][1]) //Magnetometer used retVal = retVal && (data.mag >= 3); if(sensorModeMap[_mode][2]) //Gyroscope used retVal = retVal && (data.gyro >= 3); return retVal; } /** * Get the sensors internal temperature. * @return temperature in degrees celsius. */ public int getTemp() { return (read8(reg_t.BNO055_TEMP_ADDR)); } /** * Gets a vector representing the sensors position (heading, roll, pitch). * heading: 0 to 360 degrees * roll: -90 to +90 degrees * pitch: -180 to +180 degrees * * For continuous rotation heading (doesn't roll over between 360/0) see * the getHeading() method. * * Maximum data output rates for Fusion modes - See 3.6.3 * * Operating Mode Data Output Rate * IMU 100 Hz * COMPASS 20 Hz * M4G 50 Hz * NDOF_FMC_OFF 100 Hz * NDOF 100 Hz * * @return a vector [heading, roll, pitch] */ public double[] getVector() { return xyz; } /** * The heading of the sensor (x axis) in continuous format. Eg rotating the * sensor clockwise two full rotations will return a value of 720 degrees. * The getVector method will return heading in a constrained 0 - 360 deg * format if required. * @return heading in degrees */ public double getHeading() { return xyz[0] + turns * 360; } /** * Writes an 8 bit value over I2C * @param reg the register to write the data to * @param value a byte of data to write * @return whatever I2CJNI.i2CWrite returns. It's not documented in the wpilib javadocs! */ private boolean write8(reg_t reg, byte value) { boolean retVal = false; retVal = imu.write(reg.getVal(), value); return retVal; } /** * Reads an 8 bit value over I2C * @param reg the register to read from. * @return */ private byte read8(reg_t reg) { byte[] vals = new byte[1]; readLen(reg, vals); return vals[0]; } /** * Reads the specified number of bytes over I2C * * @param reg the address to read from * @param buffer to store the read data into * @return true on success */ private boolean readLen(reg_t reg, byte[] buffer) { return readLen(reg.getVal(), buffer); } /** * Reads the specified number of bytes over I2C * * @param reg the address to read from * @param buffer the size of the data to read * @return true on success */ private boolean readLen(int reg, byte[] buffer) { boolean retVal = true; if (buffer == null || buffer.length < 1) { return false; } retVal = !imu.read(reg, buffer.length, buffer); return retVal; } private class BNO055UpdateTask extends TimerTask { private BNO055 imu; private BNO055UpdateTask(BNO055 imu) { if (imu == null) { throw new NullPointerException("BNO055 pointer null"); } this.imu = imu; } /** * Called periodically in its own thread */ public void run() { imu.update(); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: BseCharge.proto package com.xinqihd.sns.gameserver.proto; public final class XinqiBseCharge { private XinqiBseCharge() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface BseChargeOrBuilder extends com.google.protobuf.MessageOrBuilder { // required bool success = 1; boolean hasSuccess(); boolean getSuccess(); // optional string message = 2; boolean hasMessage(); String getMessage(); // optional int32 yuanbao = 3; boolean hasYuanbao(); int getYuanbao(); } public static final class BseCharge extends com.google.protobuf.GeneratedMessage implements BseChargeOrBuilder { // Use BseCharge.newBuilder() to construct. private BseCharge(Builder builder) { super(builder); } private BseCharge(boolean noInit) {} private static final BseCharge defaultInstance; public static BseCharge getDefaultInstance() { return defaultInstance; } public BseCharge getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.xinqihd.sns.gameserver.proto.XinqiBseCharge.internal_static_com_xinqihd_sns_gameserver_proto_BseCharge_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.xinqihd.sns.gameserver.proto.XinqiBseCharge.internal_static_com_xinqihd_sns_gameserver_proto_BseCharge_fieldAccessorTable; } private int bitField0_; // required bool success = 1; public static final int SUCCESS_FIELD_NUMBER = 1; private boolean success_; public boolean hasSuccess() { return ((bitField0_ & 0x00000001) == 0x00000001); } public boolean getSuccess() { return success_; } // optional string message = 2; public static final int MESSAGE_FIELD_NUMBER = 2; private java.lang.Object message_; public boolean hasMessage() { return ((bitField0_ & 0x00000002) == 0x00000002); } public String getMessage() { java.lang.Object ref = message_; if (ref instanceof String) { return (String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (com.google.protobuf.Internal.isValidUtf8(bs)) { message_ = s; } return s; } } private com.google.protobuf.ByteString getMessageBytes() { java.lang.Object ref = message_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); message_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional int32 yuanbao = 3; public static final int YUANBAO_FIELD_NUMBER = 3; private int yuanbao_; public boolean hasYuanbao() { return ((bitField0_ & 0x00000004) == 0x00000004); } public int getYuanbao() { return yuanbao_; } private void initFields() { success_ = false; message_ = ""; yuanbao_ = 0; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasSuccess()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBool(1, success_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getMessageBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeInt32(3, yuanbao_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(1, success_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, getMessageBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(3, yuanbao_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseChargeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.xinqihd.sns.gameserver.proto.XinqiBseCharge.internal_static_com_xinqihd_sns_gameserver_proto_BseCharge_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.xinqihd.sns.gameserver.proto.XinqiBseCharge.internal_static_com_xinqihd_sns_gameserver_proto_BseCharge_fieldAccessorTable; } // Construct using com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); success_ = false; bitField0_ = (bitField0_ & ~0x00000001); message_ = ""; bitField0_ = (bitField0_ & ~0x00000002); yuanbao_ = 0; bitField0_ = (bitField0_ & ~0x00000004); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge.getDescriptor(); } public com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge getDefaultInstanceForType() { return com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge.getDefaultInstance(); } public com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge build() { com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge buildPartial() { com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge result = new com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.success_ = success_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.message_ = message_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.yuanbao_ = yuanbao_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge) { return mergeFrom((com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge other) { if (other == com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge.getDefaultInstance()) return this; if (other.hasSuccess()) { setSuccess(other.getSuccess()); } if (other.hasMessage()) { setMessage(other.getMessage()); } if (other.hasYuanbao()) { setYuanbao(other.getYuanbao()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasSuccess()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 8: { bitField0_ |= 0x00000001; success_ = input.readBool(); break; } case 18: { bitField0_ |= 0x00000002; message_ = input.readBytes(); break; } case 24: { bitField0_ |= 0x00000004; yuanbao_ = input.readInt32(); break; } } } } private int bitField0_; // required bool success = 1; private boolean success_ ; public boolean hasSuccess() { return ((bitField0_ & 0x00000001) == 0x00000001); } public boolean getSuccess() { return success_; } public Builder setSuccess(boolean value) { bitField0_ |= 0x00000001; success_ = value; onChanged(); return this; } public Builder clearSuccess() { bitField0_ = (bitField0_ & ~0x00000001); success_ = false; onChanged(); return this; } // optional string message = 2; private java.lang.Object message_ = ""; public boolean hasMessage() { return ((bitField0_ & 0x00000002) == 0x00000002); } public String getMessage() { java.lang.Object ref = message_; if (!(ref instanceof String)) { String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); message_ = s; return s; } else { return (String) ref; } } public Builder setMessage(String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; message_ = value; onChanged(); return this; } public Builder clearMessage() { bitField0_ = (bitField0_ & ~0x00000002); message_ = getDefaultInstance().getMessage(); onChanged(); return this; } void setMessage(com.google.protobuf.ByteString value) { bitField0_ |= 0x00000002; message_ = value; onChanged(); } // optional int32 yuanbao = 3; private int yuanbao_ ; public boolean hasYuanbao() { return ((bitField0_ & 0x00000004) == 0x00000004); } public int getYuanbao() { return yuanbao_; } public Builder setYuanbao(int value) { bitField0_ |= 0x00000004; yuanbao_ = value; onChanged(); return this; } public Builder clearYuanbao() { bitField0_ = (bitField0_ & ~0x00000004); yuanbao_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.xinqihd.sns.gameserver.proto.BseCharge) } static { defaultInstance = new BseCharge(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:com.xinqihd.sns.gameserver.proto.BseCharge) } private static com.google.protobuf.Descriptors.Descriptor internal_static_com_xinqihd_sns_gameserver_proto_BseCharge_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_com_xinqihd_sns_gameserver_proto_BseCharge_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\017BseCharge.proto\022 com.xinqihd.sns.games" + "erver.proto\">\n\tBseCharge\022\017\n\007success\030\001 \002(" + "\010\022\017\n\007message\030\002 \001(\t\022\017\n\007yuanbao\030\003 \001(\005B\020B\016X" + "inqiBseCharge" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_com_xinqihd_sns_gameserver_proto_BseCharge_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_com_xinqihd_sns_gameserver_proto_BseCharge_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_com_xinqihd_sns_gameserver_proto_BseCharge_descriptor, new java.lang.String[] { "Success", "Message", "Yuanbao", }, com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge.class, com.xinqihd.sns.gameserver.proto.XinqiBseCharge.BseCharge.Builder.class); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); } // @@protoc_insertion_point(outer_class_scope) }
/* * 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.globalaccelerator.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/globalaccelerator-2018-08-08/ListCustomRoutingAccelerators" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListCustomRoutingAcceleratorsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The list of custom routing accelerators for a customer account. * </p> */ private java.util.List<CustomRoutingAccelerator> accelerators; /** * <p> * The token for the next set of results. You receive this token from a previous call. * </p> */ private String nextToken; /** * <p> * The list of custom routing accelerators for a customer account. * </p> * * @return The list of custom routing accelerators for a customer account. */ public java.util.List<CustomRoutingAccelerator> getAccelerators() { return accelerators; } /** * <p> * The list of custom routing accelerators for a customer account. * </p> * * @param accelerators * The list of custom routing accelerators for a customer account. */ public void setAccelerators(java.util.Collection<CustomRoutingAccelerator> accelerators) { if (accelerators == null) { this.accelerators = null; return; } this.accelerators = new java.util.ArrayList<CustomRoutingAccelerator>(accelerators); } /** * <p> * The list of custom routing accelerators for a customer account. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setAccelerators(java.util.Collection)} or {@link #withAccelerators(java.util.Collection)} if you want to * override the existing values. * </p> * * @param accelerators * The list of custom routing accelerators for a customer account. * @return Returns a reference to this object so that method calls can be chained together. */ public ListCustomRoutingAcceleratorsResult withAccelerators(CustomRoutingAccelerator... accelerators) { if (this.accelerators == null) { setAccelerators(new java.util.ArrayList<CustomRoutingAccelerator>(accelerators.length)); } for (CustomRoutingAccelerator ele : accelerators) { this.accelerators.add(ele); } return this; } /** * <p> * The list of custom routing accelerators for a customer account. * </p> * * @param accelerators * The list of custom routing accelerators for a customer account. * @return Returns a reference to this object so that method calls can be chained together. */ public ListCustomRoutingAcceleratorsResult withAccelerators(java.util.Collection<CustomRoutingAccelerator> accelerators) { setAccelerators(accelerators); return this; } /** * <p> * The token for the next set of results. You receive this token from a previous call. * </p> * * @param nextToken * The token for the next set of results. You receive this token from a previous call. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * The token for the next set of results. You receive this token from a previous call. * </p> * * @return The token for the next set of results. You receive this token from a previous call. */ public String getNextToken() { return this.nextToken; } /** * <p> * The token for the next set of results. You receive this token from a previous call. * </p> * * @param nextToken * The token for the next set of results. You receive this token from a previous call. * @return Returns a reference to this object so that method calls can be chained together. */ public ListCustomRoutingAcceleratorsResult withNextToken(String nextToken) { setNextToken(nextToken); 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 (getAccelerators() != null) sb.append("Accelerators: ").append(getAccelerators()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListCustomRoutingAcceleratorsResult == false) return false; ListCustomRoutingAcceleratorsResult other = (ListCustomRoutingAcceleratorsResult) obj; if (other.getAccelerators() == null ^ this.getAccelerators() == null) return false; if (other.getAccelerators() != null && other.getAccelerators().equals(this.getAccelerators()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAccelerators() == null) ? 0 : getAccelerators().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); return hashCode; } @Override public ListCustomRoutingAcceleratorsResult clone() { try { return (ListCustomRoutingAcceleratorsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.authenticator; import static org.mockito.MockitoAnnotations.initMocks; import com.google.android.apps.authenticator.AccountDb.OtpType; import com.google.android.apps.authenticator.dataimport.ImportController; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator2.R; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.test.ActivityInstrumentationTestCase2; import android.test.MoreAsserts; import android.view.View; import org.mockito.Mock; import java.util.ArrayList; import java.util.List; /** * Unit test for authenticator activity (part/shard 2). * * @author [email protected] (Sarvar Patel) */ public class AuthenticatorActivityPart2Test extends ActivityInstrumentationTestCase2<AuthenticatorActivity> { private AccountDb mAccountDb; @Mock private ImportController mMockDataImportController; public AuthenticatorActivityPart2Test() { super(TestUtilities.APP_PACKAGE_NAME, AuthenticatorActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext()); mAccountDb = DependencyInjector.getAccountDb(); initMocks(this); DependencyInjector.setDataImportController(mMockDataImportController); } @Override protected void tearDown() throws Exception { // Stop the activity to avoid it using the DependencyInjector after it's been closed. TestUtilities.invokeFinishActivityOnUiThread(getActivity()); DependencyInjector.close(); super.tearDown(); } public void testAccountSetup_validTotpUriAccepted() throws Throwable { getActivity(); String secret = "CQAHUXJ2VWDI7WFF"; String accountName = "9.99.99.999"; callOnActivityResultOnUiThreadWithScannedUri( "otpauth://totp/" + accountName + "?secret=" + secret); List<String> accountNames = new ArrayList<String>(); assertEquals(1, mAccountDb.getNames(accountNames)); assertEquals(accountName, accountNames.get(0)); assertEquals(secret, mAccountDb.getSecret(accountName)); assertEquals(OtpType.TOTP, mAccountDb.getType(accountName)); assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue } public void testAccountSetup_validHotpUriWithoutCounterAccepted() throws Throwable { getActivity(); String secret = "CQAHUXJ2VWDI7WFF"; String accountName = "9.99.99.999"; callOnActivityResultOnUiThreadWithScannedUri( "otpauth://hotp/" + accountName + "?secret=" + secret); List<String> accountNames = new ArrayList<String>(); assertEquals(1, mAccountDb.getNames(accountNames)); assertEquals(accountName, accountNames.get(0)); assertEquals(secret, mAccountDb.getSecret(accountName)); assertEquals(OtpType.HOTP, mAccountDb.getType(accountName)); assertEquals(new Integer(0), mAccountDb.getCounter(accountName)); assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue } public void testAccountSetup_validHotpUriWithCounterAccepted() throws Throwable { getActivity(); String secret = "CQAHUXJ2VWDI7WFF"; String accountName = "9.99.99.999"; callOnActivityResultOnUiThreadWithScannedUri( "otpauth://hotp/" + accountName + "?secret=" + secret + "&counter=264"); List<String> accountNames = new ArrayList<String>(); assertEquals(1, mAccountDb.getNames(accountNames)); assertEquals(accountName, accountNames.get(0)); assertEquals(secret, mAccountDb.getSecret(accountName)); assertEquals(OtpType.HOTP, mAccountDb.getType(accountName)); assertEquals(new Integer(264), mAccountDb.getCounter(accountName)); assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue } ///////////////////// Tests with Scanned URIs returned in ActivityResult //////////////// private void checkBadAccountSetup(String uri, int dialogId) throws Throwable { getActivity(); callOnActivityResultOnUiThreadWithScannedUri(uri); List<String> accountNames = new ArrayList<String>(); mAccountDb.getNames(accountNames); MoreAsserts.assertEmpty(accountNames); TestUtilities.assertDialogWasDisplayed(getActivity(), dialogId); assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue } public void testAccountSetup_uriWithMissingSecretRejected() throws Throwable { checkBadAccountSetup("otpauth://totp/9.99.99.999?secret2=unused", Utilities.INVALID_SECRET_IN_QR_CODE); } public void testAccountSetup_uriWithEmptySecretRejected() throws Throwable { checkBadAccountSetup("otpauth://totp/9.99.99.999?secret=", Utilities.INVALID_SECRET_IN_QR_CODE); } public void testAccountSetup_uriWithInvalidSecretRejected() throws Throwable { // The URI contains an invalid base32 characters: 1 and 8 checkBadAccountSetup("otpauth://totp/9.99.99.999?secret=CQ1HUXJ2VWDI8WFF", Utilities.INVALID_SECRET_IN_QR_CODE); } public void testAccountSetup_withNullUri() throws Throwable { checkBadAccountSetup(null, Utilities.INVALID_QR_CODE); } public void testAccountSetup_withNullScheme() throws Throwable { checkBadAccountSetup("totp/9.99.99.999?secret=CQAHUXJ2VWDI7WFF", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withBadScheme() throws Throwable { checkBadAccountSetup("otpauth?//totp/9.99.99.999?secret=CQAHUXJ2VWDI7WFF", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withEmptyAuthority() throws Throwable { checkBadAccountSetup("otpauth:///9.99.99.999?secret=CQAHUXJ2VWDI7WFF", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withBadAuthority() throws Throwable { checkBadAccountSetup("otpauth://bad/9.99.99.999?secret=CQAHUXJ2VWDI7WFF", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withEmptyUserAccount() throws Throwable { checkBadAccountSetup("otpauth://totp/?secret=CQAHUXJ2VWDI7WFF", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withWhiteSpaceForUserAccount() throws Throwable { checkBadAccountSetup("otpauth://totp/ ?secret=CQAHUXJ2VWDI7WFF", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withCounterTooBig() throws Throwable { checkBadAccountSetup("otpauth://hotp/?secret=CQAHUXJ2VWDI7WFF&counter=34359738368", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withNonNumericCounter() throws Throwable { checkBadAccountSetup("otpauth://hotp/?secret=CQAHUXJ2VWDI7WFF&counter=abc", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withNullIntent() throws Throwable { getActivity(); callOnActivityResultOnUiThread(AuthenticatorActivity.SCAN_REQUEST, Activity.RESULT_OK, null); List<String> accountNames = new ArrayList<String>(); mAccountDb.getNames(accountNames); MoreAsserts.assertEmpty(accountNames); TestUtilities.assertDialogWasDisplayed(getActivity(), Utilities.INVALID_QR_CODE); assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue } /** * Invokes the activity's {@code onActivityResult} as though it received the specified scanned * URI. */ private void callOnActivityResultOnUiThreadWithScannedUri(String uri) throws Throwable { Intent intent = new Intent(Intent.ACTION_VIEW, null); intent.putExtra("SCAN_RESULT", uri); callOnActivityResultOnUiThread(AuthenticatorActivity.SCAN_REQUEST, Activity.RESULT_OK, intent); } private void callOnActivityResultOnUiThread( final int requestCode, final int resultCode, final Intent intent) throws Throwable { runTestOnUiThread(new Runnable() { @Override public void run () { getActivity().onActivityResult(requestCode, resultCode, intent); } }); } public void testDirectAccountSetupWithConfirmationAccepted() throws Throwable { // start AuthenticatorActivity with a valid Uri for account setup. String secret = "CQAHUXJ2VWDI7WFF"; String accountName = "9.99.99.999"; Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("otpauth://totp/" + accountName + "?secret=" + secret)); setActivityIntent(intent); getActivity(); // check main screen does not have focus because of save confirmation dialog. View contentView = getActivity().findViewById(R.id.content_no_accounts); assertFalse(contentView.hasWindowFocus()); // click Ok on the dialog box which has focus. TestUtilities.tapDialogPositiveButton(this); // check main screen gets focus back after dialog window disappears. TestUtilities.waitForWindowFocus(contentView); // check update to database. List<String> accountNames = new ArrayList<String>(); assertEquals(1, mAccountDb.getNames(accountNames)); assertEquals(accountName, accountNames.get(0)); assertEquals(secret, mAccountDb.getSecret(accountName)); assertEquals(OtpType.TOTP, mAccountDb.getType(accountName)); } public void testDirectAccountSetupWithConfirmationRejected() throws Throwable { // start AuthenticatorActivity with a valid Uri for account setup. String secret = "CQAHUXJ2VWDI7WFF"; String accountName = "9.99.99.999"; Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("otpauth://totp/" + accountName + "?secret=" + secret)); setActivityIntent(intent); getActivity(); // check main screen does not have focus because of save confirmation dialog. View contentView = getActivity().findViewById(R.id.content_no_accounts); assertFalse(contentView.hasWindowFocus()); // click Cancel on the save confirmation dialog box. TestUtilities.tapDialogNegativeButton(this); // check main screen gets focus back after dialog window disappears. TestUtilities.waitForWindowFocus(contentView); // check database has not been updated. List<String> accountNames = new ArrayList<String>(); assertEquals(0, mAccountDb.getNames(accountNames)); assertEquals(null, mAccountDb.getSecret(accountName)); } }
package net.bytebuddy.benchmark; import net.bytebuddy.benchmark.specimen.ExampleClass; import org.hamcrest.CoreMatchers; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; public class ClassByExtensionBenchmarkTest { private static final boolean BOOLEAN_VALUE = true; private static final byte BYTE_VALUE = 42; private static final short SHORT_VALUE = 42; private static final char CHAR_VALUE = '@'; private static final int INT_VALUE = 42; private static final long LONG_VALUE = 42L; private static final float FLOAT_VALUE = 42f; private static final double DOUBLE_VALUE = 42d; private static final Object REFERENCE_VALUE = "foo"; private ClassByExtensionBenchmark classByExtensionBenchmark; private static void assertReturnValues(ExampleClass exampleClass) { assertThat(exampleClass.method(BOOLEAN_VALUE), is(BOOLEAN_VALUE)); assertThat(exampleClass.method(BYTE_VALUE), is(BYTE_VALUE)); assertThat(exampleClass.method(SHORT_VALUE), is(SHORT_VALUE)); assertThat(exampleClass.method(CHAR_VALUE), is(CHAR_VALUE)); assertThat(exampleClass.method(INT_VALUE), is(INT_VALUE)); assertThat(exampleClass.method(LONG_VALUE), is(LONG_VALUE)); assertThat(exampleClass.method(FLOAT_VALUE), is(FLOAT_VALUE)); assertThat(exampleClass.method(DOUBLE_VALUE), is(DOUBLE_VALUE)); assertThat(exampleClass.method(REFERENCE_VALUE), is(REFERENCE_VALUE)); assertThat(exampleClass.method(BOOLEAN_VALUE, BOOLEAN_VALUE, BOOLEAN_VALUE), is(new boolean[]{BOOLEAN_VALUE, BOOLEAN_VALUE, BOOLEAN_VALUE})); assertThat(exampleClass.method(BYTE_VALUE, BYTE_VALUE, BYTE_VALUE), is(new byte[]{BYTE_VALUE, BYTE_VALUE, BYTE_VALUE})); assertThat(exampleClass.method(SHORT_VALUE, SHORT_VALUE, SHORT_VALUE), is(new short[]{SHORT_VALUE, SHORT_VALUE, SHORT_VALUE})); assertThat(exampleClass.method(CHAR_VALUE, CHAR_VALUE, CHAR_VALUE), is(new char[]{CHAR_VALUE, CHAR_VALUE, CHAR_VALUE})); assertThat(exampleClass.method(INT_VALUE, INT_VALUE, INT_VALUE), is(new int[]{INT_VALUE, INT_VALUE, INT_VALUE})); assertThat(exampleClass.method(LONG_VALUE, LONG_VALUE, LONG_VALUE), is(new long[]{LONG_VALUE, LONG_VALUE, LONG_VALUE})); assertThat(exampleClass.method(FLOAT_VALUE, FLOAT_VALUE, FLOAT_VALUE), is(new float[]{FLOAT_VALUE, FLOAT_VALUE, FLOAT_VALUE})); assertThat(exampleClass.method(DOUBLE_VALUE, DOUBLE_VALUE, DOUBLE_VALUE), is(new double[]{DOUBLE_VALUE, DOUBLE_VALUE, DOUBLE_VALUE})); assertThat(exampleClass.method(REFERENCE_VALUE, REFERENCE_VALUE, REFERENCE_VALUE), is(new Object[]{REFERENCE_VALUE, REFERENCE_VALUE, REFERENCE_VALUE})); } @Before public void setUp() throws Exception { classByExtensionBenchmark = new ClassByExtensionBenchmark(); classByExtensionBenchmark.setup(); } @Test public void testBaseline() throws Exception { ExampleClass instance = classByExtensionBenchmark.baseline(); assertThat(instance.getClass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertReturnValues(instance); } @Test public void testByteBuddyWithProxiesClassCreation() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkByteBuddyWithProxy(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkByteBuddyWithProxy().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } @Test public void testByteBuddyWithProxiesClassCreationCached() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkByteBuddyWithProxyAndReusedDelegator(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkByteBuddyWithProxy().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } @Test public void testByteBuddyWithProxiesClassCreationWithTypePool() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkByteBuddyWithProxyWithTypePool(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkByteBuddyWithProxy().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } @Test public void testByteBuddyWithProxiesClassCreationCachedWithTypePool() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkByteBuddyWithProxyAndReusedDelegatorWithTypePool(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkByteBuddyWithProxy().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } @Test public void testByteBuddyWithAccessorClassCreation() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkByteBuddyWithAccessor(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkByteBuddyWithProxy().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } @Test public void testByteBuddyWithAccessorClassCreationCached() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkByteBuddyWithAccessorAndReusedDelegator(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkByteBuddyWithProxy().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } @Test public void testByteBuddyWithAccessorClassCreationWithTypePool() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkByteBuddyWithAccessorWithTypePool(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkByteBuddyWithProxy().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } @Test public void testByteBuddyWithAccessorClassCreationCachedWithTypePool() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkByteBuddyWithAccessorAndReusedDelegatorWithTypePool(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkByteBuddyWithProxy().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } @Test public void testByteBuddyWithPrefixClassCreation() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkByteBuddyWithPrefix(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkByteBuddyWithProxy().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } @Test public void testByteBuddyWithPrefixClassCreationCached() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkByteBuddyWithPrefixAndReusedDelegator(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkByteBuddyWithProxy().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } @Test public void testByteBuddyWithPrefixClassCreationWithTypePool() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkByteBuddyWithPrefixWithTypePool(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkByteBuddyWithProxy().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } @Test public void testByteBuddyWithPrefixClassCreationCachedWithTypePool() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkByteBuddyWithPrefixAndReusedDelegatorWithTypePool(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkByteBuddyWithProxy().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } @Test public void testByteBuddySpecializedClassCreation() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkByteBuddySpecialized(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkByteBuddySpecialized().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } @Test public void testCglibClassCreation() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkCglib(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkCglib().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } @Test public void testJavassistClassCreation() throws Exception { ExampleClass instance = classByExtensionBenchmark.benchmarkJavassist(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS))); assertThat(instance.getClass().getSuperclass(), CoreMatchers.<Class<?>>is(ClassByExtensionBenchmark.BASE_CLASS)); assertThat(classByExtensionBenchmark.benchmarkJavassist().getClass(), not(CoreMatchers.<Class<?>>is(instance.getClass()))); assertReturnValues(instance); } }
/* * Copyright 2014-2017 Groupon, Inc * Copyright 2014-2017 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.billing.subscription.api.svcs; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.killbill.billing.subscription.SubscriptionTestSuiteNoDB; import org.testng.Assert; import org.testng.annotations.Test; // // Test all possible combinations of input effectiveDate and new BCD: // (We call ComputedEffectiveDay the original day in the month extracted from the input effectiveDate) // // - effectiveDate = {null (present), past, future} // - newBCD {< ComputedEffectiveDay, equals ComputedEffectiveDay, > ComputedEffectiveDay, > End Of Month} // // => 12 possible tests // public class TestEffectiveDateForNewBCD extends SubscriptionTestSuiteNoDB { @Test(groups = "fast") public void testNullEffectiveDateWithBCDPriorComputedEffectiveDay() throws Exception { // Set by test as : 2012-05-07T00:03:42.000Z final DateTime now = clock.getUTCNow(); int newBCD = 3; // effectiveDate = 2012-05-07T00:03:42.000Z => ComputedEffectiveDay = 7 LocalDate effectiveDate = null; // newBCD < ComputedEffectiveDay final DateTime result = ((DefaultSubscriptionInternalApi) subscriptionInternalApi).getEffectiveDateForNewBCD(newBCD, effectiveDate, internalCallContext); Assert.assertEquals(result, internalCallContext.toUTCDateTime(new LocalDate("2012-06-03"))); } @Test(groups = "fast") public void testNullEffectiveDateWithBCDEqualsComputedEffectiveDay() throws Exception { // Set by test as : 2012-05-07T00:03:42.000Z final DateTime now = clock.getUTCNow(); int newBCD = 7; // effectiveDate = 2012-05-07T00:03:42.000Z => ComputedEffectiveDay = 7 LocalDate effectiveDate = null; // newBCD == ComputedEffectiveDay final DateTime result = ((DefaultSubscriptionInternalApi) subscriptionInternalApi).getEffectiveDateForNewBCD(newBCD, effectiveDate, internalCallContext); final DateTime nowAfterCall = clock.getUTCNow(); // In that case because we want the event to fire right NOW, we don't use the account reference time but instead use the clock.getUTCNOW(). In case test // takes longer than 1 mSec we need to check a (very small) range of dates Assert.assertTrue(result.compareTo(now) >= 0); Assert.assertTrue(result.compareTo(nowAfterCall) <= 0); } @Test(groups = "fast") public void testNullEffectiveDateWithBCDAfterComputedEffectiveDay() throws Exception { // Set by test as : 2012-05-07T00:03:42.000Z => New time = 2012-06-07T00:03:42.000Z (and june only has 30 days) clock.addMonths(1); int newBCD = 31; // effectiveDate = 2012-06-07T00:03:42.000Z => ComputedEffectiveDay = 7 LocalDate effectiveDate = null; // newBCD > 30 (max day in June) final DateTime result = ((DefaultSubscriptionInternalApi) subscriptionInternalApi).getEffectiveDateForNewBCD(newBCD, effectiveDate, internalCallContext); Assert.assertEquals(result, internalCallContext.toUTCDateTime(new LocalDate("2012-06-30"))); } @Test(groups = "fast") public void testNullEffectiveDateWithBCDAfterEndOfTheMonth() throws Exception { // Set by test as : 2012-05-07T00:03:42.000Z final DateTime now = clock.getUTCNow(); int newBCD = 10; // effectiveDate = 2012-05-07T00:03:42.000Z => ComputedEffectiveDay = 7 LocalDate effectiveDate = null; // newBCD < ComputedEffectiveDay final DateTime result = ((DefaultSubscriptionInternalApi) subscriptionInternalApi).getEffectiveDateForNewBCD(newBCD, effectiveDate, internalCallContext); Assert.assertEquals(result, internalCallContext.toUTCDateTime(new LocalDate("2012-05-10"))); } @Test(groups = "fast") public void testFutureEffectiveDateWithBCDPriorComputedEffectiveDay() throws Exception { // Set by test as : 2012-05-07T00:03:42.000Z final DateTime now = clock.getUTCNow(); int newBCD = 3; // effectiveDate = 2012-05-07T00:03:42.000Z => ComputedEffectiveDay = 7 LocalDate effectiveDate = new LocalDate(2012, 7, 7); // newBCD < ComputedEffectiveDay final DateTime result = ((DefaultSubscriptionInternalApi) subscriptionInternalApi).getEffectiveDateForNewBCD(newBCD, effectiveDate, internalCallContext); Assert.assertEquals(result, internalCallContext.toUTCDateTime(new LocalDate("2012-08-03"))); } @Test(groups = "fast") public void testFutureEffectiveDateWithBCDEqualsComputedEffectiveDay() throws Exception { // Set by test as : 2012-05-07T00:03:42.000Z final DateTime now = clock.getUTCNow(); int newBCD = 3; // effectiveDate = 2012-05-07T00:03:42.000Z => ComputedEffectiveDay = 7 LocalDate effectiveDate = new LocalDate(2012, 7, 3); // newBCD == ComputedEffectiveDay final DateTime result = ((DefaultSubscriptionInternalApi) subscriptionInternalApi).getEffectiveDateForNewBCD(newBCD, effectiveDate, internalCallContext); Assert.assertEquals(result, internalCallContext.toUTCDateTime(new LocalDate("2012-07-03"))); } @Test(groups = "fast") public void testFutureEffectiveDateWithBCDAfterComputedEffectiveDay() throws Exception { // Set by test as : 2012-05-07T00:03:42.000Z final DateTime now = clock.getUTCNow(); int newBCD = 10; // effectiveDate = 2012-05-07T00:03:42.000Z => ComputedEffectiveDay = 7 LocalDate effectiveDate = new LocalDate(2012, 7, 3); // newBCD > ComputedEffectiveDay final DateTime result = ((DefaultSubscriptionInternalApi) subscriptionInternalApi).getEffectiveDateForNewBCD(newBCD, effectiveDate, internalCallContext); Assert.assertEquals(result, internalCallContext.toUTCDateTime(new LocalDate("2012-07-10"))); } @Test(groups = "fast") public void testFutureEffectiveDateWithBCDAfterEndOfTheMonth() throws Exception { // Set by test as : 2012-05-07T00:03:42.000Z final DateTime now = clock.getUTCNow(); int newBCD = 31; // effectiveDate = 2012-06-03 => ComputedEffectiveDay = 3 LocalDate effectiveDate = new LocalDate(2012, 6, 3); // newBCD > 30 (max day in June) final DateTime result = ((DefaultSubscriptionInternalApi) subscriptionInternalApi).getEffectiveDateForNewBCD(newBCD, effectiveDate, internalCallContext); Assert.assertEquals(result, internalCallContext.toUTCDateTime(new LocalDate("2012-06-30"))); } @Test(groups = "fast") public void testPastEffectiveDateWithBCDPriorComputedEffectiveDay() throws Exception { // Set by test as : 2012-05-07T00:03:42.000Z final DateTime now = clock.getUTCNow(); int newBCD = 3; // effectiveDate = 2012-05-07T00:03:42.000Z => ComputedEffectiveDay = 7 LocalDate effectiveDate = new LocalDate(2012, 2, 7); // newBCD < ComputedEffectiveDay final DateTime result = ((DefaultSubscriptionInternalApi) subscriptionInternalApi).getEffectiveDateForNewBCD(newBCD, effectiveDate, internalCallContext); Assert.assertEquals(result, internalCallContext.toUTCDateTime(new LocalDate("2012-03-03"))); } @Test(groups = "fast") public void testPastEffectiveDateWithBCDEqualsComputedEffectiveDay() throws Exception { // Set by test as : 2012-05-07T00:03:42.000Z final DateTime now = clock.getUTCNow(); int newBCD = 3; // effectiveDate = 2012-05-07T00:03:42.000Z => ComputedEffectiveDay = 7 LocalDate effectiveDate = new LocalDate(2012, 2, 3); // newBCD == ComputedEffectiveDay final DateTime result = ((DefaultSubscriptionInternalApi) subscriptionInternalApi).getEffectiveDateForNewBCD(newBCD, effectiveDate, internalCallContext); Assert.assertEquals(result, internalCallContext.toUTCDateTime(new LocalDate("2012-02-03"))); } @Test(groups = "fast") public void testPastEffectiveDateWithBCDAfterComputedEffectiveDay() throws Exception { // Set by test as : 2012-05-07T00:03:42.000Z final DateTime now = clock.getUTCNow(); int newBCD = 10; // effectiveDate = 2012-05-07T00:03:42.000Z => ComputedEffectiveDay = 7 LocalDate effectiveDate = new LocalDate(2012, 2, 3); // newBCD > ComputedEffectiveDay final DateTime result = ((DefaultSubscriptionInternalApi) subscriptionInternalApi).getEffectiveDateForNewBCD(newBCD, effectiveDate, internalCallContext); Assert.assertEquals(result, internalCallContext.toUTCDateTime(new LocalDate("2012-02-10"))); } @Test(groups = "fast") public void testPastEffectiveDateWithBCDAfterEndOfTheMonth() throws Exception { // Set by test as : 2012-05-07T00:03:42.000Z final DateTime now = clock.getUTCNow(); int newBCD = 31; // effectiveDate = 2012-02-03 => ComputedEffectiveDay = 3 LocalDate effectiveDate = new LocalDate(2012, 2, 3); // newBCD > 30 (max day in June) final DateTime result = ((DefaultSubscriptionInternalApi) subscriptionInternalApi).getEffectiveDateForNewBCD(newBCD, effectiveDate, internalCallContext); Assert.assertEquals(result, internalCallContext.toUTCDateTime(new LocalDate("2012-2-29"))); } }
package com.silver.dan.castdemo; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import com.auth0.android.jwt.JWT; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.Scope; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import java.util.HashSet; import java.util.List; import java.util.Set; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener { public static String LOGOUT = "LOGOUT"; @BindView(R.id.sign_in_button) com.google.android.gms.common.SignInButton signInButton; @BindView(R.id.login_loading_spinner) ProgressBar loadingSpinner; private static GoogleApiClient mGoogleApiClient; private int RC_SIGN_IN = 10000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ButterKnife.bind(this); loadingSpinner.setVisibility(View.INVISIBLE); final AuthHelper googleAuthHelper = new AuthHelper(getApplicationContext()); mGoogleApiClient = new GoogleApiClient .Builder(this) .addApi(Auth.GOOGLE_SIGN_IN_API, googleAuthHelper.getGoogleGSO()) .enableAutoManage(this, this) .build(); Intent intent = getIntent(); final boolean shouldLogout = intent.getBooleanExtra(LoginActivity.LOGOUT, false); if (shouldLogout) { signout(); } FirebaseAuth.AuthStateListener mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { if (shouldLogout) { return; } FirebaseUser user = firebaseAuth.getCurrentUser(); if (user == null) { return; } // crack open jwt from saved storage, see if it's not expired // check if firebaseUserId == user.id (from below) // if so, save jwt, scopes to AuthHelper static fields String serviceJwt = googleAuthHelper.getSavedServiceJwt(); if (serviceJwt == null) return; JWT jwt = new JWT(serviceJwt); String firebaseUserId = jwt.getClaim("firebaseUserId").asString(); List<String> scopes = jwt.getClaim("grantedScopes").asList(String.class); Set<Scope> grantedScopes = new HashSet<>(); for (String scope : scopes) { grantedScopes.add(new Scope(scope)); } if (firebaseUserId.equals(user.getUid())) { googleAuthHelper.setServiceJwt(serviceJwt); // @todo why? didn't we just get this from authhelper? googleAuthHelper.setNewUserInfo(user, grantedScopes); AuthHelper.user = user; userFinishedAuth(); } } }; FirebaseAuth.getInstance().addAuthStateListener(mAuthListener); } static boolean restoreUser() { if (AuthHelper.user != null) { return true; } FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { AuthHelper.user = user; return true; } return false; } @OnClick(R.id.sign_in_button) public void signin() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if (result.isSuccess()) { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = result.getSignInAccount(); firebaseAuthWithGoogle(account); } else { // Google Sign In failed, update UI appropriately loadingSpinner.setVisibility(View.GONE); signInButton.setVisibility(View.VISIBLE); } } } private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) { loadingSpinner.setVisibility(View.VISIBLE); signInButton.setVisibility(View.GONE); AuthHelper authHelper = new AuthHelper(getApplicationContext()); authHelper.completeCommonAuth(acct, new SimpleCallback<String>() { @Override public void onComplete(String result) { userFinishedAuth(); } @Override public void onError(Exception e) { Toast.makeText(getApplicationContext(), "Authentication failed.", Toast.LENGTH_SHORT).show(); loadingSpinner.setVisibility(View.GONE); signInButton.setVisibility(View.VISIBLE); } }); } private void userFinishedAuth() { launchMainActivity(); } private void launchMainActivity() { Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish(); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { loadingSpinner.setVisibility(View.GONE); signInButton.setVisibility(View.VISIBLE); } public void signout() { AuthHelper.signout(); mGoogleApiClient.connect(); mGoogleApiClient.registerConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() { @Override public void onConnected(@Nullable Bundle bundle) { FirebaseAuth.getInstance().signOut(); if(mGoogleApiClient.isConnected()) { Auth.GoogleSignInApi.signOut(mGoogleApiClient); } } @Override public void onConnectionSuspended(int i) { } }); } }
package org.gsm.rcsApp.activities; import java.io.UnsupportedEncodingException; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.util.ArrayList; import java.util.UUID; import org.apache.http.auth.AuthScheme; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; import org.gsm.RCSDemo.R; import org.gsm.rcsApp.ServiceURL; import org.gsm.rcsApp.misc.RCSJsonHttpResponseHandler; import org.gsm.rcsApp.misc.Utils; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.RequestParams; public class SplashActivity extends Activity { public static String userId=null; public static final String appCredentialUsername="62acd5d3bf3c352bbbabadeccbe60563"; public static final String appCredentialPassword="A1B1C1D1"; static SplashActivity _instance=null; public static String notificationChannelURL=null; public static String notificationChannelResourceURL=null; public static ArrayList<String> notificationSubscriptions=new ArrayList<String>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); _instance=this; } public void onStart() { super.onStart(); final TextView splashStatusIndicator=(TextView) findViewById(R.id.splashStatusIndicator); splashStatusIndicator.setVisibility(View.VISIBLE); splashStatusIndicator.setText("enter username (mobile number)"); AsyncHttpClient client = new AsyncHttpClient(); if (userId!=null) { /* * De-register the previously logged in user */ String auth; try { auth = android.util.Base64.encodeToString((SplashActivity.appCredentialUsername+":"+SplashActivity.appCredentialPassword).getBytes("UTF-8"), android.util.Base64.NO_WRAP); client.addHeader("Authorization", "Basic "+ auth); client.addHeader("Accept", "application/json"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block Log.e("SplashActivity","Authorization Failed: Failed to encode in Base64"); } final String url=ServiceURL.unregisterURL(userId); Log.d("SplashActivity", "Unregistering user"); client.delete(url, new RCSJsonHttpResponseHandler() { @Override public void onSuccess(String response, int statusCode) { Log.d("SplashActivity", "unregister::success status="+statusCode); } }); /* * Clear previous notification subscriptions */ if (notificationSubscriptions.size()>0) { for (final String durl:notificationSubscriptions) { client.delete(durl, new RCSJsonHttpResponseHandler() { @Override public void onSuccess(String response, int statusCode) { Log.d("SplashActivity", "deleted subscription status="+statusCode+" response="+response); } }); } notificationSubscriptions.clear(); } if (notificationChannelResourceURL!=null) { final String durl=notificationChannelResourceURL; client.delete(durl, new RCSJsonHttpResponseHandler() { @Override public void onSuccess(String response, int statusCode) { Log.d("SplashActivity", "deleted notification channel status="+statusCode+" response="+response); } }); notificationChannelResourceURL=null; } userId=null; } MainActivity.stopMainActivity(); } public void proceedToMain(View view) throws UnsupportedEncodingException { EditText splashUsernameInput=(EditText) findViewById(R.id.splashUsernameInput); final TextView splashStatusIndicator=(TextView) findViewById(R.id.splashStatusIndicator); final String username=splashUsernameInput.getText().toString(); splashStatusIndicator.setVisibility(View.INVISIBLE); if (username!=null && username.trim().length()>0) { AsyncHttpClient client = new AsyncHttpClient(); String auth = android.util.Base64.encodeToString((SplashActivity.appCredentialUsername+":"+SplashActivity.appCredentialPassword).getBytes("UTF-8"), android.util.Base64.NO_WRAP); final String url=ServiceURL.registerURL(username); Log.d("SplashActivity","URL = "+url); client.addHeader("Authorization", "Basic "+ auth); client.addHeader("Accept", "application/json"); client.addHeader("Content-Type", "application/json"); client.post(url, new RCSJsonHttpResponseHandler() { boolean successReceived=false; @Override public void onSuccess(String response, int responseCode) throws UnsupportedEncodingException { Log.d("SplashActivity", "proceedToMain::success status="+responseCode); if (responseCode==204) { userId=username; registerForNotifications(); Intent intent = new Intent(_instance, MainActivity.class); successReceived=true; startActivity(intent); } else if (responseCode==401) { splashStatusIndicator.setVisibility(View.VISIBLE); splashStatusIndicator.setText("invalid username (mobile number)"); successReceived=true; } } @Override public void onStart() { // Initiated the request splashStatusIndicator.setVisibility(View.VISIBLE); splashStatusIndicator.setText("sending login request"); } @Override public void onFailure(Throwable e, String response) { // Response failed :( splashStatusIndicator.setVisibility(View.VISIBLE); splashStatusIndicator.setText("login request failed"); System.out.println("Response "+response); System.out.println(e.toString()); } @Override public void onFinish() { // Completed the request (either success or failure) if (!successReceived) { splashStatusIndicator.setVisibility(View.VISIBLE); splashStatusIndicator.setText("login request finished - unknown failure"); } } }); } else { splashStatusIndicator.setVisibility(View.VISIBLE); splashStatusIndicator.setText("enter username (mobile number)"); } } private void registerForNotifications() throws UnsupportedEncodingException { AsyncHttpClient client = new AsyncHttpClient(); String auth = android.util.Base64.encodeToString((SplashActivity.appCredentialUsername+":"+SplashActivity.appCredentialPassword).getBytes("UTF-8"), android.util.Base64.NO_WRAP); final String url=ServiceURL.createNotificationChannelURL(userId); String correlator=UUID.randomUUID().toString(); String jsonData="{\"notificationChannel\": {\"applicationTag\": \"myApp\", \"channelData\": {\"maxNotifications\": \"3\", \"type\": \"LongPollingData\"}, \"channelLifetime\": \"20\", \"channelType\": \"LongPolling\", \"clientCorrelator\": \""+correlator+"\"}}"; Log.d("SplashActivity", "register for notifications: URL = "+url); try { StringEntity requestData=new StringEntity(jsonData); Log.d("SplashActivity", "register for notifications: sending post request..."); client.addHeader("Authorization", "Basic "+ auth); client.addHeader("Accept", "application/json"); client.post(_instance.getApplication().getApplicationContext(), url, requestData, "application/json", new RCSJsonHttpResponseHandler() { @Override public void onSuccess(JSONObject response, int statusCode) throws UnsupportedEncodingException { Log.d("SplashActivity", "registerForNotifications::success = "+response.toString()+" statusCode="+statusCode); if (statusCode==201) { JSONObject notificationChannel=Utils.getJSONObject(response, "notificationChannel"); String callbackURL=Utils.getJSONStringElement(notificationChannel, "callbackURL"); notificationChannelResourceURL=Utils.getJSONStringElement(notificationChannel, "resourceURL"); JSONObject channelData=Utils.getJSONObject(notificationChannel, "channelData"); notificationChannelURL=channelData!=null?Utils.getJSONStringElement(channelData, "channelURL"):null; Log.d("SplashActivity", "callbackURL = "+callbackURL); Log.d("SplashActivity", "resourceURL = "+notificationChannelResourceURL); Log.d("SplashActivity", "channelURL = "+notificationChannelURL); Log.i("SplashActivity", "Subscribing User to Address Book Notifications..."); subscribeToAddressBookNotifications(callbackURL); Log.i("SplashActivity", "Subscribing User to Session Notifications..."); subscribeToSessionNotifications(callbackURL); Log.i("SplashActivity", "Subscribing User to Chat Notifications..."); subscribeToChatNotifications(callbackURL); }else{ Log.e("SplashActivity","Create Notification Channel Error: HTTP "+statusCode); } } @Override public void onFailure(Throwable error, String content, int responseCode) { super.onFailure(error, content, responseCode); Log.e("SplashActivity", "Response Code = "+responseCode); Log.e("SplashActivity", "Error Creating Notification Channel", error); } }); } catch (UnsupportedEncodingException e) { } } private void subscribeToAddressBookNotifications(String callbackURL) throws UnsupportedEncodingException { try { JSONObject abChangesSubscription=new JSONObject(); JSONObject callbackReference=new JSONObject(); callbackReference.put("callbackData", userId); callbackReference.put("notifyURL", callbackURL); abChangesSubscription.put("callbackReference", callbackReference); abChangesSubscription.put("duration", (int) 0); String jsonData="{\"abChangesSubscription\":"+abChangesSubscription.toString()+"}"; Log.d("SplashActivity", "Subscription request data = "+jsonData); AsyncHttpClient client = new AsyncHttpClient(); String auth = android.util.Base64.encodeToString((SplashActivity.appCredentialUsername+":"+SplashActivity.appCredentialPassword).getBytes("UTF-8"), android.util.Base64.NO_WRAP); client.addHeader("Authorization", "Basic "+auth); client.addHeader("Accept", "application/json"); final String url=ServiceURL.createAddressBookChangeSubscriptionURL(userId); try { StringEntity requestData=new StringEntity(jsonData); client.post(_instance.getApplication().getApplicationContext(), url, requestData, "application/json", new RCSJsonHttpResponseHandler() { @Override public void onSuccess(JSONObject response, int statusCode) { Log.d("SplashActivity", "subscribeToAddressBookNotifications::success = "+response.toString()+" statusCode="+statusCode); if (statusCode==201) { String resourceURL=Utils.getResourceURL(Utils.getJSONObject(response, "abChangesSubscription")); if (resourceURL!=null) notificationSubscriptions.add(resourceURL); } } }); } catch (UnsupportedEncodingException e) { } } catch (JSONException e) { } } private void subscribeToSessionNotifications(String callbackURL) throws UnsupportedEncodingException { try { JSONObject sessionSubscription=new JSONObject(); JSONObject callbackReference=new JSONObject(); callbackReference.put("callbackData", userId); callbackReference.put("notifyURL", callbackURL); sessionSubscription.put("callbackReference", callbackReference); sessionSubscription.put("duration", (int) 0); String jsonData="{\"sessionSubscription\":"+sessionSubscription.toString()+"}"; Log.d("SplashActivity", "Subscription request data = "+jsonData); AsyncHttpClient client = new AsyncHttpClient(); String auth = android.util.Base64.encodeToString((SplashActivity.appCredentialUsername+":"+SplashActivity.appCredentialPassword).getBytes("UTF-8"), android.util.Base64.NO_WRAP); client.addHeader("Authorization", "Basic "+auth); client.addHeader("Accept", "application/json"); final String url=ServiceURL.createSessionChangeSubscriptionURL(userId); try { StringEntity requestData=new StringEntity(jsonData); client.post(_instance.getApplication().getApplicationContext(), url, requestData, "application/json", new RCSJsonHttpResponseHandler() { @Override public void onSuccess(JSONObject response, int statusCode) { Log.d("SplashActivity", "subscribeToSessionNotifications::success = "+response.toString()+" statusCode="+statusCode); if (statusCode==201) { String resourceURL=Utils.getResourceURL(Utils.getJSONObject(response, "sessionSubscription")); if (resourceURL!=null) notificationSubscriptions.add(resourceURL); } } }); } catch (UnsupportedEncodingException e) { } } catch (JSONException e) { } } private void subscribeToChatNotifications(String callbackURL) throws UnsupportedEncodingException { try { JSONObject chatSubscription=new JSONObject(); JSONObject callbackReference=new JSONObject(); callbackReference.put("callbackData", userId); callbackReference.put("notifyURL", callbackURL); chatSubscription.put("callbackReference", callbackReference); chatSubscription.put("duration", (int) 0); String jsonData="{\"chatNotificationSubscription\":"+chatSubscription.toString()+"}"; Log.d("SplashActivity", "Subscription request data = "+jsonData); AsyncHttpClient client = new AsyncHttpClient(); String auth = android.util.Base64.encodeToString((SplashActivity.appCredentialUsername+":"+SplashActivity.appCredentialPassword).getBytes("UTF-8"), android.util.Base64.NO_WRAP); client.addHeader("Authorization", "Basic "+auth); client.addHeader("Accept", "application/json"); final String url=ServiceURL.createChatSubscriptionURL(userId); try { StringEntity requestData=new StringEntity(jsonData); client.post(_instance.getApplication().getApplicationContext(), url, requestData, "application/json", new RCSJsonHttpResponseHandler() { @Override public void onSuccess(JSONObject response, int statusCode) { Log.d("SplashActivity", "subscribeToChatNotifications::success = "+response.toString()+" statusCode="+statusCode); if (statusCode==201) { String resourceURL=Utils.getResourceURL(Utils.getJSONObject(response, "chatNotificationSubscription")); if (resourceURL!=null) notificationSubscriptions.add(resourceURL); } } }); } catch (UnsupportedEncodingException e) { } } catch (JSONException e) { } } }
package org.orienteer.core.boot.loader.util; import com.google.common.collect.Lists; import org.apache.http.util.Args; import org.orienteer.core.boot.loader.util.artifact.OArtifact; import org.orienteer.core.boot.loader.util.artifact.OArtifactReference; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.nio.file.Path; import java.util.List; /** * Utility class for update metadata.xml */ class OMetadataUpdater extends AbstractXmlUtil { private final Path pathToMetadata; private static final String ALL_MODULES_EXP = String.format("/%s/*", MetadataTag.METADATA.get()); /** * Constructor * @param pathToMetadata {@link Path} of metadata.xml * @throws IllegalArgumentException if pathToMetadata is null */ OMetadataUpdater(Path pathToMetadata) { Args.notNull(pathToMetadata, "pathToMetadata"); this.pathToMetadata = pathToMetadata; } /** * Create new metadata.xml with oArtifacts * @param oArtifacts list of {@link OArtifact} for write in metadata.xml * @throws IllegalArgumentException if oArtifacts is null */ void create(List<OArtifact> oArtifacts) { Args.notNull(oArtifacts, "oArtifacts"); Document document = createNewDocument(); if (document == null) documentCannotCreateException(pathToMetadata); Element root = document.createElement(MetadataTag.METADATA.get()); document.appendChild(root); addArtifacts(oArtifacts, document); saveDocument(document, pathToMetadata); } /** * Update metadata.xml * @param oArtifact - {@link OArtifact} for update in metadata.xml * @throws IllegalArgumentException if oArtifact is null */ void update(OArtifact oArtifact) { Args.notNull(oArtifact, "oArtifact"); update(oArtifact, false); } /** * Update metadata.xml * @param oArtifacts - list of {@link OArtifact} for update in metadata.xml * @throws IllegalArgumentException if oArtifacts is null */ void update(List<OArtifact> oArtifacts) { Args.notNull(oArtifacts, "oArtifacts"); update(oArtifacts, false); } /** * Update jar for oArtifact in metadata.xml * @param oArtifact {@link OArtifact} for update * @param updateJar true - jar will be update * false - jar will not be update * @throws IllegalArgumentException if oArtifact is null */ void update(OArtifact oArtifact, boolean updateJar) { Args.notNull(oArtifact, "oArtifact"); update(Lists.newArrayList(oArtifact), updateJar); } /** * Update metadata.xml. * oArtifacts will be write to metadata.xml or will be update its flag load or trusted. * @param oArtifacts list of {@link OArtifact} for update * @param updateJar true - jar will be update * false - jar will not be update * @throws IllegalArgumentException if oArtifacts is null */ @SuppressWarnings("unchecked") void update(List<OArtifact> oArtifacts, boolean updateJar) { Args.notNull(oArtifacts, "oArtifacts"); Document document = readDocumentFromFile(pathToMetadata); if (document == null) documentCannotReadException(pathToMetadata); NodeList nodeList = executeExpression(ALL_MODULES_EXP, document); List<OArtifact> updatedModules = Lists.newArrayList(); if (nodeList != null) { for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Element.ELEMENT_NODE) { Element element = (Element) node; Element dependencyElement = (Element) element.getElementsByTagName(MetadataTag.DEPENDENCY.get()).item(0); OArtifact oArtifact = containsInModulesConfigsList(dependencyElement, oArtifacts); if (oArtifact != null) { if (updateJar) { changeoArtifactsLoadAndJar(element, oArtifact); } else changeArtifactElement(element, oArtifact); updatedModules.add(oArtifact); } } } } if (updatedModules.size() != oArtifacts.size()) { addArtifacts(difference(updatedModules, oArtifacts), document); } saveDocument(document, pathToMetadata); } /** * Replace artifactForReplace in metadata.xml by newArtifact * @param artifactForReplace - artifact for replace * @param newArtifact - new artifact * @throws IllegalArgumentException if artifactForReplace or newArtifact is null */ @SuppressWarnings("unchecked") void update(OArtifact artifactForReplace, OArtifact newArtifact) { Args.notNull(artifactForReplace, "artifactForUpdate"); Args.notNull(newArtifact, "newArtifact"); Document document = readDocumentFromFile(pathToMetadata); if (document == null) documentCannotReadException(pathToMetadata); NodeList nodeList = executeExpression(ALL_MODULES_EXP, document); if (nodeList != null) { for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; Element dependencyElement = (Element) element.getElementsByTagName(MetadataTag.DEPENDENCY.get()).item(0); OArtifact module = containsInModulesConfigsList(dependencyElement, Lists.newArrayList(artifactForReplace)); if (module != null) { changeArtifactElement(element, newArtifact); break; } } } saveDocument(document, pathToMetadata); } } /** * Delete oArtifact from metadata.xml * @param oArtifact {@link OArtifact} for delete from metadata.xml * @throws IllegalArgumentException if oArtifact is null */ @SuppressWarnings("unchecked") void delete(OArtifact oArtifact) { Args.notNull(oArtifact, "oArtifact"); Document document = readDocumentFromFile(pathToMetadata); if (document == null) documentCannotReadException(pathToMetadata); NodeList nodeList = executeExpression(ALL_MODULES_EXP, document); if (nodeList != null) { Element root = document.getDocumentElement(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; Element dependencyElement = (Element) element.getElementsByTagName(MetadataTag.DEPENDENCY.get()).item(0); if (isNecessaryElement(dependencyElement, oArtifact)) { root.removeChild(element); break; } } } saveDocument(document, pathToMetadata); } } /** * Delete list of {@link OArtifact} from metadata.xml * @param oArtifacts list of {@link OArtifact} for delete from metadata.xml * @throws IllegalArgumentException if oArtifacts is null */ @SuppressWarnings("unchecked") void delete(List<OArtifact> oArtifacts) { Args.notNull(oArtifacts, "oArtifacts"); Document document = readDocumentFromFile(pathToMetadata); if (document == null) documentCannotReadException(pathToMetadata); NodeList nodeList = executeExpression(ALL_MODULES_EXP, document); if (nodeList != null) { Element root = document.getDocumentElement(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; Element dependencyElement = (Element) element.getElementsByTagName(MetadataTag.DEPENDENCY.get()).item(0); OArtifact metadata = containsInModulesConfigsList(dependencyElement, oArtifacts); if (metadata != null) { root.removeChild(element); } } } saveDocument(document, pathToMetadata); } } /** * Add artifacts to {@link Document} document * @param oArtifacts list of {@link OArtifact} for add to document * @param document {@link Document} of metadata.xml */ private void addArtifacts(List<OArtifact> oArtifacts, Document document) { for (OArtifact artifact : oArtifacts) { addArtifact(artifact, document); } } /** * Add artifact to {@link Document} document * @param oArtifact {@link OArtifact} for add to document * @param document {@link Document} of metadata.xml */ private void addArtifact(OArtifact oArtifact, Document document) { Element root = document.getDocumentElement(); Element module = document.createElement(MetadataTag.MODULE.get()); root.appendChild(module); Element load = document.createElement(MetadataTag.LOAD.get()); load.appendChild(document.createTextNode(Boolean.toString(oArtifact.isLoad()))); module.appendChild(load); Element trusted = document.createElement(MetadataTag.TRUSTED.get()); trusted.appendChild(document.createTextNode(Boolean.toString(oArtifact.isTrusted()))); module.appendChild(trusted); module.appendChild(createMavenDependency(oArtifact.getArtifactReference(), document)); } /** * Change oArtifact in metadata.xml * @param artifactElement {@link Element} of oArtifact in metadata.xml * @param oArtifact {@link OArtifact} for change */ @SuppressWarnings("unchecked") private void changeArtifactElement(Element artifactElement, OArtifact oArtifact) { NodeList nodeList = artifactElement.getElementsByTagName("*"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; MetadataTag tag = MetadataTag.getByName(element.getTagName()); switch (tag) { case LOAD: element.setTextContent(Boolean.toString(oArtifact.isLoad())); break; case TRUSTED: element.setTextContent(Boolean.toString(oArtifact.isTrusted())); break; case DEPENDENCY: changeMavenDependency(element, oArtifact.getArtifactReference()); break; } } } } /** * Change artifacts load and jar * @param artifactElement {@link Element} of oArtifact * @param oArtifact {@link OArtifact} artifact for change */ @SuppressWarnings("unchecked") private void changeoArtifactsLoadAndJar(Element artifactElement, OArtifact oArtifact) { Element jar = (Element) artifactElement.getElementsByTagName(MetadataTag.JAR.get()).item(0); Element load = (Element) artifactElement.getElementsByTagName(MetadataTag.LOAD.get()).item(0); Document document = artifactElement.getOwnerDocument(); load.setTextContent(Boolean.toString(oArtifact.isLoad())); if (jar == null) { Element jarElement = document.createElement(MetadataTag.JAR.get()); jarElement.appendChild(document.createTextNode(oArtifact.getArtifactReference().getFile().getAbsolutePath())); } else jar.setTextContent(oArtifact.getArtifactReference().getFile().getAbsolutePath()); } /** * Change maven dependency * @param dependency {@link Element} of dependency * @param artifactReference {@link OArtifactReference} for change */ private void changeMavenDependency(Element dependency, OArtifactReference artifactReference) { NodeList nodeList = dependency.getElementsByTagName("*"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; MetadataTag tag = MetadataTag.getByName(element.getTagName()); switch (tag) { case GROUP_ID: element.setTextContent(artifactReference.getGroupId()); break; case ARTIFACT_ID: element.setTextContent(artifactReference.getArtifactId()); break; case VERSION: element.setTextContent(artifactReference.getVersion()); break; case REPOSITORY: element.setTextContent(artifactReference.getRepository()); break; case DESCRIPTION: element.setTextContent(artifactReference.getDescription()); break; case JAR: element.setTextContent(artifactReference.getFile().getAbsolutePath()); break; } } } } private boolean isNecessaryElement(Element dependencyElement, OArtifact module) { Element groupElement = (Element) dependencyElement.getElementsByTagName(MetadataTag.GROUP_ID.get()).item(0); Element artifactElement = (Element) dependencyElement.getElementsByTagName(MetadataTag.ARTIFACT_ID.get()).item(0); OArtifactReference artifact = module.getArtifactReference(); return groupElement.getTextContent().equals(artifact.getGroupId()) && artifactElement.getTextContent().equals(artifact.getArtifactId()); } private OArtifact containsInModulesConfigsList(Element dependencyElement, List<OArtifact> modulesConfigs) { for (OArtifact moduleConfig : modulesConfigs) { if (isNecessaryElement(dependencyElement, moduleConfig)) return moduleConfig; } return null; } private List<OArtifact> difference(List<OArtifact> list1, List<OArtifact> list2) { List<OArtifact> result = Lists.newArrayList(); for (OArtifact module : list2) { if (!list1.contains(module)) result.add(module); } return result; } /** * Add maven dependency to {@link Document} document. * @param artifactReference {@link OArtifactReference} which is maven dependency * @param document {@link Document} of metadata.xml * @return {@link Element} with maven dependency */ private Element createMavenDependency(OArtifactReference artifactReference, Document document) { Element mavenElement = document.createElement(MetadataTag.DEPENDENCY.get()); Element groupId = document.createElement(MetadataTag.GROUP_ID.get()); groupId.appendChild(document.createTextNode(artifactReference.getGroupId())); mavenElement.appendChild(groupId); Element artifactId = document.createElement(MetadataTag.ARTIFACT_ID.get()); artifactId.appendChild(document.createTextNode(artifactReference.getArtifactId())); mavenElement.appendChild(artifactId); Element version = document.createElement(MetadataTag.VERSION.get()); version.appendChild(document.createTextNode(artifactReference.getVersion())); mavenElement.appendChild(version); Element description = document.createElement(MetadataTag.DESCRIPTION.get()); description.appendChild(document.createTextNode(artifactReference.getDescription())); mavenElement.appendChild(description); Element jar = document.createElement(MetadataTag.JAR.get()); jar.appendChild(document.createTextNode(artifactReference.getFile().getAbsolutePath())); mavenElement.appendChild(jar); return mavenElement; } }
/* * 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.internal.datasource; import java.sql.Connection; import java.sql.SQLException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.sql.ConnectionEvent; import javax.sql.ConnectionEventListener; import javax.sql.PooledConnection; import javax.sql.XAConnection; import javax.sql.XADataSource; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import javax.transaction.xa.XAResource; import org.apache.logging.log4j.Logger; import org.apache.geode.annotations.VisibleForTesting; import org.apache.geode.internal.jndi.JNDIInvoker; import org.apache.geode.logging.internal.log4j.api.LogService; /** * GemFireTransactionDataSource extends AbstractDataSource. This is a datasource class which * provides connections from the pool. These connection can participate in the transaction. The * objects of these class are ConnectionEventListener for connection close and error events. * * Modified the exception handling & changed the name of some functions. */ public class GemFireTransactionDataSource extends AbstractDataSource implements ConnectionEventListener { private static final Logger logger = LogService.getLogger(); private static final long serialVersionUID = -3095123666092414103L; private transient TransactionManager transManager; ConnectionProvider provider; private Map xaResourcesMap = Collections.synchronizedMap(new HashMap()); /** * Place holder for abstract method isWrapperFor(java.lang.Class) in java.sql.Wrapper required by * jdk 1.6 * * @param iface - a Class defining an interface. */ @Override public boolean isWrapperFor(Class iface) throws SQLException { return true; } /** * Place holder for abstract method java.lang Object unwrap(java.lang.Class) in java.sql.Wrapper * required by jdk 1.6 * * @param iface - a Class defining an interface. * @return java.lang.Object */ @Override public Object unwrap(Class iface) throws SQLException { return iface; } /** * Creates a new instance of GemFireTransactionDataSource * * @param xaDS The XADataSource object for the database driver. * @param configs - The ConfiguredDataSourceProperties containing the datasource properties. */ public GemFireTransactionDataSource(XADataSource xaDS, ConfiguredDataSourceProperties configs) throws SQLException { super(configs); if ((xaDS == null) || (configs == null)) { throw new SQLException( "GemFireTransactionDataSource::XADataSource class object is null or ConfiguredDataSourceProperties object is null"); } try { provider = new GemFireConnectionPoolManager(xaDS, configs, this); transManager = JNDIInvoker.getTransactionManager(); } catch (Exception ex) { String exception = "GemFireTransactionDataSource::Exception = " + ex; if (logger.isDebugEnabled()) { logger.debug(exception, ex); } throw new SQLException(exception); } } /** * Implementation of datasource function. This method is used to get the connection from the pool. * Default user name and password will be used. * * @return ??? */ @Override public Connection getConnection() throws SQLException { if (!isActive) { throw new SQLException( "GemFireTransactionDataSource::getConnection::No valid Connection available"); } XAConnection xaConn = null; try { xaConn = (XAConnection) provider.borrowConnection(); Connection conn = getSQLConnection(xaConn); registerTranxConnection(xaConn); return conn; } catch (Exception ex) { SQLException se = new SQLException(ex.getMessage()); se.initCause(ex); throw se; } } /** * Implementation of datasource function. This method is used to get the connection. The specified * user name and passowrd will be used. * * @param clUsername The username for the database connection. * @param clPassword The password for the database connection. * @return ??? */ @Override public Connection getConnection(String clUsername, String clPassword) throws SQLException { checkCredentials(clUsername, clPassword); return getConnection(); } /** * Implementation of call back function from ConnectionEventListener interface. This callback will * be invoked on connection close event. * * @param event Connection event object */ @Override public void connectionClosed(ConnectionEvent event) { if (isActive) { try { XAConnection conn = (XAConnection) event.getSource(); XAResource xar = (XAResource) xaResourcesMap.get(conn); xaResourcesMap.remove(conn); Transaction txn = transManager.getTransaction(); if (txn != null && xar != null) txn.delistResource(xar, XAResource.TMSUCCESS); provider.returnConnection(conn); } catch (Exception e) { String exception = "GemFireTransactionDataSource::connectionClosed: Exception occurred due to " + e; if (logger.isDebugEnabled()) { logger.debug(exception, e); } } } } /** * Implementation of call back function from ConnectionEventListener interface. This callback will * be invoked on connection error event. * * @param event Connection event object */ @Override public void connectionErrorOccurred(ConnectionEvent event) { if (isActive) { try { PooledConnection conn = (PooledConnection) event.getSource(); provider.returnAndExpireConnection(conn); } catch (Exception ex) { String exception = "GemFireTransactionDataSource::connectionErrorOccurred: Exception occurred due to " + ex; if (logger.isDebugEnabled()) { logger.debug(exception, ex); } } } } void registerTranxConnection(XAConnection xaConn) throws Exception { try { synchronized (this) { if (transManager == null) { transManager = JNDIInvoker.getTransactionManager(); } } Transaction txn = transManager.getTransaction(); if (txn != null) { XAResource xar = xaConn.getXAResource(); txn.enlistResource(xar); // Add in the Map after successful registration of XAResource this.xaResourcesMap.put(xaConn, xar); } } catch (Exception ex) { provider.returnAndExpireConnection(xaConn); Exception e = new Exception( String.format( "GemFireTransactionDataSource-registerTranxConnection(). Exception in registering the XAResource with the Transaction.Exception occurred= %s", ex)); e.initCause(ex); throw e; } } /** * gets the connection from the pool * * @return ??? */ protected Connection getSQLConnection(PooledConnection poolC) throws SQLException { Connection connection; try { connection = poolC.getConnection(); } catch (SQLException e) { provider.returnAndExpireConnection(poolC); throw e; } boolean val = validateConnection(connection); if (val) { return connection; } else { provider.returnAndExpireConnection(poolC); throw new SQLException( "GemFireConnPooledDataSource::getConnFromConnPool:java.sql.Connection obtained is invalid"); } } /** * Returns the connection provider for the datasource. * * @return ConnectionProvider object for the datasource */ public ConnectionProvider getConnectionProvider() { return provider; } /* * Clean up the resources before restart of Cache */ @Override public void close() { super.close(); provider.clearUp(); } /** * Used by unit tests */ @VisibleForTesting void setTransactionManager(TransactionManager transManager) { this.transManager = transManager; } }
/* ************************************************************************** * Copyright (C) 2010-2011 VMware, Inc. All rights reserved. * * This product is licensed to you under the Apache License, Version 2.0. * Please see the LICENSE file to review the full text of the Apache License 2.0. * You may not use this product except in compliance with the License. * ************************************************************************** */ package com.vmware.lmock.masquerade; import static com.vmware.lmock.checker.Occurrences.exactly; import static com.vmware.lmock.impl.InvocationResult.returnValue; import static com.vmware.lmock.impl.InvocationResult.throwException; import com.vmware.lmock.checker.OccurrenceChecker; import com.vmware.lmock.clauses.HasAppendClauses; import com.vmware.lmock.clauses.HasDirectiveClauses; import com.vmware.lmock.clauses.HasInvocationResultSpecificationClauses; import com.vmware.lmock.clauses.InnerSchemerFactoryClauses.HasExpectationClauses; import com.vmware.lmock.clauses.InnerSchemerFactoryClauses.HasWhenClause; import com.vmware.lmock.impl.InvocationCheckerClosureHandler; import com.vmware.lmock.impl.InvocationResultProvider; import com.vmware.lmock.impl.Scenario; import com.vmware.lmock.impl.Stubs; /** * Builds expectations and stubs. * * <p> * A factory is registering the different elements defined by the user with the * schemer clauses to produce the appropriate stub or expectation. * </p> * * <p> * For later argument specifications, the factory provides a specific * builder via <code>getArgumentSpecificationFactoryOrThrow</code>. Because * such a kind of constructor is outside the creation of a directive, the * implied role may be unbounded (in particular when using the static * helpers of the schemer). For that reason, this method is static and * requires a specific cleaning procedure, provided by <code>cleanup</code>. * </p> */ class SchemerFactory implements InvocationCheckerClosureHandler, HasDirectiveClauses, HasWhenClause, HasExpectationClauses { /** Occurrences scheme used by the directive under construction. */ private OccurrenceChecker occurrences; /** Result of an invocation as defined by the directive under construction. */ private InvocationResultProvider result; /** Temporary scenario object, used when building an expectation. */ private Scenario temporaryScenario; /** Temporary stubs object, used when building a stub. */ private Stubs temporaryStubs; /** Called back to register the built directive into the ongoing story. */ private final HasAppendClauses controller; /** * Creates a new builder. * * <p> * The object expects to get a controller that will be invoked each time a * new directive needs to be added to the story. * </p> * * @param controller * the controller */ protected SchemerFactory(HasAppendClauses controller) { this.controller = controller; } /** @return <code>true</code> if the built element has occurrences. */ private boolean hasOccurrences() { return occurrences != null; } /** @return <code>true</code> if the built element specifies a result. */ private boolean hasResult() { return result != null; } /** * Cleans up all the temporary fields registered during the build. */ protected void reset() { occurrences = null; result = null; temporaryScenario = null; temporaryStubs = null; } /** * Cleans up ALL the resources used by the factory. * * <p> * This method is stronger than <code>reset</code> since it also * deletes the factory used to build arguments to invocations. * </p> */ protected void cleanup() { reset(); ArgumentSpecificationProvider.cleanup(); } /** * Calls back the story controller to register the lastly built directive. */ private void registerToController() { if (temporaryScenario != null) { controller.append(temporaryScenario); } else { controller.append(temporaryStubs); } } /** * Registers the result of the built directive. * * @param resultHandler * the handler that will get the clause */ private void registerResultIfAny( HasInvocationResultSpecificationClauses<?> resultHandler) { if (hasResult()) { resultHandler.will(result); } } /** * Closes a specification by adding the registered clauses of the * expectation or stub to the ongoing scenario or stubs. */ @Override public void onClosure() { // The target invocation result handler: HasInvocationResultSpecificationClauses<?> resultHandler; if (hasOccurrences()) { resultHandler = temporaryScenario.expect(); temporaryScenario.expect().occurs(occurrences); } else { resultHandler = temporaryStubs.stub(); } registerResultIfAny(resultHandler); registerToController(); reset(); } /** * Prepares the builder to build an expectation. * * <p> * This consists in creating a new scenario and plug a handler to the * closure of the specification, so that we can add the registered * parameters. * </p> * * @param mock * The mock object for which we create an expectation. */ private <T> void prepareToBuildExpectation(T mock) { temporaryScenario = new Scenario(false); // don't clear the story track temporaryScenario.expect(mock, this); ArgumentSpecificationProvider.setArgumentSpecificationBuilder(temporaryScenario); } /** * Prepares the builder to build a stub. * * <p> * This consists in creating a new stub and plug a handler to the closure of * the specification, so that we can add the registered parameters. * </p> * * @param mock * The mock object for which we create an expectation. */ private <T> void prepareToBuildStub(T mock) { temporaryStubs = new Stubs(); temporaryStubs.stub(mock, this); ArgumentSpecificationProvider.setArgumentSpecificationBuilder(temporaryStubs); } /** * Prepares to register an expectation or a stub for a given mock. * * <p> * The method uses the previously specified clauses to guess what the best * solution is (scenario vs. stubs). * </p> */ private <T> T prepareToBuild(T mock) { if (hasOccurrences()) { prepareToBuildExpectation(mock); } else { prepareToBuildStub(mock); } return mock; } @Override public <T> HasWhenClause willReturn(T result) { this.result = returnValue(result); return this; } @Override public <T extends Throwable> HasWhenClause willThrow(T excpt) { result = throwException(excpt); return this; } @Override public HasWhenClause will(InvocationResultProvider result) { this.result = result; return this; } @Override public HasWhenClause willDelegateTo(InvocationResultProvider provider) { result = provider; return this; } @Override public HasExpectationClauses willInvoke(OccurrenceChecker occurrences) { this.occurrences = occurrences; return this; } @Override public HasExpectationClauses willInvoke(int n) { occurrences = exactly(n); return this; } @Override public <T> T of(T mock) { return prepareToBuild(mock); } @Override public <T> T when(T mock) { return prepareToBuild(mock); } }
/* Generated By:JavaCC: Do not edit this line. DSLParserConstants.java */ package de.uniwue.info2.parser; /** * Token literal values and constants. * Generated by org.javacc.parser.OtherFilesGen#start() */ public interface DSLParserConstants { /** End of File. */ int EOF = 0; /** RegularExpression Id. */ int BEGIN_BLOCK_COMMENT = 6; /** RegularExpression Id. */ int AUTHOR_TAG = 9; /** RegularExpression Id. */ int VERSION_TAG = 10; /** RegularExpression Id. */ int DESCRIPTION_TAG = 11; /** RegularExpression Id. */ int OPTIONAL_TAG = 12; /** RegularExpression Id. */ int TAG = 14; /** RegularExpression Id. */ int VARIABLE_NAME = 18; /** RegularExpression Id. */ int SHORT = 19; /** RegularExpression Id. */ int INTEGER = 20; /** RegularExpression Id. */ int LONG = 21; /** RegularExpression Id. */ int DIGITS_INTEGER = 22; /** RegularExpression Id. */ int FLOAT = 23; /** RegularExpression Id. */ int DOUBLE = 24; /** RegularExpression Id. */ int DIGITS_FLOAT = 25; /** RegularExpression Id. */ int BIN_32 = 26; /** RegularExpression Id. */ int BIN_64 = 27; /** RegularExpression Id. */ int HEX_8 = 28; /** RegularExpression Id. */ int HEX_16 = 29; /** RegularExpression Id. */ int BOOL = 30; /** RegularExpression Id. */ int BOOL_TRUE = 31; /** RegularExpression Id. */ int BOOL_FALSE = 32; /** RegularExpression Id. */ int INTERVAL = 33; /** RegularExpression Id. */ int NEGATIVE_INFINITY = 34; /** RegularExpression Id. */ int POSITIVE_INFINITY = 35; /** RegularExpression Id. */ int EMPTY_SET = 36; /** RegularExpression Id. */ int ENTIRE_SET = 37; /** RegularExpression Id. */ int EOL = 38; /** RegularExpression Id. */ int CLOSE_PAR_LIST = 39; /** RegularExpression Id. */ int OPEN_PAR_LIST = 40; /** RegularExpression Id. */ int EQUAL = 41; /** RegularExpression Id. */ int SP = 42; /** RegularExpression Id. */ int NG = 43; /** RegularExpression Id. */ int SUBSETEQ = 44; /** RegularExpression Id. */ int SUBSETNEQ = 45; /** RegularExpression Id. */ int SUPERSETEQ = 46; /** RegularExpression Id. */ int SUPERSETNEQ = 47; /** RegularExpression Id. */ int OPEN_TYPE = 48; /** RegularExpression Id. */ int CLOSE_TYPE = 49; /** RegularExpression Id. */ int OPEN_INTERVAL_VARS = 50; /** RegularExpression Id. */ int CLOSE_INTERVAL_VARS = 51; /** RegularExpression Id. */ int PRIMITIVE_PAR_SEP = 52; /** Lexical state. */ int DEFAULT = 0; /** Lexical state. */ int BLOCK_COMMENT = 1; /** Lexical state. */ int TAG_CONTENT = 2; /** Lexical state. */ int VARIABLE = 3; /** Literal token values. */ String[] tokenImage = { "<EOF>", "\" \"", "\"\\t\"", "\"\\n\"", "<token of kind 4>", "\"$\"", "\"/*\"", "<token of kind 7>", "\"*/\"", "\"@author\"", "\"@version\"", "\"@description\"", "\"@required\"", "\";\"", "<TAG>", "\" \"", "\"\\t\"", "\"\\n\"", "<VARIABLE_NAME>", "\"short\"", "\"int\"", "\"long\"", "<DIGITS_INTEGER>", "\"float\"", "\"double\"", "<DIGITS_FLOAT>", "<BIN_32>", "<BIN_64>", "<HEX_8>", "<HEX_16>", "\"bool\"", "\"true\"", "\"false\"", "\"interval\"", "\"-inf\"", "\"+inf\"", "\"empty\"", "\"entire\"", "\";\"", "\")\"", "\"(\"", "\"=\"", "\",\"", "\"!\"", "\"subseteq=\"", "\"subsetneq=\"", "\"superseteq=\"", "\"supersetneq=\"", "\"<\"", "\">\"", "\"[\"", "\"]\"", "\":\"", "\"intersect\"", "\"hull\"", "\"inf\"", "\"sup\"", "\"mid\"", "\"rad\"", "\"mid_rad\"", "\"wid\"", "\"mag\"", "\"mig\"", "\"is_empty\"", "\"is_entire\"", "\"is_equal\"", "\"contained_in\"", "\"contains\"", "\"less\"", "\"greater\"", "\"precedes\"", "\"succeeds\"", "\"is_interior\"", "\"contains_interior\"", "\"strictly_less\"", "\"strictly_greater\"", "\"strictly_precedes\"", "\"strictly_succeeds\"", "\"are_disjoint\"", "\"pos\"", "\"neg\"", "\"add\"", "\"sub\"", "\"mul\"", "\"div\"", "\"inv\"", "\"sqrt\"", "\"fma\"", "\"interval_case\"", "\"sqr\"", "\"pown\"", "\"pow\"", "\"exp\"", "\"exp2\"", "\"exp10\"", "\"log\"", "\"log2\"", "\"log10\"", "\"sin\"", "\"cos\"", "\"tan\"", "\"asin\"", "\"acos\"", "\"atan\"", "\"atan2\"", "\"sinh\"", "\"cosh\"", "\"tanh\"", "\"asinh\"", "\"acosh\"", "\"atanh\"", "\"sign\"", "\"ceil\"", "\"floor\"", "\"trunc\"", "\"round_ties_to_even\"", "\"round_ties_to_away\"", "\"abs\"", "\"min\"", "\"max\"", "\"sqr_rev\"", "\"inv_rev\"", "\"abs_rev\"", "\"pown_rev\"", "\"sin_rev\"", "\"cos_rev\"", "\"tan_rev\"", "\"cosh_rev\"", "\"mul_rev\"", "\"div_rev1\"", "\"div_rev2\"", "\"pow_rev1\"", "\"pow_rev2\"", "\"atan2_rev1\"", "\"atan2_rev2\"", "\"cancel_plus\"", "\"cancel_minus\"", "\"rootn\"", "\"expm1\"", "\"exp2m1\"", "\"exp10m1\"", "\"logp1\"", "\"log2p1\"", "\"log10p1\"", "\"compoundm1\"", "\"hypot\"", "\"r_sqrt\"", "\"sin_pi\"", "\"cos_pi\"", "\"tan_pi\"", "\"asin_pi\"", "\"acos_pi\"", "\"atan_pi\"", "\"atan2_pi\"", }; }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.appservice.v2016_08_01.implementation; import org.joda.time.DateTime; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.rest.serializer.JsonFlatten; import com.microsoft.azure.management.appservice.v2016_08_01.ProxyOnlyResource; /** * Process Thread Information. */ @JsonFlatten public class ProcessThreadInfoInner extends ProxyOnlyResource { /** * ARM Identifier for deployment. */ @JsonProperty(value = "properties.id") private Integer processThreadInfoId; /** * HRef URI. */ @JsonProperty(value = "properties.href") private String href; /** * Process URI. */ @JsonProperty(value = "properties.process") private String process; /** * Start address. */ @JsonProperty(value = "properties.startAddress") private String startAddress; /** * Current thread priority. */ @JsonProperty(value = "properties.currentPriority") private Integer currentPriority; /** * Thread priority level. */ @JsonProperty(value = "properties.priorityLevel") private String priorityLevel; /** * Base priority. */ @JsonProperty(value = "properties.basePriority") private Integer basePriority; /** * Start time. */ @JsonProperty(value = "properties.startTime") private DateTime startTime; /** * Total processor time. */ @JsonProperty(value = "properties.totalProcessorTime") private String totalProcessorTime; /** * User processor time. */ @JsonProperty(value = "properties.userProcessorTime") private String userProcessorTime; /** * Privileged processor time. */ @JsonProperty(value = "properties.priviledgedProcessorTime") private String priviledgedProcessorTime; /** * Thread state. */ @JsonProperty(value = "properties.state") private String state; /** * Wait reason. */ @JsonProperty(value = "properties.waitReason") private String waitReason; /** * Get aRM Identifier for deployment. * * @return the processThreadInfoId value */ public Integer processThreadInfoId() { return this.processThreadInfoId; } /** * Set aRM Identifier for deployment. * * @param processThreadInfoId the processThreadInfoId value to set * @return the ProcessThreadInfoInner object itself. */ public ProcessThreadInfoInner withProcessThreadInfoId(Integer processThreadInfoId) { this.processThreadInfoId = processThreadInfoId; return this; } /** * Get hRef URI. * * @return the href value */ public String href() { return this.href; } /** * Set hRef URI. * * @param href the href value to set * @return the ProcessThreadInfoInner object itself. */ public ProcessThreadInfoInner withHref(String href) { this.href = href; return this; } /** * Get process URI. * * @return the process value */ public String process() { return this.process; } /** * Set process URI. * * @param process the process value to set * @return the ProcessThreadInfoInner object itself. */ public ProcessThreadInfoInner withProcess(String process) { this.process = process; return this; } /** * Get start address. * * @return the startAddress value */ public String startAddress() { return this.startAddress; } /** * Set start address. * * @param startAddress the startAddress value to set * @return the ProcessThreadInfoInner object itself. */ public ProcessThreadInfoInner withStartAddress(String startAddress) { this.startAddress = startAddress; return this; } /** * Get current thread priority. * * @return the currentPriority value */ public Integer currentPriority() { return this.currentPriority; } /** * Set current thread priority. * * @param currentPriority the currentPriority value to set * @return the ProcessThreadInfoInner object itself. */ public ProcessThreadInfoInner withCurrentPriority(Integer currentPriority) { this.currentPriority = currentPriority; return this; } /** * Get thread priority level. * * @return the priorityLevel value */ public String priorityLevel() { return this.priorityLevel; } /** * Set thread priority level. * * @param priorityLevel the priorityLevel value to set * @return the ProcessThreadInfoInner object itself. */ public ProcessThreadInfoInner withPriorityLevel(String priorityLevel) { this.priorityLevel = priorityLevel; return this; } /** * Get base priority. * * @return the basePriority value */ public Integer basePriority() { return this.basePriority; } /** * Set base priority. * * @param basePriority the basePriority value to set * @return the ProcessThreadInfoInner object itself. */ public ProcessThreadInfoInner withBasePriority(Integer basePriority) { this.basePriority = basePriority; return this; } /** * Get start time. * * @return the startTime value */ public DateTime startTime() { return this.startTime; } /** * Set start time. * * @param startTime the startTime value to set * @return the ProcessThreadInfoInner object itself. */ public ProcessThreadInfoInner withStartTime(DateTime startTime) { this.startTime = startTime; return this; } /** * Get total processor time. * * @return the totalProcessorTime value */ public String totalProcessorTime() { return this.totalProcessorTime; } /** * Set total processor time. * * @param totalProcessorTime the totalProcessorTime value to set * @return the ProcessThreadInfoInner object itself. */ public ProcessThreadInfoInner withTotalProcessorTime(String totalProcessorTime) { this.totalProcessorTime = totalProcessorTime; return this; } /** * Get user processor time. * * @return the userProcessorTime value */ public String userProcessorTime() { return this.userProcessorTime; } /** * Set user processor time. * * @param userProcessorTime the userProcessorTime value to set * @return the ProcessThreadInfoInner object itself. */ public ProcessThreadInfoInner withUserProcessorTime(String userProcessorTime) { this.userProcessorTime = userProcessorTime; return this; } /** * Get privileged processor time. * * @return the priviledgedProcessorTime value */ public String priviledgedProcessorTime() { return this.priviledgedProcessorTime; } /** * Set privileged processor time. * * @param priviledgedProcessorTime the priviledgedProcessorTime value to set * @return the ProcessThreadInfoInner object itself. */ public ProcessThreadInfoInner withPriviledgedProcessorTime(String priviledgedProcessorTime) { this.priviledgedProcessorTime = priviledgedProcessorTime; return this; } /** * Get thread state. * * @return the state value */ public String state() { return this.state; } /** * Set thread state. * * @param state the state value to set * @return the ProcessThreadInfoInner object itself. */ public ProcessThreadInfoInner withState(String state) { this.state = state; return this; } /** * Get wait reason. * * @return the waitReason value */ public String waitReason() { return this.waitReason; } /** * Set wait reason. * * @param waitReason the waitReason value to set * @return the ProcessThreadInfoInner object itself. */ public ProcessThreadInfoInner withWaitReason(String waitReason) { this.waitReason = waitReason; return this; } }
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.cvsSupport2.changeBrowser; import com.intellij.cvsSupport2.CvsVcs2; import com.intellij.cvsSupport2.connections.CvsEnvironment; import com.intellij.cvsSupport2.cvsoperations.dateOrRevision.SimpleRevision; import com.intellij.cvsSupport2.history.CvsRevisionNumber; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.AbstractVcs; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ContentRevision; import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList; import com.intellij.openapi.vcs.versionBrowser.CommittedChangeListImpl; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.io.IOUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.netbeans.lib.cvsclient.command.log.Revision; import java.io.DataInput; import java.io.DataOutput; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; public class CvsChangeList implements CommittedChangeList { private long myDate; private long myFinishDate; private long myNumber; @NotNull private String myDescription; private final VirtualFile myRootFile; private String myRootPath; private final List<RevisionWrapper> myRevisions = new ArrayList<>(); private String myUser; public static final int SUITABLE_DIFF = 2 * 60 * 1000; private final CvsEnvironment myEnvironment; private final Project myProject; private List<Change> myChanges; @NonNls private static final String EXP_STATE = "Exp"; @NonNls private static final String ADDED_STATE = "added"; @NonNls public static final String DEAD_STATE = "dead"; public CvsChangeList(final Project project, final CvsEnvironment environment, @Nullable final VirtualFile rootFile, final long number, @NotNull final String description, final long date, String user, String rootPath) { myRootFile = rootFile; myDate = date; myFinishDate = date; myNumber = number; myDescription = description; myUser = user; myRootPath = rootPath; myEnvironment = environment; myProject = project; } public CvsChangeList(final Project project, final CvsEnvironment environment, @Nullable final VirtualFile rootFile, final DataInput stream) throws IOException { myProject = project; myEnvironment = environment; myRootFile = rootFile; readFromStream(stream); } public String getCommitterName() { return myUser; } public Date getCommitDate() { return new Date(myDate); } public long getNumber() { return myNumber; } public AbstractVcs getVcs() { return CvsVcs2.getInstance(myProject); } public Collection<Change> getChangesWithMovedTrees() { return CommittedChangeListImpl.getChangesWithMovedTreesImpl(this); } @Override public boolean isModifiable() { return true; } @Override public void setDescription(String newMessage) { myDescription = newMessage; } @Nullable public String getBranch() { if (myRevisions.size() > 0) { return myRevisions.get(0).getBranch(); } return null; } public Collection<Change> getChanges() { if (myChanges == null) { myChanges = new ArrayList<>(); for(RevisionWrapper wrapper: myRevisions) { final Revision revision = wrapper.getRevision(); final String state = revision.getState(); String path = wrapper.getFile(); final File localFile; if (myRootFile != null) { final String directorySuffix = myRootFile.isDirectory() ? "/" : ""; if (StringUtil.startsWithConcatenation(path, myRootPath, directorySuffix)) { path = path.substring(myRootPath.length() + directorySuffix.length()); localFile = new File(myRootFile.getPresentableUrl(), path); } else { localFile = new File(wrapper.getFile()); } } else { localFile = new File(wrapper.getFile()); } final boolean added = isAdded(revision); final ContentRevision beforeRevision = added ? null : new CvsContentRevision(new File(wrapper.getFile()), localFile, new SimpleRevision(new CvsRevisionNumber(revision.getNumber()).getPrevNumber().asString()), myEnvironment, myProject); final ContentRevision afterRevision = (!added && DEAD_STATE.equals(state)) ? null : new CvsContentRevision(new File(wrapper.getFile()), localFile, new SimpleRevision(revision.getNumber()), myEnvironment, myProject); myChanges.add(new Change(beforeRevision, afterRevision)); } } return myChanges; } @NotNull public String getName() { return myDescription; } public String getComment() { return myDescription; } public boolean containsDate(long date) { if (date >= myDate && date <= myFinishDate) { return true; } if (Math.abs(date - myDate) < SUITABLE_DIFF) { return true; } if (Math.abs(date - myFinishDate) < SUITABLE_DIFF) { return true; } return false; } public boolean containsFile(final String file) { for(RevisionWrapper revision: myRevisions) { if (revision.getFile().equals(file)) { return true; } } return false; } public void addFileRevision(RevisionWrapper revision) { myRevisions.add(revision); final long revisionTime = revision.getTime(); if (revisionTime < myDate) { myDate = revisionTime; } if (revisionTime > myFinishDate) { myFinishDate = revisionTime; } } public boolean containsFileRevision(RevisionWrapper revision) { return myRevisions.contains(revision); } private static boolean isAdded(final Revision revision) { final String revisionState = revision.getState(); if (EXP_STATE.equals(revisionState) && revision.getLines() == null) { return true; } if (ADDED_STATE.equals(revisionState)) { return true; } // files added on branch final int[] subRevisions = new CvsRevisionNumber(revision.getNumber()).getSubRevisions(); if (subRevisions != null && subRevisions.length > 2 && subRevisions [subRevisions.length-1] == 1) { return true; } return false; } public static boolean isAncestor(final String parent, final String child) { return child.equals(parent) || StringUtil.startsWithConcatenation(child, parent, "/"); } public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final CvsChangeList that = (CvsChangeList)o; if (!myRevisions.equals(that.myRevisions)) return false; return true; } public int hashCode() { int result = (int)(myNumber ^ (myNumber >>> 32)); result = 31 * result + myDescription.hashCode(); return result; } public String toString() { return myDescription; } public void writeToStream(DataOutput stream) throws IOException { stream.writeLong(myDate); stream.writeLong(myFinishDate); stream.writeLong(myNumber); IOUtil.writeUTFTruncated(stream, myDescription); stream.writeUTF(myUser); stream.writeUTF(myRootPath); stream.writeInt(myRevisions.size()); for(RevisionWrapper revision: myRevisions) { revision.writeToStream(stream); } } private void readFromStream(final DataInput stream) throws IOException { myDate = stream.readLong(); myFinishDate = stream.readLong(); myNumber = stream.readLong(); myDescription = stream.readUTF(); myUser = stream.readUTF(); myRootPath = stream.readUTF(); final int revisionCount = stream.readInt(); for(int i=0; i<revisionCount; i++) { myRevisions.add(RevisionWrapper.readFromStream(stream)); } } }
/* * Copyright 2013-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.io; import com.facebook.buck.util.BuckConstant; import com.facebook.buck.util.environment.Platform; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.io.ByteSource; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.annotation.Nullable; public class MorePaths { /** Utility class: do not instantiate. */ private MorePaths() {} public static final Function<String, Path> TO_PATH = new Function<String, Path>() { @Override public Path apply(String path) { return Paths.get(path); } }; private static final Path EMPTY_PATH = Paths.get(""); public static String pathWithUnixSeparators(String path) { return pathWithUnixSeparators(Paths.get(path)); } public static String pathWithUnixSeparators(Path path) { return path.toString().replace("\\", "/"); } public static String pathWithPlatformSeparators(String path) { return pathWithPlatformSeparators(Paths.get(path)); } public static String pathWithPlatformSeparators(Path path) { if (Platform.detect() == Platform.WINDOWS) { return path.toString().replace("/", "\\"); } else { return pathWithUnixSeparators(path); } } public static String pathWithUnixSeparatorsAndTrailingSlash(Path path) { return pathWithUnixSeparators(path) + "/"; } /** * @param toMakeAbsolute The {@link Path} to act upon. * @return The Path, made absolute and normalized. */ public static Path absolutify(Path toMakeAbsolute) { return toMakeAbsolute.toAbsolutePath().normalize(); } public static Path getParentOrEmpty(Path path) { Path parent = path.getParent(); if (parent == null) { parent = EMPTY_PATH; } return parent; } /** * Get the path of a file relative to a base directory. * * @param path must reference a file, not a directory. * @param baseDir must reference a directory that is relative to a common directory with the path. * may be null if referencing the same directory as the path. * @return the relative path of path from the directory baseDir. */ public static Path getRelativePath(Path path, @Nullable Path baseDir) { if (baseDir == null) { // This allows callers to use this method with "file.parent()" for files from the project // root dir. baseDir = EMPTY_PATH; } Preconditions.checkArgument(!path.isAbsolute(), "Path must be relative: %s.", path); Preconditions.checkArgument(!baseDir.isAbsolute(), "Path must be relative: %s.", baseDir); return relativize(baseDir, path); } /** * Get a relative path from path1 to path2, first normalizing each path. * * This method is a workaround for JDK-6925169 (Path.relativize * returns incorrect result if path contains "." or ".."). */ public static Path relativize(Path path1, Path path2) { Preconditions.checkArgument( path1.isAbsolute() == path2.isAbsolute(), "Both paths must be absolute or both paths must be relative. (%s is %s, %s is %s)", path1, path1.isAbsolute() ? "absolute" : "relative", path2, path2.isAbsolute() ? "absolute" : "relative"); path1 = normalize(path1); path2 = normalize(path2); // On Windows, if path1 is "" then Path.relativize returns ../path2 instead of path2 or ./path2 if (EMPTY_PATH.equals(path1)) { return path2; } return path1.relativize(path2); } /** * Get a path without unnecessary path parts. * * This method is a workaround for JDK-8037945 (Paths.get("").normalize() throws * ArrayIndexOutOfBoundsException). */ public static Path normalize(Path path) { if (!EMPTY_PATH.equals(path)) { path = path.normalize(); } return path; } /** * Creates a symlink at * {@code projectFilesystem.getRootPath().resolve(pathToDesiredLinkUnderProjectRoot)} that * points to {@code projectFilesystem.getRootPath().resolve(pathToExistingFileUnderProjectRoot)} * using a relative symlink. * * @param pathToDesiredLinkUnderProjectRoot must reference a file, not a directory. * @param pathToExistingFileUnderProjectRoot must reference a file, not a directory. * @return the relative path from the new symlink that was created to the existing file. */ public static Path createRelativeSymlink( Path pathToDesiredLinkUnderProjectRoot, Path pathToExistingFileUnderProjectRoot, ProjectFilesystem projectFilesystem) throws IOException { return createRelativeSymlink( pathToDesiredLinkUnderProjectRoot, pathToExistingFileUnderProjectRoot, projectFilesystem.getRootPath()); } /** * Creates a symlink at {@code pathToProjectRoot.resolve(pathToDesiredLinkUnderProjectRoot)} that * points to {@code pathToProjectRoot.resolve(pathToExistingFileUnderProjectRoot)} using a * relative symlink. Both params must be relative to the project root. * * @param pathToDesiredLinkUnderProjectRoot must reference a file, not a directory. * @param pathToExistingFileUnderProjectRoot must reference a file, not a directory. * @return the relative path from the new symlink that was created to the existing file. */ public static Path createRelativeSymlink( Path pathToDesiredLinkUnderProjectRoot, Path pathToExistingFileUnderProjectRoot, Path pathToProjectRoot) throws IOException { Path target = getRelativePath( pathToExistingFileUnderProjectRoot, pathToDesiredLinkUnderProjectRoot.getParent()); Files.createSymbolicLink(pathToProjectRoot.resolve(pathToDesiredLinkUnderProjectRoot), target); return target; } /** * Convert a set of input file paths as strings to {@link Path} objects. */ public static ImmutableSortedSet<Path> asPaths(Iterable<String> paths) { ImmutableSortedSet.Builder<Path> builder = ImmutableSortedSet.naturalOrder(); for (String path : paths) { builder.add(TO_PATH.apply(path)); } return builder.build(); } /** * Filters out {@link Path} objects from {@code paths} that aren't a subpath of {@code root} and * returns a set of paths relative to {@code root}. */ public static ImmutableSet<Path> filterForSubpaths(Iterable<Path> paths, final Path root) { final Path normalizedRoot = root.toAbsolutePath().normalize(); return FluentIterable.from(paths) .filter(new Predicate<Path>() { @Override public boolean apply(Path input) { if (input.isAbsolute()) { return input.normalize().startsWith(normalizedRoot); } else { return true; } } }) .transform(new Function<Path, Path>() { @Override public Path apply(Path input) { if (input.isAbsolute()) { return relativize(normalizedRoot, input); } else { return input; } } }) .toSet(); } /** * @return Whether the input path directs to a file in the buck generated files folder. */ public static boolean isGeneratedFile(Path pathRelativeToProjectRoot) { return pathRelativeToProjectRoot.startsWith(BuckConstant.GEN_PATH); } /** * Expands "~/foo" into "/home/zuck/foo". Returns regular paths unmodified. */ public static Path expandHomeDir(Path path) { if (!path.startsWith("~")) { return path; } Path homePath = Paths.get(System.getProperty("user.home")); if (path.equals(Paths.get("~"))) { return homePath; } return homePath.resolve(path.subpath(1, path.getNameCount())); } public static boolean fileContentsDiffer( InputStream contents, Path path, ProjectFilesystem projectFilesystem) throws IOException { try { // Hash the contents of the file at path so we don't have to pull the whole thing into memory. MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); byte[] pathDigest; try (InputStream is = projectFilesystem.newFileInputStream(path)) { pathDigest = inputStreamDigest(is, sha1); } // Hash 'contents' and see if the two differ. sha1.reset(); byte[] contentsDigest = inputStreamDigest(contents, sha1); return !Arrays.equals(pathDigest, contentsDigest); } catch (NoSuchFileException e) { // If the file doesn't exist, we need to create it. return true; } catch (NoSuchAlgorithmException e) { throw Throwables.propagate(e); } } public static ByteSource asByteSource(final Path path) { return new ByteSource() { @Override public InputStream openStream() throws IOException { return Files.newInputStream(path); } }; } private static byte[] inputStreamDigest(InputStream inputStream, MessageDigest messageDigest) throws IOException { try (DigestInputStream dis = new DigestInputStream(inputStream, messageDigest)) { byte[] buf = new byte[4096]; while (true) { // Read the contents of the existing file so we can hash it. if (dis.read(buf) == -1) { break; } } return dis.getMessageDigest().digest(); } } public static String getFileExtension(Path path) { String name = path.getFileName().toString(); int index = name.lastIndexOf('.'); return index == -1 ? "" : name.substring(index + 1); } public static String getNameWithoutExtension(Path file) { String name = file.getFileName().toString(); int index = name.lastIndexOf('.'); return index == -1 ? name : name.substring(0, index); } public static void append(Path path, String text, Charset charset) throws IOException{ try (Writer writer = Files.newBufferedWriter(path, charset)) { writer.append(text); writer.flush(); } } }
/* * Copyright 2016 Netflix, 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 io.rsocket.frame; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.rsocket.FrameType; import java.nio.charset.StandardCharsets; public class SetupFrameFlyweight { private SetupFrameFlyweight() {} public static final int FLAGS_RESUME_ENABLE = 0b00_1000_0000; public static final int FLAGS_WILL_HONOR_LEASE = 0b00_0100_0000; public static final int FLAGS_STRICT_INTERPRETATION = 0b00_0010_0000; public static final int VALID_FLAGS = FLAGS_RESUME_ENABLE | FLAGS_WILL_HONOR_LEASE | FLAGS_STRICT_INTERPRETATION; public static final int CURRENT_VERSION = VersionFlyweight.encode(1, 0); // relative to start of passed offset private static final int VERSION_FIELD_OFFSET = FrameHeaderFlyweight.FRAME_HEADER_LENGTH; private static final int KEEPALIVE_INTERVAL_FIELD_OFFSET = VERSION_FIELD_OFFSET + Integer.BYTES; private static final int MAX_LIFETIME_FIELD_OFFSET = KEEPALIVE_INTERVAL_FIELD_OFFSET + Integer.BYTES; private static final int VARIABLE_DATA_OFFSET = MAX_LIFETIME_FIELD_OFFSET + Integer.BYTES; public static int computeFrameLength( final int flags, final String metadataMimeType, final String dataMimeType, final int metadataLength, final int dataLength ) { return computeFrameLength(flags, 0, metadataMimeType, dataMimeType, metadataLength, dataLength); } private static int computeFrameLength( final int flags, final int resumeTokenLength, final String metadataMimeType, final String dataMimeType, final int metadataLength, final int dataLength ) { int length = FrameHeaderFlyweight.computeFrameHeaderLength(FrameType.SETUP, metadataLength, dataLength); length += Integer.BYTES * 3; if ((flags & FLAGS_RESUME_ENABLE) != 0) { length += Short.BYTES + resumeTokenLength; } length += 1 + metadataMimeType.getBytes(StandardCharsets.UTF_8).length; length += 1 + dataMimeType.getBytes(StandardCharsets.UTF_8).length; return length; } public static int encode( final ByteBuf byteBuf, int flags, final int keepaliveInterval, final int maxLifetime, final String metadataMimeType, final String dataMimeType, final ByteBuf metadata, final ByteBuf data ) { if ((flags & FLAGS_RESUME_ENABLE) != 0) { throw new IllegalArgumentException("RESUME_ENABLE not supported"); } return encode( byteBuf, flags, keepaliveInterval, maxLifetime, Unpooled.EMPTY_BUFFER, metadataMimeType, dataMimeType, metadata, data); } // Only exposed for testing, other code shouldn't create frames with resumption tokens for now static int encode( final ByteBuf byteBuf, int flags, final int keepaliveInterval, final int maxLifetime, final ByteBuf resumeToken, final String metadataMimeType, final String dataMimeType, final ByteBuf metadata, final ByteBuf data ) { final int frameLength = computeFrameLength(flags, resumeToken.readableBytes(), metadataMimeType, dataMimeType, metadata.readableBytes(), data.readableBytes()); int length = FrameHeaderFlyweight.encodeFrameHeader(byteBuf, frameLength, flags, FrameType.SETUP, 0); byteBuf.setInt(VERSION_FIELD_OFFSET, CURRENT_VERSION); byteBuf.setInt(KEEPALIVE_INTERVAL_FIELD_OFFSET, keepaliveInterval); byteBuf.setInt(MAX_LIFETIME_FIELD_OFFSET, maxLifetime); length += Integer.BYTES * 3; if ((flags & FLAGS_RESUME_ENABLE) != 0) { byteBuf.setShort(length, resumeToken.readableBytes()); length += Short.BYTES; int resumeTokenLength = resumeToken.readableBytes(); byteBuf.setBytes(length, resumeToken, resumeTokenLength); length += resumeTokenLength; } length += putMimeType(byteBuf, length, metadataMimeType); length += putMimeType(byteBuf, length, dataMimeType); length += FrameHeaderFlyweight.encodeMetadata( byteBuf, FrameType.SETUP, length, metadata); length += FrameHeaderFlyweight.encodeData(byteBuf, length, data); return length; } public static int version(final ByteBuf byteBuf) { return byteBuf.getInt(VERSION_FIELD_OFFSET); } public static int keepaliveInterval(final ByteBuf byteBuf) { return byteBuf.getInt(KEEPALIVE_INTERVAL_FIELD_OFFSET); } public static int maxLifetime(final ByteBuf byteBuf) { return byteBuf.getInt(MAX_LIFETIME_FIELD_OFFSET); } public static String metadataMimeType(final ByteBuf byteBuf) { final byte[] bytes = getMimeType(byteBuf, metadataMimetypeOffset(byteBuf)); return new String(bytes, StandardCharsets.UTF_8); } public static String dataMimeType(final ByteBuf byteBuf) { int fieldOffset = metadataMimetypeOffset(byteBuf); fieldOffset += 1 + byteBuf.getByte(fieldOffset); final byte[] bytes = getMimeType(byteBuf, fieldOffset); return new String(bytes, StandardCharsets.UTF_8); } public static int payloadOffset(final ByteBuf byteBuf) { int fieldOffset = metadataMimetypeOffset(byteBuf); final int metadataMimeTypeLength = byteBuf.getByte(fieldOffset); fieldOffset += 1 + metadataMimeTypeLength; final int dataMimeTypeLength = byteBuf.getByte(fieldOffset); fieldOffset += 1 + dataMimeTypeLength; return fieldOffset; } private static int metadataMimetypeOffset(final ByteBuf byteBuf) { return VARIABLE_DATA_OFFSET + resumeTokenTotalLength(byteBuf); } private static int resumeTokenTotalLength(final ByteBuf byteBuf) { if ((FrameHeaderFlyweight.flags(byteBuf) & FLAGS_RESUME_ENABLE) == 0) { return 0; } else { return Short.BYTES + byteBuf.getShort(VARIABLE_DATA_OFFSET); } } private static int putMimeType( final ByteBuf byteBuf, final int fieldOffset, final String mimeType) { byte[] bytes = mimeType.getBytes(StandardCharsets.UTF_8); byteBuf.setByte(fieldOffset, (byte) bytes.length); byteBuf.setBytes(fieldOffset + 1, bytes); return 1 + bytes.length; } private static byte[] getMimeType(final ByteBuf byteBuf, final int fieldOffset) { final int length = byteBuf.getByte(fieldOffset); final byte[] bytes = new byte[length]; byteBuf.getBytes(fieldOffset + 1, bytes); return bytes; } }
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.jboss.drools.impl; import java.math.BigInteger; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; import org.eclipse.emf.ecore.xml.type.XMLTypeFactory; import org.eclipse.emf.ecore.xml.type.XMLTypePackage; import org.jboss.drools.*; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class DroolsFactoryImpl extends EFactoryImpl implements DroolsFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static DroolsFactory init() { try { DroolsFactory theDroolsFactory = (DroolsFactory)EPackage.Registry.INSTANCE.getEFactory("http://www.jboss.org/drools"); if (theDroolsFactory != null) { return theDroolsFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new DroolsFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DroolsFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case DroolsPackage.DOCUMENT_ROOT: return createDocumentRoot(); case DroolsPackage.GLOBAL_TYPE: return createGlobalType(); case DroolsPackage.IMPORT_TYPE: return createImportType(); case DroolsPackage.META_DATA_TYPE: return createMetaDataType(); case DroolsPackage.ON_ENTRY_SCRIPT_TYPE: return createOnEntryScriptType(); case DroolsPackage.ON_EXIT_SCRIPT_TYPE: return createOnExitScriptType(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object createFromString(EDataType eDataType, String initialValue) { switch (eDataType.getClassifierID()) { case DroolsPackage.PACKAGE_NAME_TYPE: return createPackageNameTypeFromString(eDataType, initialValue); case DroolsPackage.PRIORITY_TYPE: return createPriorityTypeFromString(eDataType, initialValue); case DroolsPackage.RULE_FLOW_GROUP_TYPE: return createRuleFlowGroupTypeFromString(eDataType, initialValue); case DroolsPackage.TASK_NAME_TYPE: return createTaskNameTypeFromString(eDataType, initialValue); case DroolsPackage.VERSION_TYPE: return createVersionTypeFromString(eDataType, initialValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String convertToString(EDataType eDataType, Object instanceValue) { switch (eDataType.getClassifierID()) { case DroolsPackage.PACKAGE_NAME_TYPE: return convertPackageNameTypeToString(eDataType, instanceValue); case DroolsPackage.PRIORITY_TYPE: return convertPriorityTypeToString(eDataType, instanceValue); case DroolsPackage.RULE_FLOW_GROUP_TYPE: return convertRuleFlowGroupTypeToString(eDataType, instanceValue); case DroolsPackage.TASK_NAME_TYPE: return convertTaskNameTypeToString(eDataType, instanceValue); case DroolsPackage.VERSION_TYPE: return convertVersionTypeToString(eDataType, instanceValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DocumentRoot createDocumentRoot() { DocumentRootImpl documentRoot = new DocumentRootImpl(); return documentRoot; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public GlobalType createGlobalType() { GlobalTypeImpl globalType = new GlobalTypeImpl(); return globalType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ImportType createImportType() { ImportTypeImpl importType = new ImportTypeImpl(); return importType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MetaDataType createMetaDataType() { MetaDataTypeImpl metaDataType = new MetaDataTypeImpl(); return metaDataType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OnEntryScriptType createOnEntryScriptType() { OnEntryScriptTypeImpl onEntryScriptType = new OnEntryScriptTypeImpl(); return onEntryScriptType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OnExitScriptType createOnExitScriptType() { OnExitScriptTypeImpl onExitScriptType = new OnExitScriptTypeImpl(); return onExitScriptType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String createPackageNameTypeFromString(EDataType eDataType, String initialValue) { return (String)XMLTypeFactory.eINSTANCE.createFromString(XMLTypePackage.Literals.STRING, initialValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertPackageNameTypeToString(EDataType eDataType, Object instanceValue) { return XMLTypeFactory.eINSTANCE.convertToString(XMLTypePackage.Literals.STRING, instanceValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BigInteger createPriorityTypeFromString(EDataType eDataType, String initialValue) { return (BigInteger)XMLTypeFactory.eINSTANCE.createFromString(XMLTypePackage.Literals.INTEGER, initialValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertPriorityTypeToString(EDataType eDataType, Object instanceValue) { return XMLTypeFactory.eINSTANCE.convertToString(XMLTypePackage.Literals.INTEGER, instanceValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String createRuleFlowGroupTypeFromString(EDataType eDataType, String initialValue) { return (String)XMLTypeFactory.eINSTANCE.createFromString(XMLTypePackage.Literals.STRING, initialValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertRuleFlowGroupTypeToString(EDataType eDataType, Object instanceValue) { return XMLTypeFactory.eINSTANCE.convertToString(XMLTypePackage.Literals.STRING, instanceValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String createTaskNameTypeFromString(EDataType eDataType, String initialValue) { return (String)XMLTypeFactory.eINSTANCE.createFromString(XMLTypePackage.Literals.STRING, initialValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertTaskNameTypeToString(EDataType eDataType, Object instanceValue) { return XMLTypeFactory.eINSTANCE.convertToString(XMLTypePackage.Literals.STRING, instanceValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String createVersionTypeFromString(EDataType eDataType, String initialValue) { return (String)XMLTypeFactory.eINSTANCE.createFromString(XMLTypePackage.Literals.STRING, initialValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertVersionTypeToString(EDataType eDataType, Object instanceValue) { return XMLTypeFactory.eINSTANCE.convertToString(XMLTypePackage.Literals.STRING, instanceValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DroolsPackage getDroolsPackage() { return (DroolsPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static DroolsPackage getPackage() { return DroolsPackage.eINSTANCE; } } //DroolsFactoryImpl
/* 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.camunda.bpm.engine.rest.sub.runtime.impl; import com.fasterxml.jackson.databind.ObjectMapper; import org.camunda.bpm.engine.EntityTypes; import org.camunda.bpm.engine.FilterService; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.exception.NotValidException; import org.camunda.bpm.engine.exception.NullValueException; import org.camunda.bpm.engine.filter.Filter; import org.camunda.bpm.engine.impl.persistence.entity.VariableInstanceEntity; import org.camunda.bpm.engine.query.Query; import org.camunda.bpm.engine.rest.FilterRestService; import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; import org.camunda.bpm.engine.rest.dto.CountResultDto; import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; import org.camunda.bpm.engine.rest.dto.runtime.FilterDto; import org.camunda.bpm.engine.rest.dto.task.TaskDto; import org.camunda.bpm.engine.rest.dto.task.TaskQueryDto; import org.camunda.bpm.engine.rest.exception.InvalidRequestException; import org.camunda.bpm.engine.rest.hal.*; import org.camunda.bpm.engine.rest.hal.task.HalTask; import org.camunda.bpm.engine.rest.hal.task.HalTaskList; import org.camunda.bpm.engine.rest.impl.AbstractAuthorizedRestResource; import org.camunda.bpm.engine.rest.sub.runtime.FilterResource; import org.camunda.bpm.engine.runtime.VariableInstance; import org.camunda.bpm.engine.task.Task; import javax.ws.rs.HttpMethod; import javax.ws.rs.core.*; import javax.ws.rs.core.Response.Status; import java.io.IOException; import java.net.URI; import java.util.*; import java.util.regex.Pattern; import static org.camunda.bpm.engine.authorization.Permissions.*; import static org.camunda.bpm.engine.authorization.Resources.FILTER; /** * @author Sebastian Menski */ public class FilterResourceImpl extends AbstractAuthorizedRestResource implements FilterResource { public static final Pattern EMPTY_JSON_BODY = Pattern.compile("\\s*\\{\\s*\\}\\s*"); public static final String PROPERTIES_VARIABLES_KEY = "variables"; public static final String PROPERTIES_VARIABLES_NAME_KEY = "name"; public static final List<Variant> VARIANTS = Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE, Hal.APPLICATION_HAL_JSON_TYPE).add().build(); protected String relativeRootResourcePath; protected FilterService filterService; protected Filter dbFilter; public FilterResourceImpl(String processEngineName, ObjectMapper objectMapper, String filterId, String relativeRootResourcePath) { super(processEngineName, FILTER, filterId, objectMapper); this.relativeRootResourcePath = relativeRootResourcePath; filterService = processEngine.getFilterService(); } public FilterDto getFilter(Boolean itemCount) { Filter filter = getDbFilter(); FilterDto dto = FilterDto.fromFilter(filter); if (itemCount != null && itemCount) { dto.setItemCount(filterService.count(filter.getId())); } return dto; } protected Filter getDbFilter() { if (dbFilter == null) { dbFilter = filterService.getFilter(resourceId); if (dbFilter == null) { throw filterNotFound(null); } } return dbFilter; } public void deleteFilter() { try { filterService.deleteFilter(resourceId); } catch (NullValueException e) { throw filterNotFound(e); } } public void updateFilter(FilterDto filterDto) { Filter filter = getDbFilter(); try { filterDto.updateFilter(filter, processEngine); } catch (NotValidException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, "Unable to update filter with invalid content"); } filterService.saveFilter(filter); } public Object executeSingleResult(Request request) { Variant variant = request.selectVariant(VARIANTS); if (variant != null) { if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) { return executeJsonSingleResult(); } else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) { return executeHalSingleResult(); } } throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found"); } public Object executeJsonSingleResult() { return queryJsonSingleResult(null); } public Object querySingleResult(Request request, String extendingQuery) { Variant variant = request.selectVariant(VARIANTS); if (variant != null) { if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) { return queryJsonSingleResult(extendingQuery); } else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) { return queryHalSingleResult(extendingQuery); } } throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found"); } public Object queryJsonSingleResult(String extendingQuery) { Object entity = executeFilterSingleResult(extendingQuery); if (entity != null) { return convertToDto(entity); } else { return null; } } public HalResource executeHalSingleResult() { return queryHalSingleResult(null); } public HalResource queryHalSingleResult(String extendingQuery) { Object entity = executeFilterSingleResult(extendingQuery); if (entity != null) { return convertToHalResource(entity); } else { return EmptyHalResource.INSTANCE; } } protected Object executeFilterSingleResult(String extendingQuery) { try { return filterService.singleResult(resourceId, convertQuery(extendingQuery)); } catch (NullValueException e) { throw filterNotFound(e); } catch (NotValidException e) { throw invalidQuery(e); } catch (ProcessEngineException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, "Filter does not returns a valid single result"); } } public Object executeList(Request request, Integer firstResult, Integer maxResults) { Variant variant = request.selectVariant(VARIANTS); if (variant != null) { if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) { return executeJsonList(firstResult, maxResults); } else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) { return executeHalList(firstResult, maxResults); } } throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found"); } public List<Object> executeJsonList(Integer firstResult, Integer maxResults) { return queryJsonList(null, firstResult, maxResults); } public Object queryList(Request request, String extendingQuery, Integer firstResult, Integer maxResults) { Variant variant = request.selectVariant(VARIANTS); if (variant != null) { if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) { return queryJsonList(extendingQuery, firstResult ,maxResults); } else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) { return queryHalList(extendingQuery, firstResult, maxResults); } } throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found"); } public List<Object> queryJsonList(String extendingQuery, Integer firstResult, Integer maxResults) { List<?> entities = executeFilterList(extendingQuery, firstResult, maxResults); if (entities != null && !entities.isEmpty()) { return convertToDtoList(entities); } else { return Collections.emptyList(); } } public HalResource executeHalList(Integer firstResult, Integer maxResults) { return queryHalList(null, firstResult, maxResults); } public HalResource queryHalList(String extendingQuery, Integer firstResult, Integer maxResults) { List<?> entities = executeFilterList(extendingQuery, firstResult, maxResults); long count = executeFilterCount(extendingQuery); if (entities != null && !entities.isEmpty()) { return convertToHalCollection(entities, count); } else { return new EmptyHalCollection(count); } } protected List<?> executeFilterList(String extendingQueryString, Integer firstResult, Integer maxResults) { Query<?, ?> extendingQuery = convertQuery(extendingQueryString); try { if (firstResult != null || maxResults != null) { if (firstResult == null) { firstResult = 0; } if (maxResults == null) { maxResults = Integer.MAX_VALUE; } return filterService.listPage(resourceId, extendingQuery, firstResult, maxResults); } else { return filterService.list(resourceId, extendingQuery); } } catch (NullValueException e) { throw filterNotFound(e); } catch (NotValidException e) { throw invalidQuery(e); } } public CountResultDto executeCount() { return queryCount(null); } public CountResultDto queryCount(String extendingQuery) { return new CountResultDto(executeFilterCount(extendingQuery)); } protected long executeFilterCount(String extendingQuery) { try { return filterService.count(resourceId, convertQuery(extendingQuery)); } catch (NullValueException e) { throw filterNotFound(e); } catch (NotValidException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, "Filter cannot be extended by an invalid query"); } } public ResourceOptionsDto availableOperations(UriInfo context) { ResourceOptionsDto dto = new ResourceOptionsDto(); UriBuilder baseUriBuilder = context.getBaseUriBuilder() .path(relativeRootResourcePath) .path(FilterRestService.PATH) .path(resourceId); URI baseUri = baseUriBuilder.build(); if (isAuthorized(READ)) { dto.addReflexiveLink(baseUri, HttpMethod.GET, "self"); URI singleResultUri = baseUriBuilder.clone().path("/singleResult").build(); dto.addReflexiveLink(singleResultUri, HttpMethod.GET, "singleResult"); dto.addReflexiveLink(singleResultUri, HttpMethod.POST, "singleResult"); URI listUri = baseUriBuilder.clone().path("/list").build(); dto.addReflexiveLink(listUri, HttpMethod.GET, "list"); dto.addReflexiveLink(listUri, HttpMethod.POST, "list"); URI countUri = baseUriBuilder.clone().path("/count").build(); dto.addReflexiveLink(countUri, HttpMethod.GET, "count"); dto.addReflexiveLink(countUri, HttpMethod.POST, "count"); } if (isAuthorized(DELETE)) { dto.addReflexiveLink(baseUri, HttpMethod.DELETE, "delete"); } if (isAuthorized(UPDATE)) { dto.addReflexiveLink(baseUri, HttpMethod.PUT, "update"); } return dto; } protected Query convertQuery(String queryString) { if (isEmptyJson(queryString)) { return null; } else { String resourceType = getDbFilter().getResourceType(); AbstractQueryDto<?> queryDto = getQueryDtoForQuery(queryString, resourceType); queryDto.setObjectMapper(getObjectMapper()); if (queryDto != null) { return queryDto.toQuery(processEngine); } else { throw new InvalidRequestException(Status.BAD_REQUEST, "Unable to convert query for resource type '" + resourceType + "'."); } } } protected Object convertToDto(Object entity) { if (isEntityOfClass(entity, Task.class)) { return TaskDto.fromEntity((Task) entity); } else { throw unsupportedEntityClass(entity); } } protected List<Object> convertToDtoList(List<?> entities) { List<Object> dtoList = new ArrayList<Object>(); for (Object entity : entities) { dtoList.add(convertToDto(entity)); } return dtoList; } protected HalResource<?> convertToHalResource(Object entity) { if (isEntityOfClass(entity, Task.class)) { return convertToHalTask((Task) entity); } else { throw unsupportedEntityClass(entity); } } @SuppressWarnings("unchecked") protected HalTask convertToHalTask(Task task) { HalTask halTask = HalTask.generate(task, getProcessEngine()); Map<String, List<VariableInstance>> variableInstances = getVariableInstancesForTasks(halTask); if (variableInstances != null) { embedVariableValuesInHalTask(halTask, variableInstances); } return halTask; } @SuppressWarnings("unchecked") protected HalCollectionResource convertToHalCollection(List<?> entities, long count) { if (isEntityOfClass(entities.get(0), Task.class)) { return convertToHalTaskList((List<Task>) entities, count); } else { throw unsupportedEntityClass(entities.get(0)); } } @SuppressWarnings("unchecked") protected HalTaskList convertToHalTaskList(List<Task> tasks, long count) { HalTaskList halTasks = HalTaskList.generate(tasks, count, getProcessEngine()); Map<String, List<VariableInstance>> variableInstances = getVariableInstancesForTasks(halTasks); if (variableInstances != null) { for (HalTask halTask : (List<HalTask>) halTasks.getEmbedded("task")) { embedVariableValuesInHalTask(halTask, variableInstances); } } return halTasks; } protected void embedVariableValuesInHalTask( HalTask halTask, Map<String, List<VariableInstance>> variableInstances) { List<HalResource<?>> variableValues = getVariableValuesForTask(halTask, variableInstances); halTask.addEmbedded("variable", variableValues); } protected AbstractQueryDto<?> getQueryDtoForQuery(String queryString, String resourceType) { try { if (EntityTypes.TASK.equals(resourceType)) { return getObjectMapper().readValue(queryString, TaskQueryDto.class); } else { throw new InvalidRequestException(Status.BAD_REQUEST, "Queries for resource type '" + resourceType + "' are currently not supported by filters."); } } catch (IOException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, "Invalid query for resource type '" + resourceType + "'"); } } protected List<HalResource<?>> getVariableValuesForTask(HalTask halTask, Map<String, List<VariableInstance>> variableInstances) { // converted variables values List<HalResource<?>> variableValues = new ArrayList<HalResource<?>>(); // variable scope ids to check, ordered by visibility LinkedHashSet<String> variableScopeIds = getVariableScopeIds(halTask); // names of already converted variables Set<String> knownVariableNames = new HashSet<String>(); for (String variableScopeId : variableScopeIds) { if (variableInstances.containsKey(variableScopeId)) { for (VariableInstance variableInstance : variableInstances.get(variableScopeId)) { if (!knownVariableNames.contains(variableInstance.getName())) { variableValues.add(HalVariableValue.generateVariableValue(variableInstance, variableScopeId)); knownVariableNames.add(variableInstance.getName()); } } } } return variableValues; } @SuppressWarnings("unchecked") protected Map<String, List<VariableInstance>> getVariableInstancesForTasks(HalTaskList halTaskList) { List<HalTask> halTasks = (List<HalTask>) halTaskList.getEmbedded("task"); return getVariableInstancesForTasks(halTasks.toArray(new HalTask[halTasks.size()])); } protected Map<String, List<VariableInstance>> getVariableInstancesForTasks(HalTask... halTasks) { if (halTasks != null && halTasks.length > 0) { List<String> variableNames = getFilterVariableNames(); if (variableNames != null && !variableNames.isEmpty()) { LinkedHashSet<String> variableScopeIds = getVariableScopeIds(halTasks); return getSortedVariableInstances(variableNames, variableScopeIds); } } return null; } @SuppressWarnings("unchecked") protected List<String> getFilterVariableNames() { Map<String, Object> properties = getDbFilter().getProperties(); if (properties != null) { try { List<Map<String, Object>> variables = (List<Map<String, Object>>) properties.get(PROPERTIES_VARIABLES_KEY); return collectVariableNames(variables); } catch (Exception e) { throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, e, "Filter property '" + PROPERTIES_VARIABLES_KEY + "' has to be a list of variable definitions with a '" + PROPERTIES_VARIABLES_NAME_KEY + "' property"); } } else { return null; } } private List<String> collectVariableNames(List<Map<String, Object>> variables) { if (variables != null && !variables.isEmpty()) { List<String> variableNames = new ArrayList<String>(); for (Map<String, Object> variable : variables) { variableNames.add((String) variable.get(PROPERTIES_VARIABLES_NAME_KEY)); } return variableNames; } else { return null; } } protected LinkedHashSet<String> getVariableScopeIds(HalTask... halTasks) { // collect scope ids // the ordering is important because it specifies which variables are visible from a single task LinkedHashSet<String> variableScopeIds = new LinkedHashSet<String>(); if (halTasks != null && halTasks.length > 0) { for (HalTask halTask : halTasks) { variableScopeIds.add(halTask.getId()); variableScopeIds.add(halTask.getExecutionId()); variableScopeIds.add(halTask.getProcessInstanceId()); variableScopeIds.add(halTask.getCaseExecutionId()); variableScopeIds.add(halTask.getCaseInstanceId()); } } // remove null from set which was probably added due an unset id variableScopeIds.remove(null); return variableScopeIds; } protected Map<String, List<VariableInstance>> getSortedVariableInstances(Collection<String> variableNames, Collection<String> variableScopeIds) { List<VariableInstance> variableInstances = queryVariablesInstancesByVariableScopeIds(variableNames, variableScopeIds); Map<String, List<VariableInstance>> sortedVariableInstances = new HashMap<String, List<VariableInstance>>(); for (VariableInstance variableInstance : variableInstances) { String variableScopeId = ((VariableInstanceEntity) variableInstance).getVariableScope(); if (!sortedVariableInstances.containsKey(variableScopeId)) { sortedVariableInstances.put(variableScopeId, new ArrayList<VariableInstance>()); } sortedVariableInstances.get(variableScopeId).add(variableInstance); } return sortedVariableInstances; } protected List<VariableInstance> queryVariablesInstancesByVariableScopeIds(Collection<String> variableNames, Collection<String> variableScopeIds) { return getProcessEngine().getRuntimeService() .createVariableInstanceQuery() .disableBinaryFetching() .disableCustomObjectDeserialization() .variableNameIn(variableNames.toArray(new String[variableNames.size()])) .variableScopeIdIn(variableScopeIds.toArray(new String[variableScopeIds.size()])) .list(); } protected boolean isEntityOfClass(Object entity, Class<?> entityClass) { return entityClass.isAssignableFrom(entity.getClass()); } protected boolean isEmptyJson(String jsonString) { return jsonString == null || jsonString.trim().isEmpty() || EMPTY_JSON_BODY.matcher(jsonString).matches(); } protected InvalidRequestException filterNotFound(Exception cause) { return new InvalidRequestException(Status.NOT_FOUND, cause, "Filter with id '" + resourceId + "' does not exist."); } protected InvalidRequestException invalidQuery(Exception cause) { return new InvalidRequestException(Status.BAD_REQUEST, cause, "Filter cannot be extended by an invalid query"); } protected InvalidRequestException unsupportedEntityClass(Object entity) { return new InvalidRequestException(Status.BAD_REQUEST, "Entities of class '" + entity.getClass().getCanonicalName() + "' are currently not supported by filters."); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.locator; import java.io.IOException; import java.io.Serializable; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.regex.Pattern; import com.google.common.base.Preconditions; import com.google.common.net.HostAndPort; import org.apache.cassandra.io.IVersionedSerializer; import org.apache.cassandra.io.util.DataInputPlus; import org.apache.cassandra.io.util.DataOutputPlus; import org.apache.cassandra.net.MessagingService; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.FastByteOperations; /** * A class to replace the usage of InetAddress to identify hosts in the cluster. * Opting for a full replacement class so that in the future if we change the nature * of the identifier the refactor will be easier in that we don't have to change the type * just the methods. * * Because an IP might contain multiple C* instances the identification must be done * using the IP + port. InetSocketAddress is undesirable for a couple of reasons. It's not comparable, * it's toString() method doesn't correctly bracket IPv6, it doesn't handle optional default values, * and a couple of other minor behaviors that are slightly less troublesome like handling the * need to sometimes return a port and sometimes not. * */ @SuppressWarnings("UnstableApiUsage") public final class InetAddressAndPort implements Comparable<InetAddressAndPort>, Serializable { private static final long serialVersionUID = 0; //Store these here to avoid requiring DatabaseDescriptor to be loaded. DatabaseDescriptor will set //these when it loads the config. A lot of unit tests won't end up loading DatabaseDescriptor. //Tools that might use this class also might not load database descriptor. Those tools are expected //to always override the defaults. static volatile int defaultPort = 7000; public final InetAddress address; public final byte[] addressBytes; public final int port; private InetAddressAndPort(InetAddress address, byte[] addressBytes, int port) { Preconditions.checkNotNull(address); Preconditions.checkNotNull(addressBytes); validatePortRange(port); this.address = address; this.port = port; this.addressBytes = addressBytes; } public InetAddressAndPort withPort(int port) { return new InetAddressAndPort(address, addressBytes, port); } private static void validatePortRange(int port) { if (port < 0 | port > 65535) { throw new IllegalArgumentException("Port " + port + " is not a valid port number in the range 0-65535"); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InetAddressAndPort that = (InetAddressAndPort) o; if (port != that.port) return false; return address.equals(that.address); } @Override public int hashCode() { int result = address.hashCode(); result = 31 * result + port; return result; } @Override public int compareTo(InetAddressAndPort o) { int retval = FastByteOperations.compareUnsigned(addressBytes, 0, addressBytes.length, o.addressBytes, 0, o.addressBytes.length); if (retval != 0) { return retval; } return Integer.compare(port, o.port); } public String getHostAddressAndPort() { return getHostAddress(true); } private static final Pattern JMX_INCOMPATIBLE_CHARS = Pattern.compile("[\\[\\]:]"); /** * Return a version of getHostAddressAndPort suitable for use in JMX object names without * requiring any escaping. Replaces each character invalid for JMX names with an underscore. * * @return String with JMX-safe representation of the IP address and port */ public String getHostAddressAndPortForJMX() { return JMX_INCOMPATIBLE_CHARS.matcher(getHostAddressAndPort()).replaceAll("_"); } public String getHostAddress(boolean withPort) { if (withPort) { return HostAndPort.fromParts(address.getHostAddress(), port).toString(); } else { return address.getHostAddress(); } } @Override public String toString() { return toString(true); } public String toString(boolean withPort) { if (withPort) { return toString(address, port); } else { return address.toString(); } } /** Format an InetAddressAndPort in the same style as InetAddress.toString. * The string returned is of the form: hostname / literal IP address : port * (without the whitespace). Literal IPv6 addresses will be wrapped with [ ] * to make the port number clear. * * If the host name is unresolved, no reverse name service lookup * is performed. The hostname part will be represented by an empty string. * * @param address InetAddress to convert String * @param port Port number to convert to String * @return String representation of the IP address and port */ public static String toString(InetAddress address, int port) { String addressToString = address.toString(); // cannot use getHostName as it resolves int nameLength = addressToString.lastIndexOf('/'); // use last index to prevent ambiguity if host name contains / assert nameLength >= 0 : "InetAddress.toString format may have changed, expecting /"; // Check if need to wrap address with [ ] for IPv6 addresses if (addressToString.indexOf(':', nameLength) >= 0) { StringBuilder sb = new StringBuilder(addressToString.length() + 16); sb.append(addressToString, 0, nameLength + 1); // append optional host and / char sb.append('['); sb.append(addressToString, nameLength + 1, addressToString.length()); sb.append("]:"); sb.append(port); return sb.toString(); } else // can just append :port { StringBuilder sb = new StringBuilder(addressToString); // will have enough capacity for port sb.append(":"); sb.append(port); return sb.toString(); } } public static InetAddressAndPort getByName(String name) throws UnknownHostException { return getByNameOverrideDefaults(name, null); } /** * * @param name Hostname + optional ports string * @param port Port to connect on, overridden by values in hostname string, defaults to DatabaseDescriptor default if not specified anywhere. */ public static InetAddressAndPort getByNameOverrideDefaults(String name, Integer port) throws UnknownHostException { HostAndPort hap = HostAndPort.fromString(name); if (hap.hasPort()) { port = hap.getPort(); } return getByAddressOverrideDefaults(InetAddress.getByName(hap.getHost()), port); } public static InetAddressAndPort getByAddress(byte[] address) throws UnknownHostException { return getByAddressOverrideDefaults(InetAddress.getByAddress(address), address, null); } public static InetAddressAndPort getByAddress(InetAddress address) { return getByAddressOverrideDefaults(address, null); } public static InetAddressAndPort getByAddressOverrideDefaults(InetAddress address, Integer port) { if (port == null) { port = defaultPort; } return new InetAddressAndPort(address, address.getAddress(), port); } public static InetAddressAndPort getByAddressOverrideDefaults(InetAddress address, byte[] addressBytes, Integer port) { if (port == null) { port = defaultPort; } return new InetAddressAndPort(address, addressBytes, port); } public static InetAddressAndPort getLoopbackAddress() { return InetAddressAndPort.getByAddress(InetAddress.getLoopbackAddress()); } public static InetAddressAndPort getLocalHost() { return FBUtilities.getLocalAddressAndPort(); } public static void initializeDefaultPort(int port) { defaultPort = port; } static int getDefaultPort() { return defaultPort; } /** * As of version 4.0 the endpoint description includes a port number as an unsigned short * This serializer matches the 3.0 CompactEndpointSerializationHelper, encoding the number of address bytes * in a single byte before the address itself. */ public static final class Serializer implements IVersionedSerializer<InetAddressAndPort> { public static final int MAXIMUM_SIZE = 19; // We put the static instance here, to avoid complexity with dtests. // InetAddressAndPort is one of the only classes we share between instances, which is possible cleanly // because it has no type-dependencies in its public API, however Serializer requires DataOutputPlus, which requires... // and the chain becomes quite unwieldy public static final Serializer inetAddressAndPortSerializer = new Serializer(); private Serializer() {} public void serialize(InetAddressAndPort endpoint, DataOutputPlus out, int version) throws IOException { byte[] buf = endpoint.addressBytes; if (version >= MessagingService.VERSION_40) { out.writeByte(buf.length + 2); out.write(buf); out.writeShort(endpoint.port); } else { out.writeByte(buf.length); out.write(buf); } } public InetAddressAndPort deserialize(DataInputPlus in, int version) throws IOException { int size = in.readByte() & 0xFF; switch(size) { //The original pre-4.0 serialiation of just an address case 4: case 16: { byte[] bytes = new byte[size]; in.readFully(bytes, 0, bytes.length); return getByAddress(bytes); } //Address and one port case 6: case 18: { byte[] bytes = new byte[size - 2]; in.readFully(bytes); int port = in.readShort() & 0xFFFF; return getByAddressOverrideDefaults(InetAddress.getByAddress(bytes), bytes, port); } default: throw new AssertionError("Unexpected size " + size); } } /** * Extract {@link InetAddressAndPort} from the provided {@link ByteBuffer} without altering its state. */ public InetAddressAndPort extract(ByteBuffer buf, int position) throws IOException { int size = buf.get(position++) & 0xFF; if (size == 4 || size == 16) { byte[] bytes = new byte[size]; ByteBufferUtil.copyBytes(buf, position, bytes, 0, size); return getByAddress(bytes); } else if (size == 6 || size == 18) { byte[] bytes = new byte[size - 2]; ByteBufferUtil.copyBytes(buf, position, bytes, 0, size - 2); position += (size - 2); int port = buf.getShort(position) & 0xFFFF; return getByAddressOverrideDefaults(InetAddress.getByAddress(bytes), bytes, port); } throw new AssertionError("Unexpected pre-4.0 InetAddressAndPort size " + size); } public long serializedSize(InetAddressAndPort from, int version) { //4.0 includes a port number if (version >= MessagingService.VERSION_40) { if (from.address instanceof Inet4Address) return 1 + 4 + 2; assert from.address instanceof Inet6Address; return 1 + 16 + 2; } else { if (from.address instanceof Inet4Address) return 1 + 4; assert from.address instanceof Inet6Address; return 1 + 16; } } } /** Serializer for handling FWD_FRM message parameters. Pre-4.0 deserialization is a special * case in the message */ public static final class FwdFrmSerializer implements IVersionedSerializer<InetAddressAndPort> { public static final FwdFrmSerializer fwdFrmSerializer = new FwdFrmSerializer(); private FwdFrmSerializer() { } public void serialize(InetAddressAndPort endpoint, DataOutputPlus out, int version) throws IOException { byte[] buf = endpoint.addressBytes; if (version >= MessagingService.VERSION_40) { out.writeByte(buf.length + 2); out.write(buf); out.writeShort(endpoint.port); } else { out.write(buf); } } public long serializedSize(InetAddressAndPort from, int version) { //4.0 includes a port number if (version >= MessagingService.VERSION_40) { if (from.address instanceof Inet4Address) return 1 + 4 + 2; assert from.address instanceof Inet6Address; return 1 + 16 + 2; } else { if (from.address instanceof Inet4Address) return 4; assert from.address instanceof Inet6Address; return 16; } } @Override public InetAddressAndPort deserialize(DataInputPlus in, int version) throws IOException { if (version >= MessagingService.VERSION_40) { int size = in.readByte() & 0xFF; switch (size) { //Address and one port case 6: case 18: { byte[] bytes = new byte[size - 2]; in.readFully(bytes); int port = in.readShort() & 0xFFFF; return getByAddressOverrideDefaults(InetAddress.getByAddress(bytes), bytes, port); } default: throw new AssertionError("Unexpected size " + size); } } else { throw new IllegalStateException("FWD_FRM deserializations should be special-cased pre-4.0"); } } public InetAddressAndPort pre40DeserializeWithLength(DataInputPlus in, int version, int length) throws IOException { assert length == 4 || length == 16 : "unexpected length " + length; byte[] from = new byte[length]; in.readFully(from, 0, length); return InetAddressAndPort.getByAddress(from); } } }
/* * 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.apigateway.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * <p> * Import documentation parts from an external (e.g., OpenAPI) definition file. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ImportDocumentationPartsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * [Required] The string identifier of the associated <a>RestApi</a>. * </p> */ private String restApiId; /** * <p> * A query parameter to indicate whether to overwrite (<code>OVERWRITE</code>) any existing * <a>DocumentationParts</a> definition or to merge (<code>MERGE</code>) the new definition into the existing one. * The default value is <code>MERGE</code>. * </p> */ private String mode; /** * <p> * A query parameter to specify whether to rollback the documentation importation (<code>true</code>) or not ( * <code>false</code>) when a warning is encountered. The default value is <code>false</code>. * </p> */ private Boolean failOnWarnings; /** * <p> * [Required] Raw byte array representing the to-be-imported documentation parts. To import from an OpenAPI file, * this is a JSON object. * </p> */ private java.nio.ByteBuffer body; /** * <p> * [Required] The string identifier of the associated <a>RestApi</a>. * </p> * * @param restApiId * [Required] The string identifier of the associated <a>RestApi</a>. */ public void setRestApiId(String restApiId) { this.restApiId = restApiId; } /** * <p> * [Required] The string identifier of the associated <a>RestApi</a>. * </p> * * @return [Required] The string identifier of the associated <a>RestApi</a>. */ public String getRestApiId() { return this.restApiId; } /** * <p> * [Required] The string identifier of the associated <a>RestApi</a>. * </p> * * @param restApiId * [Required] The string identifier of the associated <a>RestApi</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public ImportDocumentationPartsRequest withRestApiId(String restApiId) { setRestApiId(restApiId); return this; } /** * <p> * A query parameter to indicate whether to overwrite (<code>OVERWRITE</code>) any existing * <a>DocumentationParts</a> definition or to merge (<code>MERGE</code>) the new definition into the existing one. * The default value is <code>MERGE</code>. * </p> * * @param mode * A query parameter to indicate whether to overwrite (<code>OVERWRITE</code>) any existing * <a>DocumentationParts</a> definition or to merge (<code>MERGE</code>) the new definition into the existing * one. The default value is <code>MERGE</code>. * @see PutMode */ public void setMode(String mode) { this.mode = mode; } /** * <p> * A query parameter to indicate whether to overwrite (<code>OVERWRITE</code>) any existing * <a>DocumentationParts</a> definition or to merge (<code>MERGE</code>) the new definition into the existing one. * The default value is <code>MERGE</code>. * </p> * * @return A query parameter to indicate whether to overwrite (<code>OVERWRITE</code>) any existing * <a>DocumentationParts</a> definition or to merge (<code>MERGE</code>) the new definition into the * existing one. The default value is <code>MERGE</code>. * @see PutMode */ public String getMode() { return this.mode; } /** * <p> * A query parameter to indicate whether to overwrite (<code>OVERWRITE</code>) any existing * <a>DocumentationParts</a> definition or to merge (<code>MERGE</code>) the new definition into the existing one. * The default value is <code>MERGE</code>. * </p> * * @param mode * A query parameter to indicate whether to overwrite (<code>OVERWRITE</code>) any existing * <a>DocumentationParts</a> definition or to merge (<code>MERGE</code>) the new definition into the existing * one. The default value is <code>MERGE</code>. * @return Returns a reference to this object so that method calls can be chained together. * @see PutMode */ public ImportDocumentationPartsRequest withMode(String mode) { setMode(mode); return this; } /** * <p> * A query parameter to indicate whether to overwrite (<code>OVERWRITE</code>) any existing * <a>DocumentationParts</a> definition or to merge (<code>MERGE</code>) the new definition into the existing one. * The default value is <code>MERGE</code>. * </p> * * @param mode * A query parameter to indicate whether to overwrite (<code>OVERWRITE</code>) any existing * <a>DocumentationParts</a> definition or to merge (<code>MERGE</code>) the new definition into the existing * one. The default value is <code>MERGE</code>. * @see PutMode */ public void setMode(PutMode mode) { withMode(mode); } /** * <p> * A query parameter to indicate whether to overwrite (<code>OVERWRITE</code>) any existing * <a>DocumentationParts</a> definition or to merge (<code>MERGE</code>) the new definition into the existing one. * The default value is <code>MERGE</code>. * </p> * * @param mode * A query parameter to indicate whether to overwrite (<code>OVERWRITE</code>) any existing * <a>DocumentationParts</a> definition or to merge (<code>MERGE</code>) the new definition into the existing * one. The default value is <code>MERGE</code>. * @return Returns a reference to this object so that method calls can be chained together. * @see PutMode */ public ImportDocumentationPartsRequest withMode(PutMode mode) { this.mode = mode.toString(); return this; } /** * <p> * A query parameter to specify whether to rollback the documentation importation (<code>true</code>) or not ( * <code>false</code>) when a warning is encountered. The default value is <code>false</code>. * </p> * * @param failOnWarnings * A query parameter to specify whether to rollback the documentation importation (<code>true</code>) or not * (<code>false</code>) when a warning is encountered. The default value is <code>false</code>. */ public void setFailOnWarnings(Boolean failOnWarnings) { this.failOnWarnings = failOnWarnings; } /** * <p> * A query parameter to specify whether to rollback the documentation importation (<code>true</code>) or not ( * <code>false</code>) when a warning is encountered. The default value is <code>false</code>. * </p> * * @return A query parameter to specify whether to rollback the documentation importation (<code>true</code>) or not * (<code>false</code>) when a warning is encountered. The default value is <code>false</code>. */ public Boolean getFailOnWarnings() { return this.failOnWarnings; } /** * <p> * A query parameter to specify whether to rollback the documentation importation (<code>true</code>) or not ( * <code>false</code>) when a warning is encountered. The default value is <code>false</code>. * </p> * * @param failOnWarnings * A query parameter to specify whether to rollback the documentation importation (<code>true</code>) or not * (<code>false</code>) when a warning is encountered. The default value is <code>false</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public ImportDocumentationPartsRequest withFailOnWarnings(Boolean failOnWarnings) { setFailOnWarnings(failOnWarnings); return this; } /** * <p> * A query parameter to specify whether to rollback the documentation importation (<code>true</code>) or not ( * <code>false</code>) when a warning is encountered. The default value is <code>false</code>. * </p> * * @return A query parameter to specify whether to rollback the documentation importation (<code>true</code>) or not * (<code>false</code>) when a warning is encountered. The default value is <code>false</code>. */ public Boolean isFailOnWarnings() { return this.failOnWarnings; } /** * <p> * [Required] Raw byte array representing the to-be-imported documentation parts. To import from an OpenAPI file, * this is a JSON object. * </p> * <p> * The AWS SDK for Java performs a Base64 encoding on this field before sending this request to the AWS service. * Users of the SDK should not perform Base64 encoding on this field. * </p> * <p> * Warning: ByteBuffers returned by the SDK are mutable. Changes to the content or position of the byte buffer will * be seen by all objects that have a reference to this object. It is recommended to call ByteBuffer.duplicate() or * ByteBuffer.asReadOnlyBuffer() before using or reading from the buffer. This behavior will be changed in a future * major version of the SDK. * </p> * * @param body * [Required] Raw byte array representing the to-be-imported documentation parts. To import from an OpenAPI * file, this is a JSON object. */ public void setBody(java.nio.ByteBuffer body) { this.body = body; } /** * <p> * [Required] Raw byte array representing the to-be-imported documentation parts. To import from an OpenAPI file, * this is a JSON object. * </p> * <p> * {@code ByteBuffer}s are stateful. Calling their {@code get} methods changes their {@code position}. We recommend * using {@link java.nio.ByteBuffer#asReadOnlyBuffer()} to create a read-only view of the buffer with an independent * {@code position}, and calling {@code get} methods on this rather than directly on the returned {@code ByteBuffer}. * Doing so will ensure that anyone else using the {@code ByteBuffer} will not be affected by changes to the * {@code position}. * </p> * * @return [Required] Raw byte array representing the to-be-imported documentation parts. To import from an OpenAPI * file, this is a JSON object. */ public java.nio.ByteBuffer getBody() { return this.body; } /** * <p> * [Required] Raw byte array representing the to-be-imported documentation parts. To import from an OpenAPI file, * this is a JSON object. * </p> * <p> * The AWS SDK for Java performs a Base64 encoding on this field before sending this request to the AWS service. * Users of the SDK should not perform Base64 encoding on this field. * </p> * <p> * Warning: ByteBuffers returned by the SDK are mutable. Changes to the content or position of the byte buffer will * be seen by all objects that have a reference to this object. It is recommended to call ByteBuffer.duplicate() or * ByteBuffer.asReadOnlyBuffer() before using or reading from the buffer. This behavior will be changed in a future * major version of the SDK. * </p> * * @param body * [Required] Raw byte array representing the to-be-imported documentation parts. To import from an OpenAPI * file, this is a JSON object. * @return Returns a reference to this object so that method calls can be chained together. */ public ImportDocumentationPartsRequest withBody(java.nio.ByteBuffer body) { setBody(body); 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 (getRestApiId() != null) sb.append("RestApiId: ").append(getRestApiId()).append(","); if (getMode() != null) sb.append("Mode: ").append(getMode()).append(","); if (getFailOnWarnings() != null) sb.append("FailOnWarnings: ").append(getFailOnWarnings()).append(","); if (getBody() != null) sb.append("Body: ").append(getBody()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ImportDocumentationPartsRequest == false) return false; ImportDocumentationPartsRequest other = (ImportDocumentationPartsRequest) obj; if (other.getRestApiId() == null ^ this.getRestApiId() == null) return false; if (other.getRestApiId() != null && other.getRestApiId().equals(this.getRestApiId()) == false) return false; if (other.getMode() == null ^ this.getMode() == null) return false; if (other.getMode() != null && other.getMode().equals(this.getMode()) == false) return false; if (other.getFailOnWarnings() == null ^ this.getFailOnWarnings() == null) return false; if (other.getFailOnWarnings() != null && other.getFailOnWarnings().equals(this.getFailOnWarnings()) == false) return false; if (other.getBody() == null ^ this.getBody() == null) return false; if (other.getBody() != null && other.getBody().equals(this.getBody()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getRestApiId() == null) ? 0 : getRestApiId().hashCode()); hashCode = prime * hashCode + ((getMode() == null) ? 0 : getMode().hashCode()); hashCode = prime * hashCode + ((getFailOnWarnings() == null) ? 0 : getFailOnWarnings().hashCode()); hashCode = prime * hashCode + ((getBody() == null) ? 0 : getBody().hashCode()); return hashCode; } @Override public ImportDocumentationPartsRequest clone() { return (ImportDocumentationPartsRequest) super.clone(); } }
/* * Copyright 2011 Google 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.google.ipc.invalidation.ticl.android; import com.google.ipc.invalidation.common.DigestFunction; import com.google.ipc.invalidation.common.ObjectIdDigestUtils; import com.google.ipc.invalidation.external.client.SystemResources.Logger; import com.google.ipc.invalidation.external.client.android.AndroidInvalidationClient; import com.google.ipc.invalidation.external.client.android.service.AndroidLogger; import com.google.ipc.invalidation.external.client.android.service.Request; import com.google.ipc.invalidation.external.client.android.service.Response; import com.google.ipc.invalidation.external.client.android.service.Response.Status; import com.google.ipc.invalidation.external.client.contrib.MultiplexingGcmListener; import com.google.ipc.invalidation.external.client.types.AckHandle; import com.google.ipc.invalidation.external.client.types.ObjectId; import com.google.ipc.invalidation.ticl.InvalidationClientCore; import com.google.ipc.invalidation.ticl.PersistenceUtils; import com.google.ipc.invalidation.util.TypedUtil; import com.google.protos.ipc.invalidation.Client.PersistentTiclState; import android.accounts.Account; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.util.Base64; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; /** * The AndroidInvalidationService class provides an Android service implementation that bridges * between the {@code InvalidationService} interface and invalidation client service instances * executing within the scope of that service. The invalidation service will have an associated * {@link AndroidClientManager} that is managing the set of active (in memory) clients associated * with the service. It processes requests from invalidation applications (as invocations on * the {@code InvalidationService} bound service interface along with GCM registration and * activity (from {@link ReceiverService}). * */ public class AndroidInvalidationService extends AbstractInvalidationService { /** * Service that handles system GCM messages (with support from the base class). It receives * intents for GCM registration, errors and message delivery. It does some basic processing and * then forwards the messages to the {@link AndroidInvalidationService} for handling. */ public static class ReceiverService extends MultiplexingGcmListener.AbstractListener { /** * Receiver for broadcasts by the multiplexed GCM service. It forwards them to * AndroidMessageReceiverService. */ public static class Receiver extends MultiplexingGcmListener.AbstractListener.Receiver { /* This class is public so that it can be instantiated by the Android runtime. */ @Override protected Class<?> getServiceClass() { return ReceiverService.class; } } public ReceiverService() { super("MsgRcvrSvc"); } @Override public void onRegistered(String registrationId) { logger.info("GCM Registration received: %s", registrationId); // Upon receiving a new updated GCM ID, notify the invalidation service Intent serviceIntent = AndroidInvalidationService.createRegistrationIntent(this, registrationId); startService(serviceIntent); } @Override public void onUnregistered(String registrationId) { logger.info("GCM unregistered"); } @Override protected void onMessage(Intent intent) { // Extract expected fields and do basic syntactic checks (but no value checking) // and forward the result on to the AndroidInvalidationService for processing. Intent serviceIntent; String clientKey = intent.getStringExtra(AndroidC2DMConstants.CLIENT_KEY_PARAM); if (clientKey == null) { logger.severe("GCM Intent does not contain client key value: %s", intent); return; } String encodedData = intent.getStringExtra(AndroidC2DMConstants.CONTENT_PARAM); String echoToken = intent.getStringExtra(AndroidC2DMConstants.ECHO_PARAM); if (encodedData != null) { try { byte [] rawData = Base64.decode(encodedData, Base64.URL_SAFE); serviceIntent = AndroidInvalidationService.createDataIntent(this, clientKey, echoToken, rawData); } catch (IllegalArgumentException exception) { logger.severe("Unable to decode intent data", exception); return; } } else { logger.severe("Received mailbox intent: %s", intent); return; } startService(serviceIntent); } @Override protected void onDeletedMessages(int total) { // This method must be implemented if we start using non-collapsable messages with GCM. For // now, there is nothing to do. } } /** The last created instance, for testing. */ static AtomicReference<AndroidInvalidationService> lastInstanceForTest = new AtomicReference<AndroidInvalidationService>(); /** For tests only, the number of C2DM errors received. */ static final AtomicInteger numGcmErrorsForTest = new AtomicInteger(0); /** For tests only, the number of C2DM registration messages received. */ static final AtomicInteger numGcmRegistrationForTest = new AtomicInteger(0); /** For tests only, the number of C2DM messages received. */ static final AtomicInteger numGcmMessagesForTest = new AtomicInteger(0); /** For tests only, the number of onCreate calls made. */ static final AtomicInteger numCreateForTest = new AtomicInteger(0); /** The client manager tracking in-memory client instances */ protected static AndroidClientManager clientManager; private static final Logger logger = AndroidLogger.forTag("InvService"); /** The HTTP URL of the channel service. */ private static String channelUrl = AndroidHttpConstants.CHANNEL_URL; // The AndroidInvalidationService handles a set of internal intents that are used for // communication and coordination between the it and the GCM handling service. These // are documented here with action and extra names documented with package private // visibility since they are not intended for use by external components. /** * Sent when a new GCM registration activity occurs for the service. This can occur the first * time the service is run or at any subsequent time if the Android C2DM service decides to issue * a new GCM registration ID. */ static final String REGISTRATION_ACTION = "register"; /** * The name of the String extra that contains the registration ID for a register intent. If this * extra is not present, then it indicates that a C2DM notification regarding unregistration has * been received (not expected during normal operation conditions). */ static final String REGISTER_ID = "id"; /** * This intent is sent when a GCM message targeting the service is received. */ static final String MESSAGE_ACTION = "message"; /** * The name of the String extra that contains the client key for the GCM message. */ static final String MESSAGE_CLIENT_KEY = "clientKey"; /** * The name of the byte array extra that contains the encoded event for the GCM message. */ static final String MESSAGE_DATA = "data"; /** The name of the string extra that contains the echo token in the GCM message. */ static final String MESSAGE_ECHO = "echo-token"; /** * This intent is sent when GCM registration has failed irrevocably. */ static final String ERROR_ACTION = "error"; /** * The name of the String extra that contains the error message describing the registration * failure. */ static final String ERROR_MESSAGE = "message"; /** Returns the client manager for this service */ static AndroidClientManager getClientManager() { return clientManager; } /** * Creates a new registration intent that notifies the service of a registration ID change */ static Intent createRegistrationIntent(Context context, String registrationId) { Intent intent = new Intent(REGISTRATION_ACTION); intent.setClass(context, AndroidInvalidationService.class); if (registrationId != null) { intent.putExtra(AndroidInvalidationService.REGISTER_ID, registrationId); } return intent; } /** * Creates a new message intent to contains event data to deliver directly to a client. */ static Intent createDataIntent(Context context, String clientKey, String token, byte [] data) { Intent intent = new Intent(MESSAGE_ACTION); intent.setClass(context, AndroidInvalidationService.class); intent.putExtra(MESSAGE_CLIENT_KEY, clientKey); intent.putExtra(MESSAGE_DATA, data); if (token != null) { intent.putExtra(MESSAGE_ECHO, token); } return intent; } /** * Creates a new message intent that references event data to retrieve from a mailbox. */ static Intent createMailboxIntent(Context context, String clientKey, String token) { Intent intent = new Intent(MESSAGE_ACTION); intent.setClass(context, AndroidInvalidationService.class); intent.putExtra(MESSAGE_CLIENT_KEY, clientKey); if (token != null) { intent.putExtra(MESSAGE_ECHO, token); } return intent; } /** * Creates a new error intent that notifies the service of a registration failure. */ static Intent createErrorIntent(Context context, String errorId) { Intent intent = new Intent(ERROR_ACTION); intent.setClass(context, AndroidInvalidationService.class); intent.putExtra(ERROR_MESSAGE, errorId); return intent; } /** * Overrides the channel URL set in package metadata to enable dynamic port assignment and * configuration during testing. */ static void setChannelUrlForTest(String url) { channelUrl = url; } /** * Resets the state of the service to destroy any existing clients */ static void reset() { if (clientManager != null) { clientManager.releaseAll(); } } /** The function for computing persistence state digests when rewriting them. */ private final DigestFunction digestFn = new ObjectIdDigestUtils.Sha1DigestFunction(); public AndroidInvalidationService() { lastInstanceForTest.set(this); } @Override public void onCreate() { synchronized (lock) { super.onCreate(); // Create the client manager if (clientManager == null) { clientManager = new AndroidClientManager(this); } numCreateForTest.incrementAndGet(); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { // Process GCM related messages from the ReceiverService. We do not check isCreated here because // this is part of the stop/start lifecycle, not bind/unbind. synchronized (lock) { logger.fine("Received action = %s", intent.getAction()); if (MESSAGE_ACTION.equals(intent.getAction())) { handleMessage(intent); } else if (REGISTRATION_ACTION.equals(intent.getAction())) { handleRegistration(intent); } else if (ERROR_ACTION.equals(intent.getAction())) { handleError(intent); } final int retval = super.onStartCommand(intent, flags, startId); // Unless we are explicitly being asked to start, stop ourselves. Request.SERVICE_INTENT // is the intent used by InvalidationBinder to bind the service, and // AndroidInvalidationClientImpl uses the intent returned by InvalidationBinder.getIntent // as the argument to its startService call. if (!Request.SERVICE_INTENT.getAction().equals(intent.getAction())) { stopServiceIfNoClientsRemain(intent.getAction()); } return retval; } } @Override public void onDestroy() { synchronized (lock) { reset(); super.onDestroy(); } } @Override public IBinder onBind(Intent intent) { return super.onBind(intent); } @Override public boolean onUnbind(Intent intent) { synchronized (lock) { logger.fine("onUnbind"); super.onUnbind(intent); if ((clientManager != null) && (clientManager.getClientCount() > 0)) { // This isn't wrong, per se, but it's potentially unusual. logger.info(" clients still active in onUnbind"); } stopServiceIfNoClientsRemain("onUnbind"); // We don't care about the onRebind event, which is what the documentation says a "true" // return here will get us, but if we return false then we don't get a second onUnbind() event // in a bind/unbind/bind/unbind cycle, which we require. return true; } } // The following protected methods are called holding "lock" by AbstractInvalidationService. @Override protected void create(Request request, Response.Builder response) { String clientKey = request.getClientKey(); int clientType = request.getClientType(); Account account = request.getAccount(); String authType = request.getAuthType(); Intent eventIntent = request.getIntent(); clientManager.create(clientKey, clientType, account, authType, eventIntent); response.setStatus(Status.SUCCESS); } @Override protected void resume(Request request, Response.Builder response) { String clientKey = request.getClientKey(); AndroidClientProxy client = clientManager.get(clientKey); if (setResponseStatus(client, request, response)) { response.setAccount(client.getAccount()); response.setAuthType(client.getAuthType()); } } @Override protected void start(Request request, Response.Builder response) { String clientKey = request.getClientKey(); AndroidInvalidationClient client = clientManager.get(clientKey); if (setResponseStatus(client, request, response)) { client.start(); } } @Override protected void stop(Request request, Response.Builder response) { String clientKey = request.getClientKey(); AndroidInvalidationClient client = clientManager.get(clientKey); if (setResponseStatus(client, request, response)) { client.stop(); } } @Override protected void register(Request request, Response.Builder response) { String clientKey = request.getClientKey(); AndroidInvalidationClient client = clientManager.get(clientKey); if (setResponseStatus(client, request, response)) { ObjectId objectId = request.getObjectId(); client.register(objectId); } } @Override protected void unregister(Request request, Response.Builder response) { String clientKey = request.getClientKey(); AndroidInvalidationClient client = clientManager.get(clientKey); if (setResponseStatus(client, request, response)) { ObjectId objectId = request.getObjectId(); client.unregister(objectId); } } @Override protected void acknowledge(Request request, Response.Builder response) { String clientKey = request.getClientKey(); AckHandle ackHandle = request.getAckHandle(); AndroidInvalidationClient client = clientManager.get(clientKey); if (setResponseStatus(client, request, response)) { client.acknowledge(ackHandle); } } @Override protected void destroy(Request request, Response.Builder response) { String clientKey = request.getClientKey(); AndroidInvalidationClient client = clientManager.get(clientKey); if (setResponseStatus(client, request, response)) { client.destroy(); } } /** * If {@code client} is {@code null}, sets the {@code response} status to an error. Otherwise, * sets the status to {@code success}. * @return whether {@code client} was non-{@code null}. * */ private boolean setResponseStatus(AndroidInvalidationClient client, Request request, Response.Builder response) { if (client == null) { response.setError("Client does not exist: " + request); response.setStatus(Status.INVALID_CLIENT); return false; } else { response.setStatus(Status.SUCCESS); return true; } } /** Returns the base URL used to send messages to the outbound network channel */ String getChannelUrl() { synchronized (lock) { return channelUrl; } } private void handleMessage(Intent intent) { numGcmMessagesForTest.incrementAndGet(); String clientKey = intent.getStringExtra(MESSAGE_CLIENT_KEY); AndroidClientProxy proxy = clientManager.get(clientKey); // Client is unknown or unstarted; we can't deliver the message, but we need to // remember that we dropped it if the client is known. if ((proxy == null) || !proxy.isStarted()) { logger.warning("Dropping GCM message for unknown or unstarted client: %s", clientKey); handleGcmMessageForUnstartedClient(proxy); return; } // We can deliver the message. Pass the new echo token to the channel. String echoToken = intent.getStringExtra(MESSAGE_ECHO); logger.fine("Update %s with new echo token: %s", clientKey, echoToken); proxy.getChannel().updateEchoToken(echoToken); byte [] message = intent.getByteArrayExtra(MESSAGE_DATA); if (message != null) { logger.fine("Deliver to %s message %s", clientKey, message); proxy.getChannel().receiveMessage(message); } else { logger.severe("Got mailbox intent: %s", intent); } } /** * Handles receipt of a GCM message for a client that was unknown or not started. If the client * was unknown, drops the message. If the client was not started, rewrites the client's * persistent state to have a last-message-sent-time of 0, ensuring that the client will * send a heartbeat to the server when restarted. Since we drop the received GCM message, * the client will be disconnected by the invalidation pusher; this heartbeat ensures a * timely reconnection. */ private void handleGcmMessageForUnstartedClient(AndroidClientProxy proxy) { if (proxy == null) { // Unknown client; nothing to do. return; } // Client is not started. Open its storage. We are going to use unsafe calls here that // bypass the normal storage API. This is safe in this context because we hold a lock // that prevents anyone else from starting this client or accessing its storage. We // really should not be holding a lock across I/O, but at least this is only local // file I/O, and we're only writing a few bytes. Additionally, since we currently only // have one Ticl, we should only ever enter this function if we're not being used for // anything else. final String clientKey = proxy.getClientKey(); logger.info("Received message for unloaded client; rewriting state file: %s", clientKey); // This storage must have been loaded, because we got this proxy from the client manager, // which always ensures that its entries have that property. AndroidStorage storageForClient = proxy.getStorage(); PersistentTiclState clientState = decodeTiclState(clientKey, storageForClient); if (clientState == null) { // Logging done in decodeTiclState. return; } // Rewrite the last message sent time. PersistentTiclState newState = PersistentTiclState.newBuilder(clientState) .setLastMessageSendTimeMs(0).build(); // Serialize the new state. byte[] newClientState = PersistenceUtils.serializeState(newState, digestFn); // Write it out. storageForClient.getPropertiesUnsafe().put(InvalidationClientCore.CLIENT_TOKEN_KEY, newClientState); storageForClient.storeUnsafe(); } private void handleRegistration(Intent intent) { // Notify the client manager of the updated registration ID String id = intent.getStringExtra(REGISTER_ID); clientManager.informRegistrationIdChanged(); numGcmRegistrationForTest.incrementAndGet(); } private void handleError(Intent intent) { logger.severe("Unable to perform GCM registration: %s", intent.getStringExtra(ERROR_MESSAGE)); numGcmErrorsForTest.incrementAndGet(); } /** * Stops the service if there are no clients in the client manager. * @param debugInfo short string describing why the check was made */ private void stopServiceIfNoClientsRemain(String debugInfo) { if ((clientManager == null) || clientManager.areAllClientsStopped()) { logger.info("Stopping AndroidInvalidationService since no clients remain: %s", debugInfo); stopSelf(); } else { logger.fine("Not stopping service since %s clients remain (%s)", clientManager.getClientCount(), debugInfo); } } /** * Returns the persisted state for the client with key {@code clientKey} in * {@code storageForClient}, or {@code null} if no valid state could be found. * <p> * REQUIRES: {@code storageForClient}.load() has been called successfully. */ PersistentTiclState decodeTiclState(final String clientKey, AndroidStorage storageForClient) { synchronized (lock) { // Retrieve the serialized state. final Map<String, byte[]> properties = storageForClient.getPropertiesUnsafe(); byte[] clientStateBytes = TypedUtil.mapGet(properties, InvalidationClientCore.CLIENT_TOKEN_KEY); if (clientStateBytes == null) { logger.warning("No client state found in storage for %s: %s", clientKey, properties.keySet()); return null; } // Deserialize it. PersistentTiclState clientState = PersistenceUtils.deserializeState(logger, clientStateBytes, digestFn); if (clientState == null) { logger.warning("Invalid client state found in storage for %s", clientKey); return null; } return clientState; } } /** * Returns whether the client with {@code clientKey} is loaded in the client manager. */ public static boolean isLoadedForTest(String clientKey) { return (getClientManager() != null) && getClientManager().isLoadedForTest(clientKey); } }
import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import bwapi.Color; import bwapi.DefaultBWListener; import bwapi.Game; import bwapi.Mirror; import bwapi.Player; import bwapi.Position; import bwapi.Unit; import bwapi.UnitType; import bwta.BWTA; import bwta.BaseLocation; public class TestBot1 extends DefaultBWListener { private Mirror mirror = new Mirror(); private Game game; private Player self; private Player enemy; private List<GameEntity> services; private List<UnitEntity> units; private EconomyService economyService; private BaseBuildingService baseBuildingService; private MacroService macroService; private ArmyControlService armyControlService; private ScoutingService scoutingService; private ResearchService researchService; private CounterService counterService; private SixPoolDefenseService sixPoolDefenseService; private List<UnitEntity> buildingsWithoutWorkers = Collections.synchronizedList(new ArrayList<UnitEntity>()); private SupplyService supplyService; private BaseService baseService; public void run() { units = new ArrayList<>(); services = new ArrayList<>(); // register all the service economyService = new EconomyService(); baseService = new BaseService(economyService); supplyService = new SupplyService(economyService, baseService); baseBuildingService = new BaseBuildingService(economyService, baseService); macroService = new MacroService(economyService); armyControlService = new ArmyControlService(baseService, economyService); scoutingService = new ScoutingService(baseService, armyControlService); researchService = new ResearchService(economyService); sixPoolDefenseService = new SixPoolDefenseService(); counterService = new CounterService(macroService, sixPoolDefenseService, baseBuildingService); services.add(economyService); services.add(supplyService); services.add(baseService); services.add(baseBuildingService); services.add(macroService); services.add(armyControlService); services.add(scoutingService); services.add(counterService); services.add(sixPoolDefenseService); services.add(researchService); mirror.getModule().setEventListener(this); mirror.startGame(); } @Override public void onUnitCreate(Unit unit) { // System.out.println("Created:" + unit.getType()); if (unit.getPlayer() != self) return; UnitEntity unitEntity = null; if (unit.getType() == UnitType.Terran_SCV) { unitEntity = new Builder(unit, economyService); } else if (unit.getType() == UnitType.Terran_Marine) { unitEntity = new Marine(unit); } else if (unit.getType() == UnitType.Terran_Medic) { unitEntity = new Medic(unit); } else if (unit.getType() == UnitType.Terran_Firebat) { unitEntity = new Firebat(unit); } else if (unit.getType() == UnitType.Terran_Science_Vessel) { unitEntity = new ScienceVessel(unit); } else if (unit.getType() == UnitType.Terran_Goliath) { unitEntity = new Goliath(unit); } else if (unit.getType() == UnitType.Terran_Siege_Tank_Tank_Mode) { unitEntity = new SiegeTank(unit); } else { unitEntity = new BaseUnitEntity(unit); } if (unitEntity.getUnit().getType().isBuilding() && !unitEntity.getUnit().isCompleted() && unitEntity.getUnit().getBuildUnit() == null) { buildingsWithoutWorkers.add(unitEntity); System.out.println("CORE: found building without build unit addin to queue, size: " + buildingsWithoutWorkers.size()); } else { doOnCreateEntity(unitEntity); } } /** * Addsunit entity into units and calls all on create handlers * * @param unitEntity */ private void doOnCreateEntity(UnitEntity unitEntity) { if (unitEntity != null) { units.add(unitEntity); for (GameEntity entity : services) { entity.onEntityCreate(unitEntity); } for (GameEntity entity : units) { entity.onEntityCreate(unitEntity); } } } @Override public void onStart() { game = mirror.getGame(); self = game.self(); enemy = game.enemy(); game.enableFlag(1); game.setLocalSpeed(0); // Use BWTA to analyze map // This may take a few minutes if the map is processed first time! System.out.println("Analyzing map..."); BWTA.readMap(); BWTA.analyze(); System.out.println("Map data ready"); int i = 0; for (BaseLocation baseLocation : BWTA.getBaseLocations()) { System.out.println("Base location #" + (++i) + ". Printing location's region polygon:"); for (Position position : baseLocation.getRegion().getPolygon().getPoints()) { System.out.print(position + ", "); } } for (Unit myUnit : self.getUnits()) { game.drawCircle(bwapi.CoordinateType.Enum.Map, myUnit.getPosition().getX(), myUnit.getPosition().getY(), 5, Color.Cyan); game.drawCircle(bwapi.CoordinateType.Enum.Map, myUnit.getPoint().getX(), myUnit.getPoint().getY(), 3, Color.Red); // if it's a drone and it's idle, send it to the closest mineral // patch } } @Override public void onFrame() { if (game.getFrameCount() > 9000) game.setLocalSpeed(10); Iterator<UnitEntity> itt = buildingsWithoutWorkers.iterator(); while (itt.hasNext()) { UnitEntity entity = itt.next(); if (entity.getUnit().getBuildUnit() != null) { System.out.println("CORE: building now has worker calling handlers: " + entity.getUnit().getType()); doOnCreateEntity(entity); itt.remove(); } } // figure out game.drawTextScreen(10, 10, "Playing as " + self.getName() + " - " + self.getRace() + " - " + game.getAPM() + " - " + game.getFrameCount()); for (GameEntity service : services) { service.onFrame(game, self); } for (GameEntity service : units) { service.onFrame(game, self); } // game.setTextSize(10); // for (Unit myUnit : self.getUnits()) { // if (someUnit == null && myUnit.exists()) // someUnit = myUnit; // // if there's enough minerals, train an SCV // } // // iterate through my units // bwta.Region r = BWTA.getRegion(someUnit.getPosition()); // for (int n = 0; n < r.getPolygon().getPoints().size() - 1; n++) { // game.drawLineMap(r.getPolygon().getPoints().get(n).getPoint(), r.getPolygon().getPoints().get(n + 1).getPoint(), Color.White); // for (Chokepoint ch : r.getChokepoints()) { // game.drawCircleMap(ch.getCenter(), (int) ch.getWidth(), Color.Red); // // } // } // draw my units on screen } public static void main(String[] args) { new TestBot1().run(); } @Override public void onUnitDestroy(Unit unit) { // enemy unit destroyed if (unit.getPlayer().equals(enemy)) { for (GameEntity entity : services) { if (entity instanceof EnemyUnitDestroyedListener) { ((EnemyUnitDestroyedListener) entity).onEnemyEntityDestoyed(unit); } } for (GameEntity entity : units) { if (entity instanceof EnemyUnitDestroyedListener) { ((EnemyUnitDestroyedListener) entity).onEnemyEntityDestoyed(unit); } } return; } // my unit destroyed Iterator<UnitEntity> itt = units.iterator(); UnitEntity unitEntity = null; while (itt.hasNext()) { UnitEntity u = itt.next(); if (u.getUnit().equals(unit)) { unitEntity = u; } } if (unitEntity != null) { for (GameEntity entity : services) { entity.onEntityDestroyed(unitEntity); } for (GameEntity entity : units) { entity.onEntityDestroyed(unitEntity); } units.remove(unitEntity); } } @Override public void onUnitDiscover(Unit unit) { if (unit.getPlayer().equals(enemy)) { for (GameEntity entity : services) { if (entity instanceof EnemyUnitDiscoveredListener) { ((EnemyUnitDiscoveredListener) entity).onEnemyEntityDiscovered(unit); } } for (GameEntity entity : units) { if (entity instanceof EnemyUnitDiscoveredListener) { ((EnemyUnitDiscoveredListener) entity).onEnemyEntityDiscovered(unit); } } } // System.out.println("Discovered:" + unit.getType()); } @Override public void onUnitHide(Unit arg0) { // System.out.println("Hidden:" + arg0.getType()); super.onUnitHide(arg0); } @Override public void onUnitShow(Unit arg0) { // System.out.println("Shown:" + arg0.getType()); super.onUnitShow(arg0); } @Override public void onUnitMorph(Unit unit) { if (unit.getType() == UnitType.Terran_Refinery) { BaseUnitEntity unitEntity = new BaseUnitEntity(unit); if (unitEntity != null) { units.add(unitEntity); for (GameEntity entity : services) { entity.onEntityCreate(unitEntity); } for (GameEntity entity : units) { entity.onEntityCreate(unitEntity); } } } } }
package hu.interconnect.hr.domain; import java.util.Date; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.Embedded; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import hu.interconnect.hr.backend.api.enumeration.LakcimAktualis; import hu.interconnect.hr.backend.api.enumeration.Nem; @Embeddable public class SzemelyiAdatok { @Column(name="VEZETEKNEV") private String vezeteknev; @Column(name="KERESZTNEV") private String keresztnev; @Column(name="NEM") @Enumerated(EnumType.STRING) private Nem nem; @ManyToOne @JoinColumn(name="ALLAMPOLGARSAG") private Allampolgarsag allampolgarsag; @Column(name = "SZULETESI_DATUM") @Temporal(TemporalType.DATE) private Date szuletesiDatum; @Column(name="SZULETESI_HELY") private String szuletesiHely; @Column(name="SZULETESI_ORSZAG") private String szuletesiOrszag; @Column(name="SZULETESI_NEV") private String szuletesiNev; @Column(name="SZULETESI_NEV_ANYJA") private String szuletesiNevAnyja; @Column(name="ADOAZONOSITO_JEL") private String adoazonositoJel; @Column(name="TAJ") private String taj; @Column(name="SZEMELYI_IGAZOLVANY_SZAM") private String szemelyiIgazolvanySzam; @Column(name = "SZEMELYI_IGAZOLVANY_SZAM_LEJARAT") @Temporal(TemporalType.DATE) private Date szemelyiIgazolvanySzamLejarat; @Column(name="UTLEVEL_SZAM") private String utlevelSzam; @Column(name = "UTLEVEL_SZAM_LEJARAT") @Temporal(TemporalType.DATE) private Date utlevelSzamLejarat; @Column(name="JOGOSITVANY_SZAM") private String jogositvanySzam; @Column(name = "JOGOSITVANY_SZAM_LEJARAT") @Temporal(TemporalType.DATE) private Date jogositvanySzamLejarat; @Column(name="TELEFON") private String telefon; @Column(name="MOBIL") private String mobil; @Column(name="EMAIL") private String email; @Column(name="LAKCIM_AKTUALIS") @Enumerated(EnumType.STRING) private LakcimAktualis lakcimAktualis; @Embedded @AttributeOverrides( { @AttributeOverride(name="iranyitoszam", column=@Column(name="LAKCIM_ALLANDO_IRANYITOSZAM")), @AttributeOverride(name="telepules", column=@Column(name="LAKCIM_ALLANDO_TELEPULES")), @AttributeOverride(name="kerulet", column=@Column(name="LAKCIM_ALLANDO_KERULET")), @AttributeOverride(name="kozteruletNev", column=@Column(name="LAKCIM_ALLANDO_KOZTERULET_NEV")), @AttributeOverride(name="kozteruletTipus", column=@Column(name="LAKCIM_ALLANDO_KOZTERULET_TIPUS")), @AttributeOverride(name="kozteruletSzam", column=@Column(name="LAKCIM_ALLANDO_KOZTERULET_SZAM")), @AttributeOverride(name="epulet", column=@Column(name="LAKCIM_ALLANDO_EPULET")), @AttributeOverride(name="lepcsohaz", column=@Column(name="LAKCIM_ALLANDO_LEPCSOHAZ")), @AttributeOverride(name="emelet", column=@Column(name="LAKCIM_ALLANDO_EMELET")), @AttributeOverride(name="ajto", column=@Column(name="LAKCIM_ALLANDO_AJTO")) }) private Lakcim lakcimAllando; @Embedded @AttributeOverrides( { @AttributeOverride(name="iranyitoszam", column=@Column(name="LAKCIM_IDEIGLENES_IRANYITOSZAM")), @AttributeOverride(name="telepules", column=@Column(name="LAKCIM_IDEIGLENES_TELEPULES")), @AttributeOverride(name="kerulet", column=@Column(name="LAKCIM_IDEIGLENES_KERULET")), @AttributeOverride(name="kozteruletNev", column=@Column(name="LAKCIM_IDEIGLENES_KOZTERULET_NEV")), @AttributeOverride(name="kozteruletTipus", column=@Column(name="LAKCIM_IDEIGLENES_KOZTERULET_TIPUS")), @AttributeOverride(name="kozteruletSzam", column=@Column(name="LAKCIM_IDEIGLENES_KOZTERULET_SZAM")), @AttributeOverride(name="epulet", column=@Column(name="LAKCIM_IDEIGLENES_EPULET")), @AttributeOverride(name="lepcsohaz", column=@Column(name="LAKCIM_IDEIGLENES_LEPCSOHAZ")), @AttributeOverride(name="emelet", column=@Column(name="LAKCIM_IDEIGLENES_EMELET")), @AttributeOverride(name="ajto", column=@Column(name="LAKCIM_IDEIGLENES_AJTO")) }) private Lakcim lakcimIdeiglenes; public SzemelyiAdatok(String vezeteknev, String keresztnev, Nem nem, Allampolgarsag allampolgarsag, Date szuletesiDatum, String szuletesiHely, String szuletesiOrszag, String szuletesiNev, String szuletesiNevAnyja, String adoazonositoJel, String taj, String szemelyiIgazolvanySzam, Date szemelyiIgazolvanySzamLejarat, String utlevelSzam, Date utlevelSzamLejarat, String jogositvanySzam, Date jogositvanySzamLejarat, String telefon, String mobil, String email, LakcimAktualis lakcimAktualis, Lakcim lakcimAllando, Lakcim lakcimIdeiglenes) { this.vezeteknev = vezeteknev; this.keresztnev = keresztnev; this.nem = nem; this.allampolgarsag = allampolgarsag; this.szuletesiDatum = szuletesiDatum; this.szuletesiHely = szuletesiHely; this.szuletesiOrszag = szuletesiOrszag; this.szuletesiNev = szuletesiNev; this.szuletesiNevAnyja = szuletesiNevAnyja; this.adoazonositoJel = adoazonositoJel; this.taj = taj; this.szemelyiIgazolvanySzam = szemelyiIgazolvanySzam; this.szemelyiIgazolvanySzamLejarat = szemelyiIgazolvanySzamLejarat; this.utlevelSzam = utlevelSzam; this.utlevelSzamLejarat = utlevelSzamLejarat; this.jogositvanySzam = jogositvanySzam; this.jogositvanySzamLejarat = jogositvanySzamLejarat; this.telefon = telefon; this.mobil = mobil; this.email = email; this.lakcimAktualis = lakcimAktualis; this.lakcimAllando = lakcimAllando; this.lakcimIdeiglenes = lakcimIdeiglenes; } public String getTeljesNev() { boolean vanVezeteknev = vezeteknev != null && !vezeteknev.isEmpty(); boolean vanKeresztnev = keresztnev != null && !keresztnev.isEmpty(); StringBuilder sb = new StringBuilder(); if (vanVezeteknev) { sb.append(vezeteknev); } if (vanKeresztnev && vanVezeteknev) { sb.append(" "); } if (vanKeresztnev) { sb.append(keresztnev); } return sb.toString(); } public String getVezeteknev() { return vezeteknev; } public String getKeresztnev() { return keresztnev; } public Nem getNem() { return nem; } public Allampolgarsag getAllampolgarsag() { return allampolgarsag; } public Date getSzuletesiDatum() { return szuletesiDatum; } public String getSzuletesiHely() { return szuletesiHely; } public String getSzuletesiOrszag() { return szuletesiOrszag; } public String getSzuletesiNev() { return szuletesiNev; } public String getSzuletesiNevAnyja() { return szuletesiNevAnyja; } public String getAdoazonositoJel() { return adoazonositoJel; } public String getTaj() { return taj; } public String getSzemelyiIgazolvanySzam() { return szemelyiIgazolvanySzam; } public Date getSzemelyiIgazolvanySzamLejarat() { return szemelyiIgazolvanySzamLejarat; } public String getUtlevelSzam() { return utlevelSzam; } public Date getUtlevelSzamLejarat() { return utlevelSzamLejarat; } public String getJogositvanySzam() { return jogositvanySzam; } public Date getJogositvanySzamLejarat() { return jogositvanySzamLejarat; } public String getTelefon() { return telefon; } public String getMobil() { return mobil; } public String getEmail() { return email; } public LakcimAktualis getLakcimAktualis() { return lakcimAktualis; } public Lakcim getLakcimAllando() { return lakcimAllando; } public Lakcim getLakcimIdeiglenes() { return lakcimIdeiglenes; } @SuppressWarnings("unused") private SzemelyiAdatok() { } }
/* * gleem -- OpenGL Extremely Easy-To-Use Manipulators. * Copyright (C) 1998-2003 Kenneth B. Russell ([email protected]) * * Copying, distribution and use of this software in source and binary * forms, with or without modification, is permitted provided that the * following conditions are met: * * Distributions of source code must reproduce the copyright notice, * this list of conditions and the following disclaimer in the source * code header files; and Distributions of binary code must reproduce * the copyright notice, this list of conditions and the following * disclaimer in the documentation, Read me file, license file and/or * other materials provided with the software distribution. * * The names of Sun Microsystems, Inc. ("Sun") and/or the copyright * holder may not be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED "AS IS," WITHOUT A WARRANTY OF ANY * KIND. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, NON-INTERFERENCE, ACCURACY OF * INFORMATIONAL CONTENT OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. THE * COPYRIGHT HOLDER, SUN AND SUN'S LICENSORS SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL THE * COPYRIGHT HOLDER, SUN OR SUN'S LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR * INABILITY TO USE THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGES. YOU ACKNOWLEDGE THAT THIS SOFTWARE IS NOT * DESIGNED, LICENSED OR INTENDED FOR USE IN THE DESIGN, CONSTRUCTION, * OPERATION OR MAINTENANCE OF ANY NUCLEAR FACILITY. THE COPYRIGHT * HOLDER, SUN AND SUN'S LICENSORS DISCLAIM ANY EXPRESS OR IMPLIED * WARRANTY OF FITNESS FOR SUCH USES. */ package gleem; import java.util.*; import gleem.linalg.*; import javax.media.opengl.*; /** A Translate1Manip is a Manip which translates in only one dimension and whose default representation is a two-way arrow. */ public class Translate1Manip extends Manip { private ManipPart parts; private Vec3f translation; /** Normalized */ private Vec3f axis; private Vec3f scale; /** Local-to-world transform for geometry */ private Mat4f xform; /** Dragging state */ private Line dragLine; /** Dragging state */ private Vec3f dragOffset; public Translate1Manip() { parts = new ManipPartTwoWayArrow(); translation = new Vec3f(0, 0, 0); axis = new Vec3f(1, 0, 0); scale = new Vec3f(1, 1, 1); xform = new Mat4f(); dragLine = new Line(); dragOffset = new Vec3f(); recalc(); } /** Set the translation of this Translate1Manip. This moves its on-screen representation. Manipulations cause the translation to be modified, not overwritten, so if you want the default Translate1Manip to go through the point (0, 1, 0) but still translate along the X axis, then setTranslation(0, 1, 0). */ public void setTranslation(Vec3f translation) { this.translation.set(translation); recalc(); } /** Get the translation of this Translate1Manip. This corresponds to the center of its body. */ public Vec3f getTranslation() { return new Vec3f(translation); } /** Set the axis of this Translate1Manip. This is the direction along which it will travel. Does not need to be normalized, but must not be the zero vector. */ public void setAxis(Vec3f axis) { this.axis.set(axis); recalc(); } /** Get the axis of this Translate1Manip. */ public Vec3f getAxis() { return new Vec3f(axis); } /** Set the scale of the Translate1Manip. This only affects the size of the on-screen geometry. */ public void setScale(Vec3f scale) { this.scale.set(scale); recalc(); } public Vec3f getScale() { return new Vec3f(scale); } /** Change the geometry of this manipulator to be the user-defined piece. */ public void replaceGeometry(ManipPart geom) { parts = geom; } public void intersectRay(Vec3f rayStart, Vec3f rayDirection, List results) { parts.intersectRay(rayStart, rayDirection, results, this); } public void highlight(HitPoint hit) { if (hit.manipPart != parts) { throw new RuntimeException("My old geometry disappeared; how did this happen?"); } parts.highlight(); } public void clearHighlight() { parts.clearHighlight(); } public void makeActive(HitPoint hit) { parts.highlight(); dragLine.setDirection(axis); dragLine.setPoint(hit.intPt.getIntersectionPoint()); dragOffset.sub(translation, hit.intPt.getIntersectionPoint()); } public void drag(Vec3f rayStart, Vec3f rayDirection) { // Algorithm: Find closest point of ray to dragLine. Add dragOffset // to this point to get new translation. Vec3f closestPoint = new Vec3f(); if (dragLine.closestPointToRay(rayStart, rayDirection, closestPoint) == false) { // Drag axis is parallel to ray. Punt. return; } translation.set(closestPoint); translation.add(dragOffset); recalc(); super.drag(rayStart, rayDirection); } public void makeInactive() { parts.clearHighlight(); } public void render(GL2 gl) { parts.render(gl); } private void recalc() { // Construct local to world transform for geometry. // Scale, Rotation, Translation. Since we're right multiplying // column vectors, the actual matrix composed is TRS. Mat4f scaleMat = new Mat4f(); Mat4f rotMat = new Mat4f(); Mat4f xlateMat = new Mat4f(); Mat4f tmpMat = new Mat4f(); scaleMat.makeIdent(); scaleMat.set(0, 0, scale.x()); scaleMat.set(1, 1, scale.y()); scaleMat.set(2, 2, scale.z()); // Perpendiculars Vec3f p0 = new Vec3f(); Vec3f p1 = new Vec3f(); MathUtil.makePerpendicular(axis, p0); p1.cross(axis, p0); // axis, p0, p1 correspond to x, y, z p0.normalize(); p1.normalize(); rotMat.makeIdent(); rotMat.set(0, 0, axis.x()); rotMat.set(1, 0, axis.y()); rotMat.set(2, 0, axis.z()); rotMat.set(0, 1, p0.x()); rotMat.set(1, 1, p0.y()); rotMat.set(2, 1, p0.z()); rotMat.set(0, 2, p1.x()); rotMat.set(1, 2, p1.y()); rotMat.set(2, 2, p1.z()); xlateMat.makeIdent(); xlateMat.set(0, 3, translation.x()); xlateMat.set(1, 3, translation.y()); xlateMat.set(2, 3, translation.z()); tmpMat.mul(xlateMat, rotMat); xform.mul(tmpMat, scaleMat); parts.setTransform(xform); } }
package com.neurospeech.wsclient; import javax.xml.parsers.*; import java.io.*; import java.util.Date; import java.util.HashMap; import java.util.concurrent.Executors; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.*; import org.w3c.dom.*; import org.xml.sax.*; public class SoapWebService { public static String globalBaseUrl = null; private String _baseUrl = null; public String getBaseUrl(){ return _baseUrl; } public void setBaseUrl(String b){ _baseUrl = b; } private String _url = null; public String getUrl() { return _url; } public void setUrl(String url) { _url = url; } protected void executeAsync(Runnable r){ Thread thread = Executors.defaultThreadFactory().newThread(r); thread.start(); } private UINotifyListener _listener; public void setUINotifyListener(UINotifyListener l){ _listener = l; } UINotifyListener getUINotifyListener(){ return _listener; } protected SoapRequest buildSoapRequest(String methodName, String nsUri, String action, String header) throws Exception { SoapRequest req = new SoapRequest(); req.methodName = methodName; if(action==null) req.soapAction = nsUri + methodName; else req.soapAction = action; String soapDoc = "<?xml version='1.0' encoding='utf-8'?>" + "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>" + "<s:Body><SOAPREQUEST xmlns='"+nsUri+"' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'></SOAPREQUEST></s:Body></s:Envelope>"; if(header!=null){ soapDoc = soapDoc.replaceAll("HSOAPREQUEST", header); } soapDoc = soapDoc.replaceAll("SOAPREQUEST", methodName); StringReader sr = new StringReader(soapDoc); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setIgnoringComments(true); dbf.setIgnoringElementContentWhitespace(true); dbf.setCoalescing(true); //dbf.setValidating(false); Document doc = dbf.newDocumentBuilder().parse(new InputSource(sr)); doc.normalize(); req.document = doc; //doc.normalizeDocument(); Element root = doc.getDocumentElement(); if(header!=null){ req.header = WSHelper.getElementNS(root,getSoapEnvelopeNS() , "Header"); } //root = WSHelper.getElementNS(root,getSoapEnvelopeNS(), "Body"); root = WSHelper.getElement(root, "Body"); req.method = WSHelper.getElement(root, methodName); return req; } // single cookie container for entire application private static DefaultHttpClient client = new DefaultHttpClient(); protected DefaultHttpClient GetHttpClient(){ return client; } protected void setHeaders(SoapRequest request, HashMap<String, String> headers) { } SoapResponse postWS(SoapRequest request) throws Exception{ String xml = WSHelper.getString(request.document); String url = getServiceUrl(); String userAgent = getUserAgent(); String contentType = getContentType(request.soapAction); HttpPost post = new HttpPost(url); post.setHeader("Content-Type", contentType); request.rawHttpRequest = url + "\r\n"; request.rawHttpRequest += "Content-Type: " + contentType + "\r\n"; if(userAgent!=null){ request.rawHttpRequest += "User-Agent: " + userAgent + "\r\n"; post.setHeader("User-Agent", userAgent); } if(IsSoapActionRequired()){ post.setHeader("SOAPAction",request.soapAction); request.rawHttpRequest += "SOAPAction: " + request.soapAction + "\r\n"; } HashMap<String, String> headers = new HashMap<String, String>(); setHeaders(request, headers); for(String key : headers.keySet()){ post.setHeader(key, headers.get(key)); } post.setEntity(new StringEntity(xml)); request.rawHttpRequest += "\r\n"; request.rawHttpRequest += xml; HttpUriRequest req = post; DefaultHttpClient c = GetHttpClient(); if(c==null) c = client; HttpResponse response = c.execute(req); return new SoapResponse(request, response); } protected String getUserAgent(){ return "neurospeech.wsclient.android"; } protected String getContentType(String action) { return "text/xml; charset=utf-8"; } protected String getSoapEnvelopeNS(){ return "http://schemas.xmlsoap.org/soap/envelope/"; } protected boolean IsSoapActionRequired(){ return true; } // Element postXML(SoapRequest request, SoapResponse response) throws Exception{ // // String text = WSHelper.getString(request.document); // //System.out.println(text); // // HttpResponse hr = postWS(request, text); // //InputStream stream = postWS(request, text); // // // StringBuilder sb = new StringBuilder(); // // BufferedReader br = new BufferedReader(new InputStreamReader(stream)); // do{ // String line = br.readLine(); // if(line==null) // break; // sb.append(line + "\r\n"); // }while(true); // // String textResponse = sb.toString(); // // DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // dbf.setNamespaceAware(true); // dbf.setIgnoringComments(true); // dbf.setIgnoringElementContentWhitespace(true); // dbf.setCoalescing(true); // // // // //dbf.setValidating(false); // try{ // InputSource ins = new InputSource(new StringReader(textResponse)); // Document d = dbf.newDocumentBuilder().parse(ins); // d.normalize(); // return d.getDocumentElement(); // }catch(Exception ex){ // throw new SoapParseException(textResponse, ex); // } // //d.normalizeDocument(); // // //System.out.println(getString(d)); // // } protected void addParameter(Element root, String name, Object value) { if(value==null) return; Document doc = root.getOwnerDocument(); Element e = doc.createElement(name); //e.setTextContent(value.toString()); String val = value.toString(); if(value.getClass().equals(Date.class)){ val = WSHelper.stringValueOf((Date)value); } Text txt = doc.createTextNode(val); e.appendChild(txt); root.appendChild(e); } protected String getServiceUrl(){ if(_baseUrl!=null && _baseUrl.length()>0){ return _baseUrl + _url; } if(globalBaseUrl!=null && globalBaseUrl.length()>0) { return globalBaseUrl + _url; } return _url; } protected SoapResponse getSoapResponse(SoapRequest request) throws Exception { SoapResponse rs = postWS(request); // search for fault first... Element fault = WSHelper.getElementNS(rs.root, getSoapEnvelopeNS(), "Fault"); if(fault!=null) { String code = WSHelper.getString(fault, "faultcode", false); String text = WSHelper.getString(fault, "faultstring", false); SoapFaultException fe = new SoapFaultException(code, text, request.rawHttpRequest); throw fe; } //rs.header = WSHelper.getElementNS(rs.root,getSoapEnvelopeNS(), "Header"); //rs.body = WSHelper.getElementNS(rs.root,getSoapEnvelopeNS(), "Body"); rs.header = WSHelper.getElement(rs.root, "Header"); rs.body = WSHelper.getElement(rs.root, "Body"); return rs; } }
/* * Copyright 2014 MICRORISC s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.microrisc.simply.iqrf.dpa.v30x.devices.impl; import com.microrisc.simply.CallRequestProcessingInfoContainer; import com.microrisc.simply.ConnectorService; import com.microrisc.simply.di_services.MethodArgumentsChecker; import com.microrisc.simply.iqrf.dpa.v30x.DPA_DeviceObject; import com.microrisc.simply.iqrf.dpa.v30x.devices.OS; import com.microrisc.simply.iqrf.dpa.v30x.di_services.method_id_transformers.OSStandardTransformer; import com.microrisc.simply.iqrf.dpa.v30x.types.DPA_Request; import com.microrisc.simply.iqrf.dpa.v30x.types.HWP_Configuration; import com.microrisc.simply.iqrf.dpa.v30x.types.HWP_ConfigurationByte; import com.microrisc.simply.iqrf.dpa.v30x.types.LoadingCodeProperties; import com.microrisc.simply.iqrf.dpa.v30x.types.LoadResult; import com.microrisc.simply.iqrf.dpa.v30x.types.OsInfo; import com.microrisc.simply.iqrf.dpa.v30x.types.SleepInfo; import com.microrisc.simply.iqrf.types.VoidType; import java.util.UUID; /** * Simple {@code OS} implementation. * * @author Michal Konopa * @author Martin Strouhal */ //JUNE-2015 - implemented restart //SEPTEMBER 2015 - implemented write HWP config, write HWP config byte //MARCH 2016 - implemented load code //MAY 2016 - updated WriteHWPConfigByte public final class SimpleOS extends DPA_DeviceObject implements OS { private static final int USER_ADDR_LOWER_BOUND = 0x00; private static final int USER_ADDR_UPPER_BOUND = 0xFFFF; private static int checkUserAddress(int userAddress) { if ( (userAddress < USER_ADDR_LOWER_BOUND) || (userAddress > USER_ADDR_UPPER_BOUND) ) { throw new IllegalArgumentException("User address out of bounds"); } return userAddress; } // MID key length private static final int MID_KEY_LENGTH = 24; // length of security data private static final int SECURITY_DATA_LEN = 16; private static void checkKey(short[] key) { if ( key == null ) { throw new IllegalArgumentException("Key cannot be null"); } if ( key.length != MID_KEY_LENGTH ) { throw new IllegalArgumentException( "Invalid key length. Expected: " + MID_KEY_LENGTH ); } } private static void checkLoadingCodeProperties(LoadingCodeProperties prop){ if( prop == null ) { throw new IllegalArgumentException("Properties cannot be null."); } } private static int checkType(int type) { if ( !DataTypesChecker.isByteValue(type)) { throw new IllegalArgumentException("Type out of range"); } return type; } private static short[] checkSecurityData(short[] secData) { if ( secData == null ) { throw new IllegalArgumentException("Security data cannot be null."); } if ( secData.length != SECURITY_DATA_LEN ) { throw new IllegalArgumentException( "Security data length mismatch." + "Expected: " + SECURITY_DATA_LEN + ", got: " + secData.length ); } return secData; } public SimpleOS(String networkId, String nodeId, ConnectorService connector, CallRequestProcessingInfoContainer resultsContainer ) { super(networkId, nodeId, connector, resultsContainer); } @Override public UUID call(Object methodId, Object[] args) { String methodIdStr = transform((OS.MethodID) methodId); if ( methodIdStr == null ) { return null; } switch ( (OS.MethodID)methodId ) { case READ: MethodArgumentsChecker.checkArgumentTypes(args, new Class[] { } ); return dispatchCall( methodIdStr, new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); case RESET: MethodArgumentsChecker.checkArgumentTypes(args, new Class[] { } ); return dispatchCall( methodIdStr, new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); case READ_HWP_CONFIGURATION: MethodArgumentsChecker.checkArgumentTypes(args, new Class[] { } ); return dispatchCall( methodIdStr, new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); case RUN_RFPGM: MethodArgumentsChecker.checkArgumentTypes(args, new Class[] { } ); return dispatchCall( methodIdStr, new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); case SLEEP: MethodArgumentsChecker.checkArgumentTypes(args, new Class[] { SleepInfo.class } ); return dispatchCall( methodIdStr, new Object[] { getRequestHwProfile(), (SleepInfo) args[0] }, getDefaultWaitingTimeout() ); case BATCH: MethodArgumentsChecker.checkArgumentTypes(args, new Class[] { DPA_Request[].class } ); return dispatchCall( methodIdStr, new Object[] { getRequestHwProfile(), (DPA_Request[]) args[0] }, getDefaultWaitingTimeout() ); case SET_SECURITY: MethodArgumentsChecker.checkArgumentTypes(args, new Class[]{Integer.class, short[].class}); return dispatchCall( methodIdStr, new Object[]{getRequestHwProfile(), (Integer) args[0], (short[]) args[1]}, getDefaultWaitingTimeout() ); case RESTART: MethodArgumentsChecker.checkArgumentTypes(args, new Class[] { } ); return dispatchCall( methodIdStr, new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); case WRITE_HWP_CONFIGURATION: MethodArgumentsChecker.checkArgumentTypes(args, new Class[]{HWP_Configuration.class}); return dispatchCall( methodIdStr, new Object[] { getRequestHwProfile(), (HWP_Configuration) args[0] }, getDefaultWaitingTimeout() ); case WRITE_HWP_CONFIGURATION_BYTE: MethodArgumentsChecker.checkArgumentTypes(args, new Class[]{Integer.class, Integer.class}); return dispatchCall( methodIdStr, new Object[] { getRequestHwProfile(), (Integer) args[0], (Integer) args[1] }, getDefaultWaitingTimeout() ); case LOAD_CODE: MethodArgumentsChecker.checkArgumentTypes(args, new Class[]{LoadingCodeProperties.class}); return dispatchCall( methodIdStr, new Object[] { getRequestHwProfile(), (LoadingCodeProperties) args[0] }, getDefaultWaitingTimeout() ); default: throw new IllegalArgumentException("Unsupported command: " + methodId); } } @Override public String transform(Object methodId) { return OSStandardTransformer.getInstance().transform(methodId); } // ASYNCHRONOUS METHODS IMPLEMENTATIONS @Override public UUID async_read() { return dispatchCall( "1", new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); } @Override public UUID async_reset() { return dispatchCall( "2", new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); } @Override public UUID async_readHWPConfiguration() { return dispatchCall( "3", new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); } @Override public UUID async_runRFPGM() { return dispatchCall( "4", new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); } @Override public UUID async_sleep(SleepInfo sleepInfo) { return dispatchCall( "5", new Object[] { getRequestHwProfile(), sleepInfo }, getDefaultWaitingTimeout() ); } @Override public UUID async_batch(DPA_Request[] requests) { return dispatchCall( "6", new Object[] { getRequestHwProfile(), requests }, getDefaultWaitingTimeout() ); } @Override public UUID async_setSecurity(int type, short[] data){ return dispatchCall( "7", new Object[] { getRequestHwProfile(), type, data }, getDefaultWaitingTimeout() ); } @Override public UUID async_restart(){ return dispatchCall( "8", new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); } @Override public UUID async_writeHWPConfiguration(HWP_Configuration configuration) { return dispatchCall( "9", new Object[] { getRequestHwProfile(), configuration }, getDefaultWaitingTimeout() ); } @Override public UUID async_writeHWPConfigurationByte(HWP_ConfigurationByte[] configBytes) { return dispatchCall( "10", new Object[] { getRequestHwProfile(), configBytes }, getDefaultWaitingTimeout() ); } @Override public UUID async_loadCode(LoadingCodeProperties properties) { checkLoadingCodeProperties(properties); return dispatchCall("11", new Object[]{getRequestHwProfile(), properties}, getDefaultWaitingTimeout() ); } // SYNCHRONOUS WRAPPERS IMPLEMENTATIONS @Override public OsInfo read() { UUID uid = dispatchCall( "1", new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); if ( uid == null ) { return null; } return getCallResult(uid, OsInfo.class, getDefaultWaitingTimeout() ); } @Override public VoidType reset() { UUID uid = dispatchCall( "2", new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); if ( uid == null ) { return null; } return getCallResult(uid, VoidType.class, getDefaultWaitingTimeout() ); } @Override public HWP_Configuration readHWPConfiguration() { UUID uid = dispatchCall( "3", new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); if ( uid == null ) { return null; } return getCallResult(uid, HWP_Configuration.class, getDefaultWaitingTimeout() ); } @Override public VoidType runRFPGM() { UUID uid = dispatchCall( "4", new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); if ( uid == null ) { return null; } return getCallResult(uid, VoidType.class, getDefaultWaitingTimeout() ); } @Override public VoidType sleep(SleepInfo sleepInfo) { UUID uid = dispatchCall( "5", new Object[] { getRequestHwProfile(), sleepInfo }, getDefaultWaitingTimeout() ); if ( uid == null ) { return null; } return getCallResult(uid, VoidType.class, getDefaultWaitingTimeout()); } @Override public VoidType batch(DPA_Request[] requests) { UUID uid = dispatchCall( "6", new Object[] { getRequestHwProfile(), requests }, getDefaultWaitingTimeout() ); if ( uid == null ) { return null; } return getCallResult(uid, VoidType.class, getDefaultWaitingTimeout()); } @Override public VoidType setSecurity(int type, short[] data) { checkType(type); checkSecurityData(data); UUID uid = dispatchCall( "7", new Object[] { getRequestHwProfile(), type, data }, getDefaultWaitingTimeout() ); if ( uid == null ) { return null; } return getCallResult(uid, VoidType.class, getDefaultWaitingTimeout()); } @Override public VoidType restart(){ UUID uid = dispatchCall( "8", new Object[] { getRequestHwProfile() }, getDefaultWaitingTimeout() ); if ( uid == null ) { return null; } return getCallResult(uid, VoidType.class, getDefaultWaitingTimeout()); } @Override public VoidType writeHWPConfiguration(HWP_Configuration configuration) { UUID uid = dispatchCall( "9", new Object[] { getRequestHwProfile(), configuration }, getDefaultWaitingTimeout() ); if ( uid == null ) { return null; } return getCallResult(uid, VoidType.class, getDefaultWaitingTimeout() ); } @Override public VoidType writeHWPConfigurationByte(HWP_ConfigurationByte[] configBytes) { UUID uid = dispatchCall( "10", new Object[] { getRequestHwProfile(), configBytes }, getDefaultWaitingTimeout() ); if ( uid == null ) { return null; } return getCallResult(uid, VoidType.class, getDefaultWaitingTimeout() ); } @Override public LoadResult loadCode(LoadingCodeProperties properties) { checkLoadingCodeProperties(properties); UUID uid = dispatchCall("11", new Object[]{getRequestHwProfile(), properties}, getDefaultWaitingTimeout() ); if (uid == null) { return null; } return getCallResult(uid, LoadResult.class, getDefaultWaitingTimeout()); } }
package com.communote.server.persistence.tag; import java.util.Collection; import com.communote.server.model.tag.Tag; import com.communote.server.model.tag.TagImpl; /** * Base Spring DAO Class: is able to create, update, remove, load, and find objects of type * <code>Tag</code>. * * @see Tag * @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a> */ public abstract class TagDaoBase extends org.springframework.orm.hibernate3.support.HibernateDaoSupport implements TagDao { private com.communote.server.persistence.global.GlobalIdDao globalIdDao; /** * @see TagDao#create(Collection<de.communardo.kenmei .core.api.bo.tag.Tag>) */ @Override public Collection<Tag> create(final Collection<Tag> entities) { return create(TRANSFORM_NONE, entities); } /** * @see TagDao#create(int, Collection<Tag>) */ @Override public Collection<Tag> create(final int transform, final Collection<Tag> entities) { if (entities == null) { throw new IllegalArgumentException("Tag.create - 'entities' can not be null"); } this.getHibernateTemplate().executeWithNativeSession( new org.springframework.orm.hibernate3.HibernateCallback<Tag>() { @Override public Tag doInHibernate(org.hibernate.Session session) throws org.hibernate.HibernateException { for (Tag entity : entities) { create(transform, entity); } return null; } }); return entities; } /** * @see TagDao#create(int transform, Tag) */ @Override public Object create(final int transform, final Tag tag) { if (tag == null) { throw new IllegalArgumentException("Tag.create - 'tag' can not be null"); } this.getHibernateTemplate().save(tag); return this.transformEntity(transform, tag); } /** * @see TagDao#create(Tag) */ @Override public Tag create(Tag tag) { return (Tag) this.create(TRANSFORM_NONE, tag); } /** * {@inheritDoc} */ @Override public void evict(Tag entity) { this.getHibernateTemplate().evict(entity); } /** * @see TagDao#findByPrefix(String, com.communote.server.core.filter.ResultSpecification) */ @Override public java.util.List<com.communote.server.api.core.tag.TagData> findByPrefix( final String prefix, final com.communote.server.core.filter.ResultSpecification resultSpecification) { if (prefix == null) { throw new IllegalArgumentException( "TagDao.findByPrefix(String prefix, ResultSpecification resultSpecification) - 'prefix' can not be null"); } if (resultSpecification == null) { throw new IllegalArgumentException( "TagDao.findByPrefix(String prefix, ResultSpecification resultSpecification) - 'resultSpecification' can not be null"); } try { return this.handleFindByPrefix(prefix, resultSpecification); } catch (RuntimeException rt) { throw new RuntimeException( "Error performing 'TagDao.findByPrefix(String prefix, ResultSpecification resultSpecification)' --> " + rt, rt); } } /** * @see TagDao#findByTagStore(String, String) */ @Override public Tag findByTagStore(final String tagStoreTagId, final String tagStoreAlias) { if (tagStoreTagId == null) { throw new IllegalArgumentException( "TagDao.findByTagStore(String tagStoreTagId, String tagStoreAlias) - 'tagStoreTagId' can not be null"); } if (tagStoreAlias == null) { throw new IllegalArgumentException( "TagDao.findByTagStore(String tagStoreTagId, String tagStoreAlias) - 'tagStoreAlias' can not be null"); } try { return this.handleFindByTagStore(tagStoreTagId, tagStoreAlias); } catch (RuntimeException rt) { throw new RuntimeException( "Error performing 'TagDao.findByTagStore(String tagStoreTagId, String tagStoreAlias)' --> " + rt, rt); } } /** * Gets the reference to <code>globalIdDao</code>. */ protected com.communote.server.persistence.global.GlobalIdDao getGlobalIdDao() { return this.globalIdDao; } /** * Performs the core logic for * {@link #findByPrefix(String, com.communote.server.core.filter.ResultSpecification)} */ protected abstract java.util.List<com.communote.server.api.core.tag.TagData> handleFindByPrefix( String prefix, com.communote.server.core.filter.ResultSpecification resultSpecification); /** * Performs the core logic for {@link #findByTagStore(String, String)} */ protected abstract Tag handleFindByTagStore(String tagStoreTagId, String tagStoreAlias); /** * @see TagDao#load(int, Long) */ @Override public Object load(final int transform, final Long id) { if (id == null) { throw new IllegalArgumentException("Tag.load - 'id' can not be null"); } final Object entity = this.getHibernateTemplate().get(TagImpl.class, id); return transformEntity(transform, (Tag) entity); } /** * @see TagDao#load(Long) */ @Override public Tag load(Long id) { return (Tag) this.load(TRANSFORM_NONE, id); } /** * @see TagDao#loadAll() */ @Override public Collection<TagImpl> loadAll() { return this.loadAll(TRANSFORM_NONE); } /** * @see TagDao#loadAll(int) */ @Override public Collection<TagImpl> loadAll(final int transform) { final Collection<TagImpl> results = this.getHibernateTemplate().loadAll(TagImpl.class); this.transformEntities(transform, results); return results; } /** * @see TagDao#remove(Long) */ @Override public void remove(Long id) { if (id == null) { throw new IllegalArgumentException("Tag.remove - 'id' can not be null"); } Tag entity = this.load(id); if (entity != null) { this.remove(entity); } } /** * Sets the reference to <code>globalIdDao</code>. */ public void setGlobalIdDao(com.communote.server.persistence.global.GlobalIdDao globalIdDao) { this.globalIdDao = globalIdDao; } /** * Transforms a collection of entities using the {@link #transformEntity(int,Tag)} method. This * method does not instantiate a new collection. * <p/> * This method is to be used internally only. * * @param transform * one of the constants declared in <code>TagDao</code> * @param entities * the collection of entities to transform * @see #transformEntity(int,Tag) */ protected void transformEntities(final int transform, final Collection<?> entities) { switch (transform) { case TRANSFORM_NONE: // fall-through default: // do nothing; } } /** * Allows transformation of entities into value objects (or something else for that matter), * when the <code>transform</code> flag is set to one of the constants defined in * <code>TagDao</code>, please note that the {@link #TRANSFORM_NONE} constant denotes no * transformation, so the entity itself will be returned. * * If the integer argument value is unknown {@link #TRANSFORM_NONE} is assumed. * * @param transform * one of the constants declared in {@link TagDao} * @param entity * an entity that was found * @return the transformed entity (i.e. new value object, etc) * @see #transformEntities(int,Collection) */ protected Object transformEntity(final int transform, final Tag entity) { Object target = null; if (entity != null) { switch (transform) { case TRANSFORM_NONE: // fall-through default: target = entity; } } return target; } /** * @see TagDao#update(Collection<de.communardo.kenmei .core.api.bo.tag.Tag>) */ @Override public void update(final Collection<Tag> entities) { if (entities == null) { throw new IllegalArgumentException("Tag.update - 'entities' can not be null"); } this.getHibernateTemplate().executeWithNativeSession( new org.springframework.orm.hibernate3.HibernateCallback<Tag>() { @Override public Tag doInHibernate(org.hibernate.Session session) throws org.hibernate.HibernateException { for (Tag entity : entities) { update(entity); } return null; } }); } /** * @see TagDao#update(Tag) */ @Override public void update(Tag tag) { if (tag == null) { throw new IllegalArgumentException("Tag.update - 'tag' can not be null"); } this.getHibernateTemplate().update(tag); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.http.netty4.cors; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import org.elasticsearch.common.Strings; import org.elasticsearch.http.netty4.Netty4HttpResponse; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Handles <a href="http://www.w3.org/TR/cors/">Cross Origin Resource Sharing</a> (CORS) requests. * <p> * This handler can be configured using a {@link Netty4CorsConfig}, please * refer to this class for details about the configuration options available. * * This code was borrowed from Netty 4 and refactored to work for Elasticsearch's Netty 3 setup. */ public class Netty4CorsHandler extends ChannelDuplexHandler { public static final String ANY_ORIGIN = "*"; private static Pattern SCHEME_PATTERN = Pattern.compile("^https?://"); private final Netty4CorsConfig config; private FullHttpRequest request; /** * Creates a new instance with the specified {@link Netty4CorsConfig}. */ public Netty4CorsHandler(final Netty4CorsConfig config) { if (config == null) { throw new NullPointerException(); } this.config = config; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { assert msg instanceof FullHttpRequest : "Invalid message type: " + msg.getClass(); if (config.isCorsSupportEnabled()) { request = (FullHttpRequest) msg; if (isPreflightRequest(request)) { try { handlePreflight(ctx, request); return; } finally { releaseRequest(); } } if (config.isShortCircuit() && !validateOrigin()) { try { forbidden(ctx, request); return; } finally { releaseRequest(); } } } ctx.fireChannelRead(msg); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { assert msg instanceof Netty4HttpResponse : "Invalid message type: " + msg.getClass(); Netty4HttpResponse response = (Netty4HttpResponse) msg; setCorsResponseHeaders(response.getRequest().nettyRequest(), response, config); ctx.write(response, promise); } public static void setCorsResponseHeaders(HttpRequest request, HttpResponse resp, Netty4CorsConfig config) { if (!config.isCorsSupportEnabled()) { return; } String originHeader = request.headers().get(HttpHeaderNames.ORIGIN); if (!Strings.isNullOrEmpty(originHeader)) { final String originHeaderVal; if (config.isAnyOriginSupported()) { originHeaderVal = ANY_ORIGIN; } else if (config.isOriginAllowed(originHeader) || isSameOrigin(originHeader, request.headers().get(HttpHeaderNames.HOST))) { originHeaderVal = originHeader; } else { originHeaderVal = null; } if (originHeaderVal != null) { resp.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, originHeaderVal); } } if (config.isCredentialsAllowed()) { resp.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } } private void handlePreflight(final ChannelHandlerContext ctx, final HttpRequest request) { final HttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK, true, true); if (setOrigin(response)) { setAllowMethods(response); setAllowHeaders(response); setAllowCredentials(response); setMaxAge(response); setPreflightHeaders(response); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { forbidden(ctx, request); } } private void releaseRequest() { request.release(); request = null; } private static void forbidden(final ChannelHandlerContext ctx, final HttpRequest request) { ctx.writeAndFlush(new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.FORBIDDEN)) .addListener(ChannelFutureListener.CLOSE); } private static boolean isSameOrigin(final String origin, final String host) { if (Strings.isNullOrEmpty(host) == false) { // strip protocol from origin final String originDomain = SCHEME_PATTERN.matcher(origin).replaceFirst(""); if (host.equals(originDomain)) { return true; } } return false; } /** * This is a non CORS specification feature which enables the setting of preflight * response headers that might be required by intermediaries. * * @param response the HttpResponse to which the preflight response headers should be added. */ private void setPreflightHeaders(final HttpResponse response) { response.headers().add(config.preflightResponseHeaders()); } private boolean setOrigin(final HttpResponse response) { final String origin = request.headers().get(HttpHeaderNames.ORIGIN); if (!Strings.isNullOrEmpty(origin)) { if ("null".equals(origin) && config.isNullOriginAllowed()) { setAnyOrigin(response); return true; } if (config.isAnyOriginSupported()) { if (config.isCredentialsAllowed()) { echoRequestOrigin(response); setVaryHeader(response); } else { setAnyOrigin(response); } return true; } if (config.isOriginAllowed(origin)) { setOrigin(response, origin); setVaryHeader(response); return true; } } return false; } private boolean validateOrigin() { if (config.isAnyOriginSupported()) { return true; } final String origin = request.headers().get(HttpHeaderNames.ORIGIN); if (Strings.isNullOrEmpty(origin)) { // Not a CORS request so we cannot validate it. It may be a non CORS request. return true; } if ("null".equals(origin) && config.isNullOriginAllowed()) { return true; } // if the origin is the same as the host of the request, then allow if (isSameOrigin(origin, request.headers().get(HttpHeaderNames.HOST))) { return true; } return config.isOriginAllowed(origin); } private void echoRequestOrigin(final HttpResponse response) { setOrigin(response, request.headers().get(HttpHeaderNames.ORIGIN)); } private static void setVaryHeader(final HttpResponse response) { response.headers().set(HttpHeaderNames.VARY, HttpHeaderNames.ORIGIN); } private static void setAnyOrigin(final HttpResponse response) { setOrigin(response, ANY_ORIGIN); } private static void setOrigin(final HttpResponse response, final String origin) { response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, origin); } private void setAllowCredentials(final HttpResponse response) { if (config.isCredentialsAllowed() && !response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN).equals(ANY_ORIGIN)) { response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } } private static boolean isPreflightRequest(final HttpRequest request) { final HttpHeaders headers = request.headers(); return request.method().equals(HttpMethod.OPTIONS) && headers.contains(HttpHeaderNames.ORIGIN) && headers.contains(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD); } private void setAllowMethods(final HttpResponse response) { response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, config.allowedRequestMethods().stream() .map(m -> m.name().trim()) .collect(Collectors.toList())); } private void setAllowHeaders(final HttpResponse response) { response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, config.allowedRequestHeaders()); } private void setMaxAge(final HttpResponse response) { response.headers().set(HttpHeaderNames.ACCESS_CONTROL_MAX_AGE, config.maxAge()); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.aggregations.bucket; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.search.LeafCollector; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopDocsCollector; import org.apache.lucene.search.TopScoreDocCollector; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchIllegalStateException; import org.elasticsearch.search.aggregations.BucketCollector; import org.elasticsearch.search.aggregations.LeafBucketCollector; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; /** * A specialization of {@link DeferringBucketCollector} that collects all * matches and then replays only the top scoring documents to child * aggregations. The method * {@link BestDocsDeferringCollector#createTopDocsCollector(int)} is designed to * be overridden and allows subclasses to choose a custom collector * implementation for determining the top N matches. * */ public class BestDocsDeferringCollector extends DeferringBucketCollector { final List<PerSegmentCollects> entries = new ArrayList<>(); BucketCollector deferred; TopDocsCollector<? extends ScoreDoc> tdc; boolean finished = false; private int shardSize; private PerSegmentCollects perSegCollector; private int matchedDocs; /** * Sole constructor. * * @param shardSize */ public BestDocsDeferringCollector(int shardSize) { this.shardSize = shardSize; } @Override public boolean needsScores() { return true; } /** Set the deferred collectors. */ public void setDeferredCollector(Iterable<BucketCollector> deferredCollectors) { this.deferred = BucketCollector.wrap(deferredCollectors); try { tdc = createTopDocsCollector(shardSize); } catch (IOException e) { throw new ElasticsearchException("IO error creating collector", e); } } @Override public LeafBucketCollector getLeafCollector(LeafReaderContext ctx) throws IOException { // finishLeaf(); perSegCollector = new PerSegmentCollects(ctx); entries.add(perSegCollector); // Deferring collector return new LeafBucketCollector() { @Override public void setScorer(Scorer scorer) throws IOException { perSegCollector.setScorer(scorer); } @Override public void collect(int doc, long bucket) throws IOException { perSegCollector.collect(doc); } }; } // Designed to be overridden by subclasses that may score docs by criteria // other than Lucene score protected TopDocsCollector<? extends ScoreDoc> createTopDocsCollector(int size) throws IOException { return TopScoreDocCollector.create(size); } @Override public void preCollection() throws IOException { } @Override public void postCollection() throws IOException { finished = true; } /** * Replay the wrapped collector, but only on a selection of buckets. */ @Override public void prepareSelectedBuckets(long... selectedBuckets) throws IOException { if (!finished) { throw new ElasticsearchIllegalStateException("Cannot replay yet, collection is not finished: postCollect() has not been called"); } if (selectedBuckets.length > 1) { throw new ElasticsearchIllegalStateException("Collection only supported on a single bucket"); } deferred.preCollection(); TopDocs topDocs = tdc.topDocs(); ScoreDoc[] sd = topDocs.scoreDocs; matchedDocs = sd.length; // Sort the top matches by docID for the benefit of deferred collector Arrays.sort(sd, new Comparator<ScoreDoc>() { @Override public int compare(ScoreDoc o1, ScoreDoc o2) { return o1.doc - o2.doc; } }); try { for (PerSegmentCollects perSegDocs : entries) { perSegDocs.replayRelatedMatches(sd); } // deferred.postCollection(); } catch (IOException e) { throw new ElasticsearchException("IOException collecting best scoring results", e); } deferred.postCollection(); } class PerSegmentCollects extends Scorer { private LeafReaderContext readerContext; int maxDocId = Integer.MIN_VALUE; private float currentScore; private int currentDocId = -1; private LeafCollector currentLeafCollector; PerSegmentCollects(LeafReaderContext readerContext) throws IOException { // The publisher behaviour for Reader/Scorer listeners triggers a // call to this constructor with a null scorer so we can't call // scorer.getWeight() and pass the Weight to our base class. // However, passing null seems to have no adverse effects here... super(null); this.readerContext = readerContext; currentLeafCollector = tdc.getLeafCollector(readerContext); } public void setScorer(Scorer scorer) throws IOException { currentLeafCollector.setScorer(scorer); } public void replayRelatedMatches(ScoreDoc[] sd) throws IOException { final LeafBucketCollector leafCollector = deferred.getLeafCollector(readerContext); leafCollector.setScorer(this); currentScore = 0; currentDocId = -1; if (maxDocId < 0) { return; } for (ScoreDoc scoreDoc : sd) { // Doc ids from TopDocCollector are root-level Reader so // need rebasing int rebased = scoreDoc.doc - readerContext.docBase; if ((rebased >= 0) && (rebased <= maxDocId)) { currentScore = scoreDoc.score; currentDocId = rebased; leafCollector.collect(rebased, 0); } } } @Override public float score() throws IOException { return currentScore; } @Override public int freq() throws IOException { throw new ElasticsearchException("This caching scorer implementation only implements score() and docID()"); } @Override public int docID() { return currentDocId; } @Override public int nextDoc() throws IOException { throw new ElasticsearchException("This caching scorer implementation only implements score() and docID()"); } @Override public int advance(int target) throws IOException { throw new ElasticsearchException("This caching scorer implementation only implements score() and docID()"); } @Override public long cost() { throw new ElasticsearchException("This caching scorer implementation only implements score() and docID()"); } public void collect(int docId) throws IOException { currentLeafCollector.collect(docId); maxDocId = Math.max(maxDocId, docId); } } public int getDocCount() { return matchedDocs; } }
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.checkin; import com.intellij.CommonBundle; import com.intellij.dvcs.DvcsCommitAdditionalComponent; import com.intellij.dvcs.DvcsUtil; import com.intellij.dvcs.push.ui.VcsPushDialog; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.SpellCheckingEditorCustomizationProvider; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.CheckinProjectPanel; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.*; import com.intellij.openapi.vcs.changes.ui.SelectFilePathsDialog; import com.intellij.openapi.vcs.checkin.CheckinChangeListSpecificComponent; import com.intellij.openapi.vcs.checkin.CheckinEnvironment; import com.intellij.openapi.vcs.ui.RefreshableOnComponent; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.*; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import com.intellij.vcs.log.VcsFullCommitDetails; import com.intellij.vcs.log.VcsUser; import com.intellij.vcs.log.VcsUserRegistry; import com.intellij.vcsUtil.VcsFileUtil; import com.intellij.vcsUtil.VcsUtil; import git4idea.GitUtil; import git4idea.GitVcs; import git4idea.branch.GitBranchUtil; import git4idea.commands.GitCommand; import git4idea.commands.GitSimpleHandler; import git4idea.config.GitConfigUtil; import git4idea.config.GitVcsSettings; import git4idea.config.GitVersionSpecialty; import git4idea.i18n.GitBundle; import git4idea.repo.GitRepository; import git4idea.repo.GitRepositoryFiles; import git4idea.repo.GitRepositoryManager; import git4idea.util.GitFileUtils; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; public class GitCheckinEnvironment implements CheckinEnvironment { private static final Logger log = Logger.getInstance(GitCheckinEnvironment.class.getName()); @NonNls private static final String GIT_COMMIT_MSG_FILE_PREFIX = "git-commit-msg-"; // the file name prefix for commit message file @NonNls private static final String GIT_COMMIT_MSG_FILE_EXT = ".txt"; // the file extension for commit message file private final Project myProject; public static final SimpleDateFormat COMMIT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private final VcsDirtyScopeManager myDirtyScopeManager; private final GitVcsSettings mySettings; private String myNextCommitAuthor = null; // The author for the next commit private boolean myNextCommitAmend; // If true, the next commit is amended private Boolean myNextCommitIsPushed = null; // The push option of the next commit private Date myNextCommitAuthorDate; public GitCheckinEnvironment(@NotNull Project project, @NotNull final VcsDirtyScopeManager dirtyScopeManager, final GitVcsSettings settings) { myProject = project; myDirtyScopeManager = dirtyScopeManager; mySettings = settings; } public boolean keepChangeListAfterCommit(ChangeList changeList) { return false; } @Override public boolean isRefreshAfterCommitNeeded() { return true; } @Nullable public RefreshableOnComponent createAdditionalOptionsPanel(CheckinProjectPanel panel, PairConsumer<Object, Object> additionalDataConsumer) { return new GitCheckinOptions(myProject, panel); } @Nullable public String getDefaultMessageFor(FilePath[] filesToCheckin) { LinkedHashSet<String> messages = ContainerUtil.newLinkedHashSet(); for (VirtualFile root : GitUtil.gitRoots(Arrays.asList(filesToCheckin))) { VirtualFile mergeMsg = root.findFileByRelativePath(GitRepositoryFiles.GIT_MERGE_MSG); VirtualFile squashMsg = root.findFileByRelativePath(GitRepositoryFiles.GIT_SQUASH_MSG); try { if (mergeMsg == null && squashMsg == null) { continue; } String encoding = GitConfigUtil.getCommitEncoding(myProject, root); if (mergeMsg != null) { messages.add(loadMessage(mergeMsg, encoding)); } else { messages.add(loadMessage(squashMsg, encoding)); } } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Unable to load merge message", e); } } } return DvcsUtil.joinMessagesOrNull(messages); } private static String loadMessage(@NotNull VirtualFile messageFile, @NotNull String encoding) throws IOException { return FileUtil.loadFile(new File(messageFile.getPath()), encoding); } public String getHelpId() { return null; } public String getCheckinOperationName() { return GitBundle.getString("commit.action.name"); } public List<VcsException> commit(@NotNull List<Change> changes, @NotNull String message, @NotNull NullableFunction<Object, Object> parametersHolder, Set<String> feedback) { List<VcsException> exceptions = new ArrayList<VcsException>(); Map<VirtualFile, Collection<Change>> sortedChanges = sortChangesByGitRoot(changes, exceptions); log.assertTrue(!sortedChanges.isEmpty(), "Trying to commit an empty list of changes: " + changes); for (Map.Entry<VirtualFile, Collection<Change>> entry : sortedChanges.entrySet()) { final VirtualFile root = entry.getKey(); try { File messageFile = createMessageFile(root, message); try { final Set<FilePath> added = new HashSet<FilePath>(); final Set<FilePath> removed = new HashSet<FilePath>(); for (Change change : entry.getValue()) { switch (change.getType()) { case NEW: case MODIFICATION: added.add(change.getAfterRevision().getFile()); break; case DELETED: removed.add(change.getBeforeRevision().getFile()); break; case MOVED: FilePath afterPath = change.getAfterRevision().getFile(); FilePath beforePath = change.getBeforeRevision().getFile(); added.add(afterPath); if (!GitFileUtils.shouldIgnoreCaseChange(afterPath.getPath(), beforePath.getPath())) { removed.add(beforePath); } break; default: throw new IllegalStateException("Unknown change type: " + change.getType()); } } try { try { Set<FilePath> files = new HashSet<FilePath>(); files.addAll(added); files.addAll(removed); commit(myProject, root, files, messageFile, myNextCommitAuthor, myNextCommitAmend, myNextCommitAuthorDate); } catch (VcsException ex) { PartialOperation partialOperation = isMergeCommit(ex); if (partialOperation == PartialOperation.NONE) { throw ex; } if (!mergeCommit(myProject, root, added, removed, messageFile, myNextCommitAuthor, exceptions, partialOperation)) { throw ex; } } } finally { if (!messageFile.delete()) { log.warn("Failed to remove temporary file: " + messageFile); } } } catch (VcsException e) { exceptions.add(cleanupExceptionText(e)); } } catch (IOException ex) { //noinspection ThrowableInstanceNeverThrown exceptions.add(new VcsException("Creation of commit message file failed", ex)); } } if (myNextCommitIsPushed != null && myNextCommitIsPushed.booleanValue() && exceptions.isEmpty()) { GitRepositoryManager manager = GitUtil.getRepositoryManager(myProject); Collection<GitRepository> repositories = GitUtil.getRepositoriesFromRoots(manager, sortedChanges.keySet()); final List<GitRepository> preselectedRepositories = ContainerUtil.newArrayList(repositories); UIUtil.invokeLaterIfNeeded(new Runnable() { public void run() { new VcsPushDialog(myProject, preselectedRepositories, GitBranchUtil.getCurrentRepository(myProject)).show(); } }); } return exceptions; } @NotNull private static VcsException cleanupExceptionText(VcsException original) { String msg = original.getMessage(); msg = GitUtil.cleanupErrorPrefixes(msg); final String DURING_EXECUTING_SUFFIX = GitSimpleHandler.DURING_EXECUTING_ERROR_MESSAGE; int suffix = msg.indexOf(DURING_EXECUTING_SUFFIX); if (suffix > 0) { msg = msg.substring(0, suffix); } return new VcsException(msg.trim(), original.getCause()); } public List<VcsException> commit(List<Change> changes, String preparedComment) { return commit(changes, preparedComment, FunctionUtil.nullConstant(), null); } /** * Preform a merge commit * * * @param project a project * @param root a vcs root * @param added added files * @param removed removed files * @param messageFile a message file for commit * @param author an author * @param exceptions the list of exceptions to report * @param partialOperation * @return true if merge commit was successful */ private static boolean mergeCommit(final Project project, final VirtualFile root, final Set<FilePath> added, final Set<FilePath> removed, final File messageFile, final String author, List<VcsException> exceptions, @NotNull final PartialOperation partialOperation) { HashSet<FilePath> realAdded = new HashSet<FilePath>(); HashSet<FilePath> realRemoved = new HashSet<FilePath>(); // perform diff GitSimpleHandler diff = new GitSimpleHandler(project, root, GitCommand.DIFF); diff.setSilent(true); diff.setStdoutSuppressed(true); diff.addParameters("--diff-filter=ADMRUX", "--name-status", "HEAD"); diff.endOptions(); String output; try { output = diff.run(); } catch (VcsException ex) { exceptions.add(ex); return false; } String rootPath = root.getPath(); for (StringTokenizer lines = new StringTokenizer(output, "\n", false); lines.hasMoreTokens();) { String line = lines.nextToken().trim(); if (line.length() == 0) { continue; } String[] tk = line.split("\t"); switch (tk[0].charAt(0)) { case 'M': case 'A': realAdded.add(VcsUtil.getFilePath(rootPath + "/" + tk[1])); break; case 'D': realRemoved.add(VcsUtil.getFilePathForDeletedFile(rootPath + "/" + tk[1], false)); break; default: throw new IllegalStateException("Unexpected status: " + line); } } realAdded.removeAll(added); realRemoved.removeAll(removed); if (realAdded.size() != 0 || realRemoved.size() != 0) { final List<FilePath> files = new ArrayList<FilePath>(); files.addAll(realAdded); files.addAll(realRemoved); final Ref<Boolean> mergeAll = new Ref<Boolean>(); try { GuiUtils.runOrInvokeAndWait(new Runnable() { public void run() { String message = GitBundle.message("commit.partial.merge.message", partialOperation.getName()); SelectFilePathsDialog dialog = new SelectFilePathsDialog(project, files, message, null, "Commit All Files", CommonBundle.getCancelButtonText(), false); dialog.setTitle(GitBundle.getString("commit.partial.merge.title")); dialog.show(); mergeAll.set(dialog.isOK()); } }); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException("Unable to invoke a message box on AWT thread", ex); } if (!mergeAll.get()) { return false; } // update non-indexed files if (!updateIndex(project, root, realAdded, realRemoved, exceptions)) { return false; } for (FilePath f : realAdded) { VcsDirtyScopeManager.getInstance(project).fileDirty(f); } for (FilePath f : realRemoved) { VcsDirtyScopeManager.getInstance(project).fileDirty(f); } } // perform merge commit try { GitSimpleHandler handler = new GitSimpleHandler(project, root, GitCommand.COMMIT); handler.setStdoutSuppressed(false); handler.addParameters("-F", messageFile.getAbsolutePath()); if (author != null) { handler.addParameters("--author=" + author); } handler.endOptions(); handler.run(); GitRepositoryManager manager = GitUtil.getRepositoryManager(project); manager.updateRepository(root); } catch (VcsException ex) { exceptions.add(ex); return false; } return true; } /** * Check if commit has failed due to unfinished merge or cherry-pick. * * * @param ex an exception to examine * @return true if exception means that there is a partial commit during merge */ private static PartialOperation isMergeCommit(final VcsException ex) { String message = ex.getMessage(); if (message.contains("fatal: cannot do a partial commit during a merge")) { return PartialOperation.MERGE; } if (message.contains("fatal: cannot do a partial commit during a cherry-pick")) { return PartialOperation.CHERRY_PICK; } return PartialOperation.NONE; } /** * Update index (delete and remove files) * * @param project the project * @param root a vcs root * @param added added/modified files to commit * @param removed removed files to commit * @param exceptions a list of exceptions to update * @return true if index was updated successfully */ private static boolean updateIndex(final Project project, final VirtualFile root, final Collection<FilePath> added, final Collection<FilePath> removed, final List<VcsException> exceptions) { boolean rc = true; if (!added.isEmpty()) { try { GitFileUtils.addPaths(project, root, added); } catch (VcsException ex) { exceptions.add(ex); rc = false; } } if (!removed.isEmpty()) { try { GitFileUtils.delete(project, root, removed, "--ignore-unmatch"); } catch (VcsException ex) { exceptions.add(ex); rc = false; } } return rc; } /** * Create a file that contains the specified message * * @param root a git repository root * @param message a message to write * @return a file reference * @throws IOException if file cannot be created */ private File createMessageFile(VirtualFile root, final String message) throws IOException { // filter comment lines File file = FileUtil.createTempFile(GIT_COMMIT_MSG_FILE_PREFIX, GIT_COMMIT_MSG_FILE_EXT); file.deleteOnExit(); @NonNls String encoding = GitConfigUtil.getCommitEncoding(myProject, root); Writer out = new OutputStreamWriter(new FileOutputStream(file), encoding); try { out.write(message); } finally { out.close(); } return file; } public List<VcsException> scheduleMissingFileForDeletion(List<FilePath> files) { ArrayList<VcsException> rc = new ArrayList<VcsException>(); Map<VirtualFile, List<FilePath>> sortedFiles; try { sortedFiles = GitUtil.sortFilePathsByGitRoot(files); } catch (VcsException e) { rc.add(e); return rc; } for (Map.Entry<VirtualFile, List<FilePath>> e : sortedFiles.entrySet()) { try { final VirtualFile root = e.getKey(); GitFileUtils.delete(myProject, root, e.getValue()); markRootDirty(root); } catch (VcsException ex) { rc.add(ex); } } return rc; } private static void commit(Project project, VirtualFile root, Collection<FilePath> files, File message, final String nextCommitAuthor, boolean nextCommitAmend, Date nextCommitAuthorDate) throws VcsException { boolean amend = nextCommitAmend; for (List<String> paths : VcsFileUtil.chunkPaths(root, files)) { GitSimpleHandler handler = new GitSimpleHandler(project, root, GitCommand.COMMIT); handler.setStdoutSuppressed(false); if (amend) { handler.addParameters("--amend"); } else { amend = true; } handler.addParameters("--only", "-F", message.getAbsolutePath()); if (nextCommitAuthor != null) { handler.addParameters("--author=" + nextCommitAuthor); } if (nextCommitAuthorDate != null) { handler.addParameters("--date", COMMIT_DATE_FORMAT.format(nextCommitAuthorDate)); } handler.endOptions(); handler.addParameters(paths); handler.run(); } if (!project.isDisposed()) { GitRepositoryManager manager = GitUtil.getRepositoryManager(project); manager.updateRepository(root); } } public List<VcsException> scheduleUnversionedFilesForAddition(List<VirtualFile> files) { ArrayList<VcsException> rc = new ArrayList<VcsException>(); Map<VirtualFile, List<VirtualFile>> sortedFiles; try { sortedFiles = GitUtil.sortFilesByGitRoot(files); } catch (VcsException e) { rc.add(e); return rc; } for (Map.Entry<VirtualFile, List<VirtualFile>> e : sortedFiles.entrySet()) { try { final VirtualFile root = e.getKey(); GitFileUtils.addFiles(myProject, root, e.getValue()); markRootDirty(root); } catch (VcsException ex) { rc.add(ex); } } return rc; } private enum PartialOperation { NONE("none"), MERGE("merge"), CHERRY_PICK("cherry-pick"); private final String myName; PartialOperation(String name) { myName = name; } String getName() { return myName; } } private static Map<VirtualFile, Collection<Change>> sortChangesByGitRoot(@NotNull List<Change> changes, List<VcsException> exceptions) { Map<VirtualFile, Collection<Change>> result = new HashMap<VirtualFile, Collection<Change>>(); for (Change change : changes) { final ContentRevision afterRevision = change.getAfterRevision(); final ContentRevision beforeRevision = change.getBeforeRevision(); // nothing-to-nothing change cannot happen. assert beforeRevision != null || afterRevision != null; // note that any path will work, because changes could happen within single vcs root final FilePath filePath = afterRevision != null ? afterRevision.getFile() : beforeRevision.getFile(); final VirtualFile vcsRoot; try { // the parent paths for calculating roots in order to account for submodules that contribute // to the parent change. The path "." is never is valid change, so there should be no problem // with it. vcsRoot = GitUtil.getGitRoot(filePath.getParentPath()); } catch (VcsException e) { exceptions.add(e); continue; } Collection<Change> changeList = result.get(vcsRoot); if (changeList == null) { changeList = new ArrayList<Change>(); result.put(vcsRoot, changeList); } changeList.add(change); } return result; } private void markRootDirty(final VirtualFile root) { // Note that the root is invalidated because changes are detected per-root anyway. // Otherwise it is not possible to detect moves. myDirtyScopeManager.dirDirtyRecursively(root); } public void reset() { myNextCommitAmend = false; myNextCommitAuthor = null; myNextCommitIsPushed = null; myNextCommitAuthorDate = null; } private class GitCheckinOptions extends DvcsCommitAdditionalComponent implements CheckinChangeListSpecificComponent { private final GitVcs myVcs; private final ComboBox myAuthorField; @Nullable private Date myAuthorDate; GitCheckinOptions(@NotNull final Project project, @NotNull CheckinProjectPanel panel) { super(project, panel); myVcs = GitVcs.getInstance(project); final Insets insets = new Insets(2, 2, 2, 2); // add authors drop down GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.WEST; c.insets = insets; final JLabel authorLabel = new JLabel(GitBundle.message("commit.author")); myPanel.add(authorLabel, c); c = new GridBagConstraints(); c.anchor = GridBagConstraints.CENTER; c.insets = insets; c.gridx = 1; c.gridy = 0; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; Set<String> authors = new HashSet<String>(getUsersList(project)); ContainerUtil.addAll(authors, mySettings.getCommitAuthors()); List<String> list = new ArrayList<String>(authors); Collections.sort(list); myAuthorField = new ComboBox(ArrayUtil.toObjectArray(list)) { @Override public void addNotify() { super.addNotify(); // adding in addNotify to make sure the editor is ready for further customization StringComboboxEditor comboboxEditor = new StringComboboxEditor(project, FileTypes.PLAIN_TEXT, myAuthorField, true); myAuthorField.setEditor(comboboxEditor); EditorEx editor = (EditorEx)comboboxEditor.getEditor(); assert editor != null; EditorCustomization customization = SpellCheckingEditorCustomizationProvider.getInstance().getDisabledCustomization(); if (customization != null) { customization.customize(editor); } } }; myAuthorField.setRenderer(new ListCellRendererWrapper<String>() { @Override public void customize(JList list, String value, int index, boolean selected, boolean hasFocus) { if (value != null) { setText(StringUtil.trimLog(value, 100)); } } }); myAuthorField.setMinimumAndPreferredWidth(100); myAuthorField.setEditable(true); authorLabel.setLabelFor(myAuthorField); myAuthorField.setToolTipText(GitBundle.getString("commit.author.tooltip")); myPanel.add(myAuthorField, c); } @Override @NotNull protected Set<VirtualFile> getVcsRoots(@NotNull Collection<FilePath> filePaths) { return GitUtil.gitRoots(filePaths); } @Nullable @Override protected String getLastCommitMessage(@NotNull VirtualFile root) throws VcsException { GitSimpleHandler h = new GitSimpleHandler(myProject, root, GitCommand.LOG); h.addParameters("--max-count=1"); String formatPattern; if (GitVersionSpecialty.STARTED_USING_RAW_BODY_IN_FORMAT.existsIn(myVcs.getVersion())) { formatPattern = "%B"; } else { // only message: subject + body; "%-b" means that preceding line-feeds will be deleted if the body is empty // %s strips newlines from subject; there is no way to work around it before 1.7.2 with %B (unless parsing some fixed format) formatPattern = "%s%n%n%-b"; } h.addParameters("--pretty=format:" + formatPattern); return h.run(); } @NotNull private List<String> getUsersList(@NotNull Project project) { VcsUserRegistry userRegistry = ServiceManager.getService(project, VcsUserRegistry.class); return ContainerUtil.map(userRegistry.getUsers(), new Function<VcsUser, String>() { @Override public String fun(VcsUser user) { return user.getName() + " <" + user.getEmail() + ">"; } }); } @Override public void refresh() { super.refresh(); myAuthorField.setSelectedItem(null); myAuthorDate = null; reset(); } @Override public void saveState() { String author = (String)myAuthorField.getEditor().getItem(); if (StringUtil.isEmptyOrSpaces(author)) { myNextCommitAuthor = null; } else { myNextCommitAuthor = GitCommitAuthorCorrector.correct(author); mySettings.saveCommitAuthor(myNextCommitAuthor); } myNextCommitAmend = myAmend.isSelected(); myNextCommitAuthorDate = myAuthorDate; } @Override public void restoreState() { refresh(); } @Override public void onChangeListSelected(LocalChangeList list) { Object data = list.getData(); if (data instanceof VcsFullCommitDetails) { VcsFullCommitDetails commit = (VcsFullCommitDetails)data; String author = String.format("%s <%s>", commit.getAuthor().getName(), commit.getAuthor().getEmail()); myAuthorField.setSelectedItem(author); myAuthorDate = new Date(commit.getAuthorTime()); } else { myAuthorField.setSelectedItem(null); myAuthorDate = null; } } } public void setNextCommitIsPushed(Boolean nextCommitIsPushed) { myNextCommitIsPushed = nextCommitIsPushed; } }
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.apimgt.migration.util; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.util.AXIOMUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.migration.APIMigrationException; import org.wso2.carbon.apimgt.migration.client._110Specific.dto.SynapseDTO; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.registry.core.RegistryConstants; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.utils.CarbonUtils; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; public class ResourceUtil { private static final Log log = LogFactory.getLog(ResourceUtil.class); private static boolean[] validConsumerKeyChars = new boolean[128]; static { char[] validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".toCharArray(); for (char validChar : validChars) { validConsumerKeyChars[validChar] = true; } } /** * location for the swagger 1.2 resources * * @param apiName api name * @param apiVersion api version * @param apiProvider api provider * @return swagger v1.2 location */ public static String getSwagger12ResourceLocation(String apiName, String apiVersion, String apiProvider) { return APIConstants.API_DOC_LOCATION + RegistryConstants.PATH_SEPARATOR + apiName + '-' + apiVersion + '-' + apiProvider + RegistryConstants.PATH_SEPARATOR + APIConstants.API_DOC_1_2_LOCATION; } /** * location for the swagger v2.0 resources * * @param apiName name of the API * @param apiVersion version of the API * @param apiProvider provider name of the API * @return swagger v2.0 resource location as a string */ public static String getSwagger2ResourceLocation(String apiName, String apiVersion, String apiProvider) { return APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiProvider + RegistryConstants.PATH_SEPARATOR + apiName + RegistryConstants.PATH_SEPARATOR + apiVersion + RegistryConstants.PATH_SEPARATOR + "swagger.json"; } /** * location for the rxt of the api * * @param apiName name of the API * @param apiVersion version of the API * @param apiProvider provider name of the API * @return rxt location for the api as a string */ public static String getRxtResourceLocation(String apiName, String apiVersion, String apiProvider) { return APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiProvider + RegistryConstants.PATH_SEPARATOR + apiName + RegistryConstants.PATH_SEPARATOR + apiVersion + RegistryConstants.PATH_SEPARATOR + "api"; } /** * To handle exceptions * * @param msg error message * @throws APIMigrationException */ public static void handleException(String msg, Throwable e) throws APIMigrationException { log.error(msg, e); throw new APIMigrationException(msg, e); } /** * To copy a new sequence to existing ones * * @param sequenceDirectoryFilePath sequence directory * @param sequenceName sequence name * @throws APIMigrationException */ public static void copyNewSequenceToExistingSequences(String sequenceDirectoryFilePath, String sequenceName) throws APIMigrationException { try { String namespace = "http://ws.apache.org/ns/synapse"; String filePath = sequenceDirectoryFilePath + sequenceName + ".xml"; File sequenceFile = new File(filePath); if (!sequenceFile.exists()) { log.debug("Sequence file " + sequenceName + ".xml does not exist"); return; } DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(filePath); Node sequence = doc.getElementsByTagName("sequence").item(0); Element corsSequence = doc.createElementNS(namespace, "sequence"); corsSequence.setAttribute("key", "_cors_request_handler_"); boolean available = false; for (int i = 0; i < sequence.getChildNodes().getLength(); i++) { Node tempNode = sequence.getChildNodes().item(i); if (tempNode.getNodeType() == Node.ELEMENT_NODE &&"sequence".equals(tempNode.getLocalName()) && "_cors_request_handler_".equals(tempNode.getAttributes().getNamedItem("key").getTextContent())) { available = true; break; } } if (!available) { if ("_throttle_out_handler_".equals(sequenceName)) { sequence.appendChild(corsSequence); } else if ("_auth_failure_handler_".equals(sequenceName)) { sequence.appendChild(corsSequence); } else { sequence.insertBefore(corsSequence, doc.getElementsByTagName("send").item(0)); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(filePath)); transformer.transform(source, result); } } catch (ParserConfigurationException e) { handleException("Could not initiate Document Builder.", e); } catch (TransformerConfigurationException e) { handleException("Could not initiate TransformerFactory Builder.", e); } catch (TransformerException e) { handleException("Could not transform the source.", e); } catch (SAXException e) { handleException("SAX exception occurred while parsing the file.", e); } catch (IOException e) { handleException("IO Exception occurred. Please check the file.", e); } } /** * To update synapse API * * @param document XML document object * @param file synapse file * @throws APIMigrationException */ public static void updateSynapseAPI(Document document, File file) throws APIMigrationException { try { updateAPIAttributes(document); updateHandlers(document); updateResources(document); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(file); transformer.transform(source, result); } catch (TransformerConfigurationException e) { handleException("Could not initiate TransformerFactory Builder.", e); } catch (TransformerException e) { handleException("Could not transform the source.", e); } } private static void updateAPIAttributes(Document document) { Element apiElement = document.getDocumentElement(); String versionType = apiElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_VERSION_TYPE); if (Constants.SYNAPSE_API_VALUE_VERSION_TYPE_URL.equals(versionType)) { String context = apiElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_CONTEXT); String version = apiElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_VERSION); context = context + '/' + version; apiElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_CONTEXT, context); apiElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_VERSION_TYPE, Constants.SYNAPSE_API_VALUE_VERSION_TYPE_CONTEXT); } } private static void updateHandlers(Document document) { Element handlersElement = (Element) document.getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_HANDLERS).item(0); // For blocked APIs, the Handlers element would not be there. if(handlersElement != null) { NodeList handlerNodes = handlersElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_HANDLER); for (int i = 0; i < handlerNodes.getLength(); ++i) { Element handler = (Element) handlerNodes.item(i); String className = handler.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_CLASS); if (Constants.SYNAPSE_API_VALUE_CORS_HANDLER.equals(className)) { handlersElement.removeChild(handler); break; } } } // Find the inSequence Element inSequenceElement = (Element) document.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_INSEQUENCE).item(0); NodeList sendElements = inSequenceElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_SEND); Element corsHandler = document.createElementNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_HANDLER); corsHandler.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_CLASS, Constants.SYNAPSE_API_VALUE_CORS_HANDLER); Element property = document.createElementNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_PROPERTY); property.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME, Constants.SYNAPSE_API_VALUE_INLINE); // If handlers element is null, that means this is a blocked API. Hence we need to add INLINE as the value. if (0 < sendElements.getLength() && handlersElement != null) { property.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_VALUE, Constants.SYNAPSE_API_VALUE_ENPOINT); } else { property.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_VALUE, Constants.SYNAPSE_API_VALUE_INLINE_UPPERCASE); } corsHandler.appendChild(property); // Handlers element is null for BLOCKED APIs. Therefore if the handlers element is null, we create a new // element and add the CORS handler because that is the default behavior in API Manager 1.9.x if (handlersElement != null) { handlersElement.insertBefore(corsHandler, handlersElement.getFirstChild()); }else{ handlersElement = document.createElementNS(Constants.SYNAPSE_API_XMLNS, Constants .SYNAPSE_API_ELEMENT_HANDLERS); handlersElement.appendChild(corsHandler); // document.getFirstChild() == api element document.getFirstChild().appendChild(handlersElement); } } private static void updateResources(Document document) throws APIMigrationException { NodeList resourceNodes = document.getElementsByTagName("resource"); for (int i = 0; i < resourceNodes.getLength(); i++) { Element resourceElement = (Element) resourceNodes.item(i); updateInSequence(resourceElement, document); updateOutSequence(resourceElement, document); } } private static void updateInSequence(Element resourceElement, Document doc) { // Find the inSequence Element inSequenceElement = (Element) resourceElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_INSEQUENCE).item(0); // Find the property element in the inSequence NodeList properties = inSequenceElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_PROPERTY); boolean isBackEndRequestTimeSet = false; for (int i = 0; i < properties.getLength(); ++i) { Element propertyElement = (Element) properties.item(i); if (propertyElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME)) { if (Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME.equals(propertyElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME))) { isBackEndRequestTimeSet = true; break; } } } if (!isBackEndRequestTimeSet) { NodeList filters = inSequenceElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_FILTER); for (int j = 0; j < filters.getLength(); ++j) { Element filterElement = (Element) filters.item(j); if (Constants.SYNAPSE_API_VALUE_AM_KEY_TYPE.equals(filterElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_SOURCE))) { // Only one <then> element can exist in filter mediator Element thenElement = (Element) filterElement.getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_THEN).item(0); // At least one <send> element must exist as a child of <then> element Element sendElement = (Element) thenElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_SEND).item(0); Element propertyElement = doc.createElementNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_PROPERTY); propertyElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME, Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME); propertyElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_EXPRESSION, Constants.SYNAPSE_API_VALUE_EXPRESSION); thenElement.insertBefore(propertyElement, sendElement); } } } } private static void updateOutSequence(Element resourceElement, Document doc) { // Find the outSequence Element outSequenceElement = (Element) resourceElement.getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_OUTSEQUENCE).item(0); // For blocked APIs, there is no out sequence. Hence we are returning. if(outSequenceElement == null){ return; } NodeList classNodes = outSequenceElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_CLASS); boolean isResponseHandlerSet = false; for (int i = 0; i < classNodes.getLength(); ++i) { Element classElement = (Element) classNodes.item(i); if (Constants.SYNAPSE_API_VALUE_RESPONSE_HANDLER.equals(classElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME))) { isResponseHandlerSet = true; break; } } if (!isResponseHandlerSet) { // There must be at least one <send> element for an outSequence Element sendElement = (Element) outSequenceElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_SEND).item(0); Element classElement = doc.createElementNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_CLASS); classElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME, Constants.SYNAPSE_API_VALUE_RESPONSE_HANDLER); classElement.removeAttribute(Constants.SYNAPSE_API_ATTRIBUTE_XMLNS); outSequenceElement.insertBefore(classElement, sendElement); } } public static String getResourceContent(Object content) { return new String((byte[]) content, Charset.defaultCharset()); } public static Document buildDocument(String xmlContent, String fileName) throws APIMigrationException { Document doc = null; try { DocumentBuilder docBuilder = getDocumentBuilder(fileName); doc = docBuilder.parse(new InputSource(new ByteArrayInputStream(xmlContent.getBytes(Charset.defaultCharset())))); doc.getDocumentElement().normalize(); } catch (SAXException e) { ResourceUtil.handleException("Error occurred while parsing the " + fileName + " xml document", e); } catch (IOException e) { ResourceUtil.handleException("Error occurred while reading the " + fileName + " xml document", e); } return doc; } public static Document buildDocument(InputStream inputStream, String fileName) throws APIMigrationException { Document doc = null; try { DocumentBuilder docBuilder = getDocumentBuilder(fileName); doc = docBuilder.parse(new InputSource(inputStream)); doc.getDocumentElement().normalize(); } catch (SAXException e) { ResourceUtil.handleException("Error occurred while parsing the " + fileName + " xml document", e); } catch (IOException e) { ResourceUtil.handleException("Error occurred while reading the " + fileName + " xml document", e); } return doc; } public static Document buildDocument(File file, String fileName) throws APIMigrationException { Document doc = null; try { DocumentBuilder docBuilder = getDocumentBuilder(fileName); doc = docBuilder.parse(file); doc.getDocumentElement().normalize(); } catch (SAXException e) { ResourceUtil.handleException("Error occurred while parsing the " + fileName + " xml document", e); } catch (IOException e) { ResourceUtil.handleException("Error occurred while reading the " + fileName + " xml document", e); } return doc; } private static DocumentBuilder getDocumentBuilder(String fileName) throws APIMigrationException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); DocumentBuilder docBuilder = null; try { docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); docBuilder = docFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { ResourceUtil.handleException("Error occurred while trying to build the " + fileName + " xml document", e); } return docBuilder; } public static void transformXMLDocument(Document document, File file) { document.getDocumentElement().normalize(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, Charset.defaultCharset().toString()); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(document), new StreamResult(file)); } catch (TransformerConfigurationException e) { log.error("Transformer configuration error encountered while transforming file " + file.getName(), e); } catch (TransformerException e) { log.error("Transformer error encountered while transforming file " + file.getName(), e); } } public static String getApiPath(int tenantID, String tenantDomain) { if (log.isDebugEnabled()) { log.debug("Get api synapse files for tenant " + tenantID + '(' + tenantDomain + ')'); } String apiFilePath; if (tenantID != MultitenantConstants.SUPER_TENANT_ID) { apiFilePath = CarbonUtils.getCarbonTenantsDirPath() + File.separatorChar + tenantID + File.separatorChar + "synapse-configs" + File.separatorChar + "default" + File.separatorChar + "api"; } else { apiFilePath = CarbonUtils.getCarbonRepository() + "synapse-configs" + File.separatorChar + "default" + File.separatorChar +"api"; } if (log.isDebugEnabled()) { log.debug("Path of api folder of tenant : " + tenantDomain + " is : "+ apiFilePath); } return apiFilePath; } public static List<SynapseDTO> getVersionedAPIs(String apiFilePath) { File apiFiles = new File(apiFilePath); File[] files = apiFiles.listFiles(); List<SynapseDTO> versionedAPIs = new ArrayList<>(); if (files != null) { for (File file : files) { try { if (!file.getName().endsWith(".xml")) { // Ignore non xml files continue; } Document doc = buildDocument(file, file.getName()); Element rootElement = doc.getDocumentElement(); // Ensure that we skip internal apis such as '_TokenAPI_.xml' and apis // that represent default versions if (Constants.SYNAPSE_API_ROOT_ELEMENT.equals(rootElement.getNodeName()) && rootElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_VERSION)) { if (log.isDebugEnabled()) { log.debug("API file name : " + file.getName()); } SynapseDTO synapseConfig = new SynapseDTO(doc, file); versionedAPIs.add(synapseConfig); } } catch (APIMigrationException e) { log.error("Error when passing file " + file.getName(), e); } } } return versionedAPIs; } public static boolean isConsumerKeyValid(String consumerKey) { for (int i = 0; i < consumerKey.length(); ++i) { char consumerKeyChar = consumerKey.charAt(i); if (validConsumerKeyChars.length <= consumerKeyChar) { return false; } if (!validConsumerKeyChars[consumerKeyChar]) { return false; } } return true; } /** * Returns the content configuration from a RXT file * @param payload * @return content element * @throws RegistryException */ public static String getArtifactUIContentFromConfig(String payload) throws RegistryException { try { OMElement element = AXIOMUtil.stringToOM(payload); element.build(); OMElement content = element.getFirstChildWithName(new QName("content")); if(content != null) { return content.toString(); } else { return null; } } catch (Exception e) { String message = "Unable to parse the XML configuration. Please validate the XML configuration"; log.error(message, e); throw new RegistryException(message, e); } } }
/** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> * University of Zurich, Switzerland. * <p> */ package org.olat.presentation.course.nodes.co; import org.olat.lms.commons.ModuleConfiguration; import org.olat.lms.course.ICourse; import org.olat.lms.course.assessment.AssessmentHelper; import org.olat.lms.course.condition.Condition; import org.olat.lms.course.nodes.COCourseNode; import org.olat.lms.course.run.userview.UserCourseEnvironment; import org.olat.presentation.course.condition.ConditionEditController; import org.olat.presentation.course.editor.NodeEditController; import org.olat.presentation.framework.core.UserRequest; import org.olat.presentation.framework.core.components.Component; import org.olat.presentation.framework.core.components.panel.Panel; import org.olat.presentation.framework.core.components.tabbedpane.TabbedPane; import org.olat.presentation.framework.core.components.velocity.VelocityContainer; import org.olat.presentation.framework.core.control.Controller; import org.olat.presentation.framework.core.control.ControllerEventListener; import org.olat.presentation.framework.core.control.WindowControl; import org.olat.presentation.framework.core.control.creator.ControllerCreator; import org.olat.presentation.framework.core.control.generic.popup.PopupBrowserWindow; import org.olat.presentation.framework.core.control.generic.tabbable.ActivateableTabbableDefaultController; import org.olat.presentation.framework.layout.fullWebApp.LayoutMain3ColsController; import org.olat.presentation.framework.layout.fullWebApp.popup.BaseFullWebappPopupLayoutFactory; import org.olat.presentation.group.learn.GroupAndAreaSelectController; import org.olat.system.event.Event; /** * Description:<BR/> * Edit controller for the contact form course building block Initial Date: Oct 13, 2004 * * @author Felix Jost */ public class COEditController extends ActivateableTabbableDefaultController implements ControllerEventListener { public static final String PANE_TAB_COCONFIG = "pane.tab.coconfig"; private static final String PANE_TAB_ACCESSIBILITY = "pane.tab.accessibility"; private static final String[] paneKeys = { PANE_TAB_COCONFIG, PANE_TAB_ACCESSIBILITY }; /** config key: to email addresses to be extracted from specified groups */ public static final String CONFIG_KEY_EMAILTOGROUPS = "emailToGroups"; /** config key: to email addresses to be extracted from specified learn areas */ public static final String CONFIG_KEY_EMAILTOAREAS = "emailToAreas"; /** config key: email goes to partipiciants */ public static final String CONFIG_KEY_EMAILTOPARTICIPANTS = "emailtToPartips"; /** config key: email goes to coaches */ public static final String CONFIG_KEY_EMAILTOCOACHES = "emailToCoaches"; /** config key: to email address */ public static final String CONFIG_KEY_EMAILTOADRESSES = "emailToAdresses"; /** config key: default subject text */ public static final String CONFIG_KEY_MSUBJECT_DEFAULT = "mSubjectDefault"; /** config key: default body text */ public static final String CONFIG_KEY_MBODY_DEFAULT = "mBodyDefault"; private static final String JSELEMENTID = "bel_"; private final ModuleConfiguration moduleConfiguration; private final VelocityContainer myContent; private final Panel main; private final COConfigForm configForm; private final COCourseNode courseNode; private final ConditionEditController accessibilityCondContr; private final ICourse course; private GroupAndAreaSelectController selectGroupsCtr; private GroupAndAreaSelectController selectAreasCtr; private TabbedPane myTabbedPane; /** * Constructor for a contact form edit controller * * @param config * @param ureq * @param coCourseNode * @param course */ public COEditController(final ModuleConfiguration config, final UserRequest ureq, final WindowControl wControl, final COCourseNode coCourseNode, final ICourse course, final UserCourseEnvironment euce) { super(ureq, wControl); this.moduleConfiguration = config; resolveModuleConfigurationIssues(moduleConfiguration); this.courseNode = coCourseNode; this.course = course; main = new Panel("coeditpanel"); myContent = this.createVelocityContainer("edit"); configForm = new COConfigForm(ureq, wControl, config, euce); configForm.addControllerListener(this); myContent.put("configForm", configForm.getInitialComponent()); // not needed: setInitialComponent(myContent); // Accessibility precondition final Condition accessCondition = courseNode.getPreConditionAccess(); accessibilityCondContr = new ConditionEditController(ureq, getWindowControl(), course.getCourseEnvironment().getCourseGroupManager(), accessCondition, "accessabilityConditionForm", AssessmentHelper.getAssessableNodes(course.getEditorTreeModel(), coCourseNode), euce); this.listenTo(accessibilityCondContr); main.setContent(myContent); } /** */ @Override protected void event(final UserRequest ureq, final Component source, final Event event) { // } /** */ @Override protected void event(final UserRequest ureq, final Controller source, final Event event) { if (source == accessibilityCondContr) { if (event == Event.CHANGED_EVENT) { final Condition cond = accessibilityCondContr.getCondition(); courseNode.setPreConditionAccess(cond); fireEvent(ureq, NodeEditController.NODECONFIG_CHANGED_EVENT); } } else if (source == configForm) { // those must be links if (event == Event.CANCELLED_EVENT) { return; } else if (event == Event.DONE_EVENT) { moduleConfiguration.set(CONFIG_KEY_EMAILTOGROUPS, configForm.getEmailGroups()); moduleConfiguration.set(CONFIG_KEY_EMAILTOAREAS, configForm.getEmailAreas()); moduleConfiguration.setBooleanEntry(CONFIG_KEY_EMAILTOCOACHES, configForm.sendToCoaches()); moduleConfiguration.setBooleanEntry(CONFIG_KEY_EMAILTOPARTICIPANTS, configForm.sendToPartips()); moduleConfiguration.set(CONFIG_KEY_EMAILTOADRESSES, configForm.getEmailList()); moduleConfiguration.set(CONFIG_KEY_MSUBJECT_DEFAULT, configForm.getMSubject()); moduleConfiguration.set(CONFIG_KEY_MBODY_DEFAULT, configForm.getMBody()); fireEvent(ureq, NodeEditController.NODECONFIG_CHANGED_EVENT); return; } else if (event.getCommand().equals("popupchoosegroups")) { // open a controller in a new window which only results in sending back // javascript // get preselected groups final String groups = (String) moduleConfiguration.get(CONFIG_KEY_EMAILTOGROUPS); // get group select controller final ControllerCreator ctrlCreator = new ControllerCreator() { @Override public Controller createController(final UserRequest lureq, final WindowControl lwControl) { selectGroupsCtr = new GroupAndAreaSelectController(course, lureq, lwControl, course.getCourseEnvironment().getCourseGroupManager(), GroupAndAreaSelectController.TYPE_GROUP, groups, JSELEMENTID + "popupchoosegroups" + configForm.hashCode()); // use a one-column main layout // disposed in dispose method of COEditController! final LayoutMain3ColsController layoutCtr = new LayoutMain3ColsController(lureq, lwControl, null, null, selectGroupsCtr.getInitialComponent(), "null"); return layoutCtr; } }; // wrap the content controller into a full header layout final ControllerCreator layoutCtrlr = BaseFullWebappPopupLayoutFactory.createAuthMinimalPopupLayout(ureq, ctrlCreator); // open in new browser window final PopupBrowserWindow pbw = getWindowControl().getWindowBackOffice().getWindowManager().createNewPopupBrowserWindowFor(ureq, layoutCtrlr); pbw.open(ureq); // } else if (event.getCommand().equals("popupchooseareas")) { // open a controller in a new window which only results in sending back // javascript // get preselected areas final String areas = (String) moduleConfiguration.get(CONFIG_KEY_EMAILTOAREAS); // get area select controller final ControllerCreator ctrlCreator = new ControllerCreator() { @Override public Controller createController(final UserRequest lureq, final WindowControl lwControl) { selectAreasCtr = new GroupAndAreaSelectController(course, lureq, lwControl, course.getCourseEnvironment().getCourseGroupManager(), GroupAndAreaSelectController.TYPE_AREA, areas, JSELEMENTID + "popupchooseareas" + configForm.hashCode()); // use a one-column main layout // disposed in dispose method of COEditController! final LayoutMain3ColsController layoutCtr = new LayoutMain3ColsController(lureq, lwControl, null, null, selectAreasCtr.getInitialComponent(), null); return layoutCtr; } }; // wrap the content controller into a full header layout final ControllerCreator layoutCtrlr = BaseFullWebappPopupLayoutFactory.createAuthMinimalPopupLayout(ureq, ctrlCreator); // open in new browser window final PopupBrowserWindow pbw = getWindowControl().getWindowBackOffice().getWindowManager().createNewPopupBrowserWindowFor(ureq, layoutCtrlr); pbw.open(ureq); // } } } /** */ @Override public void addTabs(final TabbedPane tabbedPane) { myTabbedPane = tabbedPane; tabbedPane.addTab(translate(PANE_TAB_ACCESSIBILITY), accessibilityCondContr.getWrappedDefaultAccessConditionVC(translate("condition.accessibility.title"))); tabbedPane.addTab(translate(PANE_TAB_COCONFIG), myContent); } /** */ @Override protected void doDispose() { // child controllers registered with listenTo() get disposed in BasicController if (selectGroupsCtr != null) { selectGroupsCtr.dispose(); } if (selectAreasCtr != null) { selectAreasCtr.dispose(); } } /** * resolving version issues of the module configuration, adds new default values for new keys * * @param moduleConfiguration2 */ private void resolveModuleConfigurationIssues(final ModuleConfiguration moduleConfiguration2) { final int version = moduleConfiguration2.getConfigurationVersion(); /* * if no version was set before -> version is 1 */ if (version == 1) { // new keys and defaults are moduleConfiguration.set(CONFIG_KEY_EMAILTOAREAS, ""); moduleConfiguration.set(CONFIG_KEY_EMAILTOGROUPS, ""); moduleConfiguration.setBooleanEntry(CONFIG_KEY_EMAILTOCOACHES, false); moduleConfiguration.setBooleanEntry(CONFIG_KEY_EMAILTOPARTICIPANTS, false); // moduleConfiguration2.setConfigurationVersion(2); } } @Override public String[] getPaneKeys() { return paneKeys; } @Override public TabbedPane getTabbedPane() { return myTabbedPane; } }
package tl3; import jburg.semantics.HostRoutine; import java.net.URI; import java.util.*; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaCompiler; import static javax.tools.JavaCompiler.CompilationTask; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; import jburg.ProductionTable; import jburg.Reducer; import jburg.semantics.JavaSemantics; import static tl3.Nonterminal.*; import static tl3.NodeType.*; public class CodeGenerator { private final Node root; private static final JavaSemantics dummySemantics = new JavaSemantics(); static class ScopeNamespace { ScopeNamespace(Object nsName) { this.nsName = nsName != null? nsName.toString(): null; } final String nsName; final Map<String,String> names = new HashMap<String,String>(); final Map<String,String> aliases = new HashMap<String,String>(); String addDefinition(String name) { names.put(name, String.format("%s%x", name, System.identityHashCode(name))); return names.get(name); } boolean hasDefinition(String name) { return names.containsKey(name); } void addAlias(String name, String aliasedExpression) { this.names.put(name, aliasedExpression); } boolean hasAlias(String name) { return aliases.containsKey(name); } String resolve(String name) { if (this.hasDefinition(name)) { return names.get(name); } else if (this.hasAlias(name)) { return aliases.get(name); } else { throw new IllegalArgumentException("Unresolved name " + name); } } } private final Stack<ScopeNamespace> namespaces = new Stack<ScopeNamespace>(); CodeGenerator(Node root, String fileName) { this.root = root; } static class JavaSourceFromString extends SimpleJavaFileObject { final String code; JavaSourceFromString(String name, String code) { super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),Kind.SOURCE); this.code = code; } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return code; } } void generate(String className) throws Exception { Reducer<Nonterminal, NodeType> reducer = new Reducer<Nonterminal,NodeType>(this, productions); reducer.label(root); String source = String.format( "import tl3.Runtime;\nclass %s {\n" + "public static void main(String[] args) {\n%s\n}" + "}", className, reducer.reduce(root, MainProgram) ); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); JavaFileObject file = new JavaSourceFromString(className, source); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file); ArrayList<String> options = new ArrayList<String>(); options.add("-d"); options.add("classes"); CompilationTask task = compiler.getTask(null, null, diagnostics, options, null, compilationUnits); boolean success = task.call(); if (!success) { System.err.printf("Compilation FAILED:\n%s\n",source); } for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { System.err.println(diagnostic.getCode()); System.err.println(diagnostic.getKind()); } } static final ProductionTable<Nonterminal, NodeType> productions = new ProductionTable<Nonterminal,NodeType>(); final static HostRoutine noPreCallback = null; final static HostRoutine noPostCallback = null; static { HostRoutine statementList = null; try { statementList = getPostCallback("statementList", Class.forName("[Ljava.lang.String;")); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } productions.addPatternMatch(MainProgram, Scope, getPreCallback("namedScope"), getPostCallback("exitScope", String.class, Object.class), Arrays.asList(Statements, Name)); productions.addPatternMatch(MainProgram, Scope, getPreCallback("unnamedScope"), getPostCallback("exitScope", String.class, Object.class), Arrays.asList(Statements, NullPtr)); productions.addPatternMatch(Statement, Scope, getPreCallback("namedScope"), getPostCallback("exitScope", String.class, Object.class), Arrays.asList(Statements, Name)); productions.addPatternMatch(Statement, Scope, getPreCallback("unnamedScope"), getPostCallback("exitScope", String.class, Object.class), Arrays.asList(Statements, NullPtr)); productions.addVarArgsPatternMatch(Statements, ScopeContents, noPreCallback, statementList, Arrays.asList(Statement)); productions.addPatternMatch(Statement, AliasDef, noPreCallback, getPostCallback("aliasDefinition", String.class, String.class), Arrays.asList(Name, Expression)); productions.addPatternMatch(Statement, VarDef, noPreCallback, getPostCallback("varDefNoInitializer", String.class), Arrays.asList(Name)); productions.addPatternMatch(Statement, VarDef, noPreCallback, getPostCallback("varDefWithInitializer", String.class, String.class), Arrays.asList(Name, Expression)); productions.addPatternMatch(Statement, Assignment, noPreCallback, getPostCallback("assignmentStmt", String.class, String.class), Arrays.asList(LValue, Expression)); productions.addPatternMatch(Statement, Print, noPreCallback, getPostCallback("printStmt", String.class), Arrays.asList(Expression)); productions.addPatternMatch(Statement, Verify, noPreCallback, getPostCallback("verify", String.class, String.class), Arrays.asList(Expression, Expression)); // Identifiers productions.addPatternMatch(LValue, Identifier, noPreCallback, getPostCallback("identifier", String.class), Arrays.asList(Name)); productions.addPatternMatch(Expression, Identifier, getPredicate("isAlias"), noPreCallback, getPostCallback("aliasedIdentifier", String.class), Arrays.asList(Name)); productions.addPatternMatch(LValue, Identifier, noPreCallback, getPostCallback("identifier", String.class, String.class), Arrays.asList(Name, Name)); productions.addPatternMatch(Name, IdentifierPart, noPreCallback, getPostCallback("nameRef")); // Binary operators productions.addPatternMatch(Expression, Equal, noPreCallback, getPostCallback("equality", String.class, String.class), Arrays.asList(Expression, Expression)); productions.addPatternMatch(Expression, Add, noPreCallback, getPostCallback("addition", String.class, String.class), Arrays.asList(Expression, Expression)); // Leaf expressions productions.addPatternMatch(Expression, IntegerLiteral, noPreCallback, getPostCallback("integerLiteral")); productions.addPatternMatch(Expression, StringLiteral, noPreCallback, getPostCallback("stringLiteral")); productions.addClosure(Expression, LValue, 2); productions.addNullPointerProduction(NullPtr, 1, null); productions.generateStates(); } static HostRoutine getPostCallback(String methodName, Class<?>... formalTypes) { Class<?>[] formalsWithNode = new Class<?>[formalTypes.length+1]; formalsWithNode[0] = Node.class; for (int i = 0; i < formalTypes.length; i++) { formalsWithNode[i+1] = formalTypes[i]; } try { return dummySemantics.getHostRoutine(CodeGenerator.class.getDeclaredMethod(methodName, formalsWithNode)); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } return null; } static HostRoutine getPreCallback(String methodName) { try { return dummySemantics.getHostRoutine(CodeGenerator.class.getDeclaredMethod(methodName, Node.class, Object.class)); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } return null; } static HostRoutine getPredicate(String methodName) { try { return dummySemantics.getHostRoutine(CodeGenerator.class.getDeclaredMethod(methodName, Node.class)); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } return null; } public String nameRef(Node node) { return node.content.toString(); } public String identifier(Node node, String name) { for (int idx = namespaces.size() - 1; idx >= 0; idx--) { if (namespaces.get(idx).hasDefinition(name)) { return namespaces.get(idx).resolve(name); } } return namespaces.peek().resolve(name); } public String aliasedIdentifier(Node node, String name) { for (int idx = namespaces.size() - 1; idx >= 0; idx--) { if (namespaces.get(idx).hasAlias(name)) { return this.namespaces.get(idx).resolve(name); } } // Shouldn't happen, the isAlias routine checked the namespaces. throw new IllegalStateException(String.format("aliasedIdentifier(%s) not found?", name)); } public String identifier(Node node, String qualifier, String name) { ScopeNamespace ns = null; for (int idx = namespaces.size() - 1; ns == null && idx >= 0; idx--) { if (qualifier.equals(namespaces.get(idx).nsName)) { ns = namespaces.get(idx); } } if (ns == null) { throw new IllegalArgumentException("Unresolved namespace " + qualifier); } return ns.resolve(name); } public String integerLiteral(Node node) { return node.content.toString(); } public String stringLiteral(Node node) { return node.content.toString(); } public String addition(Node node, String lhs, String rhs) { return String.format("Runtime.add(%s,%s)", lhs, rhs); } public String equality(Node node, String lhs, String rhs) { return String.format("Runtime.areEqual(%s,%s)", lhs, rhs); } public String verify(Node node, String condition, String text) { return String.format("Runtime.verify(%s,%s);", condition, text); } public String statementList(Node node, String... statements) { StringBuilder builder = new StringBuilder(); for (String s: statements) { builder.append(s); builder.append("\n"); } return builder.toString(); } public String identity(Node n, String... s) { return s[0]; } public String varDefNoInitializer(Node node, String varName) { return String.format("Object %s = null;", namespaces.peek().addDefinition(varName)); } public String varDefWithInitializer(Node node, String varName, String initializer) { return String.format("Object %s = %s;", namespaces.peek().addDefinition(varName), initializer); } public String aliasDefinition(Node node, String aliasName, String aliasBody) { namespaces.peek().addAlias(aliasName, aliasBody); return String.format("// alias %s = %s", aliasName, aliasBody); } public String assignmentStmt(Node node, String lvalue, String rvalue) { return String.format("%s = %s;", lvalue, rvalue); } public String printStmt(Node node, String exp) { return String.format("System.out.println(%s);", exp); } public void namedScope(Node scope, Object goal) { namespaces.push(new ScopeNamespace(scope.getSubtree(1).content)); } public void unnamedScope(Node scope, Object goal) { namespaces.push(new ScopeNamespace(null)); } public String exitScope(Node scope, String statements, Object scopeName) { // TODO: check scope name namespaces.pop(); return statements; } /* * Semantic predicates */ public boolean isAlias(Node n) { // TODO: Aliases can be general identifiers; // qualify the search through the namespaces. String name = n.getSubtree(0).content.toString(); boolean aliasFound = false; for (int idx = namespaces.size() - 1; !aliasFound && idx >= 0; idx--) { aliasFound |= namespaces.get(idx).hasAlias(name); } return aliasFound; } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), hosted at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * TIANI Medgraph AG. * Portions created by the Initial Developer are Copyright (C) 2002-2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gunter Zeilinger <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), hosted at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * TIANI Medgraph AG. * Portions created by the Initial Developer are Copyright (C) 2002-2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gunter Zeilinger <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4cheri.net; import org.dcm4che.Implementation; import org.dcm4che.net.AAssociateRQAC; import org.dcm4che.net.AAbort; import org.dcm4che.net.AsyncOpsWindow; import org.dcm4che.net.PresContext; import org.dcm4che.net.RoleSelection; import org.dcm4che.net.ExtNegotiation; import org.dcm4che.net.PDUException; import org.dcm4che.net.PDataTF; import org.dcm4che.dict.DictionaryFactory; import org.dcm4che.dict.UIDDictionary; import org.dcm4che.dict.UIDs; import org.dcm4cheri.util.StringUtils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; /** * * @author [email protected] * @version 1.0.0 */ abstract class AAssociateRQACImpl implements AAssociateRQAC { static UIDDictionary DICT = DictionaryFactory.getInstance().getDefaultUIDDictionary(); private String appCtxUID = UIDs.DICOMApplicationContextName; private int version = 1; private int maxLength = PDataTF.DEF_MAX_PDU_LENGTH; private String callingAET = "ANONYMOUS"; private String calledAET = "ANONYMOUS"; private String implClassUID = Implementation.getClassUID(); private String implVers = Implementation.getVersionName(); private AsyncOpsWindow asyncOpsWindow = null; protected final LinkedHashMap presCtxs = new LinkedHashMap(); protected final LinkedHashMap roleSels = new LinkedHashMap(); protected final LinkedHashMap extNegs = new LinkedHashMap(); protected AAssociateRQACImpl init(UnparsedPDUImpl raw) throws PDUException { if (raw.buffer() == null) { throw new PDUException("PDU length exceeds supported maximum " + raw, new AAbortImpl(AAbort.SERVICE_PROVIDER, AAbort.REASON_NOT_SPECIFIED)); } ByteArrayInputStream bin = new ByteArrayInputStream( raw.buffer(), 6, raw.length()); DataInputStream din = new DataInputStream(bin); try { version = din.readShort(); din.readUnsignedByte(); din.readUnsignedByte(); calledAET = readASCII(din, 16).trim(); callingAET = readASCII(din, 16).trim(); if (din.skip(32) != 32) { throw new EOFException(); } while (din.available() > 0) { int itemType = din.readUnsignedByte(); din.readUnsignedByte(); int itemLen = din.readUnsignedShort(); switch (itemType) { case 0x10: appCtxUID = readASCII(din, itemLen); break; case 0x20: case 0x21: if (itemType != pctype()) { throw new PDUException( "unexpected item type " + Integer.toHexString(itemType) + 'H', new AAbortImpl(AAbort.SERVICE_PROVIDER, AAbort.UNEXPECTED_PDU_PARAMETER)); } addPresContext( new PresContextImpl(itemType, din, itemLen)); break; case 0x50: readUserInfo(din, itemLen); break; default: throw new PDUException( "unrecognized item type " + Integer.toHexString(itemType) + 'H', new AAbortImpl(AAbort.SERVICE_PROVIDER, AAbort.UNRECOGNIZED_PDU_PARAMETER)); } } } catch (PDUException e) { throw e; } catch (Exception e) { throw new PDUException("Failed to parse " + raw, e, new AAbortImpl(AAbort.SERVICE_PROVIDER, AAbort.REASON_NOT_SPECIFIED)); } return this; } public final int getProtocolVersion() { return version; } public final void setProtocolVersion(int version) { this.version = version; } public String getCalledAET() { return calledAET; } public String getCallingAET() { return callingAET; } public void setCalledAET(String aet) { this.calledAET = StringUtils.checkAET(aet); } public void setCallingAET(String aet) { this.callingAET = StringUtils.checkAET(aet); } public final String getApplicationContext() { return appCtxUID; } public final void setApplicationContext(String appCtxUID) { appCtxUID = StringUtils.checkUID(appCtxUID); } public final int nextPCID() { int c = presCtxs.size(); if (c == 128) { return -1; } int retval = ((c << 1) | 1); while (presCtxs.containsKey(new Integer(retval))) { retval = (retval + 2) % 256; } return retval; } public final PresContext addPresContext(PresContext presCtx) { if (((PresContextImpl)presCtx).type() != pctype()) { throw new IllegalArgumentException("wrong type of " + presCtx); } return (PresContext)presCtxs.put( new Integer(presCtx.pcid()), presCtx); } public final PresContext removePresContext(int pcid) { return (PresContext)presCtxs.remove(new Integer(pcid)); } public final PresContext getPresContext(int pcid) { return (PresContext)presCtxs.get(new Integer(pcid)); } public final Collection listPresContext() { return presCtxs.values(); } public final void clearPresContext() { presCtxs.clear(); } public final String getImplClassUID() { return implClassUID; } public final void setImplClassUID(String uid) { this.implClassUID = StringUtils.checkUID(uid); } public final String getImplVersionName() { return implVers; } public final void setImplVersionName(String name) { this.implVers = name != null ? StringUtils.checkAET(name) : null; } public final int getMaxPDULength() { return maxLength; } public final void setMaxPDULength(int maxLength) { if (maxLength < 0) { throw new IllegalArgumentException("maxLength:" + maxLength); } this.maxLength = maxLength; } public final AsyncOpsWindow getAsyncOpsWindow() { return asyncOpsWindow; } public final void setAsyncOpsWindow(AsyncOpsWindow aow) { this.asyncOpsWindow = aow; } public final RoleSelection removeRoleSelection(String uid) { return (RoleSelection)roleSels.remove(uid); } public final RoleSelection getRoleSelection(String uid) { return (RoleSelection)roleSels.get(uid); } public Collection listRoleSelections() { return roleSels.values(); } public void clearRoleSelections() { roleSels.clear(); } public final ExtNegotiation removeExtNegotiation(String uid) { return (ExtNegotiation)extNegs.remove(uid); } public final ExtNegotiation getExtNegotiation(String uid) { return (ExtNegotiation)extNegs.get(uid); } public Collection listExtNegotiations() { return extNegs.values(); } public void clearExtNegotiations() { extNegs.clear(); } static String readASCII(DataInputStream in, int len) throws IOException, UnsupportedEncodingException { byte[] b = new byte[len]; in.readFully(b); while (len > 0 && b[len-1] == 0) --len; return new String(b, 0, len, "US-ASCII"); } public RoleSelection addRoleSelection(RoleSelection roleSel) { return (RoleSelection)roleSels.put( roleSel.getSOPClassUID(), roleSel); } public ExtNegotiation addExtNegotiation(ExtNegotiation extNeg) { return (ExtNegotiation)extNegs.put( extNeg.getSOPClassUID(), extNeg); } private void readUserInfo(DataInputStream din, int len) throws IOException, PDUException { int diff = len - din.available(); if (diff != 0) { throw new PDUException("User info item length=" + len + " mismatch PDU length (diff=" + diff + ")", new AAbortImpl(AAbort.SERVICE_PROVIDER, AAbort.INVALID_PDU_PARAMETER_VALUE)); } while (din.available() > 0) { int subItemType = din.readUnsignedByte(); din.readUnsignedByte(); int itemLen = din.readUnsignedShort(); switch (subItemType) { case 0x51: if (itemLen != 4) { throw new PDUException( "Illegal length of Maximum length sub-item: " + itemLen, new AAbortImpl(AAbort.SERVICE_PROVIDER, AAbort.INVALID_PDU_PARAMETER_VALUE)); } maxLength = din.readInt(); break; case 0x52: implClassUID = readASCII(din, itemLen); break; case 0x53: asyncOpsWindow = new AsyncOpsWindowImpl(din, itemLen); break; case 0x54: addRoleSelection(new RoleSelectionImpl(din, itemLen)); break; case 0x55: implVers = readASCII(din, itemLen); break; case 0x56: addExtNegotiation(new ExtNegotiationImpl(din, itemLen)); break; default: throw new PDUException( "unrecognized user sub-item type " + Integer.toHexString(subItemType) + 'H', new AAbortImpl(AAbort.SERVICE_PROVIDER, AAbort.UNRECOGNIZED_PDU_PARAMETER)); } } } protected abstract int type(); protected abstract int pctype(); private static final byte[] ZERO32 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; private void writeAE(DataOutputStream dout, String aet) throws IOException { dout.writeBytes(aet); for (int n = aet.length(); n < 16; ++n) { dout.write(' '); } } private static final class MyByteArrayOutputStream extends ByteArrayOutputStream { MyByteArrayOutputStream() { super(4096); write(0); write(0); write(0); write(0); write(0); write(0); } void writeTo(int type, OutputStream out) throws IOException { int len = count - 6; buf[0] = (byte)type; buf[1] = (byte)0; buf[2] = (byte)(len >> 24); buf[3] = (byte)(len >> 16); buf[4] = (byte)(len >> 8); buf[5] = (byte)(len >> 0); out.write(buf, 0, count); } } public final void writeTo(OutputStream out) throws IOException { MyByteArrayOutputStream bout = new MyByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); dout.writeShort(version); dout.write(0); dout.write(0); writeAE(dout, calledAET); writeAE(dout, callingAET); dout.write(ZERO32); dout.write(0x10); dout.write(0); dout.writeShort(appCtxUID.length()); dout.writeBytes(appCtxUID); for (Iterator it = presCtxs.values().iterator(); it.hasNext();) { ((PresContextImpl)it.next()).writeTo(dout); } writeUserInfo(dout); bout.writeTo(type(), out); } private void writeUserInfo(DataOutputStream dout) throws IOException { dout.write(0x50); dout.write(0); dout.writeShort(getUserInfoLength()); dout.write(0x51); dout.write(0); dout.writeShort(4); dout.writeInt(maxLength); dout.write(0x52); dout.write(0); dout.writeShort(implClassUID.length()); dout.writeBytes(implClassUID); if (asyncOpsWindow != null) { ((AsyncOpsWindowImpl)asyncOpsWindow).writeTo(dout); } for (Iterator it = roleSels.values().iterator(); it.hasNext();) { ((RoleSelectionImpl)it.next()).writeTo(dout); } if (implVers != null) { dout.write(0x55); dout.write(0); dout.writeShort(implVers.length()); dout.writeBytes(implVers); } for (Iterator it = extNegs.values().iterator(); it.hasNext();) { ((ExtNegotiationImpl)it.next()).writeTo(dout); } } private int getUserInfoLength() { int retval = 12 + implClassUID.length(); if (asyncOpsWindow != null) { retval += 8; } for (Iterator it = roleSels.values().iterator(); it.hasNext();) { RoleSelectionImpl rs = (RoleSelectionImpl)it.next(); retval += 4 + rs.length(); } if (implVers != null) { retval += 4 + implVers.length(); } for (Iterator it = extNegs.values().iterator(); it.hasNext();) { ExtNegotiationImpl en = (ExtNegotiationImpl)it.next(); retval += 4 + en.length(); } return retval; } protected abstract String typeAsString(); public String toString() { return toString(true); } public String toString(boolean verbose) { return toStringBuffer(new StringBuffer(), verbose).toString(); } final StringBuffer toStringBuffer(StringBuffer sb, boolean verbose) { sb.append(typeAsString()) .append("\n\tappCtxName:\t").append(DICT.lookup(appCtxUID)) .append("\n\timplClass:\t").append(implClassUID) .append("\n\timplVersion:\t").append(implVers) .append("\n\tcalledAET:\t").append(calledAET) .append("\n\tcallingAET:\t").append(callingAET) .append("\n\tmaxPDULen:\t").append(maxLength) .append("\n\tasyncOpsWindow:\t"); if (asyncOpsWindow != null) { sb.append("maxOpsInvoked=") .append(asyncOpsWindow.getMaxOpsInvoked()) .append(", maxOpsPerformed=") .append(asyncOpsWindow.getMaxOpsPerformed()); } if (verbose) { for (Iterator it = presCtxs.values().iterator(); it.hasNext();) { append((PresContext)it.next(), sb); } for (Iterator it = roleSels.values().iterator(); it.hasNext();) { sb.append("\n\t").append(it.next()); } for (Iterator it = extNegs.values().iterator(); it.hasNext();) { sb.append("\n\t").append(it.next()); } } else { appendPresCtxSummary(sb); sb.append("\n\troleSel:\t#").append(roleSels.size()) .append("\n\textNego:\t#").append(extNegs.size()); } return sb; } protected abstract void append(PresContext pc, StringBuffer sb); protected abstract void appendPresCtxSummary(StringBuffer sb); }
/* * Copyright 2013-2020 Netherlands Forensic Institute * * 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.parsingdata.metal.token; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static io.parsingdata.metal.Shorthand.add; import static io.parsingdata.metal.Shorthand.cat; import static io.parsingdata.metal.Shorthand.con; import static io.parsingdata.metal.Shorthand.def; import static io.parsingdata.metal.Shorthand.div; import static io.parsingdata.metal.Shorthand.elvis; import static io.parsingdata.metal.Shorthand.eq; import static io.parsingdata.metal.Shorthand.fold; import static io.parsingdata.metal.Shorthand.last; import static io.parsingdata.metal.Shorthand.mod; import static io.parsingdata.metal.Shorthand.nth; import static io.parsingdata.metal.Shorthand.ref; import static io.parsingdata.metal.Shorthand.rep; import static io.parsingdata.metal.Shorthand.repn; import static io.parsingdata.metal.Shorthand.rev; import static io.parsingdata.metal.Shorthand.seq; import static io.parsingdata.metal.Shorthand.sub; import static io.parsingdata.metal.Shorthand.tie; import static io.parsingdata.metal.Util.inflate; import static io.parsingdata.metal.data.ParseState.createFromByteStream; import static io.parsingdata.metal.data.selection.ByName.getAllValues; import static io.parsingdata.metal.data.selection.ByType.getReferences; import static io.parsingdata.metal.util.EncodingFactory.enc; import static io.parsingdata.metal.util.EnvironmentFactory.env; import static io.parsingdata.metal.util.ParseStateFactory.stream; import static io.parsingdata.metal.util.TokenDefinitions.any; import java.util.Optional; import java.util.zip.Deflater; import org.junit.Test; import io.parsingdata.metal.Shorthand; import io.parsingdata.metal.data.ImmutableList; import io.parsingdata.metal.data.ParseState; import io.parsingdata.metal.data.ParseValue; import io.parsingdata.metal.expression.value.ValueExpression; import io.parsingdata.metal.util.InMemoryByteStream; public class TieTest { // Starts at 1, then increases with 1, modulo 100. private static final Token INC_PREV_MOD_100 = rep(def("value", 1, eq(mod(add(elvis(nth(rev(ref("value")), con(1)), con(0)), con(1)), con(100))))); private static final Token CONTAINER = seq(def("blockSize", 1), def("tableSize", 1), repn(any("offset"), last(ref("tableSize"))), sub(def("data", last(ref("blockSize"))), ref("offset")), tie(INC_PREV_MOD_100, fold(rev(ref("data")), Shorthand::cat))); private static final Token SIMPLE_SEQ = seq(any("a"), any("b"), any("c")); @Test public void smallContainer() { final Optional<ParseState> result = parseContainer(); assertEquals(5, result.get().offset.intValueExact()); assertEquals(6, getAllValues(result.get().order, "value").size); } private Optional<ParseState> parseContainer() { final Optional<ParseState> result = CONTAINER.parse(env(stream(2, 3, 7, 5, 9, 3, 4, 1, 2, 5, 6))); assertTrue(result.isPresent()); return result; } @Test public void checkContainerSource() { final Optional<ParseState> result = parseContainer(); checkFullParse(INC_PREV_MOD_100, fold(ref("value"), Shorthand::cat).eval(result.get(), enc()).head.value()); } private Optional<ParseState> checkFullParse(Token token, byte[] data) { final Optional<ParseState> result = token.parse(env(createFromByteStream(new InMemoryByteStream(data)), enc())); assertTrue(result.isPresent()); assertEquals(data.length, result.get().offset.intValueExact()); return result; } @Test public void increasing() { checkFullParse(INC_PREV_MOD_100, generateIncreasing(1024)); } private static byte[] generateIncreasing(final int size) { final byte[] data = new byte[size]; for (int i = 0; i < data.length; i++) { data[i] = (byte)((i+1) % 100); } return data; } @Test public void multiLevelContainers() { final byte[] l3Data = generateIncreasing(880); final Token l3Token = INC_PREV_MOD_100; checkFullParse(l3Token, l3Data); final byte[] l2Data = flipBlocks(l3Data, 40); final Token l2Token = seq(rep(seq(def("left", con(40)), def("right", con(40)))), tie(l3Token, fold(cat(ref("right"), ref("left")), Shorthand::cat))); checkFullParse(l2Token, l2Data); final byte[] l1Data = prefixSize(deflate(l2Data)); final Token l1Token = seq(def("size", con(4)), def("data", last(ref("size"))), tie(l2Token, inflate(last(ref("data"))))); final Optional<ParseState> result = checkFullParse(l1Token, l1Data); assertEquals(80, result.get().order.head.asGraph().head.asGraph().head.asGraph().head.asGraph().head.asGraph().head.asGraph().head.asValue().asNumeric().intValueExact()); } private byte[] flipBlocks(byte[] input, int blockSize) { if ((input.length % (blockSize * 2)) != 0) { throw new UnsupportedOperationException("Not supported."); } final byte[] output = input.clone(); for (int i = 0; i < output.length; i+= blockSize * 2) { for (int j= 0; j < blockSize; j++) { output[j+i] = input[j+i+blockSize]; output[j+i+blockSize] = input[j+i]; } } return output; } private byte[] deflate(byte[] data) { final Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); deflater.setInput(data); deflater.finish(); final byte[] buffer = new byte[data.length * 2]; int length = deflater.deflate(buffer); deflater.end(); final byte[] output = new byte[length]; System.arraycopy(buffer, 0, output, 0, length); return output; } private byte[] prefixSize(byte[] data) { final byte[] output = new byte[data.length + 4]; output[0] = (byte)((data.length & 0xff000000) >> 24); output[1] = (byte)((data.length & 0xff0000) >> 16); output[2] = (byte)((data.length & 0xff00) >> 8); output[3] = (byte) (data.length & 0xff); System.arraycopy(data, 0, output, 4, data.length); return output; } @Test public void tieAndSubOnSameData() { final Token nestedSeq = seq(def("d", con(3)), tie(SIMPLE_SEQ, ref("d")), sub(SIMPLE_SEQ, con(0))); final Optional<ParseState> result = nestedSeq.parse(env(stream(1, 2, 3))); assertTrue(result.isPresent()); assertEquals(0, getReferences(result.get().order).size); } @Test public void multiTie() { final Token multiTie = seq(def("d", con(3)), def("d", con(3)), tie(SIMPLE_SEQ, ref("d"))); final Optional<ParseState> result = multiTie.parse(env(stream(1, 2, 3, 1, 2, 3))); assertTrue(result.isPresent()); assertEquals(0, getReferences(result.get().order).size); final String[] names = { "a", "b", "c", "d" }; for (String name : names) { ImmutableList<ParseValue> values = getAllValues(result.get().order, name); assertEquals(2, values.size); } } @Test public void tieWithDuplicate() { final ValueExpression refD = ref("d"); final Token duplicateTie = seq(def("d", con(3)), tie(SIMPLE_SEQ, refD), tie(SIMPLE_SEQ, refD)); final Optional<ParseState> result = duplicateTie.parse(env(stream(1, 2, 3))); assertTrue(result.isPresent()); assertEquals(0, getReferences(result.get().order).size); assertEquals(1, getAllValues(result.get().order, "d").size); final String[] names = { "a", "b", "c" }; for (String name : names) { ImmutableList<ParseValue> values = getAllValues(result.get().order, name); assertEquals(2, values.size); } } @Test public void tieWithEmptyListFromDataExpression() { final Token token = seq(any("a"), tie(any("b"), last(ref("c")))); final Optional<ParseState> result = token.parse(env(stream(0))); assertTrue(result.isPresent()); assertTrue(result.get().order.head.asGraph().head.asGraph().isEmpty()); } @Test public void tieFail() { final Token token = seq(def("a", con(1), eq(con(0))), tie(def("b", con(1), eq(con(1))), last(ref("a")))); assertFalse(token.parse(env(stream(0))).isPresent()); } @Test public void tieWithEmptyValueFromDataExpression() { final Token token = seq(any("a"), tie(any("b"), div(con(1), con(0)))); assertFalse(token.parse(env(stream(0))).isPresent()); } @Test public void tieOnConstant() { final Token strictSeq = seq(def("a", con(1), eq(con(1))), def("b", con(1), eq(con(2))), def("c", con(1), eq(con(3)))); assertTrue(tie(strictSeq, con(1, 2, 3)).parse(env(stream())).isPresent()); assertFalse(tie(strictSeq, con(1, 2, 4)).parse(env(stream())).isPresent()); } }
/******************************************************************************* * * Copyright (C) 2015-2021 the BBoxDB 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.bboxdb.misc; import java.net.SocketException; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.bboxdb.commons.NetworkInterfaceHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BBoxDBConfiguration { /** * The fetch modes of the continuous spatial join * */ public enum ContinuousSpatialJoinFetchMode { NONE, FETCH } /** * The directories to store data */ private List<String> storageDirectories = Arrays.asList("/tmp/bboxdb"); /** * Number of entries per memtable */ private int memtableEntriesMax = 50000; /** * Size of the memtable in bytes */ private long memtableSizeMax = 128 * 1024 * 1014; /** * Number of memtable flush threads per storage */ private int memtableFlushThreadsPerStorage = 2; /** * The classname of the spatial index builder */ private String storageSpatialIndexBuilder = "org.bboxdb.storage.sstable.spatialindex.rtree.RTreeBuilder"; /** * The classname of the spatial index reader */ private String storageSpatialIndexReader = "org.bboxdb.storage.sstable.spatialindex.rtree.mmf.RTreeMMFReader"; /** * The checkpoint interval */ private int storageCheckpointInterval = 60; /** * The write ahead log */ private boolean storageWriteAheadLog = false; /** * The port for client requests */ private int networkListenPort = 50505; /** * The amount of threads to handle client connections */ private int networkConnectionThreads = 25; /** * The name of the cluster */ private String clustername; /** * The list of zookeeper nodes */ private Collection<String> zookeepernodes; /** * The local IP address of this node. The default value is set in the constructor. */ private String localip = null; /** * The number of entries in the key cache per SSTable */ private int sstableKeyCacheEntries = 1000; /** * The port where the performance counter will be exposed */ private int performanceCounterPort = 10085; /** * The ContinuousSpatialJoinFetchMode */ private String continuousSpatialJoinFetchMode = "NONE"; /** * ContinuousSpatialJoinFetchMode as ENUM */ private ContinuousSpatialJoinFetchMode continuousSpatialJoinFetchModeENUM = ContinuousSpatialJoinFetchMode.NONE; /** * The Logger */ private final static Logger logger = LoggerFactory.getLogger(BBoxDBConfiguration.class); public BBoxDBConfiguration() { try { localip = NetworkInterfaceHelper.getFirstNonLoopbackIPv4AsString(); } catch (SocketException e) { logger.warn("Unable to determine the local IP adress of this node, please specify 'localip' in the configuration", e); } } public int getMemtableEntriesMax() { return memtableEntriesMax; } public void setMemtableEntriesMax(final int memtableEntriesMax) { this.memtableEntriesMax = memtableEntriesMax; } public long getMemtableSizeMax() { return memtableSizeMax; } public void setMemtableSizeMax(final long memtableSizeMax) { this.memtableSizeMax = memtableSizeMax; } public int getNetworkListenPort() { return networkListenPort; } public void setNetworkListenPort(final int networkListenPort) { this.networkListenPort = networkListenPort; } public int getNetworkConnectionThreads() { return networkConnectionThreads; } public void setNetworkConnectionThreads(final int networkConnectionThreads) { this.networkConnectionThreads = networkConnectionThreads; } public String getClustername() { return clustername; } public void setClustername(final String clustername) { this.clustername = clustername; } public Collection<String> getZookeepernodes() { return zookeepernodes; } public void setZookeepernodes(final Collection<String> zookeepernodes) { this.zookeepernodes = zookeepernodes; } public String getLocalip() { return localip; } public void setLocalip(final String localip) { this.localip = localip; } public int getStorageCheckpointInterval() { return storageCheckpointInterval; } public void setStorageCheckpointInterval(final int storageCheckpointInterval) { this.storageCheckpointInterval = storageCheckpointInterval; } public List<String> getStorageDirectories() { return storageDirectories; } public void setStorageDirectories(final List<String> storageDirectories) { this.storageDirectories = storageDirectories; } public int getMemtableFlushThreadsPerStorage() { return memtableFlushThreadsPerStorage; } public void setMemtableFlushThreadsPerStorage(final int memtableFlushThreadsPerStorage) { this.memtableFlushThreadsPerStorage = memtableFlushThreadsPerStorage; } public String getStorageSpatialIndexBuilder() { return storageSpatialIndexBuilder; } public void setStorageSpatialIndexBuilder(final String storageSpatialIndexBuilder) { this.storageSpatialIndexBuilder = storageSpatialIndexBuilder; } public String getStorageSpatialIndexReader() { return storageSpatialIndexReader; } public void setStorageSpatialIndexReader(final String storageSpatialIndexReader) { this.storageSpatialIndexReader = storageSpatialIndexReader; } public int getSstableKeyCacheEntries() { return sstableKeyCacheEntries; } public void setSstableKeyCacheEntries(final int sstableKeyCacheEntries) { this.sstableKeyCacheEntries = sstableKeyCacheEntries; } public int getPerformanceCounterPort() { return performanceCounterPort; } public void setPerformanceCounterPort(final int performanceCounterPort) { this.performanceCounterPort = performanceCounterPort; } public boolean isStorageWriteAheadLog() { return storageWriteAheadLog; } public void setStorageWriteAheadLog(final boolean storageWriteAheadLog) { this.storageWriteAheadLog = storageWriteAheadLog; } public String getContinuousSpatialJoinFetchMode() { return continuousSpatialJoinFetchMode; } public void setContinuousSpatialJoinFetchMode(final String continuousSpatialJoinFetchMode) { this.continuousSpatialJoinFetchMode = continuousSpatialJoinFetchMode; this.continuousSpatialJoinFetchModeENUM = ContinuousSpatialJoinFetchMode.valueOf(continuousSpatialJoinFetchMode); } public ContinuousSpatialJoinFetchMode getContinuousSpatialJoinFetchModeENUM() { return continuousSpatialJoinFetchModeENUM; } public void setContinuousSpatialJoinFetchModeENUM(final ContinuousSpatialJoinFetchMode continuousSpatialJoinFetchModeENUM) { this.continuousSpatialJoinFetchModeENUM = continuousSpatialJoinFetchModeENUM; this.continuousSpatialJoinFetchMode = continuousSpatialJoinFetchModeENUM.name(); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.network.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.management.Resource; import com.azure.core.management.SubResource; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.network.models.NatGatewaySku; import com.azure.resourcemanager.network.models.ProvisioningState; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.Map; /** Nat Gateway resource. */ @Fluent public final class NatGatewayInner extends Resource { @JsonIgnore private final ClientLogger logger = new ClientLogger(NatGatewayInner.class); /* * The nat gateway SKU. */ @JsonProperty(value = "sku") private NatGatewaySku sku; /* * Nat Gateway properties. */ @JsonProperty(value = "properties") private NatGatewayPropertiesFormat innerProperties; /* * A list of availability zones denoting the zone in which Nat Gateway * should be deployed. */ @JsonProperty(value = "zones") private List<String> zones; /* * A unique read-only string that changes whenever the resource is updated. */ @JsonProperty(value = "etag", access = JsonProperty.Access.WRITE_ONLY) private String etag; /* * Resource ID. */ @JsonProperty(value = "id") private String id; /** * Get the sku property: The nat gateway SKU. * * @return the sku value. */ public NatGatewaySku sku() { return this.sku; } /** * Set the sku property: The nat gateway SKU. * * @param sku the sku value to set. * @return the NatGatewayInner object itself. */ public NatGatewayInner withSku(NatGatewaySku sku) { this.sku = sku; return this; } /** * Get the innerProperties property: Nat Gateway properties. * * @return the innerProperties value. */ private NatGatewayPropertiesFormat innerProperties() { return this.innerProperties; } /** * Get the zones property: A list of availability zones denoting the zone in which Nat Gateway should be deployed. * * @return the zones value. */ public List<String> zones() { return this.zones; } /** * Set the zones property: A list of availability zones denoting the zone in which Nat Gateway should be deployed. * * @param zones the zones value to set. * @return the NatGatewayInner object itself. */ public NatGatewayInner withZones(List<String> zones) { this.zones = zones; return this; } /** * Get the etag property: A unique read-only string that changes whenever the resource is updated. * * @return the etag value. */ public String etag() { return this.etag; } /** * Get the id property: Resource ID. * * @return the id value. */ public String id() { return this.id; } /** * Set the id property: Resource ID. * * @param id the id value to set. * @return the NatGatewayInner object itself. */ public NatGatewayInner withId(String id) { this.id = id; return this; } /** {@inheritDoc} */ @Override public NatGatewayInner withLocation(String location) { super.withLocation(location); return this; } /** {@inheritDoc} */ @Override public NatGatewayInner withTags(Map<String, String> tags) { super.withTags(tags); return this; } /** * Get the idleTimeoutInMinutes property: The idle timeout of the nat gateway. * * @return the idleTimeoutInMinutes value. */ public Integer idleTimeoutInMinutes() { return this.innerProperties() == null ? null : this.innerProperties().idleTimeoutInMinutes(); } /** * Set the idleTimeoutInMinutes property: The idle timeout of the nat gateway. * * @param idleTimeoutInMinutes the idleTimeoutInMinutes value to set. * @return the NatGatewayInner object itself. */ public NatGatewayInner withIdleTimeoutInMinutes(Integer idleTimeoutInMinutes) { if (this.innerProperties() == null) { this.innerProperties = new NatGatewayPropertiesFormat(); } this.innerProperties().withIdleTimeoutInMinutes(idleTimeoutInMinutes); return this; } /** * Get the publicIpAddresses property: An array of public ip addresses associated with the nat gateway resource. * * @return the publicIpAddresses value. */ public List<SubResource> publicIpAddresses() { return this.innerProperties() == null ? null : this.innerProperties().publicIpAddresses(); } /** * Set the publicIpAddresses property: An array of public ip addresses associated with the nat gateway resource. * * @param publicIpAddresses the publicIpAddresses value to set. * @return the NatGatewayInner object itself. */ public NatGatewayInner withPublicIpAddresses(List<SubResource> publicIpAddresses) { if (this.innerProperties() == null) { this.innerProperties = new NatGatewayPropertiesFormat(); } this.innerProperties().withPublicIpAddresses(publicIpAddresses); return this; } /** * Get the publicIpPrefixes property: An array of public ip prefixes associated with the nat gateway resource. * * @return the publicIpPrefixes value. */ public List<SubResource> publicIpPrefixes() { return this.innerProperties() == null ? null : this.innerProperties().publicIpPrefixes(); } /** * Set the publicIpPrefixes property: An array of public ip prefixes associated with the nat gateway resource. * * @param publicIpPrefixes the publicIpPrefixes value to set. * @return the NatGatewayInner object itself. */ public NatGatewayInner withPublicIpPrefixes(List<SubResource> publicIpPrefixes) { if (this.innerProperties() == null) { this.innerProperties = new NatGatewayPropertiesFormat(); } this.innerProperties().withPublicIpPrefixes(publicIpPrefixes); return this; } /** * Get the subnets property: An array of references to the subnets using this nat gateway resource. * * @return the subnets value. */ public List<SubResource> subnets() { return this.innerProperties() == null ? null : this.innerProperties().subnets(); } /** * Get the resourceGuid property: The resource GUID property of the NAT gateway resource. * * @return the resourceGuid value. */ public String resourceGuid() { return this.innerProperties() == null ? null : this.innerProperties().resourceGuid(); } /** * Get the provisioningState property: The provisioning state of the NAT gateway resource. * * @return the provisioningState value. */ public ProvisioningState provisioningState() { return this.innerProperties() == null ? null : this.innerProperties().provisioningState(); } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (sku() != null) { sku().validate(); } if (innerProperties() != null) { innerProperties().validate(); } } }
/* * This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.jcwhatever.nucleus.internal.providers.kits; import com.jcwhatever.nucleus.Nucleus; import com.jcwhatever.nucleus.providers.kits.events.GiveKitEvent; import com.jcwhatever.nucleus.providers.kits.IKit; import com.jcwhatever.nucleus.providers.kits.IKitContext; import com.jcwhatever.nucleus.utils.ArrayUtils; import com.jcwhatever.nucleus.utils.PreCon; import com.jcwhatever.nucleus.managed.scheduler.Scheduler; import com.jcwhatever.nucleus.utils.inventory.InventoryUtils; import com.jcwhatever.nucleus.utils.items.ItemStackMatcher; import com.jcwhatever.nucleus.utils.materials.MaterialProperty; import com.jcwhatever.nucleus.utils.materials.Materials; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.annotation.Nullable; /** * Nucleus implementation of {@link IKit}. */ class NucleusKit implements IKit { private final Plugin _plugin; private final IKitContext _context; private final String _name; private final String _searchName; private ItemStack[] _armor = new ItemStack[4]; // helmet, chestplate, leggings, boots private List<ItemStack> _items; /** * Constructor. * * @param context The owning context. * @param name The name of the kit. */ public NucleusKit(IKitContext context, String name) { PreCon.notNull(context); PreCon.notNullOrEmpty(name); _plugin = context.getPlugin(); _context = context; _name = name; _searchName = name.toLowerCase(); _items = new ArrayList<ItemStack>(15); } @Override public Plugin getPlugin() { return _plugin; } @Override public String getName() { return _name; } @Override public String getSearchName() { return _searchName; } @Override public IKitContext getContext() { return _context; } @Override @Nullable public ItemStack getHelmet() { return _armor[0] != null ? _armor[0].clone() : null; } @Override @Nullable public ItemStack getChestplate() { return _armor[1] != null ? _armor[1].clone() : null; } @Override @Nullable public ItemStack getLeggings() { return _armor[2] != null ? _armor[2].clone() : null; } @Override @Nullable public ItemStack getBoots() { return _armor[3] != null ? _armor[3].clone() : null; } @Override public ItemStack[] getItems() { // deep clone into an array ItemStack[] array = new ItemStack[_items.size()]; for (int i = 0; i < _items.size(); ++i) { array[i] = _items.get(i).clone(); } return array; } @Override public ItemStack[] getArmor() { ItemStack[] armor = new ItemStack[4]; armor[0] = getHelmet(); armor[1] = getChestplate(); armor[2] = getLeggings(); armor[3] = getBoots(); return armor; } @Override public boolean take(Entity entity, int qty) { return take(entity, ItemStackMatcher.getDefault(), qty); } @Override public boolean take(Entity entity, ItemStackMatcher matcher, int qty) { PreCon.notNull(entity); PreCon.notNull(matcher); PreCon.greaterThanZero(qty); List<ItemStack> itemsToTake = new ArrayList<>(_items.size() + 4); itemsToTake.addAll(_items); if (_armor[0] != null) itemsToTake.add(getHelmet()); if (_armor[1] != null) itemsToTake.add(getChestplate()); if (_armor[2] != null) itemsToTake.add(getLeggings()); if (_armor[3] != null) itemsToTake.add(getBoots()); if (entity instanceof InventoryHolder) { InventoryHolder holder = (InventoryHolder)entity; // check entity has all required items for (ItemStack item : itemsToTake) { if (!InventoryUtils.has(holder.getInventory(), item, matcher, qty)) return false; } // take items for (ItemStack item : itemsToTake) { InventoryUtils.removeAmount(holder.getInventory(), item, matcher, qty); } return true; } return false; } @Override public void give(final Entity entity) { PreCon.notNull(entity); if (!(entity instanceof InventoryHolder) && !(entity instanceof LivingEntity)) return; final GiveKitEvent event = new GiveKitEvent(entity, NucleusKit.this); Nucleus.getEventManager().callBukkit(NucleusKit.this, event); if (event.isCancelled()) return; Scheduler.runTaskLater(_plugin, new Runnable() { @Override public void run() { Inventory inventory = entity instanceof InventoryHolder ? ((InventoryHolder) entity).getInventory() : null; EntityEquipment equipment = entity instanceof LivingEntity ? ((LivingEntity) entity).getEquipment() : null; // add items if (inventory != null) { for (ItemStack item : event.getItems()) { inventory.addItem(item); } } else if (equipment != null) { List<ItemStack> items = event.getItems(); if (items.size() > 0) equipment.setItemInHand(items.get(0)); } // add equipment if (equipment != null) { giveEquipment(equipment, event); } else if (inventory != null) { giveEquipmentInventory(inventory, event); } } }); } /** * Set the kits helmet item. * * @param helmet The helmet. */ protected void setHelmet(@Nullable ItemStack helmet) { _armor[0] = helmet != null ? helmet.clone() : null; } /** * Set the kits chest plate item. * * @param chestplate The chestplate. */ protected void setChestplate(@Nullable ItemStack chestplate) { _armor[1] = chestplate != null ? chestplate.clone() : null; } /** * Set the kits legging item. * * @param leggings The leggings. */ protected void setLeggings(@Nullable ItemStack leggings) { _armor[2] = leggings != null ? leggings.clone() : null; } /** * Set the kits boots item. * * @param boots The boots. */ protected void setBoots(@Nullable ItemStack boots) { _armor[3] = boots != null ? boots.clone() : null; } /** * Add an array of items, armor or non-armor, to the kit. * * <p>Armor items automatically replace the appropriate * armor item.</p> * * @param items The items to add. */ protected void addItems(ItemStack... items) { PreCon.notNull(items); InventoryUtils.add(_items, items); } /** * Add an array of items, armor or non-armor, to the kit. * * <p>Armor items automatically replace the appropriate * armor item.</p> * * @param items The items to add. */ protected void addItems(Collection<ItemStack> items) { PreCon.notNull(items); ItemStack[] itemArray = items.toArray(new ItemStack[items.size()]); InventoryUtils.add(_items, itemArray); } /** * Add a collection of items, armor or non-armor, to the kit. * * <p>Armor items automatically replace the appropriate * armor item.</p> * * @param items The items to add. */ protected void addAnyItems(ItemStack... items) { PreCon.notNull(items); List<ItemStack> clone = new ArrayList<>(items.length); Collections.addAll(clone, items); addAnyItems(clone); } /** * Add a collection of items, armor or non-armor, to the kit. * * <p>Armor items automatically replace the appropriate * armor item.</p> * * @param items The items to add. */ protected void addAnyItems(Collection<ItemStack> items) { PreCon.notNull(items); List<ItemStack> clone = new ArrayList<>(items); ItemStack helmet = null; ItemStack chestplate = null; ItemStack leggings = null; ItemStack boots = null; Iterator<ItemStack> iterator = clone.iterator(); while (iterator.hasNext()) { ItemStack item = iterator.next(); Set<MaterialProperty> properties = Materials.getProperties(item.getType()); if (properties.contains(MaterialProperty.ARMOR)) { if (properties.contains(MaterialProperty.HELMET)) { helmet = item; iterator.remove(); } else if (properties.contains(MaterialProperty.CHESTPLATE)) { chestplate = item; iterator.remove(); } else if (properties.contains(MaterialProperty.LEGGINGS)) { leggings = item; iterator.remove(); } else if (properties.contains(MaterialProperty.BOOTS)) { boots = item; iterator.remove(); } } if (helmet != null && chestplate != null && leggings != null && boots != null) break; } if (helmet != null) setHelmet(helmet); if (chestplate != null) setChestplate(chestplate); if (leggings != null) setLeggings(leggings); if (boots != null) setBoots(boots); if (!clone.isEmpty()) InventoryUtils.add(_items, clone.toArray(new ItemStack[clone.size()])); } /** * Remove an item from the kit, armor or non-armor. * * @param items The {@link ItemStack}'s to remove. * @return True if 1 or more items was removed, otherwise false. */ protected boolean removeItems(ItemStack... items) { PreCon.notNull(items); ItemStack[] kitItems = _items.toArray(new ItemStack[_items.size()]); if (!InventoryUtils.remove(kitItems, items).isEmpty()) { _items.clear(); kitItems = ArrayUtils.removeNull(kitItems); Collections.addAll(_items, kitItems); return true; } return false; } /** * Remove an item from the kit, armor or non-armor. * * @param items The {@link ItemStack}'s to remove. * * @return True if at least 1 of the items was found and removed, otherwise false. */ protected boolean removeAnyItems(ItemStack... items) { PreCon.notNull(items); List<ItemStack> clone = new ArrayList<>(items.length); Collections.addAll(clone, items); boolean[] armorFlags = new boolean[4]; Iterator<ItemStack> iterator = clone.iterator(); while (iterator.hasNext()) { ItemStack item = iterator.next(); Set<MaterialProperty> properties = Materials.getProperties(item.getType()); if (properties.contains(MaterialProperty.ARMOR)) { int index; if (properties.contains(MaterialProperty.HELMET)) { setHelmet(null); index = 0; } else if (properties.contains(MaterialProperty.CHESTPLATE)) { setChestplate(null); index = 1; } else if (properties.contains(MaterialProperty.LEGGINGS)) { setLeggings(null); index = 2; } else if (properties.contains(MaterialProperty.BOOTS)) { setBoots(null); index = 3; } else { continue; } armorFlags[index] = true; iterator.remove(); } if (armorFlags[0] && armorFlags[1] && armorFlags[2] && armorFlags[3]) break; } ItemStack[] kitItems = _items.toArray(new ItemStack[_items.size()]); if (!InventoryUtils.remove(kitItems, items).isEmpty()) { _items.clear(); kitItems = ArrayUtils.removeNull(kitItems); Collections.addAll(_items, kitItems); return true; } return false; } // give equipment to EntityEquipment private void giveEquipment(EntityEquipment equipment, GiveKitEvent event) { if (event.getHelmet() != null) equipment.setHelmet(event.getHelmet()); if (event.getChestplate() != null) equipment.setChestplate(event.getChestplate()); if (event.getLeggings() != null) equipment.setLeggings(event.getLeggings()); if (event.getBoots() != null) equipment.setBoots(event.getBoots()); } // give equipment to Inventory private void giveEquipmentInventory(Inventory inventory, GiveKitEvent event) { if (event.getHelmet() != null) inventory.addItem(event.getHelmet()); if (event.getChestplate() != null) inventory.addItem(event.getChestplate()); if (event.getLeggings() != null) inventory.addItem(event.getLeggings()); if (event.getBoots() != null) inventory.addItem(event.getBoots()); } }
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.ui.update; import com.intellij.ide.UiActivity; import com.intellij.ide.UiActivityMonitor; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.Disposer; import com.intellij.util.Alarm; import com.intellij.util.AlarmFactory; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Map; import java.util.TreeMap; public class MergingUpdateQueue implements Runnable, Disposable, Activatable { public static final JComponent ANY_COMPONENT = new JComponent() { }; private volatile boolean myActive; private volatile boolean mySuspended; private final Map<Update, Update> myScheduledUpdates = new TreeMap<Update, Update>(); private final Alarm myWaiterForMerge; private volatile boolean myFlushing; private final String myName; private int myMergingTimeSpan; private JComponent myModalityStateComponent; private final boolean myExecuteInDispatchThread; private boolean myPassThrough; private boolean myDisposed; private UiNotifyConnector myUiNotifyConnector; private boolean myRestartOnAdd; private boolean myTrackUiActivity; private UiActivity myUiActivity; public MergingUpdateQueue(@NonNls @NotNull String name, int mergingTimeSpan, boolean isActive, @Nullable JComponent modalityStateComponent) { this(name, mergingTimeSpan, isActive, modalityStateComponent, null); } public MergingUpdateQueue(@NonNls @NotNull String name, int mergingTimeSpan, boolean isActive, @Nullable JComponent modalityStateComponent, @Nullable Disposable parent) { this(name, mergingTimeSpan, isActive, modalityStateComponent, parent, null); } public MergingUpdateQueue(@NonNls @NotNull String name, int mergingTimeSpan, boolean isActive, @Nullable JComponent modalityStateComponent, @Nullable Disposable parent, @Nullable JComponent activationComponent) { this(name, mergingTimeSpan, isActive, modalityStateComponent, parent, activationComponent, true); } public MergingUpdateQueue(@NonNls @NotNull String name, int mergingTimeSpan, boolean isActive, @Nullable JComponent modalityStateComponent, @Nullable Disposable parent, @Nullable JComponent activationComponent, boolean executeInDispatchThread) { this(name, mergingTimeSpan, isActive, modalityStateComponent, parent, activationComponent, executeInDispatchThread ? Alarm.ThreadToUse.SWING_THREAD : Alarm.ThreadToUse.POOLED_THREAD); } public MergingUpdateQueue(@NonNls @NotNull String name, int mergingTimeSpan, boolean isActive, @Nullable JComponent modalityStateComponent, @Nullable Disposable parent, @Nullable JComponent activationComponent, @NotNull Alarm.ThreadToUse thread) { myMergingTimeSpan = mergingTimeSpan; myModalityStateComponent = modalityStateComponent; myName = name; myPassThrough = ApplicationManager.getApplication().isUnitTestMode(); myExecuteInDispatchThread = thread == Alarm.ThreadToUse.SWING_THREAD; myWaiterForMerge = createAlarm(thread, myExecuteInDispatchThread ? null : this); if (isActive) { showNotify(); } if (parent != null) { Disposer.register(parent, this); } if (activationComponent != null) { setActivationComponent(activationComponent); } } protected Alarm createAlarm(@NotNull Alarm.ThreadToUse thread, Disposable parent) { return AlarmFactory.getInstance().create(thread, parent); } public void setMergingTimeSpan(int timeSpan) { myMergingTimeSpan = timeSpan; if (myActive) { restartTimer(); } } public void cancelAllUpdates() { synchronized (myScheduledUpdates) { Update[] updates = myScheduledUpdates.keySet().toArray(new Update[myScheduledUpdates.size()]); for (Update each : updates) { try { each.setRejected(); } catch (ProcessCanceledException ignored) { } } myScheduledUpdates.clear(); finishActivity(); } } public final boolean isPassThrough() { return myPassThrough; } public final void setPassThrough(boolean passThrough) { myPassThrough = passThrough; } public void activate() { showNotify(); } public void deactivate() { hideNotify(); } public void suspend() { mySuspended = true; } public void resume() { mySuspended = false; restartTimer(); } @Override public void hideNotify() { if (!myActive) { return; } myActive = false; finishActivity(); clearWaiter(); } @Override public void showNotify() { if (myActive) { return; } myActive = true; restartTimer(); flush(); } public void restartTimer() { restart(myMergingTimeSpan); } private void restart(final int mergingTimeSpan) { if (!myActive) return; clearWaiter(); if (myExecuteInDispatchThread) { myWaiterForMerge.addRequest(this, mergingTimeSpan, getMergerModalityState()); } else { myWaiterForMerge.addRequest(this, mergingTimeSpan); } } @Override public void run() { if (mySuspended) return; flush(); } public void flush() { synchronized (myScheduledUpdates) { if (myScheduledUpdates.isEmpty()) { finishActivity(); return; } } flush(true); } public void flush(boolean invokeLaterIfNotDispatch) { if (myFlushing) { return; } if (!isModalityStateCorrect()) { return; } myFlushing = true; final Runnable toRun = new Runnable() { @Override public void run() { try { final Update[] all; synchronized (myScheduledUpdates) { all = myScheduledUpdates.keySet().toArray(new Update[myScheduledUpdates.size()]); myScheduledUpdates.clear(); } for (Update each : all) { each.setProcessed(); } execute(all); } finally { myFlushing = false; if (isEmpty()) { finishActivity(); } } } }; if (myExecuteInDispatchThread && invokeLaterIfNotDispatch) { UIUtil.invokeLaterIfNeeded(toRun); } else { toRun.run(); } } public void setModalityStateComponent(JComponent modalityStateComponent) { myModalityStateComponent = modalityStateComponent; } protected boolean isModalityStateCorrect() { if (!myExecuteInDispatchThread) return true; if (myModalityStateComponent == ANY_COMPONENT) return true; ModalityState current = ApplicationManager.getApplication().getCurrentModalityState(); final ModalityState modalityState = getModalityState(); return !current.dominates(modalityState); } public boolean isSuspended() { return mySuspended; } private static boolean isExpired(@NotNull Update each) { return each.isDisposed() || each.isExpired(); } protected void execute(@NotNull Update[] update) { for (final Update each : update) { if (isExpired(each)) { each.setRejected(); continue; } if (each.executeInWriteAction()) { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { execute(each); } }); } else { execute(each); } } } private void execute(@NotNull Update each) { if (myDisposed) { each.setRejected(); } else { each.run(); } } public void queue(@NotNull final Update update) { if (myDisposed) return; if (myTrackUiActivity) { startActivity(); } if (myPassThrough) { update.run(); finishActivity(); return; } final boolean active = myActive; synchronized (myScheduledUpdates) { try { if (eatThisOrOthers(update)) { return; } if (active && myScheduledUpdates.isEmpty()) { restartTimer(); } put(update); if (myRestartOnAdd) { restartTimer(); } } finally { if (isEmpty()) { finishActivity(); } } } } private boolean eatThisOrOthers(@NotNull Update update) { if (myScheduledUpdates.containsKey(update)) { return false; } final Update[] updates = myScheduledUpdates.keySet().toArray(new Update[myScheduledUpdates.size()]); for (Update eachInQueue : updates) { if (eachInQueue.canEat(update)) { return true; } if (update.canEat(eachInQueue)) { myScheduledUpdates.remove(eachInQueue); eachInQueue.setRejected(); } } return false; } public final void run(@NotNull Update update) { execute(new Update[]{update}); } private void put(@NotNull Update update) { final Update existing = myScheduledUpdates.remove(update); if (existing != null && existing != update) { existing.setProcessed(); existing.setRejected(); } myScheduledUpdates.put(update, update); } public boolean isActive() { return myActive; } @Override public void dispose() { myDisposed = true; myActive = false; finishActivity(); clearWaiter(); } private void clearWaiter() { myWaiterForMerge.cancelAllRequests(); } @SuppressWarnings({"HardCodedStringLiteral"}) public String toString() { synchronized (myScheduledUpdates) { return myName + " active=" + myActive + " scheduled=" + myScheduledUpdates.size(); } } @Nullable private ModalityState getMergerModalityState() { return myModalityStateComponent == ANY_COMPONENT ? null : getModalityState(); } @NotNull public ModalityState getModalityState() { if (myModalityStateComponent == null) { return ModalityState.NON_MODAL; } return ModalityState.stateForComponent(myModalityStateComponent); } public void setActivationComponent(@NotNull JComponent c) { if (myUiNotifyConnector != null) { Disposer.dispose(myUiNotifyConnector); } UiNotifyConnector connector = new UiNotifyConnector(c, this); Disposer.register(this, connector); myUiNotifyConnector = connector; } public MergingUpdateQueue setRestartTimerOnAdd(final boolean restart) { myRestartOnAdd = restart; return this; } public boolean isEmpty() { synchronized (myScheduledUpdates) { return myScheduledUpdates.isEmpty(); } } public void sendFlush() { restart(0); } public boolean isFlushing() { return myFlushing; } public void setTrackUiActivity(boolean trackUiActivity) { if (myTrackUiActivity && !trackUiActivity) { finishActivity(); } myTrackUiActivity = trackUiActivity; } private void startActivity() { if (!myTrackUiActivity) return; UiActivityMonitor.getInstance().addActivity(getActivityId(), getModalityState()); } private void finishActivity() { if (!myTrackUiActivity) return; UiActivityMonitor.getInstance().removeActivity(getActivityId()); } @NotNull protected UiActivity getActivityId() { if (myUiActivity == null) { myUiActivity = new UiActivity.AsyncBgOperation("UpdateQueue:" + myName + hashCode()); } return myUiActivity; } }
/** * The MIT License * Copyright (c) 2003 David G Jones * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package info.dgjones.abora.white.spaces.basic; import info.dgjones.abora.white.exception.AboraRuntimeException; import info.dgjones.abora.white.xpp.basic.Heaper; /** * A coordinate space represents (among other things) the domain space of a table. * Corresponding to each coordinate space will be a set of objects of the following kinds: * <p> * Position -- The elements of the coordinate space.<br> * Mapping -- (Add a description.)<br> * OrderSpec -- The ways of specifying partial orders of this coordinate space's Positions.<br> * XuRegion -- An XuRegion represents a set of Positions. The domain of a table is an * XuRegion. * <p> * When defining a new coordinate space class, one generally defines new corresponing * subclasses of each of the above classes. A kind of any of the above classes knows what * coordinate space it is a part of (the "coordinateSpace()" message will yield an * appropriate kind of CoordinateSpace). CoordinateSpace objects exist mostly just to * represent this commonality. Coordinate spaces are disjoint--it is an error to use any of * the generic protocol of any of the above classes if the objects in question are of two * different coordinate spaces. For example, "<code>dsp->of (pos)</code>" is not an error iff * "<code>dsp->coordinateSpace()->isEqual (pos->coordinateSpace())</code>". * <p> * Note that this class is not COPY or even PSEUDO_COPY. All of the instance variables for * CoordinateSpace are basically cached * quantities that require vary little actual state from the derived classes in order to be * constructed. This realization allows a knot * to be untangled when reading these objects from external storage. */ public abstract class CoordinateSpace extends Heaper { protected XnRegion myEmptyRegion; protected XnRegion myFullRegion; protected Dsp myIdentityDsp; protected OrderSpec myAscending; protected OrderSpec myDescending; /* udanax-top.st:14289: Heaper subclass: #CoordinateSpace instanceVariableNames: ' myEmptyRegion {XnRegion} myFullRegion {XnRegion} myIdentityDsp {Dsp} myAscending {OrderSpec | NULL} myDescending {OrderSpec | NULL}' classVariableNames: '' poolDictionaries: '' category: 'Xanadu-Spaces-Basic'! */ /* udanax-top.st:14298: CoordinateSpace comment: 'A coordinate space represents (among other things) the domain space of a table. Corresponding to each coordinate space will be a set of objects of the following kinds: Position -- The elements of the coordinate space. Mapping -- (Add a description.) OrderSpec -- The ways of specifying partial orders of this coordinate space''s Positions. XuRegion -- An XuRegion represents a set of Positions. The domain of a table is an XuRegion. When defining a new coordinate space class, one generally defines new corresponing subclasses of each of the above classes. A kind of any of the above classes knows what coordinate space it is a part of (the "coordinateSpace()" message will yield an appropriate kind of CoordinateSpace). CoordinateSpace objects exist mostly just to represent this commonality. Coordinate spaces are disjoint--it is an error to use any of the generic protocol of any of the above classes if the objects in question are of two different coordinate spaces. For example, "dsp->of (pos)" is not an error iff "dsp->coordinateSpace()->isEqual (pos->coordinateSpace())". Note that this class is not COPY or even PSEUDO_COPY. All of the instance variables for CoordinateSpace are basically cached quantities that require vary little actual state from the derived classes in order to be constructed. This realization allows a knot to be untangled when reading these objects from external storage.'! */ /* udanax-top.st:14311: (CoordinateSpace getOrMakeCxxClassDescription) attributes: ((Set new) add: #ON.CLIENT; add: #DEFERRED; yourself)! */ /* udanax-top.st:14486: CoordinateSpace class instanceVariableNames: ''! */ /* udanax-top.st:14489: (CoordinateSpace getOrMakeCxxClassDescription) attributes: ((Set new) add: #ON.CLIENT; add: #DEFERRED; yourself)! */ public int actualHashForEqual() { return System.identityHashCode(this); // TODO return Heaper.takeOop(); /* udanax-top.st:14316:CoordinateSpace methodsFor: 'accessing'! {UInt32} actualHashForEqual ^Heaper takeOop! */ } /** * Essential. The natural full-ordering of the coordinate space. */ public OrderSpec ascending() { return getAscending(); /* udanax-top.st:14320:CoordinateSpace methodsFor: 'accessing'! {OrderSpec CLIENT INLINE} ascending "Essential. The natural full-ordering of the coordinate space." ^self getAscending! */ } /** * Essential. A Mapping which maps each position in this space to every position in the range * region. The region can be from any CoordinateSpace. */ public Mapping completeMapping(XnRegion range) { return Mapping.make(this, range); /* udanax-top.st:14325:CoordinateSpace methodsFor: 'accessing'! {Mapping CLIENT INLINE} completeMapping: range {XnRegion} "Essential. A Mapping which maps each position in this space to every position in the range region. The region can be from any CoordinateSpace." ^Mapping make.CoordinateSpace: self with.Region: range! */ } /** * The mirror image of the partial order returned by 'CoordinateSpace::ascending'. */ public OrderSpec descending() { return getDescending(); /* udanax-top.st:14330:CoordinateSpace methodsFor: 'accessing'! {OrderSpec CLIENT INLINE} descending "The mirror image of the partial order returned by 'CoordinateSpace::ascending'." ^self getDescending! */ } /** * Essential. An empty region in this coordinate space */ public XnRegion emptyRegion() { return myEmptyRegion; /* udanax-top.st:14335:CoordinateSpace methodsFor: 'accessing'! {XnRegion CLIENT INLINE} emptyRegion "Essential. An empty region in this coordinate space" ^myEmptyRegion! */ } /** * The natural full-ordering of the coordinate space. */ public OrderSpec fetchAscending() { return myAscending; /* udanax-top.st:14340:CoordinateSpace methodsFor: 'accessing'! {(OrderSpec | NULL) INLINE} fetchAscending "The natural full-ordering of the coordinate space." ^myAscending! */ } /** * The mirror image of the partial order returned by * 'CoordinateSpace::fetchAscending'. */ public OrderSpec fetchDescending() { return myDescending; /* udanax-top.st:14345:CoordinateSpace methodsFor: 'accessing'! {(OrderSpec | NULL) INLINE} fetchDescending "The mirror image of the partial order returned by 'CoordinateSpace::fetchAscending'." ^myDescending! */ } /** * A full region in this coordinate space */ public XnRegion fullRegion() { return myFullRegion; /* udanax-top.st:14351:CoordinateSpace methodsFor: 'accessing'! {XnRegion CLIENT INLINE} fullRegion "A full region in this coordinate space" ^myFullRegion! */ } /** * Essential. The natural full-ordering of the coordinate space. */ public OrderSpec getAscending() { OrderSpec result = fetchAscending(); if (result == null) { throw new AboraRuntimeException(AboraRuntimeException.NO_FULL_ORDER); } return result; /* udanax-top.st:14356:CoordinateSpace methodsFor: 'accessing'! {OrderSpec} getAscending "Essential. The natural full-ordering of the coordinate space." | result {OrderSpec | NULL} | result := self fetchAscending. result == NULL ifTrue: [Heaper BLAST: #NoFullOrder]. ^result! */ } /** * The mirror image of the partial order returned by 'CoordinateSpace::getAscending'. */ public OrderSpec getDescending() { OrderSpec result = fetchDescending(); if (result == null) { throw new AboraRuntimeException(AboraRuntimeException.NO_FULL_ORDER); } return result; /* udanax-top.st:14365:CoordinateSpace methodsFor: 'accessing'! {OrderSpec} getDescending "The mirror image of the partial order returned by 'CoordinateSpace::getAscending'." | result {OrderSpec | NULL} | result := self fetchDescending. result == NULL ifTrue: [Heaper BLAST: #NoFullOrder]. ^result! */ } /** * A Dsp which maps all positions in the coordinate space onto themselves */ public Dsp identityDsp() { return myIdentityDsp; /* udanax-top.st:14374:CoordinateSpace methodsFor: 'accessing'! {Dsp INLINE} identityDsp "A Dsp which maps all positions in the coordinate space onto themselves" ^myIdentityDsp! */ } /** * Essential. A Mapping which maps all positions in the coordinate space onto themselves */ public Mapping identityMapping() { return identityDsp(); /* udanax-top.st:14379:CoordinateSpace methodsFor: 'accessing'! {Mapping CLIENT INLINE} identityMapping "Essential. A Mapping which maps all positions in the coordinate space onto themselves" ^self identityDsp! */ } public abstract boolean isEqual(Heaper other); /* udanax-top.st:14384:CoordinateSpace methodsFor: 'accessing'! {BooleanVar} isEqual: other{Heaper} self subclassResponsibility! */ /** * tell whether this is a valid Position/XuRegion/Dsp/OrderSpec for this space */ public boolean verify(Heaper thing) { if (thing instanceof Position) { Position position = (Position) thing; return isEqual(position.coordinateSpace()); } else if (thing instanceof XnRegion) { XnRegion region = (XnRegion) thing; return isEqual(region.coordinateSpace()); } else if (thing instanceof Dsp) { Dsp dsp = (Dsp) thing; return isEqual(dsp.coordinateSpace()); } else if (thing instanceof OrderSpec) { OrderSpec orderSpec = (OrderSpec) thing; return isEqual(orderSpec.coordinateSpace()); } else { throw new IllegalArgumentException(); } /* udanax-top.st:14388:CoordinateSpace methodsFor: 'accessing'! {BooleanVar} verify: thing {Heaper} "tell whether this is a valid Position/XuRegion/Dsp/OrderSpec for this space" thing cast: (Position | XnRegion | Dsp | OrderSpec) into: [:t | ^self isEqual: t coordinateSpace]. "cast into blasts here." ^false! */ } protected CoordinateSpace(XnRegion emptyRegion, XnRegion fullRegion, Dsp identityDsp) { this(emptyRegion, fullRegion, identityDsp, null, null); /* udanax-top.st:14398:CoordinateSpace methodsFor: 'smalltalk: defaults'! create: emptyRegion {XnRegion} with: fullRegion {XnRegion} with: identityDsp {Dsp} self create: emptyRegion with: fullRegion with: identityDsp with: NULL with: NULL! */ } protected CoordinateSpace(XnRegion emptyRegion, XnRegion fullRegion, Dsp identityDsp, OrderSpec ascending) { this(emptyRegion, fullRegion, identityDsp, ascending, null); /* udanax-top.st:14404:CoordinateSpace methodsFor: 'smalltalk: defaults'! create: emptyRegion {XnRegion} with: fullRegion {XnRegion} with: identityDsp {Dsp} with: ascending {OrderSpec default: NULL} self create: emptyRegion with: fullRegion with: identityDsp with: ascending with: NULL! */ } public void finishCreate(XnRegion emptyRegion, XnRegion fullRegion, Dsp identityDsp, OrderSpec ascending, OrderSpec descending) { myEmptyRegion = emptyRegion; myFullRegion = fullRegion; myIdentityDsp = identityDsp; myAscending = ascending; if (descending == null && (ascending != null)) { myDescending = ascending.reversed(); } else { myDescending = descending; } /* udanax-top.st:14413:CoordinateSpace methodsFor: 'protected: create followup'! {void} finishCreate: emptyRegion {XnRegion} with: fullRegion {XnRegion} with: identityDsp {Dsp} with: ascending {OrderSpec default: NULL} with: descending {OrderSpec default: NULL} myEmptyRegion := emptyRegion. myFullRegion := fullRegion. myIdentityDsp := identityDsp. myAscending := ascending. (descending == NULL and: [ascending ~~ NULL]) ifTrue: [myDescending := ascending reversed] ifFalse: [myDescending := descending].! */ } protected CoordinateSpace() { super(); myEmptyRegion = null; myFullRegion = null; myIdentityDsp = null; myAscending = null; myDescending = null; /* udanax-top.st:14430:CoordinateSpace methodsFor: 'create'! create super create. myEmptyRegion := NULL. myFullRegion := NULL. myIdentityDsp := NULL. myAscending := NULL. myDescending := NULL.! */ } protected CoordinateSpace(XnRegion emptyRegion, XnRegion fullRegion, Dsp identityDsp, OrderSpec ascending, OrderSpec descending) { super(); myEmptyRegion = emptyRegion; myFullRegion = fullRegion; myIdentityDsp = identityDsp; myAscending = ascending; if (descending == null && (ascending != null)) { myDescending = ascending.reversed(); } else { myDescending = descending; } /* udanax-top.st:14439:CoordinateSpace methodsFor: 'create'! create: emptyRegion {XnRegion} with: fullRegion {XnRegion} with: identityDsp {Dsp} with: ascending {OrderSpec default: NULL} with: descending {OrderSpec default: NULL} super create. myEmptyRegion := emptyRegion. myFullRegion := fullRegion. myIdentityDsp := identityDsp. myAscending := ascending. (descending == NULL and: [ascending ~~ NULL]) ifTrue: [myDescending := ascending reversed] ifFalse: [myDescending := descending].! */ } // public Mapping importMapping(PrimArray data, CoordinateSpace rangeSpace) { // passe(); // /* // udanax-top.st:14457:CoordinateSpace methodsFor: 'smalltalk: passe'! // {Mapping} importMapping: data {PrimArray} with: rangeSpace {CoordinateSpace default: NULL} // self passe! // */ // } // public OrderSpec importOrderSpec(PrimArray data) { // passe(); // /* // udanax-top.st:14461:CoordinateSpace methodsFor: 'smalltalk: passe'! // {OrderSpec} importOrderSpec: data {PrimArray} // self passe! // */ // } // public XnRegion importRegion(PrimArray data) { // passe(); // /* // udanax-top.st:14465:CoordinateSpace methodsFor: 'smalltalk: passe'! // {XnRegion} importRegion: data {PrimArray} // self passe! // */ // } // public Mapping mapping(PrimArray data) { // passe(); // /* // udanax-top.st:14469:CoordinateSpace methodsFor: 'smalltalk: passe'! // {Mapping} mapping: data {PrimArray} // self passe! // */ // } // public Mapping mapping(PrimArray data, CoordinateSpace rangeSpace) { // passe(); // /* // udanax-top.st:14473:CoordinateSpace methodsFor: 'smalltalk: passe'! // {Mapping} mapping: data {PrimArray} with: rangeSpace {CoordinateSpace default: NULL} // self passe! // */ // } // public OrderSpec orderSpec(PrimArray data) { // passe(); // /* // udanax-top.st:14477:CoordinateSpace methodsFor: 'smalltalk: passe'! // {OrderSpec} orderSpec: data {PrimArray} // self passe! // */ // } // public XnRegion region(PrimArray data) { // passe(); // /* // udanax-top.st:14481:CoordinateSpace methodsFor: 'smalltalk: passe'! // {XnRegion} region: data {PrimArray} // self passe! // */ // } // /** // * {OrderSpec CLIENT} ascending // * {Mapping CLIENT} completeMapping: range {XuRegion} // * {OrderSpec CLIENT} descending // * {XuRegion CLIENT} emptyRegion // * {XuRegion CLIENT} fullRegion // * {Mapping CLIENT} identityMapping // */ // public static void info() { // /* // udanax-top.st:14494:CoordinateSpace class methodsFor: 'smalltalk: system'! // info.stProtocol // "{OrderSpec CLIENT} ascending // {Mapping CLIENT} completeMapping: range {XuRegion} // {OrderSpec CLIENT} descending // {XuRegion CLIENT} emptyRegion // {XuRegion CLIENT} fullRegion // {Mapping CLIENT} identityMapping // "! // */ // } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.procedure2; import java.io.IOException; import java.lang.Thread.UncaughtExceptionHandler; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.DelayQueue; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.yetus.audience.InterfaceAudience; import org.apache.hadoop.hbase.procedure2.util.DelayedUtil; import org.apache.hadoop.hbase.procedure2.util.DelayedUtil.DelayedContainerWithTimestamp; import org.apache.hadoop.hbase.procedure2.util.DelayedUtil.DelayedWithTimeout; import org.apache.hadoop.hbase.procedure2.util.StringUtils; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.util.Threads; import org.apache.hadoop.hbase.shaded.com.google.common.collect.ArrayListMultimap; /** * A procedure dispatcher that aggregates and sends after elapsed time or after we hit * count threshold. Creates its own threadpool to run RPCs with timeout. * <ul> * <li>Each server queue has a dispatch buffer</li> * <li>Once the dispatch buffer reaches a threshold-size/time we send<li> * </ul> * <p>Call {@link #start()} and then {@link #submitTask(Callable)}. When done, * call {@link #stop()}. */ @InterfaceAudience.Private public abstract class RemoteProcedureDispatcher<TEnv, TRemote extends Comparable<TRemote>> { private static final Log LOG = LogFactory.getLog(RemoteProcedureDispatcher.class); public static final String THREAD_POOL_SIZE_CONF_KEY = "hbase.procedure.remote.dispatcher.threadpool.size"; private static final int DEFAULT_THREAD_POOL_SIZE = 128; public static final String DISPATCH_DELAY_CONF_KEY = "hbase.procedure.remote.dispatcher.delay.msec"; private static final int DEFAULT_DISPATCH_DELAY = 150; public static final String DISPATCH_MAX_QUEUE_SIZE_CONF_KEY = "hbase.procedure.remote.dispatcher.max.queue.size"; private static final int DEFAULT_MAX_QUEUE_SIZE = 32; private final AtomicBoolean running = new AtomicBoolean(false); private final ConcurrentHashMap<TRemote, BufferNode> nodeMap = new ConcurrentHashMap<TRemote, BufferNode>(); private final int operationDelay; private final int queueMaxSize; private final int corePoolSize; private TimeoutExecutorThread timeoutExecutor; private ThreadPoolExecutor threadPool; protected RemoteProcedureDispatcher(Configuration conf) { this.corePoolSize = conf.getInt(THREAD_POOL_SIZE_CONF_KEY, DEFAULT_THREAD_POOL_SIZE); this.operationDelay = conf.getInt(DISPATCH_DELAY_CONF_KEY, DEFAULT_DISPATCH_DELAY); this.queueMaxSize = conf.getInt(DISPATCH_MAX_QUEUE_SIZE_CONF_KEY, DEFAULT_MAX_QUEUE_SIZE); } public boolean start() { if (running.getAndSet(true)) { LOG.warn("Already running"); return false; } LOG.info("Starting procedure remote dispatcher; threads=" + this.corePoolSize + ", queueMaxSize=" + this.queueMaxSize + ", operationDelay=" + this.operationDelay); // Create the timeout executor timeoutExecutor = new TimeoutExecutorThread(); timeoutExecutor.start(); // Create the thread pool that will execute RPCs threadPool = Threads.getBoundedCachedThreadPool(corePoolSize, 60L, TimeUnit.SECONDS, Threads.newDaemonThreadFactory(this.getClass().getSimpleName(), getUncaughtExceptionHandler())); return true; } public boolean stop() { if (!running.getAndSet(false)) { return false; } LOG.info("Stopping procedure remote dispatcher"); // send stop signals timeoutExecutor.sendStopSignal(); threadPool.shutdownNow(); return true; } public void join() { assert !running.get() : "expected not running"; // wait the timeout executor timeoutExecutor.awaitTermination(); timeoutExecutor = null; // wait for the thread pool to terminate threadPool.shutdownNow(); try { while (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) { LOG.warn("Waiting for thread-pool to terminate"); } } catch (InterruptedException e) { LOG.warn("Interrupted while waiting for thread-pool termination", e); } } protected UncaughtExceptionHandler getUncaughtExceptionHandler() { return new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { LOG.warn("Failed to execute remote procedures " + t.getName(), e); } }; } // ============================================================================================ // Node Helpers // ============================================================================================ /** * Add a node that will be able to execute remote procedures * @param key the node identifier */ public void addNode(final TRemote key) { assert key != null: "Tried to add a node with a null key"; final BufferNode newNode = new BufferNode(key); nodeMap.putIfAbsent(key, newNode); } /** * Add a remote rpc. Be sure to check result for successful add. * @param key the node identifier * @return True if we successfully added the operation. */ public boolean addOperationToNode(final TRemote key, RemoteProcedure rp) { assert key != null : "found null key for node"; BufferNode node = nodeMap.get(key); if (node == null) { return false; } node.add(rp); // Check our node still in the map; could have been removed by #removeNode. return nodeMap.contains(node); } /** * Remove a remote node * @param key the node identifier */ public boolean removeNode(final TRemote key) { final BufferNode node = nodeMap.remove(key); if (node == null) return false; node.abortOperationsInQueue(); return true; } // ============================================================================================ // Task Helpers // ============================================================================================ protected Future<Void> submitTask(Callable<Void> task) { return threadPool.submit(task); } protected Future<Void> submitTask(Callable<Void> task, long delay, TimeUnit unit) { final FutureTask<Void> futureTask = new FutureTask(task); timeoutExecutor.add(new DelayedTask(futureTask, delay, unit)); return futureTask; } protected abstract void remoteDispatch(TRemote key, Set<RemoteProcedure> operations); protected abstract void abortPendingOperations(TRemote key, Set<RemoteProcedure> operations); /** * Data structure with reference to remote operation. */ public static abstract class RemoteOperation { private final RemoteProcedure remoteProcedure; protected RemoteOperation(final RemoteProcedure remoteProcedure) { this.remoteProcedure = remoteProcedure; } public RemoteProcedure getRemoteProcedure() { return remoteProcedure; } } /** * Remote procedure reference. * @param <TEnv> * @param <TRemote> */ public interface RemoteProcedure<TEnv, TRemote> { RemoteOperation remoteCallBuild(TEnv env, TRemote remote); void remoteCallCompleted(TEnv env, TRemote remote, RemoteOperation response); void remoteCallFailed(TEnv env, TRemote remote, IOException exception); } /** * Account of what procedures are running on remote node. * @param <TEnv> * @param <TRemote> */ public interface RemoteNode<TEnv, TRemote> { TRemote getKey(); void add(RemoteProcedure<TEnv, TRemote> operation); void dispatch(); } protected ArrayListMultimap<Class<?>, RemoteOperation> buildAndGroupRequestByType(final TEnv env, final TRemote remote, final Set<RemoteProcedure> operations) { final ArrayListMultimap<Class<?>, RemoteOperation> requestByType = ArrayListMultimap.create(); for (RemoteProcedure proc: operations) { RemoteOperation operation = proc.remoteCallBuild(env, remote); requestByType.put(operation.getClass(), operation); } return requestByType; } protected <T extends RemoteOperation> List<T> fetchType( final ArrayListMultimap<Class<?>, RemoteOperation> requestByType, final Class<T> type) { return (List<T>)requestByType.removeAll(type); } // ============================================================================================ // Timeout Helpers // ============================================================================================ private final class TimeoutExecutorThread extends Thread { private final DelayQueue<DelayedWithTimeout> queue = new DelayQueue<DelayedWithTimeout>(); public TimeoutExecutorThread() { super("ProcedureDispatcherTimeoutThread"); } @Override public void run() { while (running.get()) { final DelayedWithTimeout task = DelayedUtil.takeWithoutInterrupt(queue); if (task == null || task == DelayedUtil.DELAYED_POISON) { // the executor may be shutting down, and the task is just the shutdown request continue; } if (task instanceof DelayedTask) { threadPool.execute(((DelayedTask)task).getObject()); } else { ((BufferNode)task).dispatch(); } } } public void add(final DelayedWithTimeout delayed) { queue.add(delayed); } public void remove(final DelayedWithTimeout delayed) { queue.remove(delayed); } public void sendStopSignal() { queue.add(DelayedUtil.DELAYED_POISON); } public void awaitTermination() { try { final long startTime = EnvironmentEdgeManager.currentTime(); for (int i = 0; isAlive(); ++i) { sendStopSignal(); join(250); if (i > 0 && (i % 8) == 0) { LOG.warn("Waiting termination of thread " + getName() + ", " + StringUtils.humanTimeDiff(EnvironmentEdgeManager.currentTime() - startTime)); } } } catch (InterruptedException e) { LOG.warn(getName() + " join wait got interrupted", e); } } } // ============================================================================================ // Internals Helpers // ============================================================================================ /** * Node that contains a set of RemoteProcedures */ protected final class BufferNode extends DelayedContainerWithTimestamp<TRemote> implements RemoteNode<TEnv, TRemote> { private Set<RemoteProcedure> operations; protected BufferNode(final TRemote key) { super(key, 0); } public TRemote getKey() { return getObject(); } public synchronized void add(final RemoteProcedure operation) { if (this.operations == null) { this.operations = new HashSet<>(); setTimeout(EnvironmentEdgeManager.currentTime() + operationDelay); timeoutExecutor.add(this); } this.operations.add(operation); if (this.operations.size() > queueMaxSize) { timeoutExecutor.remove(this); dispatch(); } } public synchronized void dispatch() { if (operations != null) { remoteDispatch(getKey(), operations); this.operations = null; } } public synchronized void abortOperationsInQueue() { if (operations != null) { abortPendingOperations(getKey(), operations); this.operations = null; } } @Override public String toString() { return super.toString() + ", operations=" + this.operations; } } /** * Delayed object that holds a FutureTask. * used to submit something later to the thread-pool. */ private static final class DelayedTask extends DelayedContainerWithTimestamp<FutureTask<Void>> { public DelayedTask(final FutureTask<Void> task, final long delay, final TimeUnit unit) { super(task, EnvironmentEdgeManager.currentTime() + unit.toMillis(delay)); } }; }
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.jaxws.utils.v201505; import static org.apache.commons.lang.CharEncoding.UTF_8; import com.google.api.ads.dfp.jaxws.v201505.ApiException_Exception; import com.google.api.ads.dfp.jaxws.v201505.ExportFormat; import com.google.api.ads.dfp.jaxws.v201505.ReportDownloadOptions; import com.google.api.ads.dfp.jaxws.v201505.ReportJobStatus; import com.google.api.ads.dfp.jaxws.v201505.ReportServiceInterface; import com.google.api.ads.dfp.lib.utils.ReportCallback; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.io.ByteSource; import com.google.common.io.CharSource; import com.google.common.io.Resources; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.Set; import java.util.zip.GZIPInputStream; /** * Retrieves reports using a {@link ReportServiceInterface}. * <p> * There are two main functions of this class: * <ul> * <li>To download a report in Gzip format to a file or any {@code OutputStream} * </li> * <li>To get the report and perform a number of tasks on it</li> * </ul> * <p> * {@code ReportUtils} also provides the method * {@link #whenReportReady(ReportCallback)} to wait for a scheduled report to * finish processing before taking an action on the report through the supplied * {@link ReportCallback}. * * @author Adam Rogal */ public class ReportDownloader { public static final Charset REPORT_CHARSET = Charset.forName(UTF_8); /** The time to sleep before each request to the service. */ public static final int SLEEP_TIMER = 30000; private final ReportServiceInterface reportService; private final long reportJobId; private static final Set<ExportFormat> SUPPORTED_CHARSOUCE_EXPORT_FORMATS = ImmutableSet.of(ExportFormat.CSV_DUMP, ExportFormat.TSV, ExportFormat.XML); private static class GZippedByteSource extends ByteSource { private ByteSource containedByteSource; public GZippedByteSource(ByteSource zippedByteSource) { containedByteSource = zippedByteSource; } @Override public InputStream openStream() throws IOException { return new GZIPInputStream(containedByteSource.openStream()); } } /** * Constructs a {@code ReportDownloader} object for a * {@link ReportServiceInterface} and a report job id that the the class works * on. * * @param reportService the ReportService stub to make calls to * @param reportJobId the report job ID */ public ReportDownloader(ReportServiceInterface reportService, long reportJobId) { this.reportJobId = reportJobId; this.reportService = reportService; } /** * Waits for the report to be ready and then calls: * <ul> * <li>{@link ReportCallback#onSuccess()} for a successful scheduling</li> * <li>{@link ReportCallback#onFailure()} for a failed scheduling due to a * {@link ReportJobStatus#FAILED}</li> * <li>{@link ReportCallback#onInterruption()} if the wait thread is * interrupted</li> * <li>{@link ReportCallback#onException(Exception)} if there was an exception * while waiting for the report to finish</li> * </ul> * * @param callback the {@code ReportCallback} to call when the job has * finished, successfully or otherwise * @throws IllegalArgumentException if {@code callback == null} * @return the thread created that handles waiting for the report. * {@link Thread#interrupt()} can be called on the returned thread to * interrupt it. */ public Thread whenReportReady(final ReportCallback callback) { Preconditions.checkNotNull(callback, "Report callback cannot be null."); Thread waitThread = new Thread("ReportUtils.whenReportReady " + reportJobId) { @Override public void run() { try { if (waitForReportReady()) { callback.onSuccess(); } else { callback.onFailure(); } } catch (ApiException_Exception e) { callback.onException(e); } catch (InterruptedException e) { callback.onInterruption(); } catch (RuntimeException e) { callback.onException(e); } } }; waitThread.start(); return waitThread; } /** * Blocks and waits for a report to be ready. When a {@link ReportJobStatus} * is received that is not {@code ReportJobStatus#Pending} or {@code * ReportJobStatus#InProgress}, the report is considered finished, and the * method is returned with a {@code true} if the report was successful, or an * {@code false} if not. * * @return {@code true} if the report was successful, {@code false} otherwise * @throws ApiException_Exception if there was an error performing one of the SOAP * calls * @throws InterruptedException if the thread was interrupted */ public boolean waitForReportReady() throws InterruptedException, ApiException_Exception { ReportJobStatus status = reportService.getReportJobStatus(reportJobId); while (status == ReportJobStatus.IN_PROGRESS) { Thread.sleep(SLEEP_TIMER); status = reportService.getReportJobStatus(reportJobId); } return status == ReportJobStatus.COMPLETED; } /** * Downloads a Gzip report to file located at {@code fileName}. * * @param exportFormat the export format of the report * @param fileName the file location to download the report to * @throws IOException if there was an error performing any I/O action, * including any SOAP calls * @throws ApiException_Exception if there was any problem making the SOAP * call * @throws IllegalStateException if the report is not ready to be downloaded * @deprecated use {@link #getReportAsByteSource(ReportDownloadOptions)} */ @Deprecated public void downloadReport(ExportFormat exportFormat, String fileName) throws IOException, ApiException_Exception { downloadReport(exportFormat, new FileOutputStream(fileName)); } /** * Downloads a Gzip or plain-text format report XML to output stream indicated * by {@code outputStream}. * * @param exportFormat the export format of the report * @param outputStream the output stream to download the report to * @throws IOException if there was an error performing any I/O action, * including any SOAP calls * @throws ApiException_Exception if there was any problem making the SOAP * call * @throws IllegalStateException if the report is not ready to be downloaded * @deprecated use {@link #getReportAsByteSource(ReportDownloadOptions)} */ @Deprecated public void downloadReport(ExportFormat exportFormat, OutputStream outputStream) throws IOException, ApiException_Exception { ReportDownloadOptions options = new ReportDownloadOptions(); options.setExportFormat(exportFormat); options.setUseGzipCompression(true); Resources.asByteSource(getDownloadUrl(options)).copyTo(outputStream); } /** * Gets the plain-text format report as a {@code String}. * * * @param exportFormat the export format of the report * @return the plain-text format report XML as a {@code String} * @throws IOException if there was an error performing any I/O action, * including any SOAP calls * @throws ApiException_Exception if there was any problem making the SOAP * call * @throws IllegalStateException if the report is not ready to be downloaded * @deprecated use {@link #getReportAsCharSource(ReportDownloadOptions)} */ @Deprecated public String getReport(ExportFormat exportFormat) throws IOException, ApiException_Exception { ReportDownloadOptions options = new ReportDownloadOptions(); options.setExportFormat(exportFormat); options.setUseGzipCompression(true); return getReportAsCharSource(options).read(); } /** * Gets the download URL for a GZip or plain-text format report. If you requested * a compressed report, you may want to save your file with a gz or zip extension. * * <pre><code> * URL url = new URL(reportDownloader.getDownloadUrl(options)); * Resources.asByteSource(url).copyTo(Files.asByteSink(file)); * </code></pre> * * @param options the options to download the report with * @return the URL for the report download * @throws ApiException_Exception if there was an error performing any jaxws call * @throws MalformedURLException if there is an error forming the download URL * @throws IllegalStateException if the report is not ready to be downloaded */ public URL getDownloadUrl(ReportDownloadOptions options) throws ApiException_Exception, MalformedURLException { ReportJobStatus status = reportService.getReportJobStatus(reportJobId); Preconditions.checkState(status == ReportJobStatus.COMPLETED, "Report " + reportJobId + " must be completed before downloading. It is currently: " + status); return new URL(reportService.getReportDownloadUrlWithOptions(reportJobId, options)); } /** * Returns a CharSource of report contents with {@code ReportDownloadOptions}. The ExportFormat * must be string-based, such as * {@link com.google.api.ads.dfp.jaxws.v201505.ExportFormat#CSV_DUMP}. * * @param options the options to download the report with * @return a new CharSource of report results * @throws IOException if there was an error performing any I/O action, including any SOAP calls * @throws ApiException_Exception if there was any problem making the SOAP * call * @throws IllegalStateException if the report is not ready to be downloaded * @throws IllegalArgumentException if the {@link ExportFormat} is not a string-based format */ public CharSource getReportAsCharSource(ReportDownloadOptions options) throws IOException, ApiException_Exception { Preconditions.checkArgument( SUPPORTED_CHARSOUCE_EXPORT_FORMATS.contains(options.getExportFormat()), "ExportFormat " + options.getExportFormat() + " cannot be used with CharSource"); ByteSource byteSource = Resources.asByteSource(getDownloadUrl(options)); return (options.isUseGzipCompression() ? new GZippedByteSource(byteSource) : byteSource) .asCharSource(REPORT_CHARSET); } }
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.indexing.common.index; import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import io.druid.data.input.Committer; import io.druid.data.input.InputRow; import io.druid.java.util.common.StringUtils; import io.druid.java.util.common.logger.Logger; import io.druid.query.Query; import io.druid.query.QueryRunner; import io.druid.segment.IndexIO; import io.druid.segment.IndexMergerV9; import io.druid.segment.QueryableIndex; import io.druid.segment.SegmentUtils; import io.druid.segment.incremental.IncrementalIndexAddResult; import io.druid.segment.incremental.IndexSizeExceededException; import io.druid.segment.indexing.DataSchema; import io.druid.segment.indexing.RealtimeTuningConfig; import io.druid.segment.indexing.TuningConfigs; import io.druid.segment.loading.DataSegmentPusher; import io.druid.segment.realtime.FireDepartmentMetrics; import io.druid.segment.realtime.FireHydrant; import io.druid.segment.realtime.plumber.Plumber; import io.druid.segment.realtime.plumber.PlumberSchool; import io.druid.segment.realtime.plumber.Sink; import io.druid.timeline.DataSegment; import org.apache.commons.io.FileUtils; import org.joda.time.Interval; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Set; /** * Trains plumbers that create a single historical segment. */ @JsonTypeName("historical") public class YeOldePlumberSchool implements PlumberSchool { private final Interval interval; private final String version; private final DataSegmentPusher dataSegmentPusher; private final File tmpSegmentDir; private final IndexMergerV9 indexMergerV9; private final IndexIO indexIO; private static final Logger log = new Logger(YeOldePlumberSchool.class); @JsonCreator public YeOldePlumberSchool( @JsonProperty("interval") Interval interval, @JsonProperty("version") String version, @JacksonInject("segmentPusher") DataSegmentPusher dataSegmentPusher, @JacksonInject("tmpSegmentDir") File tmpSegmentDir, @JacksonInject IndexMergerV9 indexMergerV9, @JacksonInject IndexIO indexIO ) { this.interval = interval; this.version = version; this.dataSegmentPusher = dataSegmentPusher; this.tmpSegmentDir = tmpSegmentDir; this.indexMergerV9 = Preconditions.checkNotNull(indexMergerV9, "Null IndexMergerV9"); this.indexIO = Preconditions.checkNotNull(indexIO, "Null IndexIO"); } @Override public Plumber findPlumber( final DataSchema schema, final RealtimeTuningConfig config, final FireDepartmentMetrics metrics ) { // There can be only one. final Sink theSink = new Sink( interval, schema, config.getShardSpec(), version, config.getMaxRowsInMemory(), TuningConfigs.getMaxBytesInMemoryOrDefault(config.getMaxBytesInMemory()), config.isReportParseExceptions(), config.getDedupColumn() ); // Temporary directory to hold spilled segments. final File persistDir = new File(tmpSegmentDir, theSink.getSegment().getIdentifier()); // Set of spilled segments. Will be merged at the end. final Set<File> spilled = Sets.newHashSet(); return new Plumber() { @Override public Object startJob() { return null; } @Override public IncrementalIndexAddResult add(InputRow row, Supplier<Committer> committerSupplier) throws IndexSizeExceededException { Sink sink = getSink(row.getTimestampFromEpoch()); if (sink == null) { return Plumber.THROWAWAY; } final IncrementalIndexAddResult addResult = sink.add(row, false); if (!sink.canAppendRow()) { persist(committerSupplier.get()); } return addResult; } private Sink getSink(long timestamp) { if (theSink.getInterval().contains(timestamp)) { return theSink; } else { return null; } } @Override public <T> QueryRunner<T> getQueryRunner(Query<T> query) { throw new UnsupportedOperationException("Don't query me, bro."); } @Override public void persist(Committer committer) { spillIfSwappable(); committer.run(); } @Override public void finishJob() { // The segment we will upload File fileToUpload = null; try { // User should have persisted everything by now. Preconditions.checkState(!theSink.swappable(), "All data must be persisted before fininshing the job!"); if (spilled.size() == 0) { throw new IllegalStateException("Nothing indexed?"); } else if (spilled.size() == 1) { fileToUpload = Iterables.getOnlyElement(spilled); } else { List<QueryableIndex> indexes = Lists.newArrayList(); for (final File oneSpill : spilled) { indexes.add(indexIO.loadIndex(oneSpill)); } fileToUpload = new File(tmpSegmentDir, "merged"); indexMergerV9.mergeQueryableIndex( indexes, schema.getGranularitySpec().isRollup(), schema.getAggregators(), fileToUpload, config.getIndexSpec(), config.getSegmentWriteOutMediumFactory() ); } // Map merged segment so we can extract dimensions final QueryableIndex mappedSegment = indexIO.loadIndex(fileToUpload); final DataSegment segmentToUpload = theSink.getSegment() .withDimensions(ImmutableList.copyOf(mappedSegment.getAvailableDimensions())) .withBinaryVersion(SegmentUtils.getVersionFromDir(fileToUpload)); dataSegmentPusher.push(fileToUpload, segmentToUpload, false); log.info( "Uploaded segment[%s]", segmentToUpload.getIdentifier() ); } catch (Exception e) { log.warn(e, "Failed to merge and upload"); throw Throwables.propagate(e); } finally { try { if (fileToUpload != null) { log.info("Deleting Index File[%s]", fileToUpload); FileUtils.deleteDirectory(fileToUpload); } } catch (IOException e) { log.warn(e, "Error deleting directory[%s]", fileToUpload); } } } private void spillIfSwappable() { if (theSink.swappable()) { final FireHydrant indexToPersist = theSink.swap(); final int rowsToPersist = indexToPersist.getIndex().size(); final File dirToPersist = getSpillDir(indexToPersist.getCount()); log.info("Spilling index[%d] with rows[%d] to: %s", indexToPersist.getCount(), rowsToPersist, dirToPersist); try { indexMergerV9.persist( indexToPersist.getIndex(), dirToPersist, config.getIndexSpec(), config.getSegmentWriteOutMediumFactory() ); indexToPersist.swapSegment(null); metrics.incrementRowOutputCount(rowsToPersist); spilled.add(dirToPersist); } catch (Exception e) { log.warn(e, "Failed to spill index[%d]", indexToPersist.getCount()); throw Throwables.propagate(e); } } } private File getSpillDir(final int n) { return new File(persistDir, StringUtils.format("spill%d", n)); } }; } }
/* * Copyright (c) 2008 Pyxis Technologies inc. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, * or see the FSF site: http://www.fsf.org. * * IMPORTANT NOTE : * Kindly contributed by Bertrand Paquet from Octo Technology (http://www.octo.com) */ package com.greenpepper.phpsud.compiler; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.greenpepper.phpsud.container.IPHPJavaClassCreator; import com.greenpepper.phpsud.container.PHPClassDescriptor; import com.greenpepper.phpsud.container.PHPContainer; import com.greenpepper.phpsud.container.PHPMethodDescriptor; import com.greenpepper.phpsud.parser.PHPObject; /** * @author Bertrand Paquet */ public class PHPJavaClassCreator implements IPHPJavaClassCreator { private static final Logger LOGGER = Logger.getLogger(PHPJavaClassCreator.class); private static final String packageName = "com.greenpepper.phpsud.compiler.temp."; private static final String fieldPHPContainer = "localPHPContainer"; private String javaClassName; private PHPClassDescriptor descriptor; private Class<?> clazz; private Constructor<?> constructor; public PHPJavaClassCreator(PHPContainer container, PHPClassDescriptor descriptor, int uniqueId) { this.javaClassName = packageName + "container" + uniqueId + "." + descriptor.getClassName(); this.descriptor = descriptor; createClass(container); } private void createClass(PHPContainer container) { try { boolean equalsImplemented = false; CompilerWrapper wrapper = new CompilerWrapper(javaClassName, PHPObject.class); // Add logger field wrapper.addField( "LOGGER", Logger.class, false, true, true, Logger.class.getCanonicalName() + ".getLogger(" + javaClassName + ".class)" ); // Add container filed wrapper.addField( fieldPHPContainer, PHPContainer.class, false, true, true, PHPContainer.class.getCanonicalName() + ".getPHPContainer(" + container.getId() + ")" ); // Add constructor wrapper.addConstructor( new Class<?> []{String.class}, "super(" + fieldPHPContainer + ", \"" + descriptor.getClassName() + "\", $1)", "LOGGER.debug(\"Create object " + javaClassName + " for id : \" + $1)" ); // Add methods for(String m : descriptor.getMethodList()) { PHPMethodDescriptor method = descriptor.getMethod(m); String name = method.getMethodName(); // Add getters if (name.startsWith("get")) { wrapper.addMethod( name, Object.class, new Class<?>[]{}, false, "return invoke(\"" + name + "\")" ); } // Add toString if (name.equals("toString") && method.getParamList().size() == 0) { wrapper.addMethod( name, String.class, new Class<?>[]{}, false, "return (String) invoke(\"" + name + "\")" ); } // Add equals if (name.equals("equals") && method.getParamList().size() == 1) { wrapper.addMethod( name, Boolean.class, new Class<?>[]{Object.class}, false, "LOGGER.debug(\"Equals called : \" + $1)", "return super.equalsTo($1)" ); equalsImplemented = true; } // Add parse if (name.equals("parse") && method.getParamList().size() == 1) { wrapper.addMethod( name, null, new Class<?>[]{String.class}, true, "LOGGER.debug(\"Parse called : \" + $1)", "String id = " + PHPObject.class.getCanonicalName() + ".parse(" + fieldPHPContainer + ", \"" + descriptor.getClassName() + "\", $1)", "return id == null ? null : new " + javaClassName + "(id);" ); } } // Add default equals if not implemented in PHP if (!equalsImplemented) { wrapper.addMethod( "equals", Boolean.class, new Class<?>[]{Object.class}, false, "LOGGER.debug(\"Transfer equals to PHP : \" + this + \" and \" + $1)", "return super.phpEquals($1)" ); LOGGER.info("Warning, equals method not implemented in PHP Class " + descriptor.getClassName()); } // Add Static var and value of for enum if (descriptor.getStaticVarList().size() != 0) { List<String> l = new ArrayList<String>(); l.add("LOGGER.debug(\"valueof called for \" + $1)"); for(String s : descriptor.getStaticVarList().keySet()) { l.add("if (\"" + s +"\".equals($1)) {"); l.add("return " + s); l.add("}"); wrapper.addField( s, null, true, true, false, "new " + javaClassName + "(\"PHPOBJ_STATIC_" + descriptor.getClassName() + "_" + descriptor.getStaticVarList().get(s).substring(1) + "\")" ); } l.add("return null"); wrapper.addMethod( "valueOf", null, new Class<?>[]{String.class}, true, l.toArray(new String[0])); } clazz = wrapper.getGeneratedClass(); constructor = clazz.getConstructor(new Class<?>[] {String.class}); } catch(Exception e) { LOGGER.error("Unable to compile code " + e.toString()); e.printStackTrace(); } } public Class<?> getGeneratedClass() { return clazz; } public Object createNewObject(String id) { if (this.clazz == null || this.constructor == null) { LOGGER.error("Unable to get class or constructor"); return null; } try { Object o = constructor.newInstance(id); return o; } catch (Exception e) { LOGGER.error("Unable to create object " + e.toString()); } return null; } }
package com.elastisys.scale.commons.net.http; import static com.elastisys.scale.commons.util.precond.Preconditions.checkArgument; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.net.ssl.HostnameVerifier; import org.apache.http.Header; import org.apache.http.HttpHeaders; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.message.BasicHeader; import org.slf4j.Logger; import com.elastisys.scale.commons.net.ssl.BasicCredentials; import com.elastisys.scale.commons.net.ssl.CertificateCredentials; import com.elastisys.scale.commons.net.ssl.KeyStoreType; import com.elastisys.scale.commons.net.ssl.SslContextBuilder; import com.elastisys.scale.commons.net.ssl.SslUtils; /** * A builder of HTTP(S) clients. * * @see Http */ public class HttpBuilder { /** * The default timeout in milliseconds until a connection is established. A * timeout value of zero is interpreted as an infinite timeout. A negative * value is interpreted as undefined (system default). */ public static final int DEFAULT_CONNECTION_TIMEOUT = 20000; /** * The default socket timeout ({@code SO_TIMEOUT}) in milliseconds, which is * the timeout for waiting for data or, put differently, a maximum period * inactivity between two consecutive data packets). A timeout value of zero * is interpreted as an infinite timeout. A negative value is interpreted as * undefined (system default). */ public static final int DEFAULT_SOCKET_TIMEOUT = 20000; /** * The {@link HttpClientBuilder} that is used to collect settings for the * {@link Http} instance being built. */ private final HttpClientBuilder clientBuilder; /** * Builder that collects SSL-related settings for the {@link Http} instance * being built. */ private final SslContextBuilder sslContextBuilder; /** * Builder that collects values to set for the default {@link RequestConfig} * for the {@link Http} instance being built. */ private final RequestConfig.Builder requestConfigBuilder; /** * Collects default headers to use for the {@link Http} instance being * built. */ private final Map<String, String> defaultHeaders; private Logger logger; /** * Creates a new {@link HttpBuilder}. Without additional input, the builder * is set up to build {@link Http} instances with the following properties: * <ul> * <li>default connection timeout and socket timeout: 20 seconds</li> * <li>server authentication/verification (on SSL): none</li> * <li>client authentication: none</li> * <li>default request content type: application/json</li> * </ul> * All of these settings can be modified through the builder's methods. */ public HttpBuilder() { this.clientBuilder = HttpClients.custom(); this.clientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); this.requestConfigBuilder = RequestConfig.copy(RequestConfig.DEFAULT); this.requestConfigBuilder.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT); this.requestConfigBuilder.setSocketTimeout(DEFAULT_SOCKET_TIMEOUT); this.sslContextBuilder = SslContextBuilder.newBuilder(); verifyHostCert(false); verifyHostname(false); this.defaultHeaders = new HashMap<>(); contentType(ContentType.APPLICATION_JSON); this.logger = Http.LOG; } /** * Constructs a {@link Http} instance from the parameters supplied to the * {@link HttpBuilder}. * * @return * @throws HttpBuilderException */ public Http build() throws HttpBuilderException { try { this.clientBuilder.setSSLContext(this.sslContextBuilder.build()); } catch (Exception e) { throw new HttpBuilderException("failed to set SSL context when building HTTP client: " + e.getMessage(), e); } this.clientBuilder.setDefaultRequestConfig(this.requestConfigBuilder.build()); List<Header> headers = new ArrayList<>(); this.defaultHeaders.entrySet().stream().forEach(header -> { headers.add(new BasicHeader(header.getKey(), header.getValue())); }); this.clientBuilder.setDefaultHeaders(headers); return new Http(this.clientBuilder, this.logger); } /** * Sets the {@link Logger} to use for built {@link Http} instances. * * @param logger * @return */ public HttpBuilder logger(Logger logger) { this.logger = logger; return this; } /** * The default timeout in milliseconds until a connection is established. A * timeout value of zero is interpreted as an infinite timeout. A negative * value is interpreted as undefined (system default). * <p/> * This value can be overridden on a per-request basis in the created * {@link Http} client. * * @param connectTimeout * @return */ public HttpBuilder connectionTimeout(int connectTimeout) { this.requestConfigBuilder.setConnectTimeout(connectTimeout); return this; } /** * The default socket timeout ({@code SO_TIMEOUT}) in milliseconds, which is * the timeout for waiting for data or, put differently, a maximum period * inactivity between two consecutive data packets). A timeout value of zero * is interpreted as an infinite timeout. A negative value is interpreted as * undefined (system default). * <p/> * This value can be overridden on a per-request basis in the created * {@link Http} client. * * @param socketTimeout * @return */ public HttpBuilder socketTimeout(int socketTimeout) { this.requestConfigBuilder.setSocketTimeout(socketTimeout); return this; } /** * Sets a default header for the {@link Http} client being built. * * <p/> * Headers can be overridden on a per-request basis in the created * {@link Http} client. * * @param name * The header name. For example, {@code Content-Type}. * @param value * The header value. For example, {@code application/json}. * @return */ public HttpBuilder header(String name, String value) { this.defaultHeaders.put(name, value); return this; } /** * Sets a default {@code Content-Type} header to use for the {@link Http} * client being built. * <p/> * Headers can be overridden on a per-request basis in the created * {@link Http} client. * * @param contentType * Content type to set. For example, * {@link ContentType#TEXT_PLAIN}. * @return */ public HttpBuilder contentType(ContentType contentType) { header(HttpHeaders.CONTENT_TYPE, contentType.toString()); return this; } /** * Set to enable basic (username/password) client authentication. See * <a href="http://en.wikipedia.org/wiki/Basic_access_authentication">Basic * autentication</a>. * * @param clientBasicCredentials * @return */ public HttpBuilder clientBasicAuth(BasicCredentials clientBasicCredentials) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( clientBasicCredentials.getUsername(), clientBasicCredentials.getPassword())); this.clientBuilder.setDefaultCredentialsProvider(credentialsProvider); return this; } /** * Set to enable client certificate authentication for SSL connections. If * set, the client certificate will be included in SSL connections, and the * server may choose to authenticate the client via the provided * certificate. Client certificate authentication is further described * <a href="http://docs.oracle.com/javaee/6/tutorial/doc/glien.html">here * </a>. * * @param clientCertCredentials * The certificate credentials to be used for authenticating the * client. * @return */ public HttpBuilder clientCertAuth(CertificateCredentials clientCertCredentials) { String keystorePath = clientCertCredentials.getKeystorePath(); String keystorePassword = clientCertCredentials.getKeystorePassword(); String keyPassword = clientCertCredentials.getKeyPassword(); KeyStore keyStore = null; try { keyStore = SslUtils.loadKeyStore(clientCertCredentials.getKeystoreType(), keystorePath, keystorePassword); } catch (Exception e) { throw new HttpBuilderException("failed to set client certificate credentials: " + e.getMessage(), e); } return clientCertAuth(keyStore, keyPassword); } /** * Set to enable client certificate authentication for SSL connections. If * set, a client certificate from the supplied {@link KeyStore} will be * included in SSL connections, and the server may choose to authenticate * the client via the provided certificate. Client certificate * authentication is further described * <a href="http://docs.oracle.com/javaee/6/tutorial/doc/glien.html">here * </a>. * * @param clientCertKeystore * The {@link KeyStore} containing the client certificate and * private key to be used for authenticating the client. * @param keyPassword * The password used to recover the client key from the key * store. * @return */ public HttpBuilder clientCertAuth(KeyStore clientCertKeystore, String keyPassword) { checkArgument(clientCertKeystore != null, "null keystore given"); checkArgument(keyPassword != null, "null keyPassword given (keystore keys cannot " + "be recovered without a password)"); try { this.sslContextBuilder.clientAuthentication(clientCertKeystore, keyPassword); } catch (Exception e) { throw new HttpBuilderException("failed to set client certificate credentials: " + e.getMessage(), e); } return this; } /** * Adds a default header used to carry a signed authentication token * * <pre> * {@code Authorization: Bearer <token>} * </pre> * * Refer to the * <a href="http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-15"> * JSON Web Token specification</a> and the * <a href="http://tools.ietf.org/html/rfc6750">bearer token * specification</a>. * * @param signedAuthToken * A signed auth token to be included in a * {@code Authorization: Bearer <token>} header. * @return */ public HttpBuilder clientJwtAuth(String signedAuthToken) { return header(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", signedAuthToken)); } /** * Set to <code>true</code> to enable server certificate verification on SSL * connections. If disabled, the server peer will not be verified, which is * similar to using the {@code --insecure} flag in {@code curl}. * <p/> * If enabled, the host certificate is verified against either the * configured trust store (if one has been set via * {@link #serverAuthTrustStore(KeyStore)}) or a against a default trust * store configured with the JVM (see the guide on <a href= * "http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/JSSERefGuide.html#CustomizingStores"> * JSSE</a>) in case no trust store has been explicitly set. * * @return */ public HttpBuilder verifyHostCert(boolean shouldVerify) { try { this.sslContextBuilder.setVerifyHostCert(shouldVerify); return this; } catch (Exception e) { throw new HttpBuilderException( String.format("failed to set verifyHostCert to %s: %s", shouldVerify, e.getMessage()), e); } } /** * Sets a custom trust store to use when server authentication is requested * (via {@link #verifyHostCert}). If no custom trust store has been * specified and server authentication is requested via * {@link #verifyHostCert(boolean)}, the server certificate according to the * default trust store configured with the JVM (see the guide on <a href= * "http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/JSSERefGuide.html#CustomizingStores"> * JSSE</a>). * * @param type * The type of the trust store. * @param trustStorePath * The file system path to a trust store that contains trusted * CA/server certificates. * @param storePassword * The password used to protect the integrity of the trust store. * Can be <code>null</code>. * @return * @throws NoSuchAlgorithmException * @throws KeyStoreException */ public HttpBuilder serverAuthTrustStore(KeyStoreType type, String trustStorePath, String storePassword) throws HttpBuilderException { KeyStore trustStore = null; try { trustStore = SslUtils.loadKeyStore(type, trustStorePath, storePassword); } catch (Exception e) { throw new HttpBuilderException("failed to set server auth trust store: " + e.getMessage(), e); } return serverAuthTrustStore(trustStore); } /** * Sets a custom trust store to use when server authentication is requested * (via {@link #verifyHostCert}). If no custom trust store has been * specified and server authentication is requested via * {@link #verifyHostCert(boolean)}, the server certificate according to the * default trust store configured with the JVM (see the guide on <a href= * "http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/JSSERefGuide.html#CustomizingStores"> * JSSE</a>). * * @param trustStore * The {@link KeyStore} that contains trusted CA/server * certificates. * @return * @throws NoSuchAlgorithmException * @throws KeyStoreException */ public HttpBuilder serverAuthTrustStore(KeyStore trustStore) throws HttpBuilderException { try { this.sslContextBuilder.serverAuthTrustStore(trustStore); } catch (Exception e) { throw new HttpBuilderException("failed to set server auth trust store: " + e.getMessage(), e); } return this; } /** * Enables/disables hostname verification during SSL handshakes. * <p/> * If verification is enabled, the SSL handshake will only succeed if the * URL's hostname and the server's identification hostname match. * * @param shouldVerify * Enable (<code>true</code>) or disable (<code>false</code>). * @return */ public HttpBuilder verifyHostname(boolean shouldVerify) { HostnameVerifier sslHostnameVerifier = shouldVerify ? new DefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE; this.clientBuilder.setSSLHostnameVerifier(sslHostnameVerifier); return this; } }
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core.io; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; import java.net.URLConnection; import org.springframework.util.ResourceUtils; /** * Abstract base class for resources which resolve URLs into File references, * such as {@link UrlResource} or {@link ClassPathResource}. * * <p>Detects the "file" protocol as well as the JBoss "vfs" protocol in URLs, * resolving file system references accordingly. * * @author Juergen Hoeller * @since 3.0 */ public abstract class AbstractFileResolvingResource extends AbstractResource { /** * This implementation returns a File reference for the underlying class path * resource, provided that it refers to a file in the file system. * @see org.springframework.util.ResourceUtils#getFile(java.net.URL, String) */ @Override public File getFile() throws IOException { URL url = getURL(); if (url.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) { return VfsResourceDelegate.getResource(url).getFile(); } return ResourceUtils.getFile(url, getDescription()); } /** * This implementation determines the underlying File * (or jar file, in case of a resource in a jar/zip). */ @Override protected File getFileForLastModifiedCheck() throws IOException { URL url = getURL(); if (ResourceUtils.isJarURL(url)) { URL actualUrl = ResourceUtils.extractJarFileURL(url); if (actualUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) { return VfsResourceDelegate.getResource(actualUrl).getFile(); } return ResourceUtils.getFile(actualUrl, "Jar URL"); } else { return getFile(); } } /** * This implementation returns a File reference for the underlying class path * resource, provided that it refers to a file in the file system. * @see org.springframework.util.ResourceUtils#getFile(java.net.URI, String) */ protected File getFile(URI uri) throws IOException { if (uri.getScheme().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) { return VfsResourceDelegate.getResource(uri).getFile(); } return ResourceUtils.getFile(uri, getDescription()); } @Override public boolean exists() { try { URL url = getURL(); if (ResourceUtils.isFileURL(url)) { // Proceed with file system resolution... return getFile().exists(); } else { // Try a URL connection content-length header... URLConnection con = url.openConnection(); customizeConnection(con); HttpURLConnection httpCon = (con instanceof HttpURLConnection ? (HttpURLConnection) con : null); if (httpCon != null) { int code = httpCon.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { return true; } else if (code == HttpURLConnection.HTTP_NOT_FOUND) { return false; } } if (con.getContentLength() >= 0) { return true; } if (httpCon != null) { // no HTTP OK status, and no content-length header: give up httpCon.disconnect(); return false; } else { // Fall back to stream existence: can we open the stream? InputStream is = getInputStream(); is.close(); return true; } } } catch (IOException ex) { return false; } } @Override public boolean isReadable() { try { URL url = getURL(); if (ResourceUtils.isFileURL(url)) { // Proceed with file system resolution... File file = getFile(); return (file.canRead() && !file.isDirectory()); } else { return true; } } catch (IOException ex) { return false; } } @Override public long contentLength() throws IOException { URL url = getURL(); if (ResourceUtils.isFileURL(url)) { // Proceed with file system resolution... return getFile().length(); } else { // Try a URL connection content-length header... URLConnection con = url.openConnection(); customizeConnection(con); return con.getContentLength(); } } @Override public long lastModified() throws IOException { URL url = getURL(); if (ResourceUtils.isFileURL(url) || ResourceUtils.isJarURL(url)) { // Proceed with file system resolution... return super.lastModified(); } else { // Try a URL connection last-modified header... URLConnection con = url.openConnection(); customizeConnection(con); return con.getLastModified(); } } /** * Customize the given {@link URLConnection}, obtained in the course of an * {@link #exists()}, {@link #contentLength()} or {@link #lastModified()} call. * <p>Calls {@link ResourceUtils#useCachesIfNecessary(URLConnection)} and * delegates to {@link #customizeConnection(HttpURLConnection)} if possible. * Can be overridden in subclasses. * @param con the URLConnection to customize * @throws IOException if thrown from URLConnection methods */ protected void customizeConnection(URLConnection con) throws IOException { ResourceUtils.useCachesIfNecessary(con); if (con instanceof HttpURLConnection) { customizeConnection((HttpURLConnection) con); } } /** * Customize the given {@link HttpURLConnection}, obtained in the course of an * {@link #exists()}, {@link #contentLength()} or {@link #lastModified()} call. * <p>Sets request method "HEAD" by default. Can be overridden in subclasses. * @param con the HttpURLConnection to customize * @throws IOException if thrown from HttpURLConnection methods */ protected void customizeConnection(HttpURLConnection con) throws IOException { con.setRequestMethod("HEAD"); } /** * Inner delegate class, avoiding a hard JBoss VFS API dependency at runtime. */ private static class VfsResourceDelegate { public static Resource getResource(URL url) throws IOException { return new VfsResource(VfsUtils.getRoot(url)); } public static Resource getResource(URI uri) throws IOException { return new VfsResource(VfsUtils.getRoot(uri)); } } }
package simcity.TRestaurant; import agent.Role ; import simcity.gui.SimCityGui; import simcity.gui.trace.AlertLog; import simcity.gui.trace.AlertTag; import simcity.interfaces.Cook; import simcity.interfaces.MarketCashier; import simcity.interfaces.MarketManager; import simcity.interfaces.RestaurantCashier; import simcity.interfaces.TCook; import simcity.interfaces.TWaiter; import java.util.*; import java.util.concurrent.Semaphore; import simcity.PersonAgent; import simcity.Drew_restaurant.Drew_CookRole.Order; import simcity.Market.MFoodOrder; import simcity.TRestaurant.gui.TCookGui; import simcity.TRestaurant.gui.TWaiterGui; /** * Restaurant Cook Agent */ public class TCookRole extends Role implements TCook, Cook { private OrderStand myStand; Timer timer = new Timer(); private String name; public boolean buyingFood = false; private boolean unFullfilled = false; boolean arrived; public TCookGui cookGui = null; public List<Orders> orders = Collections.synchronizedList(new ArrayList<Orders>()); Random randomQuan = new Random(); SimCityGui gui; private Semaphore atCounter = new Semaphore(0,true); Map<String, Integer> Supply = new HashMap<String, Integer>(4); public List<Market> markets = Collections.synchronizedList(new ArrayList<Market>()); enum MarketState {none, waiting, received, confirming}; THostRole host; boolean goHome = false; public TCookRole(SimCityGui gui) { super(); this.name = name; addFood(); arrived = true; this.gui = gui; myStand = new OrderStand(); } class Orders { TWaiter thisWaiter; String order; int table; OrderStatus status; public void setTable (int t) { table = t; } public void setOrder (String choice) { order = choice; status = OrderStatus.pending; } public void setWaiter (TWaiter w) { thisWaiter = w; } } //private Food food = new Food(); int timeCooked; enum OrderStatus {pending, cooking, cooked, removed}; TWaiterRole waiter; TCashierRole cashier; //Messages @Override public void msgSetInventory(int val) { // TODO Auto-generated method stub Supply.put("Steak", val); Supply.put("Pizza", val); Supply.put("Salad", val); Supply.put("Chicken", val); } public void msgHereIsAnOrder(int t, String choice, TWaiter w) { Orders o = new Orders(); o.setWaiter(w); o.setTable(t); o.setOrder(choice); orders.add(o); AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TCookRole", "Cook has received customer orders"); Do("Cook has received customer orders."); stateChanged(); } public void msgPleaseConfirmBill(MarketCashier mart) { synchronized(markets) { for (Market m:markets) { if (m.m == mart) { m.state = MarketState.confirming; } } } stateChanged(); } private void msgCheckStand() { stateChanged(); } /** public void msgCanGive(Map<String, Integer> nS, double check, Market mart) { for (Market m:markets) { if (m.m == mart) { m.state = MarketState.receivedCheck; m.bill = check; } } Map<String, Integer> newSupply= nS; Supply.put("Steak", newSupply.get("Steak") + Supply.get("Steak")); Supply.put("Chicken", newSupply.get("Chicken") + Supply.get("Chicken")); Supply.put("Salad", newSupply.get("Salad") + Supply.get("Salad")); Supply.put("Pizza", newSupply.get("Pizza") + Supply.get("Pizza")); print("Restocking supply"); print (Supply.get("Steak") + " Steaks, " + Supply.get("Chicken") + " Chickens, " + Supply.get("Salad") + " Salads, " + Supply.get("Pizza") + " Pizzas"); newSupply.clear(); } */ /******************************** delivery from market *****************************************/ public void msgHereIsDelivery(List<MFoodOrder> canGiveMe, double bill, MarketManager manager, MarketCashier cashier) { synchronized(markets) { for (Market m:markets) { if (m.m == manager) { m.state = MarketState.received; m.bill = bill; m.c = cashier; } } } for (MFoodOrder f: canGiveMe) { Supply.put(f.type, Supply.get(f.type) + f.amount); } // set restaurant cashier so that restaurant cashier knows who to pay //Market m.cashier = cashier; stateChanged(); } /************************************************************************************************/ public void msgUnfulfilledStock() { buyingFood = false; unFullfilled = true; AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TCookRole", "Buying stock from different market"); Do("Buying stock from different market"); stateChanged(); } public void msgAtCounter() { atCounter.release(); stateChanged(); } public void msgGoHome(double moneys) { myPerson.money += moneys; goHome = true; stateChanged(); } /** * Scheduler. Determine what action is called for, and do it. */ public boolean pickAndExecuteAnAction() { if(arrived) { tellHost(); return true; } synchronized(markets) { for (Market m:markets) { if( m.state == MarketState.confirming ){ confirmCheck(m); return true; } } } if (unFullfilled == true) { BuyFood(); } if (!orders.isEmpty()){ synchronized(orders) { for (int index = 0; index < orders.size(); index++) { if (orders.get(index).status == OrderStatus.pending) { if (orders.get(index).order == "Steak") { if (Supply.get("Steak") <= 0) { orders.get(index).status = OrderStatus.removed; callWaiter(index); BuyFood(); return true; } else { orders.get(index).status = OrderStatus.cooking; cookFood(index); return true; } } if (orders.get(index).order == "Chicken") { if (Supply.get("Chicken") <= 0) { orders.get(index).status = OrderStatus.removed; callWaiter(index); BuyFood(); return true; } else { orders.get(index).status = OrderStatus.cooking; cookFood(index); return true; } } if (orders.get(index).order == "Salad") { if (Supply.get("Salad") <= 0) { orders.get(index).status = OrderStatus.removed; BuyFood(); callWaiter(index); return true; } else { orders.get(index).status = OrderStatus.cooking; cookFood(index); return true; } } if (orders.get(index).order == "Pizza") { if (Supply.get("Pizza") <= 0) { orders.get(index).status = OrderStatus.removed; callWaiter(index); //BuyFood(); return true; } else { orders.get(index).status = OrderStatus.cooking; cookFood(index); return true; } } } } } } if(goHome) { goHome(); return true; } else { checkOrders(); } return false; } // Actions private void tellHost() { AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TCookRole", "Telling manager I can work"); Do("Telling manager I can work"); arrived = false; host.msgIAmHere(this, "Cook"); if (cookGui == null) { cookGui = new TCookGui(this); gui.myPanels.get("Restaurant 6").panel.addGui(cookGui); } } private void cookFood(final int orderNumber) { goToFridge(); timer.schedule(new TimerTask() { public void run() { AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TCookRole", "Done cooking food"); Do("Done cooking food."); orders.get(orderNumber).status = OrderStatus.cooked; if (orders.get(orderNumber).order == "Steak") { Supply.put("Steak", Supply.get("Steak") - 1); Do("There are " + Supply.get("Steak") + " steaks left"); } if (orders.get(orderNumber).order == "Chicken") { Supply.put("Chicken", Supply.get("Chicken") - 1); Do("There are " + Supply.get("Chicken") + " chickens left"); } if (orders.get(orderNumber).order == "Salad") { Supply.put("Salad", Supply.get("Salad") - 1); Do("There are " + Supply.get("Salad") + " salads left"); } if (orders.get(orderNumber).order == "Pizza") { Supply.put("Pizza", Supply.get("Pizza") - 1); Do("There are " + Supply.get("Pizza") + " pizzas left"); } leaveFood(); try { atCounter.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } orders.get(orderNumber).thisWaiter.msgOrderIsReady(orders.get(orderNumber).table); waitForOrder(); stateChanged(); } }, 8000); } private void callWaiter(int orderNumber) { AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TCookRole", "Out of food"); Do("Out of food"); orders.get(orderNumber).thisWaiter.msgOutOfFood(orders.get(orderNumber).table); } private void checkOrders() { RotatingOrders newOrder = myStand.remove(); if (newOrder != null) { Orders o = new Orders(); o.setWaiter(newOrder.w); o.setTable(newOrder.table); o.setOrder(newOrder.choice); orders.add(o); AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TCookRole", "Cook has received customer orders"); Do("Cook has received customer orders."); stateChanged(); } else { timer.schedule(new TimerTask() { public void run() { msgCheckStand(); } }, 2000); } } private void BuyFood() { if (buyingFood == false) { AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TCookRole", "Buying food from market"); Do("Buying food from market."); buyingFood = true; int index = 0; int checkedMarkets = 0; while (markets.get(index).checked != true && index < markets.size()) { index++; checkedMarkets++; } if (checkedMarkets == markets.size()) { print("Checked all markets for supply"); for (index = 0; index < markets.size(); index++) { markets.get(index).checked = false; } } else { /********************************* have cook send a list of MFoodOrder (type and amount) to Market)**************/ List<MFoodOrder> neededSupply = new ArrayList<MFoodOrder>(); if (Supply.get("Steak") < 5) { neededSupply.add(new MFoodOrder("Steak", 5 - Supply.get("Steak"))); } if (Supply.get("Chicken") < 5) { neededSupply.add(new MFoodOrder("Chicken", 5 - Supply.get("Chicken"))); } if (Supply.get("Pizza") < 5) { neededSupply.add(new MFoodOrder("Pizza", 5 - Supply.get("Pizza"))); } if (Supply.get("Salad") < 5) { neededSupply.add(new MFoodOrder("Salad", 5 - Supply.get("Salad"))); } markets.get(index).m.msgIAmHere(this, neededSupply, "TRestaurant", "cook", cashier); markets.get(index).checked = true; markets.get(index).state = MarketState.waiting; /************************************************************************************************/ } } } private void confirmCheck(Market m) { cashier.msgBillIsCorrect(m.c); print("Checking the bill for the cashier."); markets.remove(m); } private void goHome() { AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TCookRole", "Going home"); Do("Going home"); cookGui.LeaveRestaurant(); isActive = false; goHome = false; } //animations private void goToFridge() { cookGui.makeFood(); } private void leaveFood() { cookGui.giveFoodToWaiter(); } private void waitForOrder() { cookGui.goHome(); } //utilities public void addMarket(MarketManager manager) { Market m = new Market(manager); markets.add(m); } public void setHost(THostRole h) { host = h; } public void addFood() { /** Supply.put("Steak", 0); Supply.put("Pizza", 0); Supply.put("Salad", 0); Supply.put("Chicken", 0); */ Supply.put("Steak", randomQuan.nextInt(10)); Supply.put("Pizza", randomQuan.nextInt(10)); Supply.put("Salad", randomQuan.nextInt(10)); Supply.put("Chicken", randomQuan.nextInt(10)); } public void setGui(TCookGui gui) { cookGui = gui; } public TCookGui getGui() { return cookGui; } @Override public void msgOrderFulfilled(Map<String, Integer> nS) { // TODO Auto-generated method stub } public class Market { MarketManager m; MarketCashier c; MarketState state; boolean checked; double bill; Market(MarketManager mar) { m = mar; checked = false; state = MarketState.none; } public List<String> foodChoices = new ArrayList<String>(); public void setMarket (MarketManager mar) { m = mar; checked = false; state = MarketState.none; } } public void setCashier(TCashierRole c){ this.cashier = c; } @Override public void msgGoToCashier(MarketCashier c) { // TODO Auto-generated method stub } @Override public void msgMarketClosed() { // TODO Auto-generated method stub } }
// Copyright 2019 The Nomulus Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package google.registry.ui.server.registrar; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.security.JsonResponseHelper.Status.SUCCESS; import static google.registry.ui.server.registrar.RegistrarConsoleModule.PARAM_CLIENT_ID; import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import com.google.appengine.api.users.User; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.flogger.FluentLogger; import com.google.common.net.MediaType; import com.google.gson.Gson; import google.registry.model.domain.RegistryLock; import google.registry.model.registrar.Registrar; import google.registry.model.registrar.RegistrarContact; import google.registry.model.tld.RegistryLockDao; import google.registry.request.Action; import google.registry.request.Action.Method; import google.registry.request.Parameter; import google.registry.request.RequestMethod; import google.registry.request.Response; import google.registry.request.auth.Auth; import google.registry.request.auth.AuthResult; import google.registry.request.auth.AuthenticatedRegistrarAccessor; import google.registry.request.auth.AuthenticatedRegistrarAccessor.RegistrarAccessDeniedException; import google.registry.security.JsonResponseHelper; import java.util.Objects; import java.util.Optional; import javax.inject.Inject; import org.joda.time.DateTime; /** * Servlet that allows for getting locks for a particular registrar. * * <p>Note: at the moment we have no mechanism for JSON GET/POSTs in the same class or at the same * URL, which is why this is distinct from the {@link RegistryLockPostAction}. */ @Action( service = Action.Service.DEFAULT, path = RegistryLockGetAction.PATH, auth = Auth.AUTH_PUBLIC_LOGGED_IN) public final class RegistryLockGetAction implements JsonGetAction { public static final String PATH = "/registry-lock-get"; private static final String LOCK_ENABLED_FOR_CONTACT_PARAM = "lockEnabledForContact"; private static final String EMAIL_PARAM = "email"; private static final String LOCKS_PARAM = "locks"; private static final String DOMAIN_NAME_PARAM = "domainName"; private static final String LOCKED_TIME_PARAM = "lockedTime"; private static final String LOCKED_BY_PARAM = "lockedBy"; private static final String IS_LOCK_PENDING_PARAM = "isLockPending"; private static final String IS_UNLOCK_PENDING_PARAM = "isUnlockPending"; private static final String USER_CAN_UNLOCK_PARAM = "userCanUnlock"; private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final Gson GSON = new Gson(); @VisibleForTesting Method method; private final Response response; @VisibleForTesting AuthenticatedRegistrarAccessor registrarAccessor; @VisibleForTesting AuthResult authResult; @VisibleForTesting Optional<String> paramClientId; @Inject RegistryLockGetAction( @RequestMethod Method method, Response response, AuthenticatedRegistrarAccessor registrarAccessor, AuthResult authResult, @Parameter(PARAM_CLIENT_ID) Optional<String> paramClientId) { this.method = method; this.response = response; this.registrarAccessor = registrarAccessor; this.authResult = authResult; this.paramClientId = paramClientId; } @Override public void run() { checkArgument(Method.GET.equals(method), "Only GET requests allowed"); checkArgument(authResult.userAuthInfo().isPresent(), "User auth info must be present"); checkArgument(paramClientId.isPresent(), "clientId must be present"); response.setContentType(MediaType.JSON_UTF_8); try { ImmutableMap<String, ?> resultMap = getLockedDomainsMap(paramClientId.get()); ImmutableMap<String, ?> payload = JsonResponseHelper.create(SUCCESS, "Successful locks retrieval", resultMap); response.setPayload(GSON.toJson(payload)); } catch (RegistrarAccessDeniedException e) { logger.atWarning().withCause(e).log( "User %s doesn't have access to this registrar.", authResult.userIdForLogging()); response.setStatus(SC_FORBIDDEN); } catch (Exception e) { logger.atWarning().withCause(e).log( "Unexpected error when retrieving locks for a registrar."); response.setStatus(SC_INTERNAL_SERVER_ERROR); } } static Optional<RegistrarContact> getContactMatchingLogin(User user, Registrar registrar) { ImmutableList<RegistrarContact> matchingContacts = registrar.getContacts().stream() .filter(contact -> contact.getGaeUserId() != null) .filter(contact -> Objects.equals(contact.getGaeUserId(), user.getUserId())) .collect(toImmutableList()); if (matchingContacts.size() > 1) { ImmutableList<String> matchingEmails = matchingContacts.stream() .map(RegistrarContact::getEmailAddress) .collect(toImmutableList()); throw new IllegalArgumentException( String.format( "User ID %s had multiple matching contacts with email addresses %s", user.getUserId(), matchingEmails)); } return matchingContacts.stream().findFirst(); } static Registrar getRegistrarAndVerifyLockAccess( AuthenticatedRegistrarAccessor registrarAccessor, String clientId, boolean isAdmin) throws RegistrarAccessDeniedException { Registrar registrar = registrarAccessor.getRegistrar(clientId); checkArgument( isAdmin || registrar.isRegistryLockAllowed(), "Registry lock not allowed for registrar %s", clientId); return registrar; } private ImmutableMap<String, ?> getLockedDomainsMap(String registrarId) throws RegistrarAccessDeniedException { // Note: admins always have access to the locks page checkArgument(authResult.userAuthInfo().isPresent(), "User auth info must be present"); boolean isAdmin = registrarAccessor.isAdmin(); Registrar registrar = getRegistrarAndVerifyLockAccess(registrarAccessor, registrarId, isAdmin); User user = authResult.userAuthInfo().get().user(); Optional<RegistrarContact> contactOptional = getContactMatchingLogin(user, registrar); boolean isRegistryLockAllowed = isAdmin || contactOptional.map(RegistrarContact::isRegistryLockAllowed).orElse(false); // Use the contact's registry lock email if it's present, else use the login email (for admins) String relevantEmail = isAdmin ? user.getEmail() // if the contact isn't present, we shouldn't display the email anyway so empty is fine : contactOptional.flatMap(RegistrarContact::getRegistryLockEmailAddress).orElse(""); return ImmutableMap.of( LOCK_ENABLED_FOR_CONTACT_PARAM, isRegistryLockAllowed, EMAIL_PARAM, relevantEmail, PARAM_CLIENT_ID, registrar.getRegistrarId(), LOCKS_PARAM, getLockedDomains(registrarId, isAdmin)); } private ImmutableList<ImmutableMap<String, ?>> getLockedDomains( String registrarId, boolean isAdmin) { return jpaTm() .transact( () -> RegistryLockDao.getLocksByRegistrarId(registrarId).stream() .filter(lock -> !lock.isLockRequestExpired(jpaTm().getTransactionTime())) .map(lock -> lockToMap(lock, isAdmin)) .collect(toImmutableList())); } private ImmutableMap<String, ?> lockToMap(RegistryLock lock, boolean isAdmin) { DateTime now = jpaTm().getTransactionTime(); return new ImmutableMap.Builder<String, Object>() .put(DOMAIN_NAME_PARAM, lock.getDomainName()) .put(LOCKED_TIME_PARAM, lock.getLockCompletionTime().map(DateTime::toString).orElse("")) .put(LOCKED_BY_PARAM, lock.isSuperuser() ? "admin" : lock.getRegistrarPocId()) .put(IS_LOCK_PENDING_PARAM, !lock.getLockCompletionTime().isPresent()) .put( IS_UNLOCK_PENDING_PARAM, lock.getUnlockRequestTime().isPresent() && !lock.getUnlockCompletionTime().isPresent() && !lock.isUnlockRequestExpired(now)) .put(USER_CAN_UNLOCK_PARAM, isAdmin || !lock.isSuperuser()) .build(); } }
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.introduceparameterobject.usageInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.impl.source.PsiImmediateClassType; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.refactoring.changeSignature.ChangeSignatureProcessor; import com.intellij.refactoring.changeSignature.ParameterInfoImpl; import com.intellij.refactoring.util.FixableUsageInfo; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.Nullable; import java.util.*; @SuppressWarnings({"MethodWithTooManyParameters"}) public class MergeMethodArguments extends FixableUsageInfo { private final PsiMethod method; private final PsiClass myContainingClass; private final boolean myChangeSignature; private final boolean myKeepMethodAsDelegate; private final List<PsiTypeParameter> typeParams; private final String className; private final String packageName; private final String parameterName; private final int[] paramsToMerge; private final boolean lastParamIsVararg; public MergeMethodArguments(PsiMethod method, String className, String packageName, String parameterName, int[] paramsToMerge, List<PsiTypeParameter> typeParams, final boolean keepMethodAsDelegate, final PsiClass containingClass, boolean changeSignature) { super(method); this.paramsToMerge = paramsToMerge; this.packageName = packageName; this.className = className; this.parameterName = parameterName; this.method = method; myContainingClass = containingClass; myChangeSignature = changeSignature; lastParamIsVararg = method.isVarArgs() && isParameterToMerge(method.getParameterList().getParametersCount() - 1); myKeepMethodAsDelegate = keepMethodAsDelegate; this.typeParams = new ArrayList<PsiTypeParameter>(typeParams); } public void fixUsage() throws IncorrectOperationException { final Project project = method.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiMethod deepestSuperMethod = method.findDeepestSuperMethod(); final PsiClass psiClass; if (myContainingClass != null) { psiClass = myContainingClass.findInnerClassByName(className, false); } else { psiClass = psiFacade.findClass(StringUtil.getQualifiedName(packageName, className), GlobalSearchScope.allScope(project)); } assert psiClass != null; PsiSubstitutor subst = PsiSubstitutor.EMPTY; if (deepestSuperMethod != null) { final PsiClass parentClass = deepestSuperMethod.getContainingClass(); final PsiSubstitutor parentSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(parentClass, method.getContainingClass(), PsiSubstitutor.EMPTY); for (int i1 = 0; i1 < psiClass.getTypeParameters().length; i1++) { final PsiTypeParameter typeParameter = psiClass.getTypeParameters()[i1]; for (PsiTypeParameter parameter : parentClass.getTypeParameters()) { if (Comparing.strEqual(typeParameter.getName(), parameter.getName())) { subst = subst.put(typeParameter, parentSubstitutor.substitute( new PsiImmediateClassType(parameter, PsiSubstitutor.EMPTY))); break; } } } } final List<ParameterInfoImpl> parametersInfo = new ArrayList<ParameterInfoImpl>(); final PsiClassType classType = JavaPsiFacade.getElementFactory(project).createType(psiClass, subst); final ParameterInfoImpl mergedParamInfo = new ParameterInfoImpl(-1, parameterName, classType, null) { @Override public PsiExpression getValue(final PsiCallExpression expr) throws IncorrectOperationException { return (PsiExpression)JavaCodeStyleManager.getInstance(project) .shortenClassReferences(psiFacade.getElementFactory().createExpressionFromText(getMergedParam(expr), expr)); } }; int firstIncludedIdx = -1; final PsiParameter[] parameters = method.getParameterList().getParameters(); for (int i = 0; i < parameters.length; i++) { if (!isParameterToMerge(i)) { parametersInfo.add(new ParameterInfoImpl(i, parameters[i].getName(), parameters[i].getType())); } else if (firstIncludedIdx == -1) { firstIncludedIdx = i; } } parametersInfo.add(firstIncludedIdx == -1 ? 0 : firstIncludedIdx, mergedParamInfo); final SmartPsiElementPointer<PsiMethod> meth = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(method); final Runnable performChangeSignatureRunnable = new Runnable() { @Override public void run() { final PsiMethod psiMethod = meth.getElement(); if (psiMethod == null) return; if (myChangeSignature) { final ChangeSignatureProcessor changeSignatureProcessor = new ChangeSignatureProcessor(psiMethod.getProject(), psiMethod, myKeepMethodAsDelegate, null, psiMethod.getName(), psiMethod.getReturnType(), parametersInfo.toArray(new ParameterInfoImpl[parametersInfo.size()])); changeSignatureProcessor.run(); } } }; if (ApplicationManager.getApplication().isUnitTestMode()) { performChangeSignatureRunnable.run(); } else { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { CommandProcessor.getInstance().runUndoTransparentAction(performChangeSignatureRunnable); } }); } } private boolean isParameterToMerge(int index) { for (int i : paramsToMerge) { if (i == index) { return true; } } return false; } private String getMergedParam(PsiCallExpression call) { final PsiExpression[] args = call.getArgumentList().getExpressions(); StringBuffer newExpression = new StringBuffer(); final String qualifiedName; if (myContainingClass != null) { final String containingClassQName = myContainingClass.getQualifiedName(); if (containingClassQName != null) { qualifiedName = containingClassQName + "." + className; } else { qualifiedName = className; } } else { qualifiedName = StringUtil.getQualifiedName(packageName, className); } newExpression.append("new ").append(qualifiedName); if (!typeParams.isEmpty()) { final JavaResolveResult resolvant = call.resolveMethodGenerics(); final PsiSubstitutor substitutor = resolvant.getSubstitutor(); newExpression.append('<'); final Map<PsiTypeParameter, PsiType> substitutionMap = substitutor.getSubstitutionMap(); newExpression.append(StringUtil.join(typeParams, new Function<PsiTypeParameter, String>() { public String fun(final PsiTypeParameter typeParameter) { final PsiType boundType = substitutionMap.get(typeParameter); if (boundType != null) { return boundType.getCanonicalText(); } else { return typeParameter.getName(); } } }, ", ")); newExpression.append('>'); } newExpression.append('('); boolean isFirst = true; for (int index : paramsToMerge) { if (!isFirst) { newExpression.append(", "); } isFirst = false; newExpression.append(getArgument(args, index)); } if (lastParamIsVararg) { final int lastArg = paramsToMerge[paramsToMerge.length - 1]; for (int i = lastArg + 1; i < args.length; i++) { newExpression.append(','); newExpression.append(getArgument(args, i)); } } newExpression.append(')'); return newExpression.toString(); } @Nullable private String getArgument(PsiExpression[] args, int i) { if (i < args.length) { return args[i].getText(); } final PsiParameter[] parameters = method.getParameterList().getParameters(); if (i < parameters.length) return parameters[i].getName(); return null; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.datanode.fsdataset.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.DFSUtilClient; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.server.datanode.DataNode; import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsVolumeReference; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * This class is a container of multiple thread pools, one for each non-RamDisk * volume with a maximum thread count of 1 so that we can schedule async lazy * persist operations easily with volume arrival and departure handled. * * This class and {@link org.apache.hadoop.util.AsyncDiskService} are similar. * They should be combined. */ class RamDiskAsyncLazyPersistService { public static final Log LOG = LogFactory.getLog(RamDiskAsyncLazyPersistService.class); // ThreadPool core pool size private static final int CORE_THREADS_PER_VOLUME = 1; // ThreadPool maximum pool size private static final int MAXIMUM_THREADS_PER_VOLUME = 1; // ThreadPool keep-alive time for threads over core pool size private static final long THREADS_KEEP_ALIVE_SECONDS = 60; private final DataNode datanode; private final Configuration conf; private final ThreadGroup threadGroup; private Map<File, ThreadPoolExecutor> executors = new HashMap<File, ThreadPoolExecutor>(); private final static HdfsConfiguration EMPTY_HDFS_CONF = new HdfsConfiguration(); /** * Create a RamDiskAsyncLazyPersistService with a set of volumes (specified by their * root directories). * * The RamDiskAsyncLazyPersistService uses one ThreadPool per volume to do the async * disk operations. */ RamDiskAsyncLazyPersistService(DataNode datanode, Configuration conf) { this.datanode = datanode; this.conf = conf; this.threadGroup = new ThreadGroup(getClass().getSimpleName()); } private void addExecutorForVolume(final File volume) { ThreadFactory threadFactory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(threadGroup, r); t.setName("Async RamDisk lazy persist worker for volume " + volume); return t; } }; ThreadPoolExecutor executor = new ThreadPoolExecutor( CORE_THREADS_PER_VOLUME, MAXIMUM_THREADS_PER_VOLUME, THREADS_KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); // This can reduce the number of running threads executor.allowCoreThreadTimeOut(true); executors.put(volume, executor); } /** * Starts AsyncLazyPersistService for a new volume * @param volume the root of the new data volume. */ synchronized void addVolume(File volume) { if (executors == null) { throw new RuntimeException("AsyncLazyPersistService is already shutdown"); } ThreadPoolExecutor executor = executors.get(volume); if (executor != null) { throw new RuntimeException("Volume " + volume + " is already existed."); } addExecutorForVolume(volume); } /** * Stops AsyncLazyPersistService for a volume. * @param volume the root of the volume. */ synchronized void removeVolume(File volume) { if (executors == null) { throw new RuntimeException("AsyncDiskService is already shutdown"); } ThreadPoolExecutor executor = executors.get(volume); if (executor == null) { throw new RuntimeException("Can not find volume " + volume + " to remove."); } else { executor.shutdown(); executors.remove(volume); } } /** * Query if the thread pool exist for the volume * @param volume the root of a volume * @return true if there is one thread pool for the volume * false otherwise */ synchronized boolean queryVolume(File volume) { if (executors == null) { throw new RuntimeException("AsyncLazyPersistService is already shutdown"); } ThreadPoolExecutor executor = executors.get(volume); return (executor != null); } /** * Execute the task sometime in the future, using ThreadPools. */ synchronized void execute(File root, Runnable task) { if (executors == null) { throw new RuntimeException("AsyncLazyPersistService is already shutdown"); } ThreadPoolExecutor executor = executors.get(root); if (executor == null) { throw new RuntimeException("Cannot find root " + root + " for execution of task " + task); } else { executor.execute(task); } } /** * Gracefully shut down all ThreadPool. Will wait for all lazy persist * tasks to finish. */ synchronized void shutdown() { if (executors == null) { LOG.warn("AsyncLazyPersistService has already shut down."); } else { LOG.info("Shutting down all async lazy persist service threads"); for (Map.Entry<File, ThreadPoolExecutor> e : executors.entrySet()) { e.getValue().shutdown(); } // clear the executor map so that calling execute again will fail. executors = null; LOG.info("All async lazy persist service threads have been shut down"); } } /** * Asynchronously lazy persist the block from the RamDisk to Disk. */ void submitLazyPersistTask(String bpId, long blockId, long genStamp, long creationTime, File metaFile, File blockFile, FsVolumeReference target) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("LazyWriter schedule async task to persist RamDisk block pool id: " + bpId + " block id: " + blockId); } FsVolumeImpl volume = (FsVolumeImpl)target.getVolume(); File lazyPersistDir = volume.getLazyPersistDir(bpId); if (!lazyPersistDir.exists() && !lazyPersistDir.mkdirs()) { FsDatasetImpl.LOG.warn("LazyWriter failed to create " + lazyPersistDir); throw new IOException("LazyWriter fail to find or create lazy persist dir: " + lazyPersistDir.toString()); } ReplicaLazyPersistTask lazyPersistTask = new ReplicaLazyPersistTask( bpId, blockId, genStamp, creationTime, blockFile, metaFile, target, lazyPersistDir); execute(volume.getCurrentDir(), lazyPersistTask); } class ReplicaLazyPersistTask implements Runnable { final String bpId; final long blockId; final long genStamp; final long creationTime; final File blockFile; final File metaFile; final FsVolumeReference targetVolume; final File lazyPersistDir; ReplicaLazyPersistTask(String bpId, long blockId, long genStamp, long creationTime, File blockFile, File metaFile, FsVolumeReference targetVolume, File lazyPersistDir) { this.bpId = bpId; this.blockId = blockId; this.genStamp = genStamp; this.creationTime = creationTime; this.blockFile = blockFile; this.metaFile = metaFile; this.targetVolume = targetVolume; this.lazyPersistDir = lazyPersistDir; } @Override public String toString() { // Called in AsyncLazyPersistService.execute for displaying error messages. return "LazyWriter async task of persist RamDisk block pool id:" + bpId + " block pool id: " + blockId + " with block file " + blockFile + " and meta file " + metaFile + " to target volume " + targetVolume;} @Override public void run() { boolean succeeded = false; final FsDatasetImpl dataset = (FsDatasetImpl)datanode.getFSDataset(); try (FsVolumeReference ref = this.targetVolume) { int smallBufferSize = DFSUtilClient.getSmallBufferSize(EMPTY_HDFS_CONF); // No FsDatasetImpl lock for the file copy File targetFiles[] = FsDatasetImpl.copyBlockFiles( blockId, genStamp, metaFile, blockFile, lazyPersistDir, true, smallBufferSize, conf); // Lock FsDataSetImpl during onCompleteLazyPersist callback dataset.onCompleteLazyPersist(bpId, blockId, creationTime, targetFiles, (FsVolumeImpl) targetVolume.getVolume()); succeeded = true; } catch (Exception e){ FsDatasetImpl.LOG.warn( "LazyWriter failed to async persist RamDisk block pool id: " + bpId + "block Id: " + blockId, e); } finally { if (!succeeded) { dataset.onFailLazyPersist(bpId, blockId); } } } } }
package com.amee.persist; import com.amee.base.resource.LocalResourceHandler; import com.amee.base.resource.RequestWrapper; import com.amee.base.resource.ResourceHandler; import com.amee.base.resource.TimedOutException; import com.amee.base.transaction.TransactionEventType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; import static junit.framework.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) public class TransactionalTest extends BaseTest { private final Logger log = LoggerFactory.getLogger(getClass()); @Autowired private DummyEntityService dummyEntityService; @Autowired private DummyAMEETransactionListener dummyAMEETransactionListener; boolean slowResourceHandlerCompleted = false; @Before public void before() { dummyAMEETransactionListener.reset(); } @After public void after() { dummyAMEETransactionListener.reset(); } @Test public void shouldHaveDummyEntityService() { assertTrue("Should have a DummyEntityService.", dummyEntityService != null); } @Test public void shouldHaveSomeDummyEntities() { // We do NOT expect a transaction here. assertFalse("Should not have a transaction", dummyEntityService.isTransactionActive()); // Fetch existing entities. List<DummyEntity> dummyEntities = dummyEntityService.getDummyEntities(); assertTrue("Should have some DummyEntities.", !dummyEntities.isEmpty()); } @Test public void shouldFetchAnExistingDummyEntity() { // We do NOT expect a transaction here. assertFalse("Should not have a transaction", dummyEntityService.isTransactionActive()); // Fetch existing entity; DummyEntity dummyEntity = dummyEntityService.getDummyEntityByUid("655B1AD17733"); assertTrue("Should fetch an existing DummyEntity.", dummyEntity != null); } @Test public void shouldCreateADummyEntity() { // We do NOT expect a transaction here. assertFalse("Should not have a transaction", dummyEntityService.isTransactionActive()); // Create an entity. DummyEntity newDummyEntity = new DummyEntity("Dummy Text."); dummyEntityService.persist(newDummyEntity); // We still do NOT expect a transaction here. assertFalse("Should not have a transaction", dummyEntityService.isTransactionActive()); // Fetch the entity. DummyEntity fetchedDummyEntity = dummyEntityService.getDummyEntityByUid(newDummyEntity.getUid()); assertTrue("Should be able to fetch the DummyEntity.", fetchedDummyEntity != null); } @Test @Transactional(propagation = Propagation.REQUIRED) public void shouldCreateAndRemoveADummyEntity() { // We do expect a transaction here. assertTrue("Should have a transaction", dummyEntityService.isTransactionActive()); // Create an entity. DummyEntity newDummyEntity = new DummyEntity("Dummy Text."); dummyEntityService.persist(newDummyEntity); // Fetch the entity. DummyEntity fetchedDummyEntity = dummyEntityService.getDummyEntityByUid(newDummyEntity.getUid()); assertTrue("Should be able to fetch the DummyEntity.", fetchedDummyEntity != null); // Remove the entity. dummyEntityService.remove(newDummyEntity); // Fetch the entity, but should be null. DummyEntity removedDummyEntity = dummyEntityService.getDummyEntityByUid(fetchedDummyEntity.getUid()); assertTrue("Should NOT be able to fetch the DummyEntity.", removedDummyEntity == null); } @Test public void shouldNotCreateAnInvalidDummyEntity() { // We do NOT expect a transaction here. assertFalse("Should not have a transaction", dummyEntityService.isTransactionActive()); List<DummyEntity> dummyEntities = new ArrayList<DummyEntity>(); // Create a new valid entity. DummyEntity newDummyEntityOne = new DummyEntity("An valid value."); dummyEntities.add(newDummyEntityOne); // Create a new invalid entity. DummyEntity newDummyEntityTwo = new DummyEntity("An illegal value."); dummyEntities.add(newDummyEntityTwo); // Attempt to persist both entities. try { dummyEntityService.persist(dummyEntities); fail("Should have thrown an IllegalArgumentException."); } catch (IllegalArgumentException e) { // Swallow } // The first entity should not be persisted (rollback). newDummyEntityOne = dummyEntityService.getDummyEntityByUid(newDummyEntityOne.getUid()); assertTrue("Should NOT be able to fetch the first DummyEntity.", newDummyEntityOne == null); // The second entity should not be persisted (invalid). newDummyEntityTwo = dummyEntityService.getDummyEntityByUid(newDummyEntityTwo.getUid()); assertTrue("Should NOT be able to fetch the second DummyEntity.", newDummyEntityTwo == null); } @Test public void shouldListenToEvents() { assertFalse("Should not have a transaction", dummyEntityService.isTransactionActive()); dummyEntityService.doNothingWithinAMEETransaction(); assertTrue("Should have three events", dummyAMEETransactionListener.getTransactionEventTypes().size() == 3); assertTrue("Should have BEFORE_BEGIN event.", dummyAMEETransactionListener.getTransactionEventTypes().get(0).equals(TransactionEventType.BEFORE_BEGIN)); assertTrue("Should have COMMIT event.", dummyAMEETransactionListener.getTransactionEventTypes().get(1).equals(TransactionEventType.COMMIT)); assertTrue("Should have END event.", dummyAMEETransactionListener.getTransactionEventTypes().get(2).equals(TransactionEventType.END)); assertFalse("Should still not have a transaction", dummyEntityService.isTransactionActive()); } @Test public void shouldListenToEventsWithTransaction() { assertFalse("Should not have a transaction", dummyEntityService.isTransactionActive()); dummyEntityService.doSomethingWithinAMEETransactionAndDBTransaction(); assertTrue("Should have three events", dummyAMEETransactionListener.getTransactionEventTypes().size() == 3); assertTrue("Should have BEFORE_BEGIN event.", dummyAMEETransactionListener.getTransactionEventTypes().get(0).equals(TransactionEventType.BEFORE_BEGIN)); assertTrue("Should have COMMIT event.", dummyAMEETransactionListener.getTransactionEventTypes().get(1).equals(TransactionEventType.COMMIT)); assertTrue("Should have END event.", dummyAMEETransactionListener.getTransactionEventTypes().get(2).equals(TransactionEventType.END)); assertFalse("Should still not have a transaction", dummyEntityService.isTransactionActive()); } @Test public void shouldSeeRollbackEvent() { try { dummyEntityService.doCauseRollbackWithinAMEETransactionAndDBTransaction(); fail("Should have thrown an IllegalArgumentException."); } catch (IllegalArgumentException e) { // Swallow } assertTrue("Should have three events", dummyAMEETransactionListener.getTransactionEventTypes().size() == 3); assertTrue("Should have BEFORE_BEGIN event.", dummyAMEETransactionListener.getTransactionEventTypes().get(0).equals(TransactionEventType.BEFORE_BEGIN)); assertTrue("Should have ROLLBACK event.", dummyAMEETransactionListener.getTransactionEventTypes().get(1).equals(TransactionEventType.ROLLBACK)); assertTrue("Should have END event.", dummyAMEETransactionListener.getTransactionEventTypes().get(2).equals(TransactionEventType.END)); } /** * Test that a slow running ResourceHandler which executes SQL can be stopped with a timeout. */ @Test public void willTrapSlowSQLInResourceHandler() throws InterruptedException { String result = null; // Create an entity. final DummyEntity dummyEntity = new DummyEntity("Dummy Text."); // Create a LocalResourceHandler that will cancel the ResourceHandler after 1 second. LocalResourceHandler lrh = new LocalResourceHandler(); lrh.setTimeout(1); try { // Invoke a ResourceHandler which takes 2 seconds to complete. result = (String) lrh.handleWithTimeout(new RequestWrapper(), new ResourceHandler() { @Override public Object handle(RequestWrapper requestWrapper) { // This method call takes a long time... double result = dummyEntityService.persistSlowly(dummyEntity); // Only return a result if the thread was not interrupted. if (!Thread.currentThread().isInterrupted()) { log.debug("Not interrupted, returning result."); slowResourceHandlerCompleted = true; return Double.toString(result); } else { log.debug("Interrupted, returning null."); return null; } } }); fail("Should have thrown a TimedOutException."); } catch (TimedOutException e) { // Let 20 seconds pass before testing (to allow ResourceHandler to complete). Thread.sleep(20 * 1000); assertNull("Result should be null.", result); assertFalse("Should not have completed.", slowResourceHandlerCompleted); assertTrue("Should have three events", dummyAMEETransactionListener.getTransactionEventTypes().size() == 3); assertTrue("Should have BEFORE_BEGIN event.", dummyAMEETransactionListener.getTransactionEventTypes().get(0).equals(TransactionEventType.BEFORE_BEGIN)); assertTrue("Should have ROLLBACK event.", dummyAMEETransactionListener.getTransactionEventTypes().get(1).equals(TransactionEventType.ROLLBACK)); assertTrue("Should have END event.", dummyAMEETransactionListener.getTransactionEventTypes().get(2).equals(TransactionEventType.END)); } // Fetch the entity, but should be null. DummyEntity removedDummyEntity = dummyEntityService.getDummyEntityByUid(dummyEntity.getUid()); assertTrue("Should NOT be able to fetch the DummyEntity.", removedDummyEntity == null); } /** * A slow method that can be called from hsqldb SQL. See implementations of doSomethingSlowly in {@link DummyEntityDAO}. * <p/> * This seems to take about 3 seconds on a mac. This doesn't use the sleep technique because that * can interfere with interrupt status. * * @return a silly value */ public static double slow() { double value = 0; for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++) { value += i; } return value; } }
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.equity.option; import java.io.Serializable; import org.apache.commons.lang.ObjectUtils; import com.opengamma.analytics.financial.ExerciseDecisionType; import com.opengamma.analytics.financial.commodity.definition.SettlementType; import com.opengamma.analytics.financial.interestrate.InstrumentDerivative; import com.opengamma.analytics.financial.interestrate.InstrumentDerivativeVisitor; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.money.Currency; /** * OG-Analytics derivative of the exchange traded Equity Index Option */ public class EquityIndexOption implements InstrumentDerivative, Serializable { /** The time to expiry in years*/ private final double _timeToExpiry; /** The time to settlement in years */ private final double _timeToSettlement; /** The option strike */ private final double _strike; /** Is the option a put or call */ private final boolean _isCall; /** The unit amount per tick */ private final double _unitAmount; /** The currency */ private final Currency _currency; /** The exercise type */ private final ExerciseDecisionType _exerciseType; /** The settlement type */ private final SettlementType _settlementType; /** * * @param timeToExpiry time (in years as a double) until the date-time at which the reference index is fixed, not negative. * @param timeToSettlement time (in years as a double) until the date-time at which the contract is settled, not negative. Must be at or after the * expiry. * @param strike Strike price at trade time. Note that we may handle margin by resetting this at the end of each trading day, not negative or zero * @param isCall True if the option is a Call, false if it is a Put. * @param currency The reporting currency of the future, not null * @param unitAmount The unit value per tick, in given currency. A negative value may represent a short position. Not zero. * @param exerciseType The exercise type of this option, not null * @param settlementType The settlement type option this option, not null */ public EquityIndexOption(final double timeToExpiry, final double timeToSettlement, final double strike, final boolean isCall, final Currency currency, final double unitAmount, final ExerciseDecisionType exerciseType, final SettlementType settlementType) { ArgumentChecker.isTrue(timeToExpiry >= 0, "Time to expiry must not be negative"); ArgumentChecker.isTrue(timeToSettlement >= 0, "Time to settlement must not be negative"); ArgumentChecker.isTrue(timeToSettlement >= timeToExpiry, "Settlement time must be after expiry"); ArgumentChecker.notNegativeOrZero(strike, "strike"); ArgumentChecker.notNull(currency, "currency"); ArgumentChecker.notZero(unitAmount, 1e-15, "unit amount"); ArgumentChecker.notNull(exerciseType, "exercise type"); ArgumentChecker.notNull(settlementType, "settlement type"); _timeToExpiry = timeToExpiry; _timeToSettlement = timeToSettlement; _strike = strike; _isCall = isCall; _unitAmount = unitAmount; _currency = currency; _exerciseType = exerciseType; _settlementType = settlementType; } /** * @return the expiry time (in years as a double) */ public double getTimeToExpiry() { return _timeToExpiry; } /** * Gets the time when payments are made * @return the delivery time (in years as a double) */ public double getTimeToSettlement() { return _timeToSettlement; } /** * @return the strike of the option. */ public double getStrike() { return _strike; } /** * @return True if the option is a Call, false if it is a Put. */ public boolean isCall() { return _isCall; } /** * Gets the unit amount, this is the notional of a single security. * @return the point value */ public double getUnitAmount() { return _unitAmount; } /** * Gets the currency. * @return The currency */ public Currency getCurrency() { return _currency; } /** * Gets the exercise type. * @return The exercise type */ public ExerciseDecisionType getExerciseType() { return _exerciseType; } /** * Gets the settlement type. * @return The settlement type */ public SettlementType getSettlementType() { return _settlementType; } @Override public <S, T> T accept(final InstrumentDerivativeVisitor<S, T> visitor, final S data) { ArgumentChecker.notNull(visitor, "visitor"); return visitor.visitEquityIndexOption(this, data); } @Override public <T> T accept(final InstrumentDerivativeVisitor<?, T> visitor) { ArgumentChecker.notNull(visitor, "visitor"); return visitor.visitEquityIndexOption(this); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + _currency.hashCode(); result = prime * result + _exerciseType.hashCode(); result = prime * result + (_isCall ? 1231 : 1237); result = prime * result + _settlementType.hashCode(); long temp; temp = Double.doubleToLongBits(_strike); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(_timeToExpiry); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(_timeToSettlement); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(_unitAmount); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof EquityIndexOption)) { return false; } final EquityIndexOption other = (EquityIndexOption) obj; if (Double.compare(_strike, other._strike) != 0) { return false; } if (Double.compare(_timeToExpiry, other._timeToExpiry) != 0) { return false; } if (_isCall != other._isCall) { return false; } if (_exerciseType != other._exerciseType) { return false; } if (_settlementType != other._settlementType) { return false; } if (Double.compare(_timeToSettlement, other._timeToSettlement) != 0) { return false; } if (Double.compare(_unitAmount, other._unitAmount) != 0) { return false; } if (!ObjectUtils.equals(_currency, other._currency)) { return false; } return true; } }
/* * Copyright (C) 2012-2020 Gregory Hedlund <https://www.phon.ca> * Copyright (C) 2012 Jason Gedge <http://www.gedge.ca> * * 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 ca.phon.opgraph.nodes.general; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.List; import java.util.logging.*; import java.util.stream.*; import javax.script.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import ca.phon.opgraph.*; import ca.phon.opgraph.app.*; import ca.phon.opgraph.app.edits.node.*; import ca.phon.opgraph.app.extensions.*; import ca.phon.opgraph.exceptions.*; import ca.phon.opgraph.nodes.general.script.*; /** * A node that runs a script. */ @OpNodeInfo( name="Script", description="Executes a script.", category="Scripting", showInLibrary=true ) public class ScriptNode extends OpNode implements NodeSettings { private static final Logger LOGGER = Logger.getLogger(ScriptNode.class.getName()); /** The script engine manager being used */ private ScriptEngineManager manager; /** The script engine being used */ private ScriptEngine engine; /** The scripting language of this node */ private String language; /** The script source */ private String script; /** * Constructs a script node that uses Javascript as its language. */ public ScriptNode() { this(null); } /** * Constructs a script node that uses a given scripting language. * * @param language the name of the language */ public ScriptNode(String language) { this.manager = new ScriptEngineManager(); this.script = ""; setScriptLanguage(language); putExtension(NodeSettings.class, this); } /** * Gets the scripting language of this node. * * @return the name of the scripting language currently used */ public String getScriptLanguage() { return language; } /** * Sets the scripting language of this node. * * @param language the name of a supported language */ public void setScriptLanguage(String language) { language = (language == null ? "" : language); if(!language.equals(this.language)) { this.language = language; this.engine = manager.getEngineByName(language); if(this.engine == null) engine = manager.getEngineByExtension(language); // Only work with invocable script engines if(this.engine == null || !(this.engine instanceof Invocable)) { this.engine = null; } else { this.engine.put("Logging", new LoggingHelper()); } reloadFields(); } } /** * Gets the script source used in this node. * * @return the script source */ public String getScriptSource() { return script; } /** * Sets the script source used in this node. * * @param script the script source */ public void setScriptSource(String script) { script = (script == null ? "" : script); if(!script.equals(this.script)) { this.script = script; reloadFields(); } } /** * Reload the input/output fields from the script. */ private void reloadFields() { if(engine != null) { try { engine.eval(script); final List<InputField> fixedInputs = getInputFields().stream().filter( f -> f.isFixed() && f != ENABLED_FIELD ).collect( Collectors.toList() ); final List<OutputField> fixedOutputs = getOutputFields().stream().filter( OutputField::isFixed ).collect( Collectors.toList() ); removeAllInputFields(); removeAllOutputFields(); for(InputField field:fixedInputs) { putField(field); } for(OutputField field:fixedOutputs) { putField(field); } final InputFields inputFields = new InputFields(this); final OutputFields outputFields = new OutputFields(this); try { ((Invocable)engine).invokeFunction("init", inputFields, outputFields); } catch(NoSuchMethodException exc) { LOGGER.fine(exc.getLocalizedMessage()); } } catch(ScriptException exc) { LOGGER.warning("Script error: " + exc.getLocalizedMessage()); } } } // // Overrides // @Override public void operate(OpContext context) throws ProcessingException { if(engine != null) { try { // Creating bindings from context for(String key : context.keySet()) engine.put(key, context.get(key)); // provide logger for script as 'logger' Logger logger = Logger.getLogger(Processor.class.getName()); engine.put("logger", logger); // Execute run() method in script ((Invocable)engine).invokeFunction("run", context); // // Put output values in context // for(OutputField field : getOutputFields()) // context.put(field, engine.get(field.getKey())); // Erase values for(String key : context.keySet()) engine.put(key, null); } catch(ScriptException exc) { throw new ProcessingException(null, "Could not execute script script", exc); } catch(NoSuchMethodException exc) { throw new ProcessingException(null, "No run() method in script", exc); } } } // // NodeSettings // /** * Constructs a math expression settings for the given node. */ public static class ScriptNodeSettings extends JPanel { private GraphDocument document; /** * Constructs a component for editing a {@link ScriptNode}'s settings. * * @param node the {@link ScriptNode} */ public ScriptNodeSettings(final ScriptNode node, final GraphDocument document) { super(new GridBagLayout()); this.document = document; // Script source components final JEditorPane sourceEditor = new JEditorPane() { @Override public boolean getScrollableTracksViewportWidth() { // Only track width if the preferred with is less than the viewport width if(getParent() != null) return (getUI().getPreferredSize(this).width <= getParent().getSize().width); return super.getScrollableTracksViewportWidth(); } @Override public Dimension getPreferredSize() { // Add a little for the cursor final Dimension dim = super.getPreferredSize(); //dim.width += 5; return dim; } }; sourceEditor.setText(node.getScriptSource()); sourceEditor.setCaretPosition(0); sourceEditor.addCaretListener(new CaretListener() { @Override public void caretUpdate(CaretEvent e) { try { final Rectangle rect = sourceEditor.modelToView(e.getMark()); if(rect != null) { rect.width += 5; rect.height += 5; sourceEditor.scrollRectToVisible(rect); } } catch(BadLocationException exc) {} } }); sourceEditor.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { // Post an undoable edit if(document != null) { final Properties settings = new Properties(); settings.put(SCRIPT_KEY, sourceEditor.getText()); document.getUndoSupport().postEdit(new NodeSettingsEdit(node, settings)); } else { node.setScriptSource(sourceEditor.getText()); } } @Override public void focusGained(FocusEvent e) {} }); final JScrollPane sourcePane = new JScrollPane(sourceEditor); sourcePane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); sourcePane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); // Script language components final Vector<ScriptEngineFactory> factories = new Vector<ScriptEngineFactory>(); final Vector<String> languageChoices = new Vector<String>(); factories.add(null); languageChoices.add("<no language>"); for(ScriptEngineFactory factory : (new ScriptEngineManager()).getEngineFactories()) { factories.add(factory); languageChoices.add(factory.getLanguageName()); } final JComboBox<String> languageBox = new JComboBox<>(languageChoices); languageBox.setEditable(false); languageBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Post an undoable edit final ScriptEngineFactory factory = factories.get(languageBox.getSelectedIndex()); if(document != null) { final Properties settings = new Properties(); settings.put(LANGUAGE_KEY, factory == null ? "" : factory.getLanguageName()); document.getUndoSupport().postEdit(new NodeSettingsEdit(node, settings)); } else { node.setScriptLanguage(factory == null ? null : factory.getLanguageName()); } // Update editor kit final int ss = sourceEditor.getSelectionStart(); final int se = sourceEditor.getSelectionEnd(); final String source = sourceEditor.getText(); // TODO editor kit with syntax highlighting sourceEditor.setContentType("text/plain"); sourceEditor.setText(source); sourceEditor.select(ss, se); } }); languageBox.setSelectedItem(node.getScriptLanguage()); // Add components final GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 0; gbc.fill = GridBagConstraints.NONE; gbc.anchor = GridBagConstraints.EAST; add(new JLabel("Script Language: "), gbc); gbc.gridx = 1; gbc.gridy = 0; gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.EAST; add(languageBox, gbc); gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 2; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.BOTH; add(sourcePane, gbc); // Put the cursor at the beginning of the document SwingUtilities.invokeLater(new Runnable() { @Override public void run() { sourceEditor.select(0, 0); } }); } } private static final String LANGUAGE_KEY = "scriptLanguage"; private static final String SCRIPT_KEY = "scriptSource"; @Override public Component getComponent(GraphDocument document) { return new ScriptNodeSettings(this, document); } @Override public Properties getSettings() { final Properties props = new Properties(); props.setProperty(LANGUAGE_KEY, getScriptLanguage()); props.setProperty(SCRIPT_KEY, getScriptSource()); return props; } @Override public void loadSettings(Properties properties) { if(properties.containsKey(LANGUAGE_KEY)) setScriptLanguage(properties.getProperty(LANGUAGE_KEY)); if(properties.containsKey(SCRIPT_KEY)) setScriptSource(properties.getProperty(SCRIPT_KEY)); } }
package de.hub.clickwatch.connection.internal; import java.io.IOException; import java.util.Collections; import java.util.List; import click.ClickException; import click.ControlSocket.HandlerInfo; import com.google.common.base.Preconditions; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.name.Named; import de.hub.clickcontrol.IClickSocket; import de.hub.clickwatch.ClickWatchModule; import de.hub.clickwatch.connection.adapter.IEditingDomainAdapter; import de.hub.clickwatch.connection.adapter.IErrorAdapter; import de.hub.clickwatch.connection.adapter.IHandlerAdapter; import de.hub.clickwatch.connection.adapter.IHandlerEventAdapter; import de.hub.clickwatch.connection.adapter.IMergeAdapter; import de.hub.clickwatch.connection.adapter.IMetaDataAdapter; import de.hub.clickwatch.connection.adapter.INodeAdapter; import de.hub.clickwatch.connection.adapter.internal.AbstractAdapter; import de.hub.clickwatch.connection.adapter.values.IValueAdapter; import de.hub.clickwatch.model.Node; import de.hub.clickwatch.util.ILogger; import de.hub.clickwatch.util.Tasks; public class NodeConnection implements IInternalNodeConnection { @Inject private ILogger logger; @Inject private Provider<IClickSocket> clickSocketProvider; @Inject @Named(ClickWatchModule.I_DEFAULT_TIMEOUT) private int timeout; private IClickSocket clickSocket = null; private IClickSocket blockingClickSocket = new SynchronizedClickSocket(); @Inject private IMetaDataAdapter metaDataAdapter; @Inject private IValueAdapter valueAdapter; @Inject private IHandlerAdapter handlerAdapter; @Inject private IHandlerEventAdapter handlerEventAdapter; @Inject private INodeAdapter nodeAdapter; @Inject private IErrorAdapter errorAdapter; @Inject private IMergeAdapter mergeAdapter; @Inject private IEditingDomainAdapter editingDomainAdapter; @Inject private Tasks tasks; private Node node; protected void init(Node node) { this.node = node; } @Override public Node getNode() { return node; } private IClickSocket clickSocket() { if (node == null) { return null; } else if (!node.getErrors().isEmpty()) { return nullSocket; } if (clickSocket == null) { clickSocket = clickSocketProvider.get(); } if (!clickSocket.isConnected()) { try { clickSocket.connect(node.getINetAddress(), Integer.parseInt(node.getPort()), timeout); } catch (Exception e) { logger.log(ILogger.ERROR, "could not connect to " + node.getINetAddress() + " on port " + node.getPort(), e); try { clickSocket.close(); } catch (Exception followException) { } clickSocket = null; String errorMessage = "exception during connect: could not connect to " + node.getINetAddress() + " on port " + node.getPort(); getAdapter(IErrorAdapter.class).createError(errorMessage, e); } } return clickSocket; } @Override public void close() { getAdapter(IHandlerEventAdapter.class).stop(); tasks.dispatchTask(this, new Runnable() { @Override public void run() { if (clickSocket() != null) { clickSocket().close(); clickSocket = null; } logger.log(ILogger.DEBUG, "closed connection for " + node.getINetAddress(), null); } }); } @Override public void dispose() { close(); tasks.dispatchTask(this, new Runnable() { @Override public void run() { String iNetAddress = node.getINetAddress(); ((AbstractAdapter)metaDataAdapter).dispose(); ((AbstractAdapter)valueAdapter).dispose(); ((AbstractAdapter)handlerAdapter).dispose(); ((AbstractAdapter)handlerEventAdapter).dispose(); ((AbstractAdapter)nodeAdapter).dispose(); ((AbstractAdapter)errorAdapter).dispose(); ((AbstractAdapter)mergeAdapter).dispose(); ((AbstractAdapter)editingDomainAdapter).dispose(); node.getErrors().clear(); node.setConnection(null); node = null; logger.log(ILogger.DEBUG, "disposed connection for " + iNetAddress, null); } }); } @Override public IClickSocket getBlockingSocket() { return blockingClickSocket; } protected void init(AbstractAdapter abstractAdapter) { abstractAdapter.init(this); } @SuppressWarnings("unchecked") @Override public <T> T getAdapter(Class<T> adapterClass) { if (adapterClass == IMetaDataAdapter.class) { init((AbstractAdapter) metaDataAdapter); return (T) metaDataAdapter; } else if (adapterClass == IHandlerEventAdapter.class) { init((AbstractAdapter) handlerEventAdapter); return (T) handlerEventAdapter; } else if (adapterClass == INodeAdapter.class) { init((AbstractAdapter) nodeAdapter); return (T) nodeAdapter; } else if (adapterClass == IValueAdapter.class) { init((AbstractAdapter) valueAdapter); return (T) valueAdapter; } else if (adapterClass == IErrorAdapter.class) { init((AbstractAdapter) errorAdapter); return (T) errorAdapter; } else if (adapterClass == IMergeAdapter.class) { init((AbstractAdapter) mergeAdapter); return (T) mergeAdapter; } else if (adapterClass == IEditingDomainAdapter.class) { init((AbstractAdapter)editingDomainAdapter); return (T) editingDomainAdapter; } else if (adapterClass == IHandlerAdapter.class) { init((AbstractAdapter) handlerAdapter); return (T) handlerAdapter; // } else if (adapterClass == SocketStatisticsAdapter.class) { // if (socketStatisticsAdapter == null) { // if (clickSocket.getAdapter(ClickSocketStatistics.class) != null) // { // socketStatisticsAdapter = new SocketStatisticsAdapter(); // init(socketStatisticsAdapter); // } // } // return (T)socketStatisticsAdapter; } else { Preconditions.checkArgument(false, "Unknown adapter " + adapterClass.getCanonicalName()); return null; } } @Override public String toString() { if (node != null) { return node.getINetAddress(); } else { return "[non connected]"; } } private static final NullSocket nullSocket = new NullSocket(); private static class NullSocket implements IClickSocket { @Override public void connect(String host, int port, int socketTimeOut) throws IOException { } @Override public boolean isConnected() { return true; } @Override public void close() { } @SuppressWarnings("unchecked") @Override public List<String> getConfigElementNames() throws ClickException, IOException { return Collections.EMPTY_LIST; } @SuppressWarnings("unchecked") @Override public List<HandlerInfo> getElementHandlers(String name) throws ClickException, IOException { return Collections.EMPTY_LIST; } @Override public char[] read(String elementName, String handlerName) throws ClickException, IOException { return new char[] {}; } @Override public void write(String string, String string2, char[] charArray) throws ClickException, IOException { } @Override public <T> T getAdapter(Class<T> theClass) { return null; } } private class SynchronizedClickSocket implements IClickSocket { @Override public void connect(String host, int port, int socketTimeOut) throws IOException { throw new UnsupportedOperationException(); } @Override public synchronized boolean isConnected() { return clickSocket().isConnected(); } @Override public synchronized void close() { clickSocket().close(); } @Override public synchronized List<String> getConfigElementNames() throws ClickException, IOException { return clickSocket().getConfigElementNames(); } @Override public synchronized List<HandlerInfo> getElementHandlers(String name) throws ClickException, IOException { return clickSocket().getElementHandlers(name); } @Override public synchronized char[] read(String elementName, String handlerName) throws ClickException, IOException { return clickSocket().read(elementName, handlerName); } @Override public synchronized void write(String string, String string2, char[] charArray) throws ClickException, IOException { clickSocket().write(string, string2, charArray); } @Override public synchronized <T> T getAdapter(Class<T> theClass) { return clickSocket().getAdapter(theClass); } } @Override public void waitForOpenTasks() { tasks.waitForCompletion(this); } }
package es.gob.afirma.signers.xml; import java.io.ByteArrayInputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.logging.Logger; import javax.xml.crypto.Data; import javax.xml.crypto.URIDereferencer; import javax.xml.crypto.URIReference; import javax.xml.crypto.URIReferenceException; import javax.xml.crypto.XMLCryptoContext; import javax.xml.crypto.dom.DOMURIReference; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import es.gob.afirma.core.misc.http.UrlHttpManagerFactory; /** Dereferenciador a medida de referencias XML DOM. */ public final class CustomUriDereferencer implements URIDereferencer { private static final String ID = "Id"; //$NON-NLS-1$ private static final String DEFAULT_SUN_URI_DEREFERENCER_CLASSNAME = "org.jcp.xml.dsig.internal.dom.DOMURIDereferencer"; //$NON-NLS-1$ private static final String DEFAULT_APACHE_URI_DEREFERENCER_CLASSNAME = "org.apache.jcp.xml.dsig.internal.dom.DOMURIDereferencer"; //$NON-NLS-1$ private static final String DEFAULT_SUN_XML_SIGNATURE_INPUT_CLASSNAME = "com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput"; //$NON-NLS-1$ private static final String DEFAULT_APACHE_XML_SIGNATURE_INPUT_CLASSNAME = "org.apache.xml.security.signature.XMLSignatureInput"; //$NON-NLS-1$ private static final String DEFAULT_SUN_OCTET_STREAM_DATA = "org.jcp.xml.dsig.internal.dom.ApacheOctetStreamData"; //$NON-NLS-1$ private static final String DEFAULT_APACHE_OCTET_STREAM_DATA = "org.apache.jcp.xml.dsig.internal.dom.ApacheOctetStreamData"; //$NON-NLS-1$ private static final String DEFAULT_SUN_NODESET_DATA = "org.jcp.xml.dsig.internal.dom.ApacheNodeSetData"; //$NON-NLS-1$ private static final String DEFAULT_APACHE_NODESET_DATA = "org.apache.jcp.xml.dsig.internal.dom.ApacheNodeSetData"; //$NON-NLS-1$ private final URIDereferencer defaultUriDereferencer; /** Crea un dereferenciador a medida que act&uacute;a solo cuando falla el dereferenciador por defecto * @param defaultDereferencer Dereferenciador por defecto */ public CustomUriDereferencer(final URIDereferencer defaultDereferencer) { this.defaultUriDereferencer = defaultDereferencer; } private static Class<?> getNodesetDataClass() throws ClassNotFoundException { try { return Class.forName(DEFAULT_APACHE_NODESET_DATA); } catch (final Exception e) { return Class.forName(DEFAULT_SUN_NODESET_DATA); } catch (final Error e) { return Class.forName(DEFAULT_SUN_NODESET_DATA); } } private static Class<?> getOctetStreamDataClass() throws ClassNotFoundException { try { return Class.forName(DEFAULT_APACHE_OCTET_STREAM_DATA); } catch (final Exception e) { return Class.forName(DEFAULT_SUN_OCTET_STREAM_DATA); } catch (final Error e) { return Class.forName(DEFAULT_SUN_OCTET_STREAM_DATA); } } private static Class<?> getXmlSignatureInputClass() throws ClassNotFoundException { try { return Class.forName(DEFAULT_APACHE_XML_SIGNATURE_INPUT_CLASSNAME); } catch (final Exception e) { return Class.forName(DEFAULT_SUN_XML_SIGNATURE_INPUT_CLASSNAME); } catch (final Error e) { return Class.forName(DEFAULT_SUN_XML_SIGNATURE_INPUT_CLASSNAME); } } /** Obtiene el dereferenciador XML por defecto del JRE. * Este sera el de Apache o el de Sun. * @return Dereferenciador XML por defecto del JRE. * @throws ClassNotFoundException Si no se encuentra ni el dereferenciador de Sun ni el de Apache. */ private static Class<?> getDereferencerClass() throws ClassNotFoundException { try { return Class.forName(DEFAULT_APACHE_URI_DEREFERENCER_CLASSNAME); } catch (final Exception e) { return Class.forName(DEFAULT_SUN_URI_DEREFERENCER_CLASSNAME); } catch (final Error e) { return Class.forName(DEFAULT_SUN_URI_DEREFERENCER_CLASSNAME); } } /** Obtiene el dereferenciador a medida por defecto de Java. * @return Dereferenciador a medida por defecto de Java * @throws NoSuchFieldException Si falla la reflexi&oacute;n por cambios de las clases internas * de Java * @throws SecurityException Si no se tienen permisos para la reflexi&oacute;n * @throws ClassNotFoundException Si falla la reflexi&oacute;n por desaparici&oacute;n de las clases internas * de Java * @throws IllegalAccessException Si falla la reflexi&oacute;n por fallos de visibilidad */ public static URIDereferencer getDefaultDereferencer() throws NoSuchFieldException, ClassNotFoundException, IllegalAccessException { final Field instanceField = getDereferencerClass().getDeclaredField("INSTANCE"); //$NON-NLS-1$ instanceField.setAccessible(true); return (URIDereferencer) instanceField.get(null); } @Override public Data dereference(final URIReference domRef, final XMLCryptoContext context) throws URIReferenceException { try { return this.defaultUriDereferencer.dereference(domRef, context); } catch(final Exception e) { // Aqui ha fallado el dereferenciador por defecto, probamos a dereferenciar nosotros // Si la referencia es http o https salimos, esta clase es para referencias dentro del mismo contexto XML final String uri = domRef.getURI(); if (uri.startsWith("http://") || uri.startsWith("https://")) { //$NON-NLS-1$ //$NON-NLS-2$ Logger.getLogger("es.gob.afirma").info("Se ha pedido dereferenciar una URI externa: " + uri); //$NON-NLS-1$//$NON-NLS-2$ final byte[] externalContent; try { externalContent = UrlHttpManagerFactory.getInstalledManager().readUrlByGet(uri); } catch (final Exception e1) { throw new URIReferenceException( "No se ha podido descargar manualmente el contenido externo: " + e1, e1 //$NON-NLS-1$ ); } try { return getStreamData(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(externalContent))); } catch (final ParserConfigurationException e1) { throw new URIReferenceException( "No se ha podido crear un XML a partir del contenido externo dereferenciado por error del analizador: " + e1, e1 //$NON-NLS-1$ ); } catch (final SAXException e1) { throw new URIReferenceException( "No se ha podido crear un XML a partir del contenido externo dereferenciado por error SAX: " + e1, e1 //$NON-NLS-1$ ); } catch (final IOException e1) { throw new URIReferenceException( "No se ha podido crear un XML a partir del contenido externo dereferenciado: " + e1, e1 //$NON-NLS-1$ ); } } final Attr uriAttr = (Attr) ((DOMURIReference)domRef).getHere(); final Document doc = uriAttr.getOwnerDocument(); final String uriValue = uriAttr.getNodeValue(); // Derreferenciacion de todo el XML en firmas enveloped if ("".equals(uriValue)) { //$NON-NLS-1$ return getStreamData(doc); } // Buscamos el nodo en todo el XML String id = uriValue; if (uriValue.length() > 0 && uriValue.charAt(0) == '#') { id = uriValue.substring(1); } final Node targetNode = getElementById(doc, id); if (targetNode == null) { throw new URIReferenceException(e); } return getStreamData(targetNode); } } private static Data getStreamData(final Node targetNode) throws URIReferenceException { try { final Class<?> xmlSignatureInputClass = getXmlSignatureInputClass(); final Constructor<?> xmlSignatureInputConstructor = xmlSignatureInputClass.getConstructor(Node.class); final Object in = xmlSignatureInputConstructor.newInstance(targetNode); final Method isOctetStreamMethod = xmlSignatureInputClass.getMethod("isOctetStream"); //$NON-NLS-1$ if (((Boolean) isOctetStreamMethod.invoke(in)).booleanValue()) { final Class<?> octetStreamDataClass = getOctetStreamDataClass(); final Constructor<?> octetStreamDataConstructor = octetStreamDataClass.getConstructor(in.getClass()); return (Data) octetStreamDataConstructor.newInstance(in); } final Constructor<?> nodeSetDataConstructor = getNodesetDataClass().getConstructor(in.getClass()); return (Data) nodeSetDataConstructor.newInstance(in); } catch (final Exception ioe) { throw new URIReferenceException(ioe); } catch (final Error ioe) { throw new URIReferenceException(ioe); } } /** Busca el primer nodo de un documento XML que tenga un atributo con nombre * <i>Id</i> cuyo valor sea el indicado o <code>null</code> si no se encuentra * ninguno. * @param doc Documento XML * @param nodeId Valor del atributo <i>Id</i> del nodo a buscar * @return Primer nodo de un documento XML que tenga un atributo <i>Id</i> con el * valor indicado o <code>null</code> si no se encuentra ninguno */ public static Element getElementById(final Document doc, final String nodeId) { if (doc == null || nodeId == null) { return null; } final NodeList nodeList = doc.getElementsByTagName("*"); //$NON-NLS-1$ for (int i = 0, len = nodeList.getLength(); i < len; i++) { final Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { // Buscamos un atributo 'Id' final NamedNodeMap nnm = node.getAttributes(); for (int j = 0; j < nnm.getLength(); ++j) { final Node attr = nnm.item(j); if (ID.equalsIgnoreCase(attr.getNodeName()) && nodeId.equals(attr.getNodeValue()) && node instanceof Element) { return (Element) node; } } } } return null; } }
/* * 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.pig.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.Properties; import org.apache.pig.FuncSpec; import org.apache.pig.PigServer; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.POStatus; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.Result; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhysicalPlan; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POFilter; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POForEach; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POLoad; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POUnion; import org.apache.pig.builtin.PigStorage; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.DefaultBagFactory; import org.apache.pig.data.DefaultTuple; import org.apache.pig.data.Tuple; import org.apache.pig.impl.PigContext; import org.apache.pig.impl.io.FileSpec; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.test.utils.GenPhyOp; import org.apache.pig.test.utils.TestHelper; import org.junit.Before; import org.junit.Test; /** * Start Plan - --4430968173902769765 * | * |---Filter - -3398344075398026874 * | | * | |---For Each - --3361918026493682288 * | | * | |---Load - --7021057205133896020 * | * |---Filter - -4449068980110713814 * | * |---For Each - -7192652407897311774 * | * |---Load - --3816247505117325386 * * Tests the Start Plan operator with the above plan. * The verification is done as follows: * Both loads load the same file(/etc/passwd). * The filters cover the input. Here the filters used * are $2<=50 & $2>50 * The bags coming out of Start Plan is checked against * the projected input bag. * Since types are not supported yet, there is an explicit * conversion from DataByteArray to native types for computation * and back to DataByteArray for comparison with input. */ public class TestUnion { POUnion sp; DataBag expBag; PigContext pc; PigServer pigServer; @Before public void setUp() throws Exception { pigServer = new PigServer(Util.getLocalTestMode(), new Properties()); pc = pigServer.getPigContext(); pc.connect(); GenPhyOp.setPc(pc); POLoad ld1 = GenPhyOp.topLoadOp(); String curDir = System.getProperty("user.dir"); String inpDir = curDir + File.separatorChar + "test/org/apache/pig/test/data/InputFiles/"; FileSpec fSpec = new FileSpec(Util.generateURI(inpDir + "passwd", pc), new FuncSpec(PigStorage.class.getName() , new String[]{":"})); ld1.setLFile(fSpec); POLoad ld2 = GenPhyOp.topLoadOp(); ld2.setLFile(fSpec); POFilter fl1 = GenPhyOp.topFilterOpWithProj(1, 50, GenPhyOp.LTE); POFilter fl2 = GenPhyOp.topFilterOpWithProj(1, 50, GenPhyOp.GT); int[] flds = {0,2}; Tuple sample = new DefaultTuple(); sample.append(new String("S")); sample.append(new String("x")); sample.append(new Integer("10")); sample.append(new Integer("20")); sample.append(new String("S")); sample.append(new String("x")); sample.append(new String("S")); sample.append(new String("x")); POForEach fe1 = GenPhyOp.topForEachOPWithPlan(flds , sample); POForEach fe2 = GenPhyOp.topForEachOPWithPlan(flds , sample); sp = GenPhyOp.topUnionOp(); PhysicalPlan plan = new PhysicalPlan(); plan.add(ld1); plan.add(ld2); plan.add(fl1); plan.add(fl2); plan.add(fe1); plan.add(fe2); plan.add(sp); plan.connect(ld1, fe1); plan.connect(fe1, fl1); plan.connect(ld2, fe2); plan.connect(fe2, fl2); plan.connect(fl1, sp); plan.connect(fl2, sp); /*PlanPrinter ppp = new PlanPrinter(plan); ppp.visit();*/ POLoad ld3 = GenPhyOp.topLoadOp(); ld3.setLFile(fSpec); DataBag fullBag = DefaultBagFactory.getInstance().newDefaultBag(); Tuple t=null; for(Result res=ld3.getNextTuple();res.returnStatus!=POStatus.STATUS_EOP;res=ld3.getNextTuple()){ fullBag.add((Tuple)res.result); } int[] fields = {0,2}; expBag = TestHelper.projectBag(fullBag, fields); } private Tuple castToDBA(Tuple in) throws ExecException{ Tuple res = new DefaultTuple(); for (int i=0;i<in.size();i++) { DataByteArray dba = new DataByteArray(in.get(i).toString()); res.append(dba); } return res; } @Test public void testGetNextTuple() throws ExecException, IOException { Tuple t = null; DataBag outBag = DefaultBagFactory.getInstance().newDefaultBag(); for(Result res=sp.getNextTuple();res.returnStatus!=POStatus.STATUS_EOP;res=sp.getNextTuple()){ outBag.add(castToDBA((Tuple)res.result)); } assertTrue(TestHelper.compareBags(expBag, outBag)); } // Test the case when POUnion is one of the roots in a map reduce // plan and the input to it can be null // This can happen when we have // a plan like below // POUnion // | // |--POLocalRearrange // | | // | |-POUnion (root 2)--> This union's getNext() can lead the code here // | // |--POLocalRearrange (root 1) // The inner POUnion above is a root in the plan which has 2 roots. // So these 2 roots would have input coming from different input // sources (dfs files). So certain maps would be working on input only // meant for "root 1" above and some maps would work on input // meant only for "root 2". In the former case, "root 2" would // neither get input attached to it nor does it have predecessors @Test public void testGetNextNullInput() throws Exception { File f1 = Util.createInputFile("tmp", "a.txt", new String[] {"1\t2\t3", "4\t5\t6"}); File f2 = Util.createInputFile("tmp", "b.txt", new String[] {"7\t8\t9", "1\t200\t300"}); File f3 = Util.createInputFile("tmp", "c.txt", new String[] {"1\t20\t30"}); //FileLocalizer.deleteTempFiles(); pigServer.registerQuery("a = load '" + Util.encodeEscape(f1.getAbsolutePath()) + "' ;"); pigServer.registerQuery("b = load '" + Util.encodeEscape(f2.getAbsolutePath()) + "';"); pigServer.registerQuery("c = union a, b;"); pigServer.registerQuery("d = load '" + Util.encodeEscape(f3.getAbsolutePath()) + "' ;"); pigServer.registerQuery("e = cogroup c by $0 inner, d by $0 inner;"); pigServer.explain("e", System.err); // output should be // (1,{(1,2,3),(1,200,300)},{(1,20,30)}) Tuple expectedResult = new DefaultTuple(); expectedResult.append(new DataByteArray("1")); Tuple[] secondFieldContents = new DefaultTuple[2]; secondFieldContents[0] = Util.createTuple(Util.toDataByteArrays(new String[] {"1", "2", "3"})); secondFieldContents[1] = Util.createTuple(Util.toDataByteArrays(new String[] {"1", "200", "300"})); DataBag secondField = Util.createBag(secondFieldContents); expectedResult.append(secondField); DataBag thirdField = Util.createBag(new Tuple[]{Util.createTuple(Util.toDataByteArrays(new String[]{"1", "20", "30"}))}); expectedResult.append(thirdField); Iterator<Tuple> it = pigServer.openIterator("e"); assertEquals(expectedResult, it.next()); assertFalse(it.hasNext()); } // Test schema merge in union when one of the fields is a bag @Test public void testSchemaMergeWithBag() throws Exception { File f1 = Util.createInputFile("tmp", "input1.txt", new String[] {"dummy"}); File f2 = Util.createInputFile("tmp", "input2.txt", new String[] {"dummy"}); Util.registerMultiLineQuery(pigServer, "a = load '" + Util.encodeEscape(f1.getAbsolutePath()) + "';" + "b = load '" + Util.encodeEscape(f2.getAbsolutePath()) + "';" + "c = foreach a generate 1, {(1, 'str1')};" + "d = foreach b generate 2, {(2, 'str2')};" + "e = union c,d;" + ""); Iterator<Tuple> it = pigServer.openIterator("e"); Object[] expected = new Object[] { Util.getPigConstant("(1, {(1, 'str1')})"), Util.getPigConstant("(2, {(2, 'str2')})")}; Object[] results = new Object[2]; int i = 0; while(it.hasNext()) { if(i == 2) { fail("Got more tuples than expected!"); } Tuple t = it.next(); if(t.get(0).equals(1)) { // this is the first tuple results[0] = t; } else { results[1] = t; } i++; } for (int j = 0; j < expected.length; j++) { assertEquals(expected[j], results[j]); } } @Test public void testCastingAfterUnion() throws Exception { File f1 = Util.createInputFile("tmp", "i1.txt", new String[] {"aaa\t111"}); File f2 = Util.createInputFile("tmp", "i2.txt", new String[] {"bbb\t222"}); PigServer ps = new PigServer(Util.getLocalTestMode(), new Properties()); ps.registerQuery("A = load '" + Util.encodeEscape(f1.getAbsolutePath()) + "' as (a,b);"); ps.registerQuery("B = load '" + Util.encodeEscape(f2.getAbsolutePath()) + "' as (a,b);"); ps.registerQuery("C = union A,B;"); ps.registerQuery("D = foreach C generate (chararray)a as a,(int)b as b;"); Schema dumpSchema = ps.dumpSchema("D"); Schema expected = new Schema (); expected.add(new Schema.FieldSchema("a", DataType.CHARARRAY)); expected.add(new Schema.FieldSchema("b", DataType.INTEGER)); assertEquals(expected, dumpSchema); Iterator<Tuple> itr = ps.openIterator("D"); int recordCount = 0; while(itr.next() != null) ++recordCount; assertEquals(2, recordCount); } @Test public void testCastingAfterUnionWithMultipleLoadersDifferentCasters() throws Exception { // Note that different caster case only works when each field is still coming // from the single Loader. // In the case below, 'a' is coming from A(PigStorage) // and 'b' is coming from B(TextLoader). No overlaps. File f1 = Util.createInputFile("tmp", "i1.txt", new String[] {"1","2","3"}); File f2 = Util.createInputFile("tmp", "i2.txt", new String[] {"a","b","c"}); PigServer ps = new PigServer(Util.getLocalTestMode(), new Properties()); //PigStorage and TextLoader have different LoadCasters ps.registerQuery("A = load '" + Util.encodeEscape(f1.getAbsolutePath()) + "' as (a:bytearray);"); ps.registerQuery("B = load '" + Util.encodeEscape(f2.getAbsolutePath()) + "' using TextLoader() as (b:bytearray);"); ps.registerQuery("C = union onschema A,B;"); ps.registerQuery("D = foreach C generate (int)a as a,(chararray)b as b;"); Schema dumpSchema = ps.dumpSchema("D"); Schema expected = new Schema (); expected.add(new Schema.FieldSchema("a", DataType.INTEGER)); expected.add(new Schema.FieldSchema("b", DataType.CHARARRAY)); assertEquals(expected, dumpSchema); Iterator<Tuple> itr = ps.openIterator("D"); int recordCount = 0; while(itr.next() != null) ++recordCount; assertEquals(6, recordCount); } @Test public void testCastingAfterUnionWithMultipleLoadersDifferentCasters2() throws Exception { // A bit more complicated pattern but still same requirement of each // field coming from the same Loader. // 'a' is coming from A(PigStorage) // 'i' is coming from B and C but both from the TextLoader. File f1 = Util.createInputFile("tmp", "i1.txt", new String[] {"b","c", "1", "3"}); File f2 = Util.createInputFile("tmp", "i2.txt", new String[] {"a","b","c"}); File f3 = Util.createInputFile("tmp", "i3.txt", new String[] {"1","2","3"}); PigServer ps = new PigServer(Util.getLocalTestMode(), new Properties()); ps.registerQuery("A = load '" + Util.encodeEscape(f1.getAbsolutePath()) + "' as (a:bytearray);"); // Using PigStorage() ps.registerQuery("B = load '" + Util.encodeEscape(f2.getAbsolutePath()) + "' using TextLoader() as (i:bytearray);"); ps.registerQuery("C = load '" + Util.encodeEscape(f3.getAbsolutePath()) + "' using TextLoader() as (i:bytearray);"); ps.registerQuery("B2 = join B by i, A by a;"); //{A::a: bytearray,B::i: bytearray} ps.registerQuery("B3 = foreach B2 generate a, B::i as i;"); //{A::a: bytearray,i: bytearray} ps.registerQuery("C2 = join C by i, A by a;"); //{A::a: bytearray,C::i: bytearray} ps.registerQuery("C3 = foreach C2 generate a, C::i as i;"); //{A::a: bytearray,i: bytearray} ps.registerQuery("D = union onschema B3,C3;"); // {A::a: bytearray,i: bytearray} ps.registerQuery("E = foreach D generate (chararray) a, (chararray) i;");//{A::a: chararray,i: chararray} Iterator<Tuple> itr = ps.openIterator("E"); int recordCount = 0; while(itr.next() != null) ++recordCount; assertEquals(4, recordCount); } @Test public void testCastingAfterUnionWithMultipleLoadersSameCaster() throws Exception { // Fields coming from different loaders but // having the same LoadCaster. File f1 = Util.createInputFile("tmp", "i1.txt", new String[] {"1\ta","2\tb","3\tc"}); PigServer ps = new PigServer(Util.getLocalTestMode(), new Properties()); // PigStorage and PigStorageWithStatistics have the same // LoadCaster(== Utf8StorageConverter) ps.registerQuery("A = load '" + Util.encodeEscape(f1.getAbsolutePath()) + "' as (a:bytearray, b:bytearray);"); ps.registerQuery("B = load '" + Util.encodeEscape(f1.getAbsolutePath()) + "' using org.apache.pig.test.PigStorageWithStatistics() as (a:bytearray, b:bytearray);"); ps.registerQuery("C = union onschema A,B;"); ps.registerQuery("D = foreach C generate (int)a as a,(chararray)b as b;"); // 'a' is coming from A and 'b' is coming from B; No overlaps. Schema dumpSchema = ps.dumpSchema("D"); Schema expected = new Schema (); expected.add(new Schema.FieldSchema("a", DataType.INTEGER)); expected.add(new Schema.FieldSchema("b", DataType.CHARARRAY)); assertEquals(expected, dumpSchema); Iterator<Tuple> itr = ps.openIterator("D"); int recordCount = 0; while(itr.next() != null) ++recordCount; assertEquals(6, recordCount); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/errors/image_error.proto package com.google.ads.googleads.v9.errors; /** * <pre> * Container for enum describing possible image errors. * </pre> * * Protobuf type {@code google.ads.googleads.v9.errors.ImageErrorEnum} */ public final class ImageErrorEnum extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v9.errors.ImageErrorEnum) ImageErrorEnumOrBuilder { private static final long serialVersionUID = 0L; // Use ImageErrorEnum.newBuilder() to construct. private ImageErrorEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ImageErrorEnum() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new ImageErrorEnum(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ImageErrorEnum( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.errors.ImageErrorProto.internal_static_google_ads_googleads_v9_errors_ImageErrorEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.errors.ImageErrorProto.internal_static_google_ads_googleads_v9_errors_ImageErrorEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.errors.ImageErrorEnum.class, com.google.ads.googleads.v9.errors.ImageErrorEnum.Builder.class); } /** * <pre> * Enum describing possible image errors. * </pre> * * Protobuf enum {@code google.ads.googleads.v9.errors.ImageErrorEnum.ImageError} */ public enum ImageError implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> * Enum unspecified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ UNSPECIFIED(0), /** * <pre> * The received error code is not known in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ UNKNOWN(1), /** * <pre> * The image is not valid. * </pre> * * <code>INVALID_IMAGE = 2;</code> */ INVALID_IMAGE(2), /** * <pre> * The image could not be stored. * </pre> * * <code>STORAGE_ERROR = 3;</code> */ STORAGE_ERROR(3), /** * <pre> * There was a problem with the request. * </pre> * * <code>BAD_REQUEST = 4;</code> */ BAD_REQUEST(4), /** * <pre> * The image is not of legal dimensions. * </pre> * * <code>UNEXPECTED_SIZE = 5;</code> */ UNEXPECTED_SIZE(5), /** * <pre> * Animated image are not permitted. * </pre> * * <code>ANIMATED_NOT_ALLOWED = 6;</code> */ ANIMATED_NOT_ALLOWED(6), /** * <pre> * Animation is too long. * </pre> * * <code>ANIMATION_TOO_LONG = 7;</code> */ ANIMATION_TOO_LONG(7), /** * <pre> * There was an error on the server. * </pre> * * <code>SERVER_ERROR = 8;</code> */ SERVER_ERROR(8), /** * <pre> * Image cannot be in CMYK color format. * </pre> * * <code>CMYK_JPEG_NOT_ALLOWED = 9;</code> */ CMYK_JPEG_NOT_ALLOWED(9), /** * <pre> * Flash images are not permitted. * </pre> * * <code>FLASH_NOT_ALLOWED = 10;</code> */ FLASH_NOT_ALLOWED(10), /** * <pre> * Flash images must support clickTag. * </pre> * * <code>FLASH_WITHOUT_CLICKTAG = 11;</code> */ FLASH_WITHOUT_CLICKTAG(11), /** * <pre> * A flash error has occurred after fixing the click tag. * </pre> * * <code>FLASH_ERROR_AFTER_FIXING_CLICK_TAG = 12;</code> */ FLASH_ERROR_AFTER_FIXING_CLICK_TAG(12), /** * <pre> * Unacceptable visual effects. * </pre> * * <code>ANIMATED_VISUAL_EFFECT = 13;</code> */ ANIMATED_VISUAL_EFFECT(13), /** * <pre> * There was a problem with the flash image. * </pre> * * <code>FLASH_ERROR = 14;</code> */ FLASH_ERROR(14), /** * <pre> * Incorrect image layout. * </pre> * * <code>LAYOUT_PROBLEM = 15;</code> */ LAYOUT_PROBLEM(15), /** * <pre> * There was a problem reading the image file. * </pre> * * <code>PROBLEM_READING_IMAGE_FILE = 16;</code> */ PROBLEM_READING_IMAGE_FILE(16), /** * <pre> * There was an error storing the image. * </pre> * * <code>ERROR_STORING_IMAGE = 17;</code> */ ERROR_STORING_IMAGE(17), /** * <pre> * The aspect ratio of the image is not allowed. * </pre> * * <code>ASPECT_RATIO_NOT_ALLOWED = 18;</code> */ ASPECT_RATIO_NOT_ALLOWED(18), /** * <pre> * Flash cannot have network objects. * </pre> * * <code>FLASH_HAS_NETWORK_OBJECTS = 19;</code> */ FLASH_HAS_NETWORK_OBJECTS(19), /** * <pre> * Flash cannot have network methods. * </pre> * * <code>FLASH_HAS_NETWORK_METHODS = 20;</code> */ FLASH_HAS_NETWORK_METHODS(20), /** * <pre> * Flash cannot have a Url. * </pre> * * <code>FLASH_HAS_URL = 21;</code> */ FLASH_HAS_URL(21), /** * <pre> * Flash cannot use mouse tracking. * </pre> * * <code>FLASH_HAS_MOUSE_TRACKING = 22;</code> */ FLASH_HAS_MOUSE_TRACKING(22), /** * <pre> * Flash cannot have a random number. * </pre> * * <code>FLASH_HAS_RANDOM_NUM = 23;</code> */ FLASH_HAS_RANDOM_NUM(23), /** * <pre> * Ad click target cannot be '_self'. * </pre> * * <code>FLASH_SELF_TARGETS = 24;</code> */ FLASH_SELF_TARGETS(24), /** * <pre> * GetUrl method should only use '_blank'. * </pre> * * <code>FLASH_BAD_GETURL_TARGET = 25;</code> */ FLASH_BAD_GETURL_TARGET(25), /** * <pre> * Flash version is not supported. * </pre> * * <code>FLASH_VERSION_NOT_SUPPORTED = 26;</code> */ FLASH_VERSION_NOT_SUPPORTED(26), /** * <pre> * Flash movies need to have hard coded click URL or clickTAG * </pre> * * <code>FLASH_WITHOUT_HARD_CODED_CLICK_URL = 27;</code> */ FLASH_WITHOUT_HARD_CODED_CLICK_URL(27), /** * <pre> * Uploaded flash file is corrupted. * </pre> * * <code>INVALID_FLASH_FILE = 28;</code> */ INVALID_FLASH_FILE(28), /** * <pre> * Uploaded flash file can be parsed, but the click tag can not be fixed * properly. * </pre> * * <code>FAILED_TO_FIX_CLICK_TAG_IN_FLASH = 29;</code> */ FAILED_TO_FIX_CLICK_TAG_IN_FLASH(29), /** * <pre> * Flash movie accesses network resources * </pre> * * <code>FLASH_ACCESSES_NETWORK_RESOURCES = 30;</code> */ FLASH_ACCESSES_NETWORK_RESOURCES(30), /** * <pre> * Flash movie attempts to call external javascript code * </pre> * * <code>FLASH_EXTERNAL_JS_CALL = 31;</code> */ FLASH_EXTERNAL_JS_CALL(31), /** * <pre> * Flash movie attempts to call flash system commands * </pre> * * <code>FLASH_EXTERNAL_FS_CALL = 32;</code> */ FLASH_EXTERNAL_FS_CALL(32), /** * <pre> * Image file is too large. * </pre> * * <code>FILE_TOO_LARGE = 33;</code> */ FILE_TOO_LARGE(33), /** * <pre> * Image data is too large. * </pre> * * <code>IMAGE_DATA_TOO_LARGE = 34;</code> */ IMAGE_DATA_TOO_LARGE(34), /** * <pre> * Error while processing the image. * </pre> * * <code>IMAGE_PROCESSING_ERROR = 35;</code> */ IMAGE_PROCESSING_ERROR(35), /** * <pre> * Image is too small. * </pre> * * <code>IMAGE_TOO_SMALL = 36;</code> */ IMAGE_TOO_SMALL(36), /** * <pre> * Input was invalid. * </pre> * * <code>INVALID_INPUT = 37;</code> */ INVALID_INPUT(37), /** * <pre> * There was a problem reading the image file. * </pre> * * <code>PROBLEM_READING_FILE = 38;</code> */ PROBLEM_READING_FILE(38), /** * <pre> * Image constraints are violated, but details like ASPECT_RATIO_NOT_ALLOWED * can't be provided. This happens when asset spec contains more than one * constraint and different criteria of different constraints are violated. * </pre> * * <code>IMAGE_CONSTRAINTS_VIOLATED = 39;</code> */ IMAGE_CONSTRAINTS_VIOLATED(39), /** * <pre> * Image format is not allowed. * </pre> * * <code>FORMAT_NOT_ALLOWED = 40;</code> */ FORMAT_NOT_ALLOWED(40), UNRECOGNIZED(-1), ; /** * <pre> * Enum unspecified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ public static final int UNSPECIFIED_VALUE = 0; /** * <pre> * The received error code is not known in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ public static final int UNKNOWN_VALUE = 1; /** * <pre> * The image is not valid. * </pre> * * <code>INVALID_IMAGE = 2;</code> */ public static final int INVALID_IMAGE_VALUE = 2; /** * <pre> * The image could not be stored. * </pre> * * <code>STORAGE_ERROR = 3;</code> */ public static final int STORAGE_ERROR_VALUE = 3; /** * <pre> * There was a problem with the request. * </pre> * * <code>BAD_REQUEST = 4;</code> */ public static final int BAD_REQUEST_VALUE = 4; /** * <pre> * The image is not of legal dimensions. * </pre> * * <code>UNEXPECTED_SIZE = 5;</code> */ public static final int UNEXPECTED_SIZE_VALUE = 5; /** * <pre> * Animated image are not permitted. * </pre> * * <code>ANIMATED_NOT_ALLOWED = 6;</code> */ public static final int ANIMATED_NOT_ALLOWED_VALUE = 6; /** * <pre> * Animation is too long. * </pre> * * <code>ANIMATION_TOO_LONG = 7;</code> */ public static final int ANIMATION_TOO_LONG_VALUE = 7; /** * <pre> * There was an error on the server. * </pre> * * <code>SERVER_ERROR = 8;</code> */ public static final int SERVER_ERROR_VALUE = 8; /** * <pre> * Image cannot be in CMYK color format. * </pre> * * <code>CMYK_JPEG_NOT_ALLOWED = 9;</code> */ public static final int CMYK_JPEG_NOT_ALLOWED_VALUE = 9; /** * <pre> * Flash images are not permitted. * </pre> * * <code>FLASH_NOT_ALLOWED = 10;</code> */ public static final int FLASH_NOT_ALLOWED_VALUE = 10; /** * <pre> * Flash images must support clickTag. * </pre> * * <code>FLASH_WITHOUT_CLICKTAG = 11;</code> */ public static final int FLASH_WITHOUT_CLICKTAG_VALUE = 11; /** * <pre> * A flash error has occurred after fixing the click tag. * </pre> * * <code>FLASH_ERROR_AFTER_FIXING_CLICK_TAG = 12;</code> */ public static final int FLASH_ERROR_AFTER_FIXING_CLICK_TAG_VALUE = 12; /** * <pre> * Unacceptable visual effects. * </pre> * * <code>ANIMATED_VISUAL_EFFECT = 13;</code> */ public static final int ANIMATED_VISUAL_EFFECT_VALUE = 13; /** * <pre> * There was a problem with the flash image. * </pre> * * <code>FLASH_ERROR = 14;</code> */ public static final int FLASH_ERROR_VALUE = 14; /** * <pre> * Incorrect image layout. * </pre> * * <code>LAYOUT_PROBLEM = 15;</code> */ public static final int LAYOUT_PROBLEM_VALUE = 15; /** * <pre> * There was a problem reading the image file. * </pre> * * <code>PROBLEM_READING_IMAGE_FILE = 16;</code> */ public static final int PROBLEM_READING_IMAGE_FILE_VALUE = 16; /** * <pre> * There was an error storing the image. * </pre> * * <code>ERROR_STORING_IMAGE = 17;</code> */ public static final int ERROR_STORING_IMAGE_VALUE = 17; /** * <pre> * The aspect ratio of the image is not allowed. * </pre> * * <code>ASPECT_RATIO_NOT_ALLOWED = 18;</code> */ public static final int ASPECT_RATIO_NOT_ALLOWED_VALUE = 18; /** * <pre> * Flash cannot have network objects. * </pre> * * <code>FLASH_HAS_NETWORK_OBJECTS = 19;</code> */ public static final int FLASH_HAS_NETWORK_OBJECTS_VALUE = 19; /** * <pre> * Flash cannot have network methods. * </pre> * * <code>FLASH_HAS_NETWORK_METHODS = 20;</code> */ public static final int FLASH_HAS_NETWORK_METHODS_VALUE = 20; /** * <pre> * Flash cannot have a Url. * </pre> * * <code>FLASH_HAS_URL = 21;</code> */ public static final int FLASH_HAS_URL_VALUE = 21; /** * <pre> * Flash cannot use mouse tracking. * </pre> * * <code>FLASH_HAS_MOUSE_TRACKING = 22;</code> */ public static final int FLASH_HAS_MOUSE_TRACKING_VALUE = 22; /** * <pre> * Flash cannot have a random number. * </pre> * * <code>FLASH_HAS_RANDOM_NUM = 23;</code> */ public static final int FLASH_HAS_RANDOM_NUM_VALUE = 23; /** * <pre> * Ad click target cannot be '_self'. * </pre> * * <code>FLASH_SELF_TARGETS = 24;</code> */ public static final int FLASH_SELF_TARGETS_VALUE = 24; /** * <pre> * GetUrl method should only use '_blank'. * </pre> * * <code>FLASH_BAD_GETURL_TARGET = 25;</code> */ public static final int FLASH_BAD_GETURL_TARGET_VALUE = 25; /** * <pre> * Flash version is not supported. * </pre> * * <code>FLASH_VERSION_NOT_SUPPORTED = 26;</code> */ public static final int FLASH_VERSION_NOT_SUPPORTED_VALUE = 26; /** * <pre> * Flash movies need to have hard coded click URL or clickTAG * </pre> * * <code>FLASH_WITHOUT_HARD_CODED_CLICK_URL = 27;</code> */ public static final int FLASH_WITHOUT_HARD_CODED_CLICK_URL_VALUE = 27; /** * <pre> * Uploaded flash file is corrupted. * </pre> * * <code>INVALID_FLASH_FILE = 28;</code> */ public static final int INVALID_FLASH_FILE_VALUE = 28; /** * <pre> * Uploaded flash file can be parsed, but the click tag can not be fixed * properly. * </pre> * * <code>FAILED_TO_FIX_CLICK_TAG_IN_FLASH = 29;</code> */ public static final int FAILED_TO_FIX_CLICK_TAG_IN_FLASH_VALUE = 29; /** * <pre> * Flash movie accesses network resources * </pre> * * <code>FLASH_ACCESSES_NETWORK_RESOURCES = 30;</code> */ public static final int FLASH_ACCESSES_NETWORK_RESOURCES_VALUE = 30; /** * <pre> * Flash movie attempts to call external javascript code * </pre> * * <code>FLASH_EXTERNAL_JS_CALL = 31;</code> */ public static final int FLASH_EXTERNAL_JS_CALL_VALUE = 31; /** * <pre> * Flash movie attempts to call flash system commands * </pre> * * <code>FLASH_EXTERNAL_FS_CALL = 32;</code> */ public static final int FLASH_EXTERNAL_FS_CALL_VALUE = 32; /** * <pre> * Image file is too large. * </pre> * * <code>FILE_TOO_LARGE = 33;</code> */ public static final int FILE_TOO_LARGE_VALUE = 33; /** * <pre> * Image data is too large. * </pre> * * <code>IMAGE_DATA_TOO_LARGE = 34;</code> */ public static final int IMAGE_DATA_TOO_LARGE_VALUE = 34; /** * <pre> * Error while processing the image. * </pre> * * <code>IMAGE_PROCESSING_ERROR = 35;</code> */ public static final int IMAGE_PROCESSING_ERROR_VALUE = 35; /** * <pre> * Image is too small. * </pre> * * <code>IMAGE_TOO_SMALL = 36;</code> */ public static final int IMAGE_TOO_SMALL_VALUE = 36; /** * <pre> * Input was invalid. * </pre> * * <code>INVALID_INPUT = 37;</code> */ public static final int INVALID_INPUT_VALUE = 37; /** * <pre> * There was a problem reading the image file. * </pre> * * <code>PROBLEM_READING_FILE = 38;</code> */ public static final int PROBLEM_READING_FILE_VALUE = 38; /** * <pre> * Image constraints are violated, but details like ASPECT_RATIO_NOT_ALLOWED * can't be provided. This happens when asset spec contains more than one * constraint and different criteria of different constraints are violated. * </pre> * * <code>IMAGE_CONSTRAINTS_VIOLATED = 39;</code> */ public static final int IMAGE_CONSTRAINTS_VIOLATED_VALUE = 39; /** * <pre> * Image format is not allowed. * </pre> * * <code>FORMAT_NOT_ALLOWED = 40;</code> */ public static final int FORMAT_NOT_ALLOWED_VALUE = 40; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static ImageError valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static ImageError forNumber(int value) { switch (value) { case 0: return UNSPECIFIED; case 1: return UNKNOWN; case 2: return INVALID_IMAGE; case 3: return STORAGE_ERROR; case 4: return BAD_REQUEST; case 5: return UNEXPECTED_SIZE; case 6: return ANIMATED_NOT_ALLOWED; case 7: return ANIMATION_TOO_LONG; case 8: return SERVER_ERROR; case 9: return CMYK_JPEG_NOT_ALLOWED; case 10: return FLASH_NOT_ALLOWED; case 11: return FLASH_WITHOUT_CLICKTAG; case 12: return FLASH_ERROR_AFTER_FIXING_CLICK_TAG; case 13: return ANIMATED_VISUAL_EFFECT; case 14: return FLASH_ERROR; case 15: return LAYOUT_PROBLEM; case 16: return PROBLEM_READING_IMAGE_FILE; case 17: return ERROR_STORING_IMAGE; case 18: return ASPECT_RATIO_NOT_ALLOWED; case 19: return FLASH_HAS_NETWORK_OBJECTS; case 20: return FLASH_HAS_NETWORK_METHODS; case 21: return FLASH_HAS_URL; case 22: return FLASH_HAS_MOUSE_TRACKING; case 23: return FLASH_HAS_RANDOM_NUM; case 24: return FLASH_SELF_TARGETS; case 25: return FLASH_BAD_GETURL_TARGET; case 26: return FLASH_VERSION_NOT_SUPPORTED; case 27: return FLASH_WITHOUT_HARD_CODED_CLICK_URL; case 28: return INVALID_FLASH_FILE; case 29: return FAILED_TO_FIX_CLICK_TAG_IN_FLASH; case 30: return FLASH_ACCESSES_NETWORK_RESOURCES; case 31: return FLASH_EXTERNAL_JS_CALL; case 32: return FLASH_EXTERNAL_FS_CALL; case 33: return FILE_TOO_LARGE; case 34: return IMAGE_DATA_TOO_LARGE; case 35: return IMAGE_PROCESSING_ERROR; case 36: return IMAGE_TOO_SMALL; case 37: return INVALID_INPUT; case 38: return PROBLEM_READING_FILE; case 39: return IMAGE_CONSTRAINTS_VIOLATED; case 40: return FORMAT_NOT_ALLOWED; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<ImageError> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< ImageError> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<ImageError>() { public ImageError findValueByNumber(int number) { return ImageError.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.ads.googleads.v9.errors.ImageErrorEnum.getDescriptor().getEnumTypes().get(0); } private static final ImageError[] VALUES = values(); public static ImageError valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private ImageError(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.ads.googleads.v9.errors.ImageErrorEnum.ImageError) } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v9.errors.ImageErrorEnum)) { return super.equals(obj); } com.google.ads.googleads.v9.errors.ImageErrorEnum other = (com.google.ads.googleads.v9.errors.ImageErrorEnum) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v9.errors.ImageErrorEnum parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.errors.ImageErrorEnum parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.errors.ImageErrorEnum parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.errors.ImageErrorEnum parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.errors.ImageErrorEnum parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.errors.ImageErrorEnum parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.errors.ImageErrorEnum parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.errors.ImageErrorEnum parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.errors.ImageErrorEnum parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.errors.ImageErrorEnum parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.errors.ImageErrorEnum parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.errors.ImageErrorEnum parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v9.errors.ImageErrorEnum prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Container for enum describing possible image errors. * </pre> * * Protobuf type {@code google.ads.googleads.v9.errors.ImageErrorEnum} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v9.errors.ImageErrorEnum) com.google.ads.googleads.v9.errors.ImageErrorEnumOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.errors.ImageErrorProto.internal_static_google_ads_googleads_v9_errors_ImageErrorEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.errors.ImageErrorProto.internal_static_google_ads_googleads_v9_errors_ImageErrorEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.errors.ImageErrorEnum.class, com.google.ads.googleads.v9.errors.ImageErrorEnum.Builder.class); } // Construct using com.google.ads.googleads.v9.errors.ImageErrorEnum.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v9.errors.ImageErrorProto.internal_static_google_ads_googleads_v9_errors_ImageErrorEnum_descriptor; } @java.lang.Override public com.google.ads.googleads.v9.errors.ImageErrorEnum getDefaultInstanceForType() { return com.google.ads.googleads.v9.errors.ImageErrorEnum.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v9.errors.ImageErrorEnum build() { com.google.ads.googleads.v9.errors.ImageErrorEnum result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v9.errors.ImageErrorEnum buildPartial() { com.google.ads.googleads.v9.errors.ImageErrorEnum result = new com.google.ads.googleads.v9.errors.ImageErrorEnum(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v9.errors.ImageErrorEnum) { return mergeFrom((com.google.ads.googleads.v9.errors.ImageErrorEnum)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v9.errors.ImageErrorEnum other) { if (other == com.google.ads.googleads.v9.errors.ImageErrorEnum.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v9.errors.ImageErrorEnum parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v9.errors.ImageErrorEnum) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v9.errors.ImageErrorEnum) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v9.errors.ImageErrorEnum) private static final com.google.ads.googleads.v9.errors.ImageErrorEnum DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v9.errors.ImageErrorEnum(); } public static com.google.ads.googleads.v9.errors.ImageErrorEnum getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ImageErrorEnum> PARSER = new com.google.protobuf.AbstractParser<ImageErrorEnum>() { @java.lang.Override public ImageErrorEnum parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ImageErrorEnum(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ImageErrorEnum> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ImageErrorEnum> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v9.errors.ImageErrorEnum getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
package com.fasterxml.jackson.databind.ser; import com.fasterxml.jackson.annotation.ObjectIdGenerator; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.JsonSerializer.None; import com.fasterxml.jackson.databind.SerializationConfig; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.NoClass; import com.fasterxml.jackson.databind.cfg.HandlerInstantiator; import com.fasterxml.jackson.databind.introspect.Annotated; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper; import com.fasterxml.jackson.databind.jsonschema.JsonSchema; import com.fasterxml.jackson.databind.jsonschema.SchemaAware; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.ser.impl.WritableObjectId; import com.fasterxml.jackson.databind.util.ClassUtil; import com.fasterxml.jackson.databind.util.RootNameLookup; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.IdentityHashMap; public abstract class DefaultSerializerProvider extends SerializerProvider implements Serializable { private static final long serialVersionUID = 1L; protected transient ArrayList<ObjectIdGenerator<?>> _objectIdGenerators; protected transient IdentityHashMap<Object, WritableObjectId> _seenObjectIds; protected DefaultSerializerProvider() { } protected DefaultSerializerProvider(SerializerProvider paramSerializerProvider, SerializationConfig paramSerializationConfig, SerializerFactory paramSerializerFactory) { super(paramSerializerProvider, paramSerializationConfig, paramSerializerFactory); } public void acceptJsonFormatVisitor(JavaType paramJavaType, JsonFormatVisitorWrapper paramJsonFormatVisitorWrapper) { if (paramJavaType == null) throw new IllegalArgumentException("A class must be provided"); paramJsonFormatVisitorWrapper.setProvider(this); findValueSerializer(paramJavaType, null).acceptJsonFormatVisitor(paramJsonFormatVisitorWrapper, paramJavaType); } public int cachedSerializersCount() { return this._serializerCache.size(); } public abstract DefaultSerializerProvider createInstance(SerializationConfig paramSerializationConfig, SerializerFactory paramSerializerFactory); public WritableObjectId findObjectId(Object paramObject, ObjectIdGenerator<?> paramObjectIdGenerator) { if (this._seenObjectIds == null) { this._seenObjectIds = new IdentityHashMap(); } else { WritableObjectId localWritableObjectId1 = (WritableObjectId)this._seenObjectIds.get(paramObject); if (localWritableObjectId1 != null) return localWritableObjectId1; } Object localObject; if (this._objectIdGenerators == null) { this._objectIdGenerators = new ArrayList(8); localObject = null; } else { int i = 0; int j = this._objectIdGenerators.size(); while (true) { localObject = null; if (i >= j) break; ObjectIdGenerator localObjectIdGenerator = (ObjectIdGenerator)this._objectIdGenerators.get(i); if (localObjectIdGenerator.canUseFor(paramObjectIdGenerator)) { localObject = localObjectIdGenerator; break; } i++; } } if (localObject == null) { localObject = paramObjectIdGenerator.newForSerialization(this); this._objectIdGenerators.add(localObject); } WritableObjectId localWritableObjectId2 = new WritableObjectId((ObjectIdGenerator)localObject); this._seenObjectIds.put(paramObject, localWritableObjectId2); return localWritableObjectId2; } public void flushCachedSerializers() { this._serializerCache.flush(); } public JsonSchema generateJsonSchema(Class<?> paramClass) { if (paramClass == null) throw new IllegalArgumentException("A class must be provided"); JsonSerializer localJsonSerializer = findValueSerializer(paramClass, null); JsonNode localJsonNode1; if ((localJsonSerializer instanceof SchemaAware)) localJsonNode1 = ((SchemaAware)localJsonSerializer).getSchema(this, null); else localJsonNode1 = JsonSchema.getDefaultSchemaNode(); JsonNode localJsonNode2 = localJsonNode1; if (!(localJsonNode1 instanceof ObjectNode)) throw new IllegalArgumentException("Class " + paramClass.getName() + " would not be serialized as a JSON object and therefore has no schema"); return new JsonSchema((ObjectNode)localJsonNode2); } // ERROR // public boolean hasSerializerFor(Class<?> paramClass) { // Byte code: // 0: aload_0 // 1: aload_1 // 2: invokevirtual 159 com/fasterxml/jackson/databind/ser/DefaultSerializerProvider:_findExplicitUntypedSerializer (Ljava/lang/Class;)Lcom/fasterxml/jackson/databind/JsonSerializer; // 5: ifnull +5 -> 10 // 8: iconst_1 // 9: ireturn // 10: iconst_0 // 11: ireturn // 12: iconst_0 // 13: ireturn // // Exception table: // from to target type // 0 8 12 com/fasterxml/jackson/databind/JsonMappingException } public void serializeValue(JsonGenerator paramJsonGenerator, Object paramObject) { JsonSerializer localJsonSerializer; int i; if (paramObject == null) { localJsonSerializer = getDefaultNullValueSerializer(); i = 0; } else { localJsonSerializer = findTypedValueSerializer(paramObject.getClass(), true, null); String str1 = this._config.getRootName(); if (str1 == null) { boolean bool = this._config.isEnabled(SerializationFeature.WRAP_ROOT_VALUE); i = bool; if (bool) { paramJsonGenerator.writeStartObject(); paramJsonGenerator.writeFieldName(this._rootNames.findRootName(paramObject.getClass(), this._config)); } } else if (str1.length() == 0) { i = 0; } else { i = 1; paramJsonGenerator.writeStartObject(); paramJsonGenerator.writeFieldName(str1); } } try { localJsonSerializer.serialize(paramObject, paramJsonGenerator, this); if (i != 0) paramJsonGenerator.writeEndObject(); return; } catch (IOException localIOException) { throw localIOException; } catch (Exception localException) { String str2 = localException.getMessage(); String str3 = str2; if (str2 == null) str3 = "[no message for " + localException.getClass().getName() + "]"; throw new JsonMappingException(str3, localException); } } public void serializeValue(JsonGenerator paramJsonGenerator, Object paramObject, JavaType paramJavaType) { JsonSerializer localJsonSerializer; int i; if (paramObject == null) { localJsonSerializer = getDefaultNullValueSerializer(); i = 0; } else { if (!paramJavaType.getRawClass().isAssignableFrom(paramObject.getClass())) _reportIncompatibleRootType(paramObject, paramJavaType); localJsonSerializer = findTypedValueSerializer(paramJavaType, true, null); boolean bool = this._config.isEnabled(SerializationFeature.WRAP_ROOT_VALUE); i = bool; if (bool) { paramJsonGenerator.writeStartObject(); paramJsonGenerator.writeFieldName(this._rootNames.findRootName(paramJavaType, this._config)); } } try { localJsonSerializer.serialize(paramObject, paramJsonGenerator, this); if (i != 0) paramJsonGenerator.writeEndObject(); return; } catch (IOException localIOException) { throw localIOException; } catch (Exception localException) { String str1 = localException.getMessage(); String str2 = str1; if (str1 == null) str2 = "[no message for " + localException.getClass().getName() + "]"; throw new JsonMappingException(str2, localException); } } public void serializeValue(JsonGenerator paramJsonGenerator, Object paramObject, JavaType paramJavaType, JsonSerializer<Object> paramJsonSerializer) { int i; if (paramObject == null) { paramJsonSerializer = getDefaultNullValueSerializer(); i = 0; } else { if ((paramJavaType != null) && (!paramJavaType.getRawClass().isAssignableFrom(paramObject.getClass()))) _reportIncompatibleRootType(paramObject, paramJavaType); if (paramJsonSerializer == null) paramJsonSerializer = findTypedValueSerializer(paramJavaType, true, null); boolean bool = this._config.isEnabled(SerializationFeature.WRAP_ROOT_VALUE); i = bool; if (bool) { paramJsonGenerator.writeStartObject(); paramJsonGenerator.writeFieldName(this._rootNames.findRootName(paramJavaType, this._config)); } } try { paramJsonSerializer.serialize(paramObject, paramJsonGenerator, this); if (i != 0) paramJsonGenerator.writeEndObject(); return; } catch (IOException localIOException) { throw localIOException; } catch (Exception localException) { String str1 = localException.getMessage(); String str2 = str1; if (str1 == null) str2 = "[no message for " + localException.getClass().getName() + "]"; throw new JsonMappingException(str2, localException); } } public JsonSerializer<Object> serializerInstance(Annotated paramAnnotated, Object paramObject) { if (paramObject == null) return null; Object localObject; if ((paramObject instanceof JsonSerializer)) { localObject = (JsonSerializer)paramObject; } else { if (!(paramObject instanceof Class)) throw new IllegalStateException("AnnotationIntrospector returned serializer definition of type " + paramObject.getClass().getName() + "; expected type JsonSerializer or Class<JsonSerializer> instead"); Class localClass = (Class)paramObject; if ((localClass == JsonSerializer.None.class) || (localClass == NoClass.class)) return null; if (!JsonSerializer.class.isAssignableFrom(localClass)) throw new IllegalStateException("AnnotationIntrospector returned Class " + localClass.getName() + "; expected Class<JsonSerializer>"); HandlerInstantiator localHandlerInstantiator = this._config.getHandlerInstantiator(); JsonSerializer localJsonSerializer; if (localHandlerInstantiator == null) localJsonSerializer = null; else localJsonSerializer = localHandlerInstantiator.serializerInstance(this._config, paramAnnotated, localClass); localObject = localJsonSerializer; if (localJsonSerializer == null) localObject = (JsonSerializer)ClassUtil.createInstance(localClass, this._config.canOverrideAccessModifiers()); } return _handleResolvable((JsonSerializer)localObject); } public static final class Impl extends DefaultSerializerProvider { private static final long serialVersionUID = 1L; public Impl() { } protected Impl(SerializerProvider paramSerializerProvider, SerializationConfig paramSerializationConfig, SerializerFactory paramSerializerFactory) { super(paramSerializationConfig, paramSerializerFactory); } public final Impl createInstance(SerializationConfig paramSerializationConfig, SerializerFactory paramSerializerFactory) { return new Impl(this, paramSerializationConfig, paramSerializerFactory); } } } /* Location: /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar * Qualified Name: com.fasterxml.jackson.databind.ser.DefaultSerializerProvider * JD-Core Version: 0.6.2 */
package mml2asm; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.io.*; public class MML2ASM { //Initialize some music data variables public static String definedLabel = ""; public static int loopCount = 0; public static Channel ChA = new Channel("ChA"); public static Channel ChB = new Channel("ChB"); public static Channel ChC = new Channel("ChC"); public static Channel ChD = new Channel("ChD"); public static List<String> outputBank = new ArrayList<String>(); public static int currentOctave = 4; //Default octave starts at 4 (1 through 8) public static int previousOctave = 4; //Keep track of the previously-changed octave public static int currentNote = 1; //96 total notes, starting from 1 public static int currentFileLine = 0; public static String defaultNoteLength = "4"; public static boolean usingChA = false; public static boolean usingChB = false; public static boolean usingChC = false; public static boolean usingChD = false; public static String songName = "Untitled"; public static boolean loopSongA = false; public static boolean loopSongB = false; public static boolean loopSongC = false; public static boolean loopSongD = false; public static boolean noLoop = false; public static int firstChanInHeader = 1; public static void main(String [] args) { // Create an input scanner for keyboard Scanner stdIn = new Scanner(System.in); // The name of the file to open. String inputFile=""; try { inputFile = args[0]; } catch (ArrayIndexOutOfBoundsException e) { System.out.print("Which .txt MML file are we reading?\n(Default file extension is .txt): "); inputFile = stdIn.next(); } String outputFile = ""; //Is the filename exactly or shorter than 3 characters? if (inputFile.length()<=3) { //If false, add .txt for the default outputFile = inputFile + ".asm"; inputFile = inputFile + ".txt"; } //Is the fourth-to-last character of our inputFile a period? (For .txt/.mml detection) else if (inputFile.charAt(inputFile.length()-4)!='.') { //If false, add .txt for the default outputFile = inputFile + ".asm"; inputFile = inputFile + ".txt"; } else { //If true, get everything before that, store it to "outputFile", then add "_edit.txt". for(int i=0; (i<(inputFile.length()-4)); i++) { outputFile = outputFile + inputFile.charAt(i); } outputFile = outputFile + ".asm"; } System.out.println("Attempting to open " + inputFile + "..."); convert(inputFile, outputFile); //Close the scanner stdIn.close(); System.exit(0); } public static void convert(String inputFile, String outputFile) { //Loop through the whole file until we have all the data we need. File file = new File(inputFile); try(Scanner reader = new Scanner(file)) { System.out.println("File found! Reading..."); parseText(reader); } catch (IOException e) { //Crash and throw an error if we catch any trouble reading the file System.out.println("Couldn't read the file!"); System.exit(0); } System.out.println("Writing..."); try(FileWriter writer = new FileWriter(outputFile)) { //Merge all the separated channel data into a single text string with a header break in-between outputBank.add(";Song: " + songName); //Handle the music header int chanCount = 0; if (usingChA){chanCount++; firstChanInHeader=1;} if (usingChB){chanCount++; if(!usingChA){firstChanInHeader=2;}} if (usingChC){chanCount++; if(!usingChA && !usingChB){firstChanInHeader=3;}} if (usingChD){chanCount++; if(!usingChA && !usingChB && !usingChC){firstChanInHeader=4;}} outputBank.add("\nMusic_" + songName + ":"); //firstChanInHeader String tempHeader = ""; if (usingChA) { tempHeader+="\n\tmusicheader "; if (firstChanInHeader==1) {tempHeader += chanCount;} else{System.out.println("Impossible???");tempHeader+=1;} tempHeader += ", 1, Music_" + songName + "_Ch1"; } if (usingChB) { tempHeader+="\n\tmusicheader "; if (firstChanInHeader==2) {tempHeader += chanCount;} else{tempHeader+=1;} tempHeader += ", 2, Music_" + songName + "_Ch2"; } if (usingChC) { tempHeader+="\n\tmusicheader "; if (firstChanInHeader==3) {tempHeader += chanCount;} else{tempHeader+=1;} tempHeader += ", 3, Music_" + songName + "_Ch3"; } if (usingChD) { tempHeader+="\n\tmusicheader "; if (firstChanInHeader==4) {tempHeader += chanCount;} else{tempHeader+=1;} tempHeader += ", 4, Music_" + songName + "_Ch4"; } outputBank.add(tempHeader); //Start writing channel data if (usingChA) { if (ChA.getChannelDataSize()>0) { outputBank.add("\n\nMusic_" + songName + "_Ch1: ; Channel A (Pulse 1)"); outputBank.add(ChA.toString()); } if (loopSongA) { outputBank.add("\n\tloopchannel 0, Music_" + songName + "_LoopStart_Ch1"); } else if (noLoop) { outputBank.add("\n\tendchannel"); } else { outputBank.add("\n\tloopchannel 0, Music_" + songName + "_Ch1"); } if (ChA.getLoopDataSize()>0) { outputBank.add("\n\n;Loop Defines for Channel A (Pulse 1)"); outputBank.add("\n" + ChA.loopToString()); } } if (usingChB) { if (ChB.getChannelDataSize()>0) { outputBank.add("\n\nMusic_" + songName + "_Ch2: ; Channel B (Pulse 2)"); outputBank.add(ChB.toString()); } if (loopSongB) { outputBank.add("\n\tloopchannel 0, Music_" + songName + "_LoopStart_Ch2"); } else if (noLoop) { outputBank.add("\n\tendchannel"); } else { outputBank.add("\n\tloopchannel 0, Music_" + songName + "_Ch2"); } if (ChB.getLoopDataSize()>0) { outputBank.add("\n\n;Loop Defines for Channel B (Pulse 2)"); outputBank.add("\n" + ChB.loopToString()); } } if (usingChC) { if (ChC.getChannelDataSize()>0) { outputBank.add("\n\nMusic_" + songName + "_Ch3: ; Channel C (Wave)"); outputBank.add(ChC.toString()); } if (loopSongC) { outputBank.add("\n\tloopchannel 0, Music_" + songName + "_LoopStart_Ch3"); } else if (noLoop) { outputBank.add("\n\tendchannel"); } else { outputBank.add("\n\tloopchannel 0, Music_" + songName + "_Ch3"); } if (ChC.getLoopDataSize()>0) { outputBank.add("\n\n;Loop Defines for Channel C (Wave)"); outputBank.add("\n" + ChC.loopToString()); } } if (usingChD) { if (ChD.getChannelDataSize()>0) { outputBank.add("\n\nMusic_" + songName + "_Ch4: ; Channel D (White Noise)"); outputBank.add(ChD.toString()); } if (loopSongD) { outputBank.add("\n\tloopchannel 0, Music_" + songName + "_LoopStart_Ch4"); } else if (noLoop) { outputBank.add("\n\tendchannel"); } else { outputBank.add("\n\tloopchannel 0, Music_" + songName + "_Ch4"); } if (ChD.getLoopDataSize()>0) { outputBank.add("\n\n;Loop Defines for Channel D (White Noise)"); outputBank.add("\n" + ChD.loopToString()); } } //Then, write all the combined data into the actual .txt int q=0; while (q<outputBank.size()) { String outputTempLine = outputBank.get(q); q++; writer.write(outputTempLine); } System.out.println("Done!"); } catch(IOException e) { //Crash and throw an error if we catch any trouble writing the file System.out.println("Couldn't write to the file!"); System.exit(0); } } public static void parseText(Scanner reader) { String parsedLine = null; boolean checkedTitle = false; boolean endReading = false; while(reader.hasNextLine()) { //Disable all channels every line before deeming them relevant to the line ChA.setChannelEnabled(false); ChB.setChannelEnabled(false); ChC.setChannelEnabled(false); ChD.setChannelEnabled(false); //Get the current line and start reading it parsedLine = reader.nextLine(); //Skip all lines that are entirely empty/nothing but spaces while (parsedLine.replaceAll("\\s", "").equals("")) { if (!reader.hasNextLine()){endReading=true; break;} parsedLine = reader.nextLine();currentFileLine++;} if (endReading){break;} if (songName.equals("Untitled") && !checkedTitle) { if (parsedLine.subSequence(0, 7).equals(";title=")) { songName = parsedLine.substring(7, parsedLine.length()); System.out.println("Parsing data for " + songName + "..."); } else { System.out.println("Song title not found! Resorting to \"Untitled.\"\n(Please declare your song title using \";title=\" at the top of your txt!)"); } checkedTitle=true; } currentFileLine++; boolean hitAComment = false; //Ignore anything past ; so the parser ignores comments //Determine which audio channels are relevant int k=0; if (parsedLine.replaceAll("\\s", "").charAt(0)!=';') { while (parsedLine.trim().charAt(k)!=' ' && k<=parsedLine.length()) { switch(parsedLine.trim().toUpperCase().charAt(k)) { case 'A': ChA.setChannelEnabled(true); usingChA=true; break; case 'B': ChB.setChannelEnabled(true); usingChB=true; break; case 'C': ChC.setChannelEnabled(true); usingChC=true; break; case 'D': ChD.setChannelEnabled(true); usingChD=true; break; case ';': break; //Ignore all commented lines default: System.out.println("Invalid or missing channel declaration on line " + currentFileLine + "Skipping..."); break; } k++; } //If we have any channel declaration, find out what it was so we can determine how many characters to skip String chanDec = null; if (ChA.getChannelEnabled()||ChB.getChannelEnabled()||ChC.getChannelEnabled()||ChD.getChannelEnabled()) { chanDec = parsedLine.trim().substring(0, parsedLine.indexOf(" ")); } //Remove all spaces from the parsed line before we actually start reading it parsedLine = parsedLine.replaceAll("\\s",""); //Keep track of how far into the line we are. int dataStart = chanDec.length(); int w = dataStart; //Find data length all the way up to the comment or end of the line while (parsedLine.charAt(w)!=';' && w<parsedLine.length()-1) { w++; } //Loop through every character of the parsed line and amend what to do about each one. for (int i=dataStart; i<=w;i++) { if (!hitAComment) //As long as we haven't hit a comment yet... { //amend the type of command we hit and choose what to do with it. if (parsedLine.charAt(i)=='L') { //Handle loop point for each channel individually handleLoop(); } else if (parsedLine.charAt(i)=='l') { i += setDefaultNoteLength(parsedLine, i); } switch(parsedLine.toLowerCase().charAt(i)) { case ';': hitAComment=true; break; case 'o': i += amendOctave(parsedLine, i); break; case 'a': i += amendNote('a', parsedLine, i); break; case 'b': i += amendNote('b', parsedLine, i); break; case 'c': i += amendNote('c', parsedLine, i); break; case 'd': i += amendNote('d', parsedLine, i); break; case 'e': i += amendNote('e', parsedLine, i); break; case 'f': i += amendNote('f', parsedLine, i); break; case 'g': i += amendNote('g', parsedLine, i); break; case '^': i += amendNote('^', parsedLine, i); break; case 'y': i += amendStereoPan(parsedLine, i); break; case 't': i += amendTempo(parsedLine, i); break; case 'v': i += amendVolume(parsedLine, i); break; case '@': i += amendCommand(parsedLine, i) -1; break; case '(': i = defineMacro(parsedLine, i, reader, 2); break; case '[': i = defineMacro(parsedLine, i, reader, 1); break; case ']': i = handleLoopEnd(parsedLine, i); break; case '>': shiftOctave('>', parsedLine, i); break; case '<': shiftOctave('<', parsedLine, i); break; default: //The compiler will completely ignore anything else not on this list. break; } } else { //If we hit a comment, just print the rest of the line normally (because we flagged it as a comment in the ASM, too). String remainderString = ""; while (i<parsedLine.length()) { remainderString += parsedLine.charAt(i); i++; } chanWrite("\t; " + remainderString); } } } } } public static int handleLoopEnd(String parsedLine, int i) { ChA.setLoopMode(false); ChB.setLoopMode(false); ChC.setLoopMode(false); ChD.setLoopMode(false); try { System.out.println(parsedLine.charAt(i+1)); } catch(StringIndexOutOfBoundsException e) { System.out.println("No Loop."); } return i; } public static int defineMacro(String parsedLine, int i, Scanner reader, int dataType) { /* case '(': i = defineMacro(parsedLine, i, reader, 2); case '[': i = defineMacro(parsedLine, i, reader, 1); */ if (dataType==1) { //case '[' ChA.setMacroLoopStart(); ChB.setMacroLoopStart(); ChC.setMacroLoopStart(); ChD.setMacroLoopStart(); } else if (dataType==2) { //case '(' } return i; } public static int noiseNote(String parsedLine, int i, String note) { String nFreq = ""; String noteLength = ""; switch(note) { case "kik": nFreq="D#"; break; case "hop": nFreq="F#"; break; case "hcl": nFreq="C#"; break; case "snr": nFreq="C_"; break; default: nFreq="D#"; break; } if (parsedLine.charAt(i) > '9' || parsedLine.charAt(i) < '0' ) { noteLength = defaultNoteLength; } else { while(parsedLine.charAt(i) <= '9' && parsedLine.charAt(i) >= '0' ) { noteLength+=parsedLine.charAt(i); if (i<parsedLine.length()-1) {i++;} else {break;} } } noteLength = getNoteLength(noteLength); i--; chanWrite("\n\tnote " + nFreq + ", " + noteLength); return noteLength.length(); } public static String getNoteLength(String input) { //Given the input note length, translate it in terms of pokecrystal's music engine and output the numerical value as a string. return input; } public static int setDefaultNoteLength(String parsedLine, int i) { String defaultNoteLength = ""; i++; while(parsedLine.charAt(i) <= '9' && parsedLine.charAt(i) >= '0' ) { defaultNoteLength+=parsedLine.charAt(i); i++; } return defaultNoteLength.length(); } public static int amendNote(char inputNotePitch, String parsedLine, int i) { int charsToSkip = 0; boolean hasSharpOrFlat = false; boolean tempOctave = false; //Calculate where we are on the pitch table //Start by re-assinging the note value: switch(inputNotePitch) { case '^': currentNote=777; break; case 'c': currentNote=13; break; case 'd': currentNote=3; break; case 'e': currentNote=5; break; case 'f': currentNote=6; break; case 'g': currentNote=8; break; case 'a': currentNote=10; break; case 'b': currentNote=12; break; default: break; } if (parsedLine.charAt(i+1)=='+') { if (inputNotePitch=='b') { //If we happen to hit the bounds of the octave, fix it automatically. setOctave(currentOctave+1); tempOctave=true; } if (currentNote<96){currentNote++;} //Check all notes to account for b+ and c- hasSharpOrFlat=true; charsToSkip++; } else if (parsedLine.charAt(i+1)=='-') { if (inputNotePitch=='c') { //If we happen to hit the bounds of the octave, fix it automatically. setOctave(currentOctave-1); tempOctave=true; } if (currentNote>1){currentNote--;} hasSharpOrFlat=true; charsToSkip++; } //Let's find our note. String outputNote = ""; switch(currentNote) { case 777: outputNote = "__"; break; case 1: outputNote = "C_"; break; case 2: outputNote = "C#"; break; case 3: outputNote = "D_"; break; case 4: outputNote = "D#"; break; case 5: outputNote = "E_"; break; case 6: outputNote = "F_"; break; case 7: outputNote = "F#"; break; case 8: outputNote = "G_"; break; case 9: outputNote = "G#"; break; case 10: outputNote = "A_"; break; case 11: outputNote = "A#"; break; case 12: outputNote = "B_"; break; case 13: outputNote = "C_"; break; default: outputNote = "__"; break; } //Now, let's amend the length of the note. String noteLength = ""; int j = 1; if (hasSharpOrFlat){j++;} //Skip one character if we're dealing with a sharp or flat in our note length value //First, we'll keep track of every number after the sharp or flat until we hit something entirely different. while(parsedLine.charAt(i+j)>='0' && parsedLine.charAt(i+j)<='9') { noteLength += parsedLine.charAt(i+j); if ((i+j)<parsedLine.length()-1) { j++; } else { break; } } //Store the current line into an arraylist chanWrite("\n\tnote " + outputNote + ", " + noteLength); //Revert the octave if we changed it earlier for getting out of the octave range if (tempOctave) { if (inputNotePitch=='c') { setOctave(currentOctave+1); tempOctave=false; } else if (inputNotePitch=='b') { setOctave(currentOctave+1); tempOctave=false; } } return charsToSkip; } public static int amendOctave(String parsedLine, int i) { if (parsedLine.charAt(i+1) > '8' ||parsedLine.charAt(i+1) < '1' ) { System.out.println("Found an invalid octave on line " + currentFileLine + " at position " + (i+1) + ": Skipping..."); } else { currentOctave = parsedLine.charAt(i+1) - '0'; //Default octave starts at 4 (1 through 8) setOctave(currentOctave); } return 1; } public static void setOctave(int currentOctave) { ChA.setOctave(currentOctave); ChB.setOctave(currentOctave); ChC.setOctave(currentOctave); ChD.setOctave(currentOctave); } public static int amendStereoPan(String parsedLine, int i) { int charsToSkip = 1; switch(parsedLine.charAt(i+1)) { case '1': //right chanWrite("\n\tstereopanning $0f"); break; case '-': //left chanWrite("\n\tstereopanning $f0"); charsToSkip++; break; case '0': //center chanWrite("\n\tstereopanning $ff"); break; } return charsToSkip; } public static int amendTempo(String parsedLine, int i) { int charsToSkip = 0; String findTempo = ""; i++; while(parsedLine.charAt(i) >= '0' && parsedLine.charAt(i) <= '9' || parsedLine.charAt(i) == '$') { findTempo += parsedLine.charAt(i) - '0'; if (i+1<parsedLine.length()) { i++; } else { break; } charsToSkip++; } int intTempo = Integer.parseInt(findTempo); ChA.setTempo(intTempo); ChB.setTempo(intTempo); ChC.setTempo(intTempo); ChD.setTempo(intTempo); return charsToSkip; } public static int amendVolume(String parsedLine, int i) { int charsToSkip = 0; String findVol = ""; i++; while(parsedLine.charAt(i) >= '0' && parsedLine.charAt(i) <= '9' || parsedLine.charAt(i) == '$') { findVol += parsedLine.charAt(i) - '0'; if (i+1<parsedLine.length()) { i++; } else { break; } charsToSkip++; } ChA.setVol(findVol); ChB.setVol(findVol); ChC.setVol(findVol); ChD.setVol(findVol); return charsToSkip; } public static int amendCommand(String parsedLine, int i) { String findCommand = ""; int charsToSkip = 0; while(!(parsedLine.charAt(i) >= '0' && parsedLine.charAt(i) <= '9' && parsedLine.charAt(i) != '$')) { if (parsedLine.charAt(i) != '$') { findCommand += parsedLine.charAt(i); } if (i+1<parsedLine.length()) { i++; } else { break; } charsToSkip++; } //Determine the command in question switch(findCommand) { case "@wd": charsToSkip += waveDuty(parsedLine, i); break; case "@ve": charsToSkip += volumeEnvelope(parsedLine, i); break; case "@v": charsToSkip += vibChange(); break; case "@k": charsToSkip += noiseNote(parsedLine, i, "kik"); break; case "@s": charsToSkip += noiseNote(parsedLine, i, "snr"); break; case "@hc": charsToSkip += noiseNote(parsedLine, i, "hcl"); break; case "@ho": charsToSkip += noiseNote(parsedLine, i, "hop"); break; case "@tn": charsToSkip += toggleNoise(parsedLine, i); break; default: break; } return charsToSkip; } public static int toggleNoise(String parsedLine, int i) { String findVal = ""; while(parsedLine.charAt(i) >= '0' && parsedLine.charAt(i) <= '9' || parsedLine.charAt(i) == '$') { findVal += parsedLine.charAt(i) - '0'; if (i+1<parsedLine.length()) { i++; } else { break; } } chanWrite("\n\ttogglenoise $" + findVal); return 1; } public static int waveDuty(String parsedLine, int i) { String findVal = ""; while(parsedLine.charAt(i) >= '0' && parsedLine.charAt(i) <= '9' || parsedLine.charAt(i) == '$') { findVal += parsedLine.charAt(i) - '0'; if (i+1<parsedLine.length()) { i++; } else { break; } } ChA.setDutyWave(findVal); ChB.setDutyWave(findVal); ChC.setDutyWave(findVal); ChD.setDutyWave(findVal); return 1; } public static int volumeEnvelope(String parsedLine, int i) { boolean envelopeUp = true; int charsToSkip = 1; if (parsedLine.charAt(i)=='-') { envelopeUp = false; charsToSkip++; i++; } if (envelopeUp) { } return charsToSkip; } public static int vibChange() { return 1; } public static void shiftOctave(char direction, String parsedLine, int i) { //Shift the octave if (direction=='<' && currentOctave>1) { currentOctave--; setOctave(currentOctave); } else if (direction=='>' && currentOctave<9) { currentOctave++; setOctave(currentOctave); } } public static void handleLoop() { //Handle loop point for each channel individually if (ChA.getChannelEnabled()) { ChA.add("\nMusic_" + songName + "_LoopStart_Ch1: ;The loop point for this channel"); loopSongA=true; } if (ChB.getChannelEnabled()) { ChB.add("\nMusic_" + songName + "_LoopStart_Ch2: ;The loop point for this channel"); loopSongB=true; } if (ChC.getChannelEnabled()) { ChC.add("\nMusic_" + songName + "_LoopStart_Ch3: ;The loop point for this channel"); loopSongC=true; } if (ChD.getChannelEnabled()) { ChD.add("\nMusic_" + songName + "_LoopStart_Ch4: ;The loop point for this channel"); loopSongD=true; } } public static void chanWrite(String input) { ChA.chanWrite(input); ChB.chanWrite(input); ChC.chanWrite(input); ChD.chanWrite(input); } }
/* * 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.internal.cache.wan; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.logging.log4j.Logger; import org.apache.geode.DataSerializer; import org.apache.geode.cache.Cache; import org.apache.geode.cache.CacheFactory; import org.apache.geode.cache.wan.GatewayQueueEvent; import org.apache.geode.cache.wan.GatewaySender; 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.DataSerializableFixedID; import org.apache.geode.internal.Version; import org.apache.geode.internal.cache.GemFireCacheImpl; import org.apache.geode.internal.cache.InitialImageOperation; import org.apache.geode.internal.cache.InternalRegion; import org.apache.geode.internal.cache.LocalRegion; import org.apache.geode.internal.cache.versions.VersionTag; import org.apache.geode.internal.i18n.LocalizedStrings; import org.apache.geode.internal.logging.LogService; import org.apache.geode.internal.logging.log4j.LocalizedMessage; public class GatewaySenderQueueEntrySynchronizationOperation { private InternalDistributedMember recipient; private InternalRegion region; private List<GatewaySenderQueueEntrySynchronizationEntry> entriesToSynchronize; private static final Logger logger = LogService.getLogger(); protected GatewaySenderQueueEntrySynchronizationOperation(InternalDistributedMember recipient, InternalRegion internalRegion, List<InitialImageOperation.Entry> giiEntriesToSynchronize) { this.recipient = recipient; this.region = internalRegion; initializeEntriesToSynchronize(giiEntriesToSynchronize); } protected void synchronizeEntries() { if (logger.isDebugEnabled()) { logger.debug( "{}: Requesting synchronization from member={}; regionPath={}; entriesToSynchronize={}", getClass().getSimpleName(), this.recipient, this.region.getFullPath(), this.entriesToSynchronize); } // Create and send message DistributionManager dm = this.region.getDistributionManager(); GatewaySenderQueueEntrySynchronizationReplyProcessor processor = new GatewaySenderQueueEntrySynchronizationReplyProcessor(dm, this.recipient, this); GatewaySenderQueueEntrySynchronizationMessage message = new GatewaySenderQueueEntrySynchronizationMessage(this.recipient, processor.getProcessorId(), this); dm.putOutgoing(message); // Wait for replies try { processor.waitForReplies(); } catch (ReplyException e) { e.handleCause(); } catch (InterruptedException e) { dm.getCancelCriterion().checkCancelInProgress(e); Thread.currentThread().interrupt(); } } protected GemFireCacheImpl getCache() { return (GemFireCacheImpl) CacheFactory.getAnyInstance(); } private void initializeEntriesToSynchronize( List<InitialImageOperation.Entry> giiEntriesToSynchronize) { this.entriesToSynchronize = new ArrayList<>(); for (InitialImageOperation.Entry entry : giiEntriesToSynchronize) { this.entriesToSynchronize.add( new GatewaySenderQueueEntrySynchronizationEntry(entry.getKey(), entry.getVersionTag())); } } public static class GatewaySenderQueueEntrySynchronizationReplyProcessor extends ReplyProcessor21 { private GatewaySenderQueueEntrySynchronizationOperation operation; public GatewaySenderQueueEntrySynchronizationReplyProcessor(DistributionManager dm, InternalDistributedMember recipient, GatewaySenderQueueEntrySynchronizationOperation operation) { super(dm, recipient); this.operation = operation; } @Override public void process(DistributionMessage msg) { try { if (msg instanceof ReplyMessage) { ReplyMessage reply = (ReplyMessage) msg; if (reply.getException() == null) { if (logger.isDebugEnabled()) { logger.debug( "{}: Processing reply from member={}; regionPath={}; key={}; entriesToSynchronize={}", getClass().getSimpleName(), reply.getSender(), this.operation.region.getFullPath(), this.operation.entriesToSynchronize, reply.getReturnValue()); } List<Map<String, GatewayQueueEvent>> events = (List<Map<String, GatewayQueueEvent>>) reply.getReturnValue(); for (int i = 0; i < events.size(); i++) { Map<String, GatewayQueueEvent> eventsForOneEntry = events.get(i); if (events.isEmpty()) { GatewaySenderQueueEntrySynchronizationEntry entry = this.operation.entriesToSynchronize.get(i); logger.info(LocalizedMessage.create( LocalizedStrings.GatewaySenderQueueEntrySynchronizationReplyProcessor_REPLY_IS_EMPTY, new Object[] {reply.getSender(), this.operation.region.getFullPath(), entry.key, entry.entryVersion})); } else { putSynchronizationEvents(eventsForOneEntry); } } } } } finally { super.process(msg); } } private void putSynchronizationEvents(Map<String, GatewayQueueEvent> senderIdsAndEvents) { for (Map.Entry<String, GatewayQueueEvent> senderIdAndEvent : senderIdsAndEvents.entrySet()) { AbstractGatewaySender sender = (AbstractGatewaySender) getCache().getGatewaySender(senderIdAndEvent.getKey()); sender.putSynchronizationEvent(senderIdAndEvent.getValue()); } } private Cache getCache() { return CacheFactory.getAnyInstance(); } } public static class GatewaySenderQueueEntrySynchronizationMessage extends PooledDistributionMessage implements MessageWithReply { private int processorId; private String regionPath; private List<GatewaySenderQueueEntrySynchronizationEntry> entriesToSynchronize; /* For serialization */ public GatewaySenderQueueEntrySynchronizationMessage() {} protected GatewaySenderQueueEntrySynchronizationMessage(InternalDistributedMember recipient, int processorId, GatewaySenderQueueEntrySynchronizationOperation operation) { super(); setRecipient(recipient); this.processorId = processorId; this.regionPath = operation.region.getFullPath(); this.entriesToSynchronize = operation.entriesToSynchronize; } @Override protected void process(ClusterDistributionManager dm) { Object result = null; ReplyException replyException = null; try { if (logger.isDebugEnabled()) { logger.debug("{}: Providing synchronization region={}; entriesToSynchronize={}", getClass().getSimpleName(), this.regionPath, this.entriesToSynchronize); } result = getSynchronizationEvents(); } catch (Throwable t) { replyException = new ReplyException(t); } finally { ReplyMessage replyMsg = new ReplyMessage(); replyMsg.setRecipient(getSender()); replyMsg.setProcessorId(this.processorId); if (replyException == null) { replyMsg.setReturnValue(result); } else { replyMsg.setException(replyException); } if (logger.isDebugEnabled()) { logger.debug("{}: Sending synchronization reply returnValue={}; exception={}", getClass().getSimpleName(), replyMsg.getReturnValue(), replyMsg.getException()); } dm.putOutgoing(replyMsg); } } private Object getSynchronizationEvents() { List<Map<String, GatewayQueueEvent>> results = new ArrayList<>(); // Get the region GemFireCacheImpl gfci = (GemFireCacheImpl) getCache(); LocalRegion region = (LocalRegion) gfci.getRegion(this.regionPath); // Add the appropriate GatewaySenderEventImpl from each GatewaySender for each entry Set<String> allGatewaySenderIds = region.getAllGatewaySenderIds(); for (GatewaySender sender : gfci.getAllGatewaySenders()) { if (allGatewaySenderIds.contains(sender.getId())) { for (GatewaySenderQueueEntrySynchronizationEntry entry : this.entriesToSynchronize) { Map<String, GatewayQueueEvent> resultForOneEntry = new HashMap<>(); GatewayQueueEvent event = ((AbstractGatewaySender) sender) .getSynchronizationEvent(entry.key, entry.entryVersion.getVersionTimeStamp()); if (event != null) { resultForOneEntry.put(sender.getId(), event); } results.add(resultForOneEntry); } } } return results; } private Cache getCache() { return CacheFactory.getAnyInstance(); } @Override public int getDSFID() { return GATEWAY_SENDER_QUEUE_ENTRY_SYNCHRONIZATION_MESSAGE; } @Override public void toData(DataOutput out) throws IOException { super.toData(out); out.writeInt(this.processorId); DataSerializer.writeString(this.regionPath, out); DataSerializer.writeArrayList((ArrayList) this.entriesToSynchronize, out); } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); this.processorId = in.readInt(); this.regionPath = DataSerializer.readString(in); this.entriesToSynchronize = DataSerializer.readArrayList(in); } } public static class GatewaySenderQueueEntrySynchronizationEntry implements DataSerializableFixedID { private Object key; private VersionTag entryVersion; /* For serialization */ public GatewaySenderQueueEntrySynchronizationEntry() {} public GatewaySenderQueueEntrySynchronizationEntry(Object key, VersionTag entryVersion) { this.key = key; this.entryVersion = entryVersion; } @Override public int getDSFID() { return GATEWAY_SENDER_QUEUE_ENTRY_SYNCHRONIZATION_ENTRY; } @Override public Version[] getSerializationVersions() { return null; } @Override public void toData(DataOutput out) throws IOException { DataSerializer.writeObject(this.key, out); DataSerializer.writeObject(this.entryVersion, out); } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { this.key = DataSerializer.readObject(in); this.entryVersion = DataSerializer.readObject(in); } @Override public String toString() { return new StringBuilder().append(getClass().getSimpleName()).append("[").append("key=") .append(this.key).append("; entryVersion=").append(this.entryVersion).append("]") .toString(); } } }
package org.holoeverywhere.widget; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.holoeverywhere.FontLoader; import org.holoeverywhere.LayoutInflater; import android.content.Context; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; public class ArrayAdapter<T> extends BaseAdapter implements Filterable { private class ArrayFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence prefix) { FilterResults results = new FilterResults(); if (mOriginalValues == null) { synchronized (mLock) { mOriginalValues = new ArrayList<T>(mObjects); } } if (prefix == null || prefix.length() == 0) { ArrayList<T> list; synchronized (mLock) { list = new ArrayList<T>(mOriginalValues); } results.values = list; results.count = list.size(); } else { String prefixString = prefix.toString().toLowerCase(); ArrayList<T> values; synchronized (mLock) { values = new ArrayList<T>(mOriginalValues); } final int count = values.size(); final ArrayList<T> newValues = new ArrayList<T>(); for (int i = 0; i < count; i++) { final T value = values.get(i); final String valueText = value.toString().toLowerCase(); if (valueText.startsWith(prefixString)) { newValues.add(value); } else { final String[] words = valueText.split(" "); final int wordCount = words.length; for (int k = 0; k < wordCount; k++) { if (words[k].startsWith(prefixString)) { newValues.add(value); break; } } } } results.values = newValues; results.count = newValues.size(); } return results; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) { mObjects = (List<T>) results.values; if (results.count > 0) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } } public static ArrayAdapter<CharSequence> createFromResource( Context context, int textArrayResId, int textViewResId) { CharSequence[] strings = context.getResources().getTextArray( textArrayResId); return new ArrayAdapter<CharSequence>(context, textViewResId, strings); } private boolean mAutoSetNotifyFlag = true; private Context mContext; private int mDropDownResource; private int mFieldId = 0; private ArrayFilter mFilter; private LayoutInflater mInflater; private final Object mLock = new Object(); private boolean mNotifyOnChange = true; private List<T> mObjects; private ArrayList<T> mOriginalValues; private int mResource; public ArrayAdapter(Context context, int textViewResourceId) { init(context, textViewResourceId, 0, new ArrayList<T>()); } public ArrayAdapter(Context context, int resource, int textViewResourceId) { init(context, resource, textViewResourceId, new ArrayList<T>()); } public ArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects) { init(context, resource, textViewResourceId, objects); } public ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) { init(context, resource, textViewResourceId, Arrays.asList(objects)); } public ArrayAdapter(Context context, int textViewResourceId, List<T> objects) { init(context, textViewResourceId, 0, objects); } public ArrayAdapter(Context context, int textViewResourceId, T[] objects) { init(context, textViewResourceId, 0, Arrays.asList(objects)); } public void add(T object) { synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues.add(object); } else { mObjects.add(object); } } if (mNotifyOnChange) { notifyDataSetChanged(); } } public void addAll(Collection<? extends T> collection) { synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues.addAll(collection); } else { mObjects.addAll(collection); } } if (mNotifyOnChange) { notifyDataSetChanged(); } } public void addAll(T... items) { synchronized (mLock) { if (mOriginalValues != null) { Collections.addAll(mOriginalValues, items); } else { Collections.addAll(mObjects, items); } } if (mNotifyOnChange) { notifyDataSetChanged(); } } public void clear() { synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues.clear(); } else { mObjects.clear(); } } if (mNotifyOnChange) { notifyDataSetChanged(); } } private View createViewFromResource(int position, View convertView, ViewGroup parent, int resource) { View view; TextView text = null; if (convertView == null) { view = FontLoader.apply(mInflater.inflate(resource, parent, false)); } else { view = convertView; } try { if (view != null) { if (mFieldId > 0) { text = (TextView) view.findViewById(mFieldId); } else { text = (TextView) view.findViewById(android.R.id.text1); } if (text == null && view instanceof TextView) { text = (TextView) view; } } if (text == null) { throw new NullPointerException(); } } catch (RuntimeException e) { Log.e("ArrayAdapter", "You must supply a resource ID for a TextView"); throw new IllegalStateException( "ArrayAdapter requires the resource ID to be a TextView", e); } T item = getItem(position); if (item instanceof CharSequence) { text.setText((CharSequence) item); } else { text.setText(item.toString()); } return view; } public Context getContext() { return mContext; } @Override public int getCount() { return mObjects.size(); } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return createViewFromResource(position, convertView, parent, mDropDownResource); } @Override public Filter getFilter() { if (mFilter == null) { mFilter = new ArrayFilter(); } return mFilter; } @Override public T getItem(int position) { return mObjects.get(position); } @Override public long getItemId(int position) { return position; } public int getPosition(T item) { return mObjects.indexOf(item); } @Override public View getView(int position, View convertView, ViewGroup parent) { return createViewFromResource(position, convertView, parent, mResource); } private void init(Context context, int resource, int textViewResourceId, List<T> objects) { mContext = context; mInflater = LayoutInflater.from(context); mResource = mDropDownResource = resource; mObjects = objects; mFieldId = textViewResourceId; } public void insert(T object, int index) { synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues.add(index, object); } else { mObjects.add(index, object); } } if (mNotifyOnChange) { notifyDataSetChanged(); } } public boolean isAutoSetNotifyFlag() { return mAutoSetNotifyFlag; } @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); if (mAutoSetNotifyFlag) { mNotifyOnChange = true; } } public void remove(T object) { synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues.remove(object); } else { mObjects.remove(object); } } if (mNotifyOnChange) { notifyDataSetChanged(); } } public void setAutoSetNotifyFlag(boolean autoSetNotifyFlag) { this.mAutoSetNotifyFlag = autoSetNotifyFlag; } public void setDropDownViewResource(int resource) { this.mDropDownResource = resource; } public void setNotifyOnChange(boolean notifyOnChange) { mNotifyOnChange = notifyOnChange; } public void sort(Comparator<? super T> comparator) { synchronized (mLock) { if (mOriginalValues != null) { Collections.sort(mOriginalValues, comparator); } else { Collections.sort(mObjects, comparator); } } if (mNotifyOnChange) { notifyDataSetChanged(); } } }
/* * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.dataflow.shell.command; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.cloud.dataflow.rest.client.DataFlowServerException; import org.springframework.cloud.dataflow.rest.client.DataFlowTemplate; import org.springframework.cloud.dataflow.rest.resource.about.AboutResource; import org.springframework.cloud.dataflow.rest.resource.about.FeatureInfo; import org.springframework.cloud.dataflow.rest.resource.about.RuntimeEnvironmentDetails; import org.springframework.cloud.dataflow.rest.resource.about.SecurityInfo; import org.springframework.cloud.dataflow.rest.resource.security.SecurityInfoResource; import org.springframework.cloud.dataflow.rest.util.CheckableResource; import org.springframework.cloud.dataflow.rest.util.HttpClientConfigurer; import org.springframework.cloud.dataflow.rest.util.ProcessOutputResource; import org.springframework.cloud.dataflow.rest.util.ResourceBasedAuthorizationInterceptor; import org.springframework.cloud.dataflow.shell.Target; import org.springframework.cloud.dataflow.shell.TargetCredentials; import org.springframework.cloud.dataflow.shell.TargetHolder; import org.springframework.cloud.dataflow.shell.command.support.RoleType; import org.springframework.cloud.dataflow.shell.config.DataFlowShell; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.shell.CommandLine; import org.springframework.shell.core.CommandMarker; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.springframework.shell.table.BorderSpecification; import org.springframework.shell.table.BorderStyle; import org.springframework.shell.table.CellMatchers; import org.springframework.shell.table.KeyValueHorizontalAligner; import org.springframework.shell.table.KeyValueSizeConstraints; import org.springframework.shell.table.KeyValueTextWrapper; import org.springframework.shell.table.SimpleHorizontalAligner; import org.springframework.shell.table.SimpleVerticalAligner; import org.springframework.shell.table.TableBuilder; import org.springframework.shell.table.TableModelBuilder; import org.springframework.shell.table.Tables; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; /** * Configuration commands for the Shell. The default Data Flow Server location is * <code>http://localhost:9393</code> * * @author Gunnar Hillert * @author Marius Bogoevici * @author Ilayaperumal Gopinathan * @author Gary Russell * @author Mark Pollack * @author Eric Bottard * @author Mike Heath */ @Component @Configuration public class ConfigCommands implements CommandMarker, InitializingBean, ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware { public static final String HORIZONTAL_LINE = "-------------------------------------------------------------------------------\n"; private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private DataFlowShell shell; @Autowired private RestTemplate restTemplate; @Value("${dataflow.uri:" + Target.DEFAULT_TARGET + "}") private String serverUri; @Value("${dataflow.username:" + Target.DEFAULT_USERNAME + "}") private String userName; @Value("${dataflow.password:" + Target.DEFAULT_SPECIFIED_PASSWORD + "}") private String password; @Value("${dataflow.skip-ssl-validation:" + Target.DEFAULT_UNSPECIFIED_SKIP_SSL_VALIDATION + "}") private boolean skipSslValidation; @Value("${dataflow.proxy.uri:" + Target.DEFAULT_PROXY_URI + "}") private String proxyUri; @Value("${dataflow.proxy.username:" + Target.DEFAULT_PROXY_USERNAME + "}") private String proxyUsername; @Value("${dataflow.proxy.password:" + Target.DEFAULT_PROXY_SPECIFIED_PASSWORD + "}") private String proxyPassword; @Value("${dataflow.credentials-provider-command:" + Target.DEFAULT_CREDENTIALS_PROVIDER_COMMAND + "}") private String credentialsProviderCommand; private UserInput userInput; private TargetHolder targetHolder; private ApplicationContext applicationContext; private volatile boolean initialized; @Autowired private CommandLine commandLine; @Autowired public void setUserInput(UserInput userInput) { this.userInput = userInput; } @Autowired public void setTargetHolder(TargetHolder targetHolder) { this.targetHolder = targetHolder; } @Autowired public void setDataFlowShell(DataFlowShell shell) { this.shell = shell; } @Autowired public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @Bean public RestTemplate restTemplate(Environment ev) { return DataFlowTemplate.getDefaultDataflowRestTemplate(); } // This is for unit testing public void setServerUri(String serverUri) { this.serverUri = serverUri; } @CliCommand(value = { "dataflow config server" }, help = "Configure the Spring Cloud Data Flow REST server to use") public String target( @CliOption(mandatory = false, key = { "", "uri" }, help = "the location of the Spring Cloud Data Flow REST endpoint", unspecifiedDefaultValue = Target.DEFAULT_TARGET) String targetUriString, @CliOption(mandatory = false, key = { "username" }, help = "the username for authenticated access to the Admin REST endpoint", unspecifiedDefaultValue = Target.DEFAULT_USERNAME) String targetUsername, @CliOption(mandatory = false, key = { "password" }, help = "the password for authenticated access to the Admin REST endpoint (valid only with a " + "username)", specifiedDefaultValue = Target.DEFAULT_SPECIFIED_PASSWORD, unspecifiedDefaultValue = Target.DEFAULT_UNSPECIFIED_PASSWORD) String targetPassword, @CliOption(mandatory = false, key = { "credentials-provider-command" }, help = "a command to run that outputs the HTTP credentials used for authentication", unspecifiedDefaultValue = Target.DEFAULT_CREDENTIALS_PROVIDER_COMMAND) String credentialsProviderCommand, @CliOption(mandatory = false, key = { "skip-ssl-validation" }, help = "accept any SSL certificate (even self-signed)", specifiedDefaultValue = Target.DEFAULT_SPECIFIED_SKIP_SSL_VALIDATION, unspecifiedDefaultValue = Target.DEFAULT_UNSPECIFIED_SKIP_SSL_VALIDATION) boolean skipSslValidation, @CliOption(mandatory = false, key = { "proxy-uri" }, help = "the uri of the proxy server", specifiedDefaultValue = Target.DEFAULT_SPECIFIED_PASSWORD, unspecifiedDefaultValue = Target.DEFAULT_UNSPECIFIED_PASSWORD) String proxyUri, @CliOption(mandatory = false, key = { "proxy-username" }, help = "the username for authenticated access to the secured proxy server", specifiedDefaultValue = Target.DEFAULT_SPECIFIED_PASSWORD, unspecifiedDefaultValue = Target.DEFAULT_UNSPECIFIED_PASSWORD) String proxyUsername, @CliOption(mandatory = false, key = { "proxy-password" }, help = "the password for authenticated access to the secured proxy server (valid only with a " + "username)", specifiedDefaultValue = Target.DEFAULT_SPECIFIED_PASSWORD, unspecifiedDefaultValue = Target.DEFAULT_UNSPECIFIED_PASSWORD) String proxyPassword) { if (StringUtils.isEmpty(credentialsProviderCommand) && !StringUtils.isEmpty(targetPassword) && StringUtils.isEmpty(targetUsername)) { return "A password may be specified only together with a username"; } try { this.targetHolder.setTarget(new Target(targetUriString, targetUsername, targetPassword, skipSslValidation)); final HttpClientConfigurer httpClientConfigurer = HttpClientConfigurer.create(this.targetHolder.getTarget().getTargetUri()) .skipTlsCertificateVerification(skipSslValidation); if (StringUtils.hasText(proxyUri)) { if (StringUtils.isEmpty(proxyPassword) && !StringUtils.isEmpty(proxyUsername)) { // read password from the command line proxyPassword = userInput.prompt("Proxy Server Password", "", false); } httpClientConfigurer.withProxyCredentials(URI.create(proxyUri), proxyUsername, proxyPassword); } this.restTemplate.setRequestFactory(httpClientConfigurer.buildClientHttpRequestFactory()); final SecurityInfoResource securityInfoResourceBeforeLogin = restTemplate .getForObject(targetUriString + "/security/info", SecurityInfoResource.class); boolean authenticationEnabled = false; if (securityInfoResourceBeforeLogin != null) { authenticationEnabled = securityInfoResourceBeforeLogin.isAuthenticationEnabled(); } if (StringUtils.isEmpty(credentialsProviderCommand) && StringUtils.isEmpty(targetUsername) && authenticationEnabled) { targetUsername = userInput.prompt("Username", "", true); } if (StringUtils.isEmpty(credentialsProviderCommand) && authenticationEnabled && StringUtils.isEmpty(targetPassword) && !StringUtils.isEmpty(targetUsername)) { targetPassword = userInput.prompt("Password", "", false); } if (StringUtils.hasText(credentialsProviderCommand) && authenticationEnabled) { this.targetHolder.getTarget().setTargetCredentials(new TargetCredentials(true)); final CheckableResource credentialsResource = new ProcessOutputResource(credentialsProviderCommand.split("\\s+")); httpClientConfigurer.addInterceptor(new ResourceBasedAuthorizationInterceptor(credentialsResource)); } if (authenticationEnabled && StringUtils.hasText(targetUsername) && StringUtils.hasText(targetPassword)) { httpClientConfigurer.basicAuthCredentials(targetUsername, targetPassword); } this.restTemplate.setRequestFactory(httpClientConfigurer.buildClientHttpRequestFactory()); this.shell.setDataFlowOperations( new DataFlowTemplate(targetHolder.getTarget().getTargetUri(), this.restTemplate)); this.targetHolder.getTarget() .setTargetResultMessage(String.format("Successfully targeted %s", targetUriString)); final SecurityInfoResource securityInfoResource = restTemplate .getForObject(targetUriString + "/security/info", SecurityInfoResource.class); if (securityInfoResource.isAuthenticated() && this.targetHolder.getTarget().getTargetCredentials() != null) { for (String roleAsString : securityInfoResource.getRoles()) { final RoleType shellRoleType = RoleType.fromKey(roleAsString); this.targetHolder.getTarget().getTargetCredentials().getRoles().add(shellRoleType); } } this.targetHolder.getTarget().setAuthenticated(securityInfoResource.isAuthenticated()); this.targetHolder.getTarget().setAuthenticationEnabled(securityInfoResource.isAuthenticationEnabled()); this.targetHolder.getTarget().setTargetResultMessage(String.format("Successfully targeted %s", targetUriString)); } catch (Exception e) { this.targetHolder.getTarget().setTargetException(e); this.shell.setDataFlowOperations(null); handleTargetException(this.targetHolder.getTarget()); } return (this.targetHolder.getTarget().getTargetResultMessage()); } @CliCommand(value = { "dataflow config info" }, help = "Show the Dataflow server being used") @SuppressWarnings("unchecked") public List<Object> info() { Target target = targetHolder.getTarget(); if (target.getTargetException() != null) { handleTargetException(target); throw new DataFlowServerException(this.targetHolder.getTarget().getTargetResultMessage()); } AboutResource about = this.shell.getDataFlowOperations().aboutOperation().get(); List<Object> result = new ArrayList<>(); int rowIndex = 0; List<Integer> rowsWithThinSeparators = new ArrayList<>(); TableModelBuilder<Object> modelBuilder = new TableModelBuilder<>(); modelBuilder.addRow().addValue("Target").addValue(target.getTargetUriAsString()); rowIndex++; if (target.getTargetResultMessage() != null) { modelBuilder.addRow().addValue("Result").addValue(target.getTargetResultMessage()); rowIndex++; } modelBuilder.addRow().addValue("Features").addValue(about.getFeatureInfo()); rowIndex++; Map<String, String> versions = new LinkedHashMap<>(); modelBuilder.addRow().addValue("Versions").addValue(versions); rowIndex++; versions.compute(about.getVersionInfo().getImplementation().getName(), (k, v) -> about.getVersionInfo().getImplementation().getVersion()); versions.compute(about.getVersionInfo().getCore().getName(), (k, v) -> about.getVersionInfo().getCore().getVersion()); versions.compute(about.getVersionInfo().getDashboard().getName(), (k, v) -> about.getVersionInfo().getDashboard().getVersion()); versions.compute(about.getVersionInfo().getShell().getName(), (k, v) -> about.getVersionInfo().getShell().getVersion()); SecurityInfo securityInfo = about.getSecurityInfo(); modelBuilder.addRow().addValue("Security").addValue(securityInfo); rowIndex++; if (securityInfo.isAuthenticated()) { modelBuilder.addRow().addValue("Roles").addValue(securityInfo.getRoles()); rowsWithThinSeparators.add(rowIndex++); } RuntimeEnvironmentDetails appDeployer = about.getRuntimeEnvironment().getAppDeployer(); List<RuntimeEnvironmentDetails> taskLaunchers = about.getRuntimeEnvironment().getTaskLaunchers(); String deployerColumnName = "Skipper Deployer"; modelBuilder.addRow().addValue(deployerColumnName).addValue(appDeployer); rowIndex++; if (!appDeployer.getPlatformSpecificInfo().isEmpty()) { modelBuilder.addRow().addValue("Platform Specific").addValue(appDeployer.getPlatformSpecificInfo()); rowsWithThinSeparators.add(rowIndex++); } for (RuntimeEnvironmentDetails taskLauncher : taskLaunchers) { modelBuilder.addRow().addValue("Task Launcher").addValue(taskLauncher); rowIndex++; if (!taskLauncher.getPlatformSpecificInfo().isEmpty()) { modelBuilder.addRow().addValue("Platform Specific").addValue(taskLauncher.getPlatformSpecificInfo()); rowsWithThinSeparators.add(rowIndex++); } } TableBuilder builder = new TableBuilder(modelBuilder.build()); builder.addOutlineBorder(BorderStyle.fancy_double) .paintBorder(BorderStyle.fancy_light, BorderSpecification.INNER).fromTopLeft().toBottomRight() .on(CellMatchers.table()).addAligner(SimpleHorizontalAligner.center).on(CellMatchers.table()) .addAligner(SimpleVerticalAligner.middle); Tables.configureKeyValueRendering(builder, ": "); builder.on(CellMatchers.ofType(FeatureInfo.class)).addFormatter(new DataFlowTables.BeanWrapperFormatter(": ")) .addAligner(new KeyValueHorizontalAligner(":")).addSizer(new KeyValueSizeConstraints(": ")) .addWrapper(new KeyValueTextWrapper(": ")); List<String> excludes = securityInfo.isAuthenticated() ? Arrays.asList("roles", "class") : Arrays.asList("roles", "class", "username"); builder.on(CellMatchers.ofType(SecurityInfo.class)) .addFormatter(new DataFlowTables.BeanWrapperFormatter(": ", null, excludes)) .addAligner(new KeyValueHorizontalAligner(":")).addSizer(new KeyValueSizeConstraints(": ")) .addWrapper(new KeyValueTextWrapper(": ")); builder.on(CellMatchers.ofType(List.class)) .addFormatter(value -> ((List<String>) value).toArray(new String[0])); builder.on(CellMatchers.ofType(RuntimeEnvironmentDetails.class)) .addFormatter(new DataFlowTables.BeanWrapperFormatter(": ", null, Arrays.asList("class", "platformSpecificInfo"))) .addAligner(new KeyValueHorizontalAligner(":")).addSizer(new KeyValueSizeConstraints(": ")) .addWrapper(new KeyValueTextWrapper(": ")); rowsWithThinSeparators.forEach(row -> builder.paintBorder(BorderStyle.fancy_light_quadruple_dash, BorderSpecification.TOP) .fromRowColumn(row, 0).toRowColumn(row + 1, builder.getModel().getColumnCount())); result.add(builder.build()); if (Target.TargetStatus.ERROR.equals(target.getStatus())) { StringWriter stringWriter = new StringWriter(); stringWriter.write("\nAn exception occurred during targeting:\n"); target.getTargetException().printStackTrace(new PrintWriter(stringWriter)); result.add(stringWriter.toString()); } return result; } private void handleTargetException(Target target) { Exception targetException = target.getTargetException(); Assert.isTrue(targetException != null, "TargetException must not be null"); if (targetException instanceof DataFlowServerException) { String message = String.format("Unable to parse server response: %s - at URI '%s'.", targetException.getMessage(), target.getTargetUriAsString()); if (logger.isDebugEnabled()) { logger.debug(message, targetException); } else { logger.warn(message); } this.targetHolder.getTarget().setTargetResultMessage(message); } else { if (targetException instanceof HttpClientErrorException && targetException.getMessage().startsWith("401")) { this.targetHolder.getTarget() .setTargetResultMessage(String.format( "Unable to access Data Flow Server" + " at '%s': '%s'. Unauthorized, did you forget to authenticate?", target.getTargetUriAsString(), targetException.toString())); } else { this.targetHolder.getTarget() .setTargetResultMessage(String.format("Unable to contact Data Flow " + "Server at '%s': '%s'.", target.getTargetUriAsString(), targetException.toString())); } } } public String triggerTarget() { return target( this.serverUri, this.userName, this.password, this.credentialsProviderCommand, this.skipSslValidation, this.proxyUri, this.proxyUsername, this.proxyPassword ); } /** * Will execute the targeting of the Data Flow server ONLY if the shell * is executing shell command passed directly from the console using * {@code --spring.shell.commandFile}. * * see also: https://github.com/spring-projects/spring-shell/issues/252 */ @Override public void onApplicationEvent(ApplicationReadyEvent event) { // Only invoke if the shell is executing in the same application context as the data flow server. if (!initialized && this.commandLine.getShellCommandsToExecute() != null) { triggerTarget(); } } /** * Will execute the targeting of the Data Flow server ONLY if the shell * is executing shell command passed directly from the console using * {@code --spring.shell.commandFile}. * * see also: https://github.com/spring-projects/spring-shell/issues/252 */ @Override public void afterPropertiesSet() throws Exception { if (this.commandLine.getShellCommandsToExecute() != null) { // Only invoke this lifecycle method if the shell is executing in stand-alone mode. if (applicationContext != null && !applicationContext.containsBean("streamDefinitionRepository")) { initialized = true; System.out.println(triggerTarget()); } } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
/** * 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.wss4j.dom.saml; import org.apache.wss4j.common.WSEncryptionPart; import org.apache.wss4j.common.saml.SamlAssertionWrapper; import org.apache.wss4j.dom.WSConstants; import org.apache.wss4j.dom.WSDataRef; import org.apache.wss4j.dom.WSSConfig; import org.apache.wss4j.dom.WSSecurityEngine; import org.apache.wss4j.dom.WSSecurityEngineResult; import org.apache.wss4j.dom.common.KeystoreCallbackHandler; import org.apache.wss4j.dom.common.SAML1CallbackHandler; import org.apache.wss4j.dom.common.SAML2CallbackHandler; import org.apache.wss4j.dom.common.SOAPUtil; import org.apache.wss4j.dom.common.SecurityTestUtil; import org.apache.wss4j.dom.handler.RequestData; import org.apache.wss4j.dom.handler.WSHandlerResult; import org.apache.wss4j.common.crypto.Crypto; import org.apache.wss4j.common.crypto.CryptoFactory; import org.apache.wss4j.common.crypto.Merlin; import org.apache.wss4j.common.saml.SAMLCallback; import org.apache.wss4j.common.saml.SAMLUtil; import org.apache.wss4j.common.saml.builder.SAML1Constants; import org.apache.wss4j.common.saml.builder.SAML2Constants; import org.apache.wss4j.common.util.Loader; import org.apache.wss4j.common.util.XMLUtils; import org.apache.wss4j.dom.message.WSSecEncrypt; import org.apache.wss4j.dom.message.WSSecHeader; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.io.InputStream; import java.security.KeyStore; import java.util.List; import javax.security.auth.callback.CallbackHandler; /** * Some tests for how SAML tokens are referenced. */ public class SamlReferenceTest extends org.junit.Assert { private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(SamlReferenceTest.class); private WSSecurityEngine secEngine = new WSSecurityEngine(); private CallbackHandler callbackHandler = new KeystoreCallbackHandler(); private Crypto crypto = CryptoFactory.getInstance("crypto.properties"); private Crypto trustCrypto = null; private Crypto issuerCrypto = null; private Crypto userCrypto = CryptoFactory.getInstance("wss40.properties"); @org.junit.AfterClass public static void cleanup() throws Exception { SecurityTestUtil.cleanup(); } public SamlReferenceTest() throws Exception { WSSConfig config = WSSConfig.getNewInstance(); secEngine.setWssConfig(config); // Load the issuer keystore issuerCrypto = new Merlin(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); ClassLoader loader = Loader.getClassLoader(SignedSamlTokenHOKTest.class); InputStream input = Merlin.loadInputStream(loader, "keys/wss40_server.jks"); keyStore.load(input, "security".toCharArray()); ((Merlin)issuerCrypto).setKeyStore(keyStore); // Load the server truststore trustCrypto = new Merlin(); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); input = Merlin.loadInputStream(loader, "keys/wss40CA.jks"); trustStore.load(input, "security".toCharArray()); ((Merlin)trustCrypto).setTrustStore(trustStore); } /** * Test that creates, sends and processes an signed SAML 1.1 sender-vouches assertion, * where the SecurityTokenReference that points to the SAML Assertion uses a KeyIdentifier, * and not a direct reference. */ @org.junit.Test @SuppressWarnings("unchecked") public void testSAML1SVKeyIdentifier() throws Exception { SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler(); callbackHandler.setStatement(SAML1CallbackHandler.Statement.AUTHN); callbackHandler.setConfirmationMethod(SAML1Constants.CONF_SENDER_VOUCHES); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); secHeader.insertSecurityHeader(); WSSecSignatureSAML wsSign = new WSSecSignatureSAML(); wsSign.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE); Document signedDoc = wsSign.build( doc, null, samlAssertion, crypto, "16c73ab6-b892-458f-abf5-2f875f74882e", "security", secHeader ); String outputString = XMLUtils.PrettyDocumentToString(signedDoc); if (LOG.isDebugEnabled()) { LOG.debug("Signed SAML message Key Identifier (sender vouches):"); LOG.debug(outputString); } assertTrue(outputString.contains(WSConstants.WSS_SAML_KI_VALUE_TYPE)); assertTrue(outputString.contains(WSConstants.WSS_SAML_TOKEN_TYPE)); WSHandlerResult results = verify(signedDoc, crypto, null); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_UNSIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertTrue(receivedSamlAssertion != null); // Test we processed a signature (SAML assertion + SOAP body) actionResult = results.getActionResults().get(WSConstants.SIGN).get(0); assertTrue(actionResult != null); assertFalse(actionResult.isEmpty()); final List<WSDataRef> refs = (List<WSDataRef>) actionResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS); assertTrue(refs.size() == 2); WSDataRef wsDataRef = refs.get(0); String xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Body", xpath); wsDataRef = refs.get(1); xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/saml1:Assertion", xpath); } /** * Test that creates, sends and processes an signed SAML 1.1 sender-vouches assertion, * where the SecurityTokenReference that points to the SAML Assertion uses a direct reference, * and not a KeyIdentifier. This method is not spec compliant and is included to make sure * we can process third-party Assertions referenced in this way. */ @org.junit.Test @SuppressWarnings("unchecked") public void testSAML1SVDirectReference() throws Exception { SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler(); callbackHandler.setStatement(SAML1CallbackHandler.Statement.AUTHN); callbackHandler.setConfirmationMethod(SAML1Constants.CONF_SENDER_VOUCHES); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); secHeader.insertSecurityHeader(); WSSecSignatureSAML wsSign = new WSSecSignatureSAML(); wsSign.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE); wsSign.setUseDirectReferenceToAssertion(true); Document signedDoc = wsSign.build( doc, null, samlAssertion, crypto, "16c73ab6-b892-458f-abf5-2f875f74882e", "security", secHeader ); String outputString = XMLUtils.PrettyDocumentToString(doc); if (LOG.isDebugEnabled()) { LOG.debug("Signed SAML message Direct Reference (sender vouches):"); LOG.debug(outputString); } assertTrue(outputString.contains(WSConstants.WSS_SAML_KI_VALUE_TYPE)); assertTrue(outputString.contains(WSConstants.WSS_SAML_TOKEN_TYPE)); WSHandlerResult results = verify(signedDoc, crypto, null); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_UNSIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertTrue(receivedSamlAssertion != null); // Test we processed a signature (SAML assertion + SOAP body) actionResult = results.getActionResults().get(WSConstants.SIGN).get(0); assertTrue(actionResult != null); assertFalse(actionResult.isEmpty()); final List<WSDataRef> refs = (List<WSDataRef>) actionResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS); assertTrue(refs.size() == 2); WSDataRef wsDataRef = refs.get(0); String xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Body", xpath); wsDataRef = refs.get(1); xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/saml1:Assertion", xpath); } /** * Test that creates, sends and processes an signed SAML 1.1 holder-of-key assertion, * where the SecurityTokenReference that points to the SAML Assertion uses a KeyIdentifier, * and not a direct reference. This tests that we can process a KeyIdentifier to a SAML * Assertion in the KeyInfo of a Signature. */ @org.junit.Test @SuppressWarnings("unchecked") public void testSAML1HOKKeyIdentifier() throws Exception { SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler(); callbackHandler.setStatement(SAML1CallbackHandler.Statement.AUTHN); callbackHandler.setConfirmationMethod(SAML1Constants.CONF_HOLDER_KEY); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); samlAssertion.signAssertion("wss40_server", "security", issuerCrypto, false); WSSecSignatureSAML wsSign = new WSSecSignatureSAML(); wsSign.setUserInfo("wss40", "security"); wsSign.setDigestAlgo("http://www.w3.org/2001/04/xmlenc#sha256"); wsSign.setSignatureAlgorithm("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); secHeader.insertSecurityHeader(); Document signedDoc = wsSign.build(doc, userCrypto, samlAssertion, null, null, null, secHeader); String outputString = XMLUtils.PrettyDocumentToString(doc); if (LOG.isDebugEnabled()) { LOG.debug("Signed SAML message Key Identifier (holder-of-key):"); LOG.debug(outputString); } assertTrue(outputString.contains(WSConstants.WSS_SAML_KI_VALUE_TYPE)); assertTrue(outputString.contains(WSConstants.WSS_SAML_TOKEN_TYPE)); WSHandlerResult results = verify(signedDoc, trustCrypto, null); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_SIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertTrue(receivedSamlAssertion != null); assertTrue(receivedSamlAssertion.isSigned()); // Test we processed a signature (SOAP body) actionResult = results.getActionResults().get(WSConstants.SIGN).get(0); assertTrue(actionResult != null); assertFalse(actionResult.isEmpty()); final List<WSDataRef> refs = (List<WSDataRef>) actionResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS); assertTrue(refs.size() == 1); WSDataRef wsDataRef = refs.get(0); String xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Body", xpath); } /** * Test that creates, sends and processes an signed SAML 1.1 holder-of-key assertion, * where the SecurityTokenReference that points to the SAML Assertion uses a direct reference, * and not a KeyIdentifier. This method is not spec compliant and is included to make sure * we can process third-party Assertions referenced in this way. This tests that we can * process a Direct Reference to a SAML Assertion in the KeyInfo of a Signature. */ @org.junit.Test @SuppressWarnings("unchecked") public void testSAML1HOKDirectReference() throws Exception { SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler(); callbackHandler.setStatement(SAML1CallbackHandler.Statement.AUTHN); callbackHandler.setConfirmationMethod(SAML1Constants.CONF_HOLDER_KEY); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); samlAssertion.signAssertion("wss40_server", "security", issuerCrypto, false); WSSecSignatureSAML wsSign = new WSSecSignatureSAML(); wsSign.setUserInfo("wss40", "security"); wsSign.setDigestAlgo("http://www.w3.org/2001/04/xmlenc#sha256"); wsSign.setSignatureAlgorithm("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"); wsSign.setUseDirectReferenceToAssertion(true); wsSign.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); secHeader.insertSecurityHeader(); Document signedDoc = wsSign.build(doc, userCrypto, samlAssertion, null, null, null, secHeader); String outputString = XMLUtils.PrettyDocumentToString(doc); if (LOG.isDebugEnabled()) { LOG.debug("Signed SAML message Direct Reference (holder-of-key):"); LOG.debug(outputString); } assertTrue(outputString.contains(WSConstants.WSS_SAML_KI_VALUE_TYPE)); assertTrue(outputString.contains(WSConstants.WSS_SAML_TOKEN_TYPE)); WSHandlerResult results = verify(signedDoc, trustCrypto, null); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_SIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertTrue(receivedSamlAssertion != null); assertTrue(receivedSamlAssertion.isSigned()); // Test we processed a signature (SOAP body) actionResult = results.getActionResults().get(WSConstants.SIGN).get(0); assertTrue(actionResult != null); assertFalse(actionResult.isEmpty()); final List<WSDataRef> refs = (List<WSDataRef>) actionResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS); assertTrue(refs.size() == 1); WSDataRef wsDataRef = refs.get(0); String xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Body", xpath); } /** * WS-Security Test Case for WSS-178 - "signature verification failure of signed saml token * due to "The Reference for URI (bst-saml-uri) has no XMLSignatureInput". * * The problem is that the signature is referring to a SecurityTokenReference via the * STRTransform, which in turn is referring to the SAML Assertion. The request is putting * the SAML Assertion below the SecurityTokenReference, and this is causing * SecurityTokenReference.getTokenElement to fail. */ @org.junit.Test public void testAssertionBelowSTR() throws Exception { Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); secHeader.insertSecurityHeader(); SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler(); callbackHandler.setStatement(SAML1CallbackHandler.Statement.ATTR); callbackHandler.setConfirmationMethod(SAML1Constants.CONF_SENDER_VOUCHES); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); Crypto crypto = CryptoFactory.getInstance("crypto.properties"); WSSecSignatureSAML wsSign = new WSSecSignatureSAML(); wsSign.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE); Document samlDoc = wsSign.build(doc, null, samlAssertion, crypto, "16c73ab6-b892-458f-abf5-2f875f74882e", "security", secHeader ); WSSecEncrypt builder = new WSSecEncrypt(); builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e"); builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE); Document encryptedDoc = builder.build(samlDoc, crypto, secHeader); // // Remove the assertion its place in the security header and then append it // org.w3c.dom.Element secHeaderElement = secHeader.getSecurityHeader(); org.w3c.dom.Node assertionNode = secHeaderElement.getElementsByTagNameNS(WSConstants.SAML_NS, "Assertion").item(0); secHeaderElement.removeChild(assertionNode); secHeaderElement.appendChild(assertionNode); String outputString = XMLUtils.PrettyDocumentToString(encryptedDoc); if (LOG.isDebugEnabled()) { LOG.debug("Encrypted message:"); LOG.debug(outputString); } assertTrue(outputString.contains(WSConstants.WSS_SAML_KI_VALUE_TYPE)); assertTrue(outputString.contains(WSConstants.WSS_SAML_TOKEN_TYPE)); verify(encryptedDoc, crypto, crypto); } /** * The body of the SOAP request is encrypted using a secret key, which is in turn encrypted * using the certificate embedded in the SAML assertion and referenced using a Key Identifier. * This tests that we can process a KeyIdentifier to a SAML Assertion in the KeyInfo of an * EncryptedKey. */ @org.junit.Test @SuppressWarnings("unchecked") public void testSAML1HOKEKKeyIdentifier() throws Exception { // Create a SAML assertion SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler(); callbackHandler.setStatement(SAML1CallbackHandler.Statement.AUTHN); callbackHandler.setConfirmationMethod(SAML1Constants.CONF_HOLDER_KEY); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); samlAssertion.signAssertion("wss40_server", "security", issuerCrypto, false); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); Node assertionNode = samlAssertion.toDOM(doc); secHeader.insertSecurityHeader(); secHeader.getSecurityHeader().appendChild(assertionNode); // Encrypt the SOAP body WSSecEncrypt builder = new WSSecEncrypt(); builder.setUserInfo("wss40"); builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES); builder.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); builder.setCustomEKTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); builder.setCustomEKTokenId(samlAssertion.getId()); builder.prepare(doc, userCrypto); WSEncryptionPart encP = new WSEncryptionPart( "add", "http://ws.apache.org/counter/counter_port_type", "Element" ); builder.getParts().add(encP); Element refElement = builder.encrypt(); builder.addInternalRefElement(refElement); builder.appendToHeader(secHeader); String outputString = XMLUtils.PrettyDocumentToString(doc); if (LOG.isDebugEnabled()) { LOG.debug("Encrypted SAML 1.1 message Key Identifier (holder-of-key):"); LOG.debug(outputString); } assertTrue(outputString.contains(WSConstants.WSS_SAML_KI_VALUE_TYPE)); assertTrue(outputString.contains(WSConstants.WSS_SAML_TOKEN_TYPE)); WSHandlerResult results = verify(doc, trustCrypto, userCrypto); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_SIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertTrue(receivedSamlAssertion != null); assertTrue(receivedSamlAssertion.isSigned()); // Test we processed an encrypted element actionResult = results.getActionResults().get(WSConstants.ENCR).get(0); assertTrue(actionResult != null); assertFalse(actionResult.isEmpty()); final List<WSDataRef> refs = (List<WSDataRef>) actionResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS); assertTrue(refs.size() == 1); WSDataRef wsDataRef = refs.get(0); String xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Body/add", xpath); } /** * The body of the SOAP request is encrypted using a secret key, which is in turn encrypted * using the certificate embedded in the SAML assertion and referenced using Direct * Reference. This method is not spec compliant and is included to make sure we can process * third-party Assertions referenced in this way. This tests that we can process a Direct * Reference to a SAML Assertion in the KeyInfo of an EncryptedKey. */ @org.junit.Test @SuppressWarnings("unchecked") public void testSAML1HOKEKDirectReference() throws Exception { // Create a SAML assertion SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler(); callbackHandler.setStatement(SAML1CallbackHandler.Statement.AUTHN); callbackHandler.setConfirmationMethod(SAML1Constants.CONF_HOLDER_KEY); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); samlAssertion.signAssertion("wss40_server", "security", issuerCrypto, false); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); Node assertionNode = samlAssertion.toDOM(doc); secHeader.insertSecurityHeader(); secHeader.getSecurityHeader().appendChild(assertionNode); // Encrypt the SOAP body WSSecEncrypt builder = new WSSecEncrypt(); builder.setUserInfo("wss40"); builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES); builder.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING); builder.setCustomEKTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); builder.setCustomEKTokenId(samlAssertion.getId()); builder.prepare(doc, userCrypto); WSEncryptionPart encP = new WSEncryptionPart( "add", "http://ws.apache.org/counter/counter_port_type", "Element" ); builder.getParts().add(encP); Element refElement = builder.encrypt(); builder.addInternalRefElement(refElement); builder.appendToHeader(secHeader); String outputString = XMLUtils.PrettyDocumentToString(doc); if (LOG.isDebugEnabled()) { LOG.debug("Encrypted SAML 1.1 message Direct Reference (holder-of-key):"); LOG.debug(outputString); } assertTrue(outputString.contains(WSConstants.WSS_SAML_KI_VALUE_TYPE)); assertTrue(outputString.contains(WSConstants.WSS_SAML_TOKEN_TYPE)); WSHandlerResult results = verify(doc, trustCrypto, userCrypto); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_SIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertTrue(receivedSamlAssertion != null); assertTrue(receivedSamlAssertion.isSigned()); // Test we processed an encrypted element actionResult = results.getActionResults().get(WSConstants.ENCR).get(0); assertTrue(actionResult != null); assertFalse(actionResult.isEmpty()); final List<WSDataRef> refs = (List<WSDataRef>) actionResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS); assertTrue(refs.size() == 1); WSDataRef wsDataRef = refs.get(0); String xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Body/add", xpath); } /** * Test that creates, sends and processes an signed SAML 2 sender-vouches assertion, * where the SecurityTokenReference that points to the SAML Assertion uses a KeyIdentifier, * and not a direct reference. */ @org.junit.Test @SuppressWarnings("unchecked") public void testSAML2SVKeyIdentifier() throws Exception { SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler(); callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN); callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); secHeader.insertSecurityHeader(); WSSecSignatureSAML wsSign = new WSSecSignatureSAML(); wsSign.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE); Document signedDoc = wsSign.build( doc, null, samlAssertion, crypto, "16c73ab6-b892-458f-abf5-2f875f74882e", "security", secHeader ); String outputString = XMLUtils.PrettyDocumentToString(signedDoc); if (LOG.isDebugEnabled()) { LOG.debug("Signed SAML2 message Key Identifier (sender vouches):"); LOG.debug(outputString); } assertTrue(outputString.contains(WSConstants.WSS_SAML2_KI_VALUE_TYPE)); assertTrue(outputString.contains(WSConstants.WSS_SAML2_TOKEN_TYPE)); WSHandlerResult results = verify(signedDoc, crypto, null); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_UNSIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertTrue(receivedSamlAssertion != null); // Test we processed a signature (SAML assertion + SOAP body) actionResult = results.getActionResults().get(WSConstants.SIGN).get(0); assertTrue(actionResult != null); assertFalse(actionResult.isEmpty()); final List<WSDataRef> refs = (List<WSDataRef>) actionResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS); assertTrue(refs.size() == 2); WSDataRef wsDataRef = refs.get(0); String xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Body", xpath); wsDataRef = refs.get(1); xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/saml2:Assertion", xpath); } /** * Test that creates, sends and processes an signed SAML 2 sender-vouches assertion, * where the SecurityTokenReference that points to the SAML Assertion uses a direct reference, * and not a KeyIdentifier. Unlike the SAML 1.1 case, this is spec-compliant. */ @org.junit.Test @SuppressWarnings("unchecked") public void testSAML2SVDirectReference() throws Exception { SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler(); callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN); callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); secHeader.insertSecurityHeader(); WSSecSignatureSAML wsSign = new WSSecSignatureSAML(); wsSign.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE); wsSign.setUseDirectReferenceToAssertion(true); Document signedDoc = wsSign.build( doc, null, samlAssertion, crypto, "16c73ab6-b892-458f-abf5-2f875f74882e", "security", secHeader ); String outputString = XMLUtils.PrettyDocumentToString(doc); if (LOG.isDebugEnabled()) { LOG.debug("Signed SAML2 message Direct Reference (sender vouches):"); LOG.debug(outputString); } assertFalse(outputString.contains(WSConstants.WSS_SAML2_KI_VALUE_TYPE)); assertTrue(outputString.contains(WSConstants.WSS_SAML2_TOKEN_TYPE)); WSHandlerResult results = verify(signedDoc, crypto, null); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_UNSIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertTrue(receivedSamlAssertion != null); // Test we processed a signature (SAML assertion + SOAP body) actionResult = results.getActionResults().get(WSConstants.SIGN).get(0); assertTrue(actionResult != null); assertFalse(actionResult.isEmpty()); final List<WSDataRef> refs = (List<WSDataRef>) actionResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS); assertTrue(refs.size() == 2); WSDataRef wsDataRef = refs.get(0); String xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Body", xpath); wsDataRef = refs.get(1); xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/saml2:Assertion", xpath); } /** * Test that creates, sends and processes an signed SAML 2 holder-of-key assertion, * where the SecurityTokenReference that points to the SAML Assertion uses a KeyIdentifier, * and not a direct reference. This tests that we can process a KeyIdentifier to a SAML * Assertion in the KeyInfo of a Signature. */ @org.junit.Test @SuppressWarnings("unchecked") public void testSAML2HOKKeyIdentifier() throws Exception { SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler(); callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN); callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); samlAssertion.signAssertion("wss40_server", "security", issuerCrypto, false); WSSecSignatureSAML wsSign = new WSSecSignatureSAML(); wsSign.setUserInfo("wss40", "security"); wsSign.setDigestAlgo("http://www.w3.org/2001/04/xmlenc#sha256"); wsSign.setSignatureAlgorithm("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); secHeader.insertSecurityHeader(); Document signedDoc = wsSign.build(doc, userCrypto, samlAssertion, null, null, null, secHeader); String outputString = XMLUtils.PrettyDocumentToString(doc); if (LOG.isDebugEnabled()) { LOG.debug("Signed SAML2 message Key Identifier (holder-of-key):"); LOG.debug(outputString); } assertTrue(outputString.contains(WSConstants.WSS_SAML2_KI_VALUE_TYPE)); assertTrue(outputString.contains(WSConstants.WSS_SAML2_TOKEN_TYPE)); WSHandlerResult results = verify(signedDoc, trustCrypto, null); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_SIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertTrue(receivedSamlAssertion != null); assertTrue(receivedSamlAssertion.isSigned()); // Test we processed a signature (SOAP body) actionResult = results.getActionResults().get(WSConstants.SIGN).get(0); assertTrue(actionResult != null); assertFalse(actionResult.isEmpty()); final List<WSDataRef> refs = (List<WSDataRef>) actionResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS); assertTrue(refs.size() == 1); WSDataRef wsDataRef = refs.get(0); String xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Body", xpath); } /** * Test that creates, sends and processes an signed SAML 2 holder-of-key assertion, * where the SecurityTokenReference that points to the SAML Assertion uses a direct reference, * and not a KeyIdentifier. Unlike the SAML 1.1 case, this is spec-compliant. This tests that * we can process a Direct Reference to a SAML Assertion in the KeyInfo of a Signature. */ @org.junit.Test @SuppressWarnings("unchecked") public void testSAML2HOKDirectReference() throws Exception { SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler(); callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN); callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); samlAssertion.signAssertion("wss40_server", "security", issuerCrypto, false); WSSecSignatureSAML wsSign = new WSSecSignatureSAML(); wsSign.setUserInfo("wss40", "security"); wsSign.setDigestAlgo("http://www.w3.org/2001/04/xmlenc#sha256"); wsSign.setSignatureAlgorithm("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"); wsSign.setUseDirectReferenceToAssertion(true); wsSign.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); secHeader.insertSecurityHeader(); Document signedDoc = wsSign.build(doc, userCrypto, samlAssertion, null, null, null, secHeader); String outputString = XMLUtils.PrettyDocumentToString(doc); if (LOG.isDebugEnabled()) { LOG.debug("Signed SAML2 message Direct Reference (holder-of-key):"); LOG.debug(outputString); } assertFalse(outputString.contains(WSConstants.WSS_SAML2_KI_VALUE_TYPE)); assertTrue(outputString.contains(WSConstants.WSS_SAML2_TOKEN_TYPE)); WSHandlerResult results = verify(signedDoc, trustCrypto, null); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_SIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertTrue(receivedSamlAssertion != null); assertTrue(receivedSamlAssertion.isSigned()); // Test we processed a signature (SOAP body) actionResult = results.getActionResults().get(WSConstants.SIGN).get(0); assertTrue(actionResult != null); assertFalse(actionResult.isEmpty()); final List<WSDataRef> refs = (List<WSDataRef>) actionResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS); assertTrue(refs.size() == 1); WSDataRef wsDataRef = refs.get(0); String xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Body", xpath); } /** * The body of the SOAP request is encrypted using a secret key, which is in turn encrypted * using the certificate embedded in the SAML assertion and referenced using a Key Identifier. * This tests that we can process a KeyIdentifier to a SAML Assertion in the KeyInfo of an * EncryptedKey. */ @org.junit.Test @SuppressWarnings("unchecked") public void testSAML2HOKEKKeyIdentifier() throws Exception { // Create a SAML assertion SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler(); callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN); callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); samlAssertion.signAssertion("wss40_server", "security", issuerCrypto, false); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); Node assertionNode = samlAssertion.toDOM(doc); secHeader.insertSecurityHeader(); secHeader.getSecurityHeader().appendChild(assertionNode); // Encrypt the SOAP body WSSecEncrypt builder = new WSSecEncrypt(); builder.setUserInfo("wss40"); builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES); builder.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); builder.setCustomEKTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE); builder.setCustomEKTokenId(samlAssertion.getId()); builder.prepare(doc, userCrypto); WSEncryptionPart encP = new WSEncryptionPart( "add", "http://ws.apache.org/counter/counter_port_type", "Element" ); builder.getParts().add(encP); Element refElement = builder.encrypt(); builder.addInternalRefElement(refElement); builder.appendToHeader(secHeader); String outputString = XMLUtils.PrettyDocumentToString(doc); if (LOG.isDebugEnabled()) { LOG.debug("Encrypted SAML 2 message Key Identifier (holder-of-key):"); LOG.debug(outputString); } assertTrue(outputString.contains(WSConstants.WSS_SAML2_KI_VALUE_TYPE)); assertTrue(outputString.contains(WSConstants.WSS_SAML2_TOKEN_TYPE)); WSHandlerResult results = verify(doc, trustCrypto, userCrypto); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_SIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertTrue(receivedSamlAssertion != null); assertTrue(receivedSamlAssertion.isSigned()); // Test we processed an encrypted element actionResult = results.getActionResults().get(WSConstants.ENCR).get(0); assertTrue(actionResult != null); assertFalse(actionResult.isEmpty()); final List<WSDataRef> refs = (List<WSDataRef>) actionResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS); assertTrue(refs.size() == 1); WSDataRef wsDataRef = refs.get(0); String xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Body/add", xpath); } /** * The body of the SOAP request is encrypted using a secret key, which is in turn encrypted * using the certificate embedded in the SAML assertion and referenced using Direct * Reference. Unlike the SAML 1.1 case, this is spec-compliant. This tests that we can process * a Direct Reference to a SAML Assertion in the KeyInfo of an EncryptedKey. */ @org.junit.Test @SuppressWarnings("unchecked") public void testSAML2HOKEKDirectReference() throws Exception { // Create a SAML assertion SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler(); callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN); callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); samlAssertion.signAssertion("wss40_server", "security", issuerCrypto, false); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); Node assertionNode = samlAssertion.toDOM(doc); secHeader.insertSecurityHeader(); secHeader.getSecurityHeader().appendChild(assertionNode); // Encrypt the SOAP body WSSecEncrypt builder = new WSSecEncrypt(); builder.setUserInfo("wss40"); builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES); builder.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING); builder.setCustomEKTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE); builder.setCustomEKTokenId(samlAssertion.getId()); builder.prepare(doc, userCrypto); WSEncryptionPart encP = new WSEncryptionPart( "add", "http://ws.apache.org/counter/counter_port_type", "Element" ); builder.getParts().add(encP); Element refElement = builder.encrypt(); builder.addInternalRefElement(refElement); builder.appendToHeader(secHeader); String outputString = XMLUtils.PrettyDocumentToString(doc); if (LOG.isDebugEnabled()) { LOG.debug("Encrypted SAML 2 message Direct Reference (holder-of-key):"); LOG.debug(outputString); } assertFalse(outputString.contains(WSConstants.WSS_SAML2_KI_VALUE_TYPE)); assertTrue(outputString.contains(WSConstants.WSS_SAML2_TOKEN_TYPE)); WSHandlerResult results = verify(doc, trustCrypto, userCrypto); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_SIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertTrue(receivedSamlAssertion != null); assertTrue(receivedSamlAssertion.isSigned()); // Test we processed an encrypted element actionResult = results.getActionResults().get(WSConstants.ENCR).get(0); assertTrue(actionResult != null); assertFalse(actionResult.isEmpty()); final List<WSDataRef> refs = (List<WSDataRef>) actionResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS); assertTrue(refs.size() == 1); WSDataRef wsDataRef = refs.get(0); String xpath = wsDataRef.getXpath(); assertEquals("/SOAP-ENV:Envelope/SOAP-ENV:Body/add", xpath); } /** * Verifies the soap envelope * * @param doc * @throws Exception Thrown when there is a problem in verification */ private WSHandlerResult verify( Document doc, Crypto verifyCrypto, Crypto decCrypto ) throws Exception { RequestData requestData = new RequestData(); requestData.setCallbackHandler(callbackHandler); requestData.setDecCrypto(decCrypto); requestData.setSigVerCrypto(verifyCrypto); requestData.setValidateSamlSubjectConfirmation(false); WSHandlerResult results = secEngine.processSecurityHeader(doc, requestData); String outputString = XMLUtils.PrettyDocumentToString(doc); assertTrue(outputString.indexOf("counter_port_type") > 0 ? true : false); return results; } }
/* * * * Copyright (C) 2015 yelo.red * * * * 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 red.yelo.utils; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.drawable.Drawable; import android.location.Location; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.provider.MediaStore; import android.support.v7.internal.view.menu.ActionMenuItemView; import android.support.v7.internal.widget.TintImageView; import android.support.v7.widget.Toolbar; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Base64; import android.util.DisplayMetrics; import android.view.Display; import android.view.View; import android.view.ViewGroup; import android.view.ViewPropertyAnimator; import android.view.ViewTreeObserver; import android.view.inputmethod.InputMethodManager; import android.widget.ActionMenuView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.amulyakhare.textdrawable.TextDrawable; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.Target; import com.bumptech.glide.request.target.ViewTarget; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.Phonenumber; import com.melnykov.fab.FloatingActionButton; import com.vinaysshenoy.okulus.OkulusImageView; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.HTTP; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.URLEncoder; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.ClosedChannelException; import java.nio.channels.FileChannel; import java.nio.channels.NonReadableChannelException; import java.nio.channels.NonWritableChannelException; import java.security.InvalidKeyException; import java.security.Key; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Locale; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import red.yelo.R; import red.yelo.YeloApplication; import red.yelo.analytics.MixpanelAnalytics; import red.yelo.data.DatabaseColumns; import red.yelo.utils.AppConstants.DeviceInfo; /** * Utility methods for yelo */ public class Utils { private static final String TAG = "Utils"; public static float density = 1; public static final int SCALE_FACTOR = 30; /** * Checks if the current thread is the main thread or not * * @return <code>true</code> if the current thread is the main/UI thread, <code>false</code> * otherwise */ public static boolean isMainThread() { return Looper.getMainLooper() == Looper.myLooper(); } /** * Makes an SHA1 Hash of the given string * * @param string The string to shash * @return The hashed string * @throws java.security.NoSuchAlgorithmException */ public static String sha1(final String string) throws NoSuchAlgorithmException { final MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); final byte[] data = digest.digest(string.getBytes()); return String.format("%0" + (data.length * 2) + "X", new BigInteger(1, data)); } /** * Registers the referral values in analytics */ public static void registerReferralValuesInAnalytics() { final String utmSource = SharedPreferenceHelper.getString(R.string.pref_utm_source, "Google Play"); final String utmCampaign = SharedPreferenceHelper.getString(R.string.pref_utm_campaign, "discovery"); final String utmMedium = SharedPreferenceHelper.getString(R.string.pref_utm_medium, "App Store"); final String utmContent = SharedPreferenceHelper.getString(R.string.pref_utm_content, "Store Listing"); final String utmTerm = SharedPreferenceHelper.getString(R.string.pref_utm_term, "Store Listing"); MixpanelAnalytics.getInstance().setReferralInfo(utmSource, utmCampaign, utmMedium, utmContent, utmTerm); } /** * Reads the network info from service and sets up the singleton * return typechanged flag */ public static boolean setupNetworkInfo(final Context context) { boolean mTypeChanged; final ConnectivityManager connManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo activeNetwork = connManager.getActiveNetworkInfo(); if (activeNetwork != null) { if (DeviceInfo.INSTANCE.getCurrentNetworkType() == activeNetwork.getType()) { mTypeChanged = false; } else { mTypeChanged = true; } DeviceInfo.INSTANCE.setNetworkConnected(activeNetwork .isConnectedOrConnecting()); DeviceInfo.INSTANCE.setCurrentNetworkType(activeNetwork.getType()); } else { DeviceInfo.INSTANCE.setNetworkConnected(false); DeviceInfo.INSTANCE .setCurrentNetworkType(ConnectivityManager.TYPE_DUMMY); } Logger.d(TAG, "Network State Updated Connected: %b Type: %d", DeviceInfo.INSTANCE.isNetworkConnected(), DeviceInfo.INSTANCE.getCurrentNetworkType()); return true; } public static boolean copyFile(final File src, final File dst) { boolean returnValue = true; FileChannel inChannel = null, outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dst).getChannel(); } catch (final FileNotFoundException fnfe) { Logger.d(TAG, "inChannel/outChannel FileNotFoundException"); fnfe.printStackTrace(); return false; } try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IllegalArgumentException iae) { Logger.d(TAG, "TransferTo IllegalArgumentException"); iae.printStackTrace(); returnValue = false; } catch (final NonReadableChannelException nrce) { Logger.d(TAG, "TransferTo NonReadableChannelException"); nrce.printStackTrace(); returnValue = false; } catch (final NonWritableChannelException nwce) { Logger.d(TAG, "TransferTo NonWritableChannelException"); nwce.printStackTrace(); returnValue = false; } catch (final ClosedByInterruptException cie) { Logger.d(TAG, "TransferTo ClosedByInterruptException"); cie.printStackTrace(); returnValue = false; } catch (final AsynchronousCloseException ace) { Logger.d(TAG, "TransferTo AsynchronousCloseException"); ace.printStackTrace(); returnValue = false; } catch (final ClosedChannelException cce) { Logger.d(TAG, "TransferTo ClosedChannelException"); cce.printStackTrace(); returnValue = false; } catch (final IOException ioe) { Logger.d(TAG, "TransferTo IOException"); ioe.printStackTrace(); returnValue = false; } finally { if (inChannel != null) { try { inChannel.close(); } catch (final IOException e) { e.printStackTrace(); } } if (outChannel != null) { try { outChannel.close(); } catch (final IOException e) { e.printStackTrace(); } } } return returnValue; } /** * Generate a user's name from the first name last name * * @param firstName * @param lastName * @return */ public static String makeUserFullName(String firstName, String lastName) { if (TextUtils.isEmpty(firstName)) { return ""; } final StringBuilder builder = new StringBuilder(firstName); if (!TextUtils.isEmpty(lastName)) { builder.append(" ").append(lastName); } return builder.toString(); } /** * Generates as chat ID which will be unique for a given sender/receiver pair * * @param receiverId The receiver of the chat * @param senderId The sender of the chat * @return The chat Id */ public static String generateChatId(final String receiverId, final String senderId) { /* * Method of generating the chat ID is simple. First we compare the two * ids and combine them in ascending order separate by a '#'. Then we * SHA1 the result to make the chat id */ String combined = null; if (receiverId.compareTo(senderId) < 0) { combined = String .format(Locale.US, AppConstants.CHAT_ID_FORMAT, receiverId, senderId); } else { combined = String .format(Locale.US, AppConstants.CHAT_ID_FORMAT, senderId, receiverId); } String hashed = null; try { hashed = Utils.sha1(combined); } catch (final NoSuchAlgorithmException e) { /* * Shouldn't happen sinch SHA-1 is standard, but in case it does use * the combined string directly since they are local chat IDs */ hashed = combined; } return hashed; } /** * Gets the distance between two Locations(in metres) * * @param start The start location * @param end The end location * @return The distance between two locations(in metres) */ public static float distanceBetween(final Location start, final Location end) { final float[] results = new float[1]; Location.distanceBetween(start.getLatitude(), start.getLongitude(), end .getLatitude(), end.getLongitude(), results); return results[0]; } /** * Gets the current epoch time. Is dependent on the device's H/W time. */ public static long getCurrentEpochTime() { return System.currentTimeMillis() / 1000; } /** * Converts a cursor to a bundle. Field datatypes will be maintained. Floats will be stored in * the Bundle as Doubles, and Integers will be stored as Longs due to Cursor limitationcs * * @param cursor The cursor to convert to a Bundle. This must be positioned to the row to be * read * @return The converted bundle */ public static Bundle cursorToBundle(Cursor cursor) { final int columnCount = cursor.getColumnCount(); final Bundle bundle = new Bundle(columnCount); for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { final String columnName = cursor.getColumnName(columnIndex); switch (cursor.getType(columnIndex)) { case Cursor.FIELD_TYPE_STRING: { bundle.putString(columnName, cursor.getString(columnIndex)); break; } case Cursor.FIELD_TYPE_BLOB: { bundle.putByteArray(columnName, cursor.getBlob(columnIndex)); break; } case Cursor.FIELD_TYPE_FLOAT: { bundle.putDouble(columnName, cursor.getDouble(columnIndex)); break; } case Cursor.FIELD_TYPE_INTEGER: { bundle.putLong(columnName, cursor.getLong(columnIndex)); break; } } } return bundle; } public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { return; } int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.AT_MOST); int totalHeight = 0; View view = null; for (int i = 0; i < listAdapter.getCount(); i++) { view = listAdapter.getView(i, view, listView); if (i == 0) { view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT)); } view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED); totalHeight += view.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); listView.requestLayout(); } /** * Creates an intent for sharing the app * * @param context * @return */ public static Intent createAppShareIntent(Context context, String message, String appDownloadLink) { final String messageShare = context.getString(R.string.share_message_format, message, appDownloadLink); return createShareIntent(context, messageShare); } /** * Creates an intent for sharing the app * * @param context * @return */ public static Intent createTagShareIntent(Context context, String tagName, String category, String appDownloadLink) { final String messageShare = context.getString(R.string.share_tag_message_format, tagName, category, appDownloadLink); return createShareIntentForTag(context, messageShare); } public static String getShareLink() { final StringBuilder shareLinkBuilder = new StringBuilder(384); shareLinkBuilder.append(AppConstants.PLAY_STORE_MARKET_LINK); String referrerValue = String.format(Locale.US, AppConstants.REFERRER_VALUE, AppConstants.POST_SHARE, AppConstants.APP_VIRALITY, AppConstants.ANDROID_APP, AppConstants.CHECK_THIS_OUT); final String shareToken = SharedPreferenceHelper.getString(R.string.pref_share_token); if (!TextUtils.isEmpty(shareToken)) { referrerValue = String.format(Locale.US, "%s&share_token=%s", referrerValue, shareToken); } String referrer; try { referrer = String.format(Locale.US, AppConstants.REFERRER_FORMAT, URLEncoder.encode(referrerValue, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); referrer = null; } if (!TextUtils.isEmpty(referrer)) { shareLinkBuilder.append('&').append(referrer); } return shareLinkBuilder.toString(); } public static String getShareLinkForTag() { final StringBuilder shareLinkBuilder = new StringBuilder(384); shareLinkBuilder.append(AppConstants.PLAY_STORE_MARKET_LINK); //String referrerValue = String.format(Locale.US, AppConstants.REFERRER_VALUE, AppConstants.POST_SHARE, AppConstants.APP_VIRALITY, AppConstants.ANDROID_APP, AppConstants.CHECK_THIS_OUT); String referrerValue = ""; final String shareToken = SharedPreferenceHelper.getString(R.string.pref_share_token); if (!TextUtils.isEmpty(shareToken)) { referrerValue = String.format(Locale.US, "%s", shareToken); } String referrer; try { referrer = String.format(Locale.US, AppConstants.REFERRER_FORMAT, URLEncoder.encode(referrerValue, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); referrer = null; } if (!TextUtils.isEmpty(referrer)) { shareLinkBuilder.append('&').append(referrer); } return shareLinkBuilder.toString(); } /** * Creates a share intent * * @param context * @param shareText The text to share * @return */ private static Intent createShareIntent(Context context, final String shareText) { final Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, context.getString(R.string.share_subject)); shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareText); shareIntent.setType("text/plain"); return shareIntent; } /** * Creates a share intent * * @param context * @param shareText The text to share * @return */ private static Intent createShareIntentForTag(Context context, final String shareText) { final Intent shareIntent = new Intent(Intent.ACTION_SEND); // try { shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, context.getString(R.string.share_tag_subject)); // PackageManager pm= context.getPackageManager(); // // PackageInfo info=pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA); // //Check if package exists or not. If not then code // //in catch block will be called // shareIntent.setPackage("com.whatsapp"); shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareText); shareIntent.setType("text/plain"); // } catch (PackageManager.NameNotFoundException e) { // Toast.makeText(context, "WhatsApp not Installed", Toast.LENGTH_SHORT) // .show(); // } return shareIntent; } /** * Splits a time interval into hours, minutes and seconds * * @param time The time interval to split(in seconds) * @return An array with capacity 3, with the different variables in each of the positions * <p/> * <ul> * <li>0 - Hours</li> * <li>1 - Minutes</li> * <li>2 - Seconds</li> * </ul> */ public static int[] getHoursMinsSecs(long time) { int hours = (int) time / 3600; int remainder = (int) time - hours * 3600; int mins = remainder / 60; remainder = remainder - mins * 60; int secs = remainder; return new int[]{hours, mins, secs}; } public static String getEmail(Context context) { AccountManager accountManager = AccountManager.get(context); Account account = getAccount(accountManager); if (account == null) { return null; } else { return account.name; } } private static Account getAccount(AccountManager accountManager) { Account[] accounts = accountManager.getAccountsByType("com.google"); Account account; if (accounts.length > 0) { account = accounts[0]; } else { account = null; } return account; } /** * Checks whether the given user id is the current user or not * * @param userId The user id to check * @return {@code true} if the user is the current user, {@code false} otherwise */ public static boolean isCurrentUser(final String userId) { final String currentUserId = AppConstants.UserInfo.INSTANCE.getId(); return !TextUtils.isEmpty(currentUserId) && currentUserId.equals(userId); } /** * Loads an image into the OkulusImageView * * @param context A reference to the context * @param imageView The ImageView to load the bitmap into * @param imageUrl The image url to load * @param avatarSize The size to scale the image to */ public static void loadCircularImage(Context context, OkulusImageView imageView, String imageUrl, AvatarBitmapTransformation.AvatarSize avatarSize) { Glide.with(context) .load(imageUrl) .asBitmap() .animate(R.anim.fade_in) .transform(AvatarBitmapTransformation.transformationFor(context, avatarSize)) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(imageView); } /** * Loads an image into the OkulusImageView * * @param context A reference to the context * @param imageView The ImageView to load the bitmap into * @param imageUrl The image url to load * @param avatarSize The size to scale the image to */ public static void loadCircularImageForEditProfile(final Context context, final OkulusImageView imageView, String imageUrl, AvatarBitmapTransformation.AvatarSize avatarSize, View view) { final ImageView addView = (ImageView) view.findViewById(R.id.gallery_ic); final TextView textView = (TextView) view.findViewById(R.id.add_image_text); imageView.setImageBitmap(null); Glide.with(context) .load(imageUrl) .asBitmap() .animate(R.anim.fade_in) .transform(AvatarBitmapTransformation.transformationFor(context, avatarSize)) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .listener(new RequestListener<String, Bitmap>() { @Override public boolean onException(Exception e, String model, Target<Bitmap> target, boolean isFirstResource) { addView.setVisibility(View.VISIBLE); textView.setVisibility(View.VISIBLE); imageView.setImageBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.light_grey_image)); return true; } @Override public boolean onResourceReady(Bitmap resource, String model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) { return false; } }) .into(imageView); } /** * Loads an image into the OkulusImageView * * @param context A reference to the context * @param imageView The ImageView to load the bitmap into * @param imageUrl The image url to load * @param avatarSize The size to scale the image to */ public static void loadCircularImage(Context context, OkulusImageView imageView, String imageUrl, AvatarBitmapTransformation.AvatarSize avatarSize, TextDrawable drawable) { Glide.with(context) .load(imageUrl) .asBitmap() .animate(R.anim.fade_in) .placeholder(drawable) .transform(AvatarBitmapTransformation.transformationFor(context, avatarSize)) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .error(drawable) .into(imageView); } /** * Loads an image into the ImageView * * @param context A reference to the context * @param imageView The ImageView to load the bitmap into * @param imageUrl The image url to load */ public static void loadImage(Context context, ImageView imageView, String imageUrl, TextDrawable drawable) { Glide.with(context) .load(imageUrl) .asBitmap() .animate(R.anim.fade_in) .placeholder(drawable) .centerCrop() .error(drawable) .into(imageView); } /** * Loads an image into the OkulusImageView * * @param context A reference to the context * @param imageView The ImageView to load the bitmap into * @param image The drawable to load * @param avatarSize The size to scale the image to */ public static void loadCircularImage(Context context, OkulusImageView imageView, Drawable image, AvatarBitmapTransformation.AvatarSize avatarSize) { Glide.with(context) .load(image) .asBitmap() .placeholder(R.drawable.ic_placeholder_profile) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .error(R.drawable.ic_placeholder_profile) .into(imageView); } /** * Loads an image into the OkulusImageView * * @param context A reference to the context * @param imageView The ImageView to load the bitmap into * @param imageResourceId The image resource to load * @param avatarSize The size to scale the image to */ public static void loadCircularImage(Context context, OkulusImageView imageView, int imageResourceId, AvatarBitmapTransformation.AvatarSize avatarSize) { Glide.with(context) .load(imageResourceId) .asBitmap() .transform(AvatarBitmapTransformation.transformationFor(context, avatarSize)) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(new ViewTarget<OkulusImageView, Bitmap>(imageView) { @Override public void onResourceReady(Bitmap resource, GlideAnimation anim) { OkulusImageView myView = this.view; myView.setImageBitmap(resource); // Set your resource on myView and/or start your animation here. } }); } /** * Sets the compound drawables for the TextViews * * @param textView The TextView to set compound drawables for * @param left The left drawable resource id * @param top The top drawable resource id * @param right The right drawable resource id * @param bottom The bottom drawable resource id */ public static void setCompoundDrawables(final TextView textView, final int left, final int top, final int right, final int bottom) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { textView.setCompoundDrawablesRelativeWithIntrinsicBounds(left, top, right, bottom); } else { textView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); } } /** * Sets the compound drawables for the TextViews * * @param textView The TextView to set compound drawables for * @param left The left drawable * @param top The top drawable * @param right The right drawable * @param bottom The bottom drawable */ public static void setCompoundDrawables(final TextView textView, final Drawable left, final Drawable top, final Drawable right, final Drawable bottom) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { textView.setCompoundDrawablesRelativeWithIntrinsicBounds(left, top, right, bottom); } else { textView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); } } /** * Checks whether a number is a valid phone number or not * * @param number The number to validate */ public static boolean isValidPhoneNumber(String number) { final PhoneNumberUtil util = PhoneNumberUtil.getInstance(); try { final Phonenumber.PhoneNumber phoneNumber = util.parse(number, getSimCountryCode()); //Using the | case is a quick hack to check validity of numbers which are returned wrongly as PhoneNumberUtil as invalid(fix for India) return (util.isValidNumber(phoneNumber)) | (String.valueOf(phoneNumber.getNationalNumber()).length() == 10); } catch (NumberParseException e) { return false; } } public static String getSimCountryCode() { TelephonyManager manager = (TelephonyManager) (YeloApplication.getStaticContext().getSystemService(Context.TELEPHONY_SERVICE)); return manager.getSimCountryIso().toUpperCase(); } public static String decrypt(String key, String encrypted) { try { encrypted.trim(); Key k = new SecretKeySpec(key.getBytes(), "SHA256"); Cipher c = Cipher.getInstance("AES"); c.init(Cipher.DECRYPT_MODE, k); byte[] decodedValue = Base64.decode(encrypted, Base64.DEFAULT); byte[] decValue = c.doFinal(decodedValue); String decryptedValue = new String(decValue); return decryptedValue; } catch (IllegalBlockSizeException ex) { ex.printStackTrace(); } catch (BadPaddingException ex) { ex.printStackTrace(); } catch (InvalidKeyException ex) { ex.printStackTrace(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } catch (NoSuchPaddingException ex) { ex.printStackTrace(); } return null; } public static Intent getPickImageIntent(final Context context) { Intent intent = new Intent(); if (Build.VERSION.SDK_INT < 19) { intent = new Intent(); intent.setAction(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); } else { intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); } return Intent.createChooser(intent, "Select picture"); } public static void setNetworkAvailableWithPing() { // ask fo message '0' (not connected) or '1' (connected) on 'handler' // the answer must be send before before within the 'timeout' (in milliseconds) final int timeout = 4000; final Handler h = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what != 1) { // code if not connected DeviceInfo.INSTANCE.setNetworkConnected(false); Logger.d("Handle", "PING Failed"); } else { // code if connected DeviceInfo.INSTANCE.setNetworkConnected(true); if (DeviceInfo.INSTANCE.isNetworkConnected()) { //YeloApplication.startChatService(); } Logger.d("Handle", "PING Success"); } } }; new Thread() { private boolean responded = false; @Override public void run() { // set 'responded' to TRUE if is able to connect with google mobile (responds fast) new Thread() { @Override public void run() { HttpGet requestForTest = new HttpGet("http://m.google.com"); try { new DefaultHttpClient().execute(requestForTest); // can last... responded = true; } catch (Exception e) { } } }.start(); try { int waited = 0; while (!responded && (waited < timeout)) { sleep(100); if (!responded) { waited += 100; } } } catch (InterruptedException e) { } // do nothing finally { if (!responded) { h.sendEmptyMessage(0); } else { h.sendEmptyMessage(1); } } } }.start(); } public static int dp(float value) { return (int) Math.ceil(density * value); } public static void hideKeyboard(View view) { if (view == null) { return; } InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); if (!imm.isActive()) { return; } imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } public static void hideShowViewByScale(final View view, final int icon) { ViewPropertyAnimator propertyAnimator = view.animate().setStartDelay(SCALE_FACTOR) .scaleX(0).scaleY(0); propertyAnimator.setDuration(300); propertyAnimator.start(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { ((FloatingActionButton) view).setImageResource(icon); showViewByScale(view); } }, 300); } public static void showViewByScale(View view) { ViewPropertyAnimator propertyAnimator = view.animate().setStartDelay(SCALE_FACTOR) .scaleX(1).scaleY(1); propertyAnimator.setDuration(300); propertyAnimator.start(); } public static void openWhatsappContact(String number, Context context) { Uri uri = Uri.parse("smsto:" + "+91" + number); Intent i = new Intent(Intent.ACTION_SENDTO, uri); i.setPackage("com.whatsapp"); context.startActivity(Intent.createChooser(i, "")); // Intent whatsapp = new Intent(Intent.ACTION_VIEW, Uri.parse("content://com.android.contacts/data/" + number+"@s.whatsapp.net")); // //i.setPackage("com.whatsapp"); // context.startActivity(whatsapp); } public static float convertDpToPixel(float dp, Context context) { Resources resources = context.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); float px = dp * (metrics.densityDpi / 160f); return px; } /** * This method converts device specific pixels to density independent pixels. * * @param px A value in px (pixels) unit. Which we need to convert into db * @param context Context to get resources and device specific display metrics * @return A float value to represent dp equivalent to px value */ public static float convertPixelsToDp(float px, Context context) { Resources resources = context.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); float dp = px / (metrics.densityDpi / 160f); return dp; } /** * Use this method to colorize toolbar icons to the desired target color * * @param toolbarView toolbar view being colored * @param toolbarIconsColor the target color of toolbar icons * @param activity reference to activity needed to register observers */ public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) { final PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.MULTIPLY); for (int i = 0; i < toolbarView.getChildCount(); i++) { final View v = toolbarView.getChildAt(i); //Step 1 : Changing the color of back button (or open drawer button). if (v instanceof ImageButton) { //Action Bar back button ((ImageButton) v).getDrawable().setColorFilter(colorFilter); } if (v instanceof ActionMenuView) { for (int j = 0; j < ((ActionMenuView) v).getChildCount(); j++) { //Step 2: Changing the color of any ActionMenuViews - icons that //are not back button, nor text, nor overflow menu icon. final View innerView = ((ActionMenuView) v).getChildAt(j); if (innerView instanceof ActionMenuItemView) { int drawablesCount = ((ActionMenuItemView) innerView).getCompoundDrawables().length; for (int k = 0; k < drawablesCount; k++) { if (((ActionMenuItemView) innerView).getCompoundDrawables()[k] != null) { final int finalK = k; //Important to set the color filter in seperate thread, //by adding it to the message queue //Won't work otherwise. innerView.post(new Runnable() { @Override public void run() { ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter); } }); } } } } } //Step 3: Changing the color of title and subtitle. toolbarView.setTitleTextColor(toolbarIconsColor); toolbarView.setSubtitleTextColor(toolbarIconsColor); //Step 4: Changing the color of the Overflow Menu icon. setOverflowButtonColor(activity, colorFilter); } } /** * It's important to set overflowDescription atribute in styles, so we can grab the reference * to the overflow icon. Check: res/values/styles.xml * * @param activity * @param colorFilter */ private static void setOverflowButtonColor(final Activity activity, final PorterDuffColorFilter colorFilter) { final String overflowDescription = activity.getString(R.string.abc_action_menu_overflow_description); final ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); final ViewTreeObserver viewTreeObserver = decorView.getViewTreeObserver(); viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { final ArrayList<View> outViews = new ArrayList<View>(); decorView.findViewsWithText(outViews, overflowDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION); if (outViews.isEmpty()) { return; } TintImageView overflow = (TintImageView) outViews.get(0); overflow.setColorFilter(colorFilter); removeOnGlobalLayoutListener(decorView, this); } }); } private static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { v.getViewTreeObserver().removeGlobalOnLayoutListener(listener); } else { v.getViewTreeObserver().removeOnGlobalLayoutListener(listener); } } /** * This function returns the formatted time. * * @param timeEpoch * @param cursor * @param context * @return the formatted time */ public static String getElapsedTimeFormat(long timeEpoch, Cursor cursor, Context context) { long timeElapsed = Utils.getCurrentEpochTime() - timeEpoch; int[] timeValues = Utils.getHoursMinsSecs(timeElapsed); final int hours = timeValues[0]; final int minutes = timeValues[1]; final int seconds = timeValues[2]; final int days = hours / 24; final int weeks = days / 7; if (hours < 1) { if (minutes < 1) { if (seconds < 10) { return context.getString(R.string.just_now); } else { return context.getString(R.string.seconds_ago, seconds); } } else { return context.getString(R.string.minutes_ago, minutes); } } else if (hours < 23) { return context.getString(R.string.hours_ago, hours); } else if (hours > 23 && hours < 167) { return context.getString(R.string.days_ago, days); } else if (weeks > 0) { return context.getString(R.string.weeks_ago, weeks); } else { return cursor.getString(cursor .getColumnIndex(DatabaseColumns.TIMESTAMP_HUMAN)); } } /** * Function used to get the storage directory of the app based on memory card present or not. * * @param context Context of the current activity. */ public static File getStorageDirectory(Context context) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) return context.getExternalFilesDir(null); else return context.getFilesDir(); } public static void hideViewByScale(final View view) { ViewPropertyAnimator propertyAnimator = view.animate().setStartDelay(SCALE_FACTOR) .scaleX(0).scaleY(0); propertyAnimator.setDuration(300); propertyAnimator.start(); } public static void shareImageAsBitmap(Bitmap shareImage,Context context,String message){ Bitmap icon = shareImage; Intent share = new Intent(Intent.ACTION_SEND); share.setType("image/jpeg"); ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, "title"); values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); OutputStream outstream; if(icon!=null) { try { outstream = context.getContentResolver().openOutputStream(uri); icon.compress(Bitmap.CompressFormat.PNG, 100, outstream); outstream.close(); } catch (Exception e) { System.err.println(e.toString()); } share.putExtra(Intent.EXTRA_STREAM, uri); share.putExtra(Intent.EXTRA_TEXT, message); context.startActivity(Intent.createChooser(share, "Share Image")); } } public static void setDefaultLocation(Context context){ String[] cityNames = context.getResources().getStringArray(R.array.city_names); String[] cityLatitudes = context.getResources().getStringArray(R.array.city_latitudes); String[] cityLongitudes = context.getResources().getStringArray(R.array.city_longitudes); SharedPreferenceHelper.set(R.string.pref_latitude, cityLatitudes[0]); SharedPreferenceHelper.set(R.string.pref_longitude, cityLongitudes[0]); SharedPreferenceHelper.set(R.string.pref_location, cityNames[0]); SharedPreferenceHelper.set(R.string.pref_city, cityNames[0]); } }
/* * 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.jackrabbit.oak.core; import java.util.Iterator; import java.util.Random; import org.apache.jackrabbit.mk.api.MicroKernel; import org.apache.jackrabbit.mk.core.MicroKernelImpl; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.Tree; import org.apache.jackrabbit.oak.commons.PathUtils; import org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.Rebase; import org.apache.jackrabbit.oak.kernel.KernelNodeStore; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.AddNode; import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.CopyNode; import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.MoveNode; import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.RemoveNode; import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.RemoveProperty; import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.Save; import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.SetProperty; import static org.junit.Assert.assertEquals; /** * Fuzz test running random sequences of operations on {@link Tree}. * Run with -DKernelRootFuzzIT-seed=42 to set a specific seed (i.e. 42); */ public class RootImplFuzzIT { static final Logger log = LoggerFactory.getLogger(RootImplFuzzIT.class); private static final int OP_COUNT = 5000; private static final int SEED = Integer.getInteger( RootImplFuzzIT.class.getSimpleName() + "-seed", new Random().nextInt()); private static final Random random = new Random(SEED); private KernelNodeStore store1; private RootImpl root1; private KernelNodeStore store2; private RootImpl root2; private int counter; @Before public void setup() { counter = 0; MicroKernel mk1 = new MicroKernelImpl("./target/mk1/" + random.nextInt()); store1 = new KernelNodeStore(mk1); mk1.commit("", "+\"/root\":{}", mk1.getHeadRevision(), ""); root1 = new RootImpl(store1); MicroKernel mk2 = new MicroKernelImpl("./target/mk2/" + random.nextInt()); store2 = new KernelNodeStore(mk2); mk2.commit("", "+\"/root\":{}", mk2.getHeadRevision(), ""); root2 = new RootImpl(store2); } @Test public void fuzzTest() throws Exception { for (Operation op : operations(OP_COUNT)) { log.info("{}", op); op.apply(root1); op.apply(root2); checkEqual(root1.getTree("/"), root2.getTree("/")); root1.commit(); checkEqual(root1.getTree("/"), root2.getTree("/")); if (op instanceof Save) { root2.commit(); assertEquals("seed " + SEED, store1.getRoot(), store2.getRoot()); } } } private Iterable<Operation> operations(final int count) { return new Iterable<Operation>() { int k = count; @Override public Iterator<Operation> iterator() { return new Iterator<Operation>() { @Override public boolean hasNext() { return k-- > 0; } @Override public Operation next() { return createOperation(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } abstract static class Operation { abstract void apply(RootImpl root); static class AddNode extends Operation { private final String parentPath; private final String name; AddNode(String parentPath, String name) { this.parentPath = parentPath; this.name = name; } @Override void apply(RootImpl root) { root.getTree(parentPath).addChild(name); } @Override public String toString() { return '+' + PathUtils.concat(parentPath, name) + ":{}"; } } static class RemoveNode extends Operation { private final String path; RemoveNode(String path) { this.path = path; } @Override void apply(RootImpl root) { String parentPath = PathUtils.getParentPath(path); String name = PathUtils.getName(path); root.getTree(parentPath).getChild(name).remove(); } @Override public String toString() { return '-' + path; } } static class MoveNode extends Operation { private final String source; private final String destination; MoveNode(String source, String destParent, String destName) { this.source = source; destination = PathUtils.concat(destParent, destName); } @Override void apply(RootImpl root) { root.move(source, destination); } @Override public String toString() { return '>' + source + ':' + destination; } } static class CopyNode extends Operation { private final String source; private final String destination; CopyNode(String source, String destParent, String destName) { this.source = source; destination = PathUtils.concat(destParent, destName); } @Override void apply(RootImpl root) { root.copy(source, destination); } @Override public String toString() { return '*' + source + ':' + destination; } } static class SetProperty extends Operation { private final String parentPath; private final String propertyName; private final String propertyValue; SetProperty(String parentPath, String name, String value) { this.parentPath = parentPath; this.propertyName = name; this.propertyValue = value; } @Override void apply(RootImpl root) { root.getTree(parentPath).setProperty(propertyName, propertyValue); } @Override public String toString() { return '^' + PathUtils.concat(parentPath, propertyName) + ':' + propertyValue; } } static class RemoveProperty extends Operation { private final String parentPath; private final String name; RemoveProperty(String parentPath, String name) { this.parentPath = parentPath; this.name = name; } @Override void apply(RootImpl root) { root.getTree(parentPath).removeProperty(name); } @Override public String toString() { return '^' + PathUtils.concat(parentPath, name) + ":null"; } } static class Save extends Operation { @Override void apply(RootImpl root) { // empty } @Override public String toString() { return "save"; } } static class Rebase extends Operation { @Override void apply(RootImpl root) { root.rebase(); } @Override public String toString() { return "rebase"; } } } private Operation createOperation() { Operation op; do { switch (random.nextInt(11)) { case 0: case 1: case 2: op = createAddNode(); break; case 3: op = createRemoveNode(); break; case 4: op = createMoveNode(); break; case 5: // Too many copy ops make the test way slow op = random.nextInt(10) == 0 ? createCopyNode() : null; break; case 6: op = createAddProperty(); break; case 7: op = createSetProperty(); break; case 8: op = createRemoveProperty(); break; case 9: op = new Save(); break; case 10: op = new Rebase(); break; default: throw new IllegalStateException(); } } while (op == null); return op; } private Operation createAddNode() { String parentPath = chooseNodePath(); String name = createNodeName(); return new AddNode(parentPath, name); } private Operation createRemoveNode() { String path = chooseNodePath(); return "/root".equals(path) ? null : new RemoveNode(path); } private Operation createMoveNode() { String source = chooseNodePath(); String destParent = chooseNodePath(); String destName = createNodeName(); return "/root".equals(source) || destParent.startsWith(source) ? null : new MoveNode(source, destParent, destName); } private Operation createCopyNode() { String source = chooseNodePath(); String destParent = chooseNodePath(); String destName = createNodeName(); return "/root".equals(source) ? null : new CopyNode(source, destParent, destName); } private Operation createAddProperty() { String parent = chooseNodePath(); String name = createPropertyName(); String value = createValue(); return new SetProperty(parent, name, value); } private Operation createSetProperty() { String path = choosePropertyPath(); if (path == null) { return null; } String value = createValue(); return new SetProperty(PathUtils.getParentPath(path), PathUtils.getName(path), value); } private Operation createRemoveProperty() { String path = choosePropertyPath(); if (path == null) { return null; } return new RemoveProperty(PathUtils.getParentPath(path), PathUtils.getName(path)); } private String createNodeName() { return "N" + counter++; } private String createPropertyName() { return "P" + counter++; } private String chooseNodePath() { String path = "/root"; String next; while ((next = chooseNode(path)) != null) { path = next; } return path; } private String choosePropertyPath() { return chooseProperty(chooseNodePath()); } private String chooseNode(String parentPath) { Tree state = root1.getTree(parentPath); int k = random.nextInt((int) (state.getChildrenCount() + 1)); int c = 0; for (Tree child : state.getChildren()) { if (c++ == k) { return PathUtils.concat(parentPath, child.getName()); } } return null; } private String chooseProperty(String parentPath) { Tree state = root1.getTree(parentPath); int k = random.nextInt((int) (state.getPropertyCount() + 1)); int c = 0; for (PropertyState entry : state.getProperties()) { if (c++ == k) { return PathUtils.concat(parentPath, entry.getName()); } } return null; } private String createValue() { return ("V" + counter++); } private static void checkEqual(Tree tree1, Tree tree2) { String message = tree1.getPath() + "!=" + tree2.getPath() + " (seed " + SEED + ')'; assertEquals(message, tree1.getPath(), tree2.getPath()); assertEquals(message, tree1.getChildrenCount(), tree2.getChildrenCount()); assertEquals(message, tree1.getPropertyCount(), tree2.getPropertyCount()); for (PropertyState property1 : tree1.getProperties()) { PropertyState property2 = tree2.getProperty(property1.getName()); assertEquals(message, property1, property2); } for (Tree child1 : tree1.getChildren()) { checkEqual(child1, tree2.getChild(child1.getName())); } } }
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.events; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.toImmutableList; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Comparator.comparing; import com.google.common.collect.ImmutableClassToInstanceMap; import com.google.devtools.build.lib.util.io.FileOutErr; import com.google.devtools.build.lib.vfs.PathFragment; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Function; import java.util.stream.Stream; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import net.starlark.java.eval.StarlarkThread; import net.starlark.java.syntax.Location; import net.starlark.java.syntax.SyntaxError; /** * A situation encountered by the build system that's worth reporting. * * <p>An event specifies an {@link EventKind}, a message, and (optionally) additional properties. * * <p>Although this is serializable, use caution if {@link Class}es with the same name and different * classloaders are expected to be found in the same event's properties. Common class object * serialization techniques ignore classloaders, so duplicate entry keys may be deserialized, * violating assumptions. */ @Immutable @CheckReturnValue public final class Event implements Serializable { private final EventKind kind; /** * This field has type {@link String} or {@link byte[]}. * * <p>If this field is a byte array then it contains the UTF-8-encoded bytes of a message. This * optimization avoids converting back and forth between strings and bytes. */ private final Object message; /** * This map's entries are ordered by {@link Class#getName}. * * <p>That is not a total ordering because of classloaders. The order of entries whose key names * are equal is not deterministic. */ private final ImmutableClassToInstanceMap<Object> properties; private int hashCode; private Event(EventKind kind, Object message, ImmutableClassToInstanceMap<Object> properties) { this.kind = checkNotNull(kind); this.message = checkNotNull(message); this.properties = checkNotNull(properties); } public EventKind getKind() { return kind; } public String getMessage() { return message instanceof String ? (String) message : new String((byte[]) message, UTF_8); } /** * Returns this event's message as a {@link byte[]}. If this event was instantiated using a {@link * String}, the returned byte array is encoded using {@link * java.nio.charset.StandardCharsets#UTF_8}. */ public byte[] getMessageBytes() { return message instanceof byte[] ? (byte[]) message : ((String) message).getBytes(UTF_8); } /** Returns the property value associated with {@code type} if any, and {@code null} otherwise. */ @Nullable public <T> T getProperty(Class<T> type) { return properties.getInstance(type); } /** * Returns an {@link Event} instance that has the same type, message, and properties as the event * this is called on, and additionally associates {@code propertyValue} (if non-{@code null}) with * {@code type}. * * <p>If the event this is called on already has a property associated with {@code type} and * {@code propertyValue} is non-{@code null}, the returned event will have {@code propertyValue} * associated with it instead. If {@code propertyValue} is non-{@code null}, the returned event * will have no property associated with {@code type}. * * <p>If the event this is called on has no property associated with {@code type}, and {@code * propertyValue} is {@code null}, then this returns that event (it does not create a new {@link * Event} instance). * * <p>In any case, the event this is called on does not change. */ // This implementation would be inefficient if #withProperty is called repeatedly because it may // copy and sort the key collection. In practice we expect it to be called a small number of times // per event (e.g. fewer than 5; usually 0). // // If that changes then consider an Event.Builder strategy instead. public <T> Event withProperty(Class<T> type, @Nullable T propertyValue) { Iterable<Class<?>> orderedKeys; boolean containsKey = properties.containsKey(type); if (!containsKey && propertyValue != null) { orderedKeys = Stream.concat(properties.keySet().stream(), Stream.of(type)) .sorted(comparing(Class::getName)) .collect(toImmutableList()); } else if (containsKey) { orderedKeys = properties.keySet(); } else { // !containsKey and propertyValue is null, so there's nothing to change. return this; } ImmutableClassToInstanceMap.Builder<Object> newProperties = new ImmutableClassToInstanceMap.Builder<>(); for (Class<?> key : orderedKeys) { if (key.equals(type)) { if (propertyValue != null) { newProperties.put(type, propertyValue); } } else { addToBuilder(newProperties, key); } } return new Event(kind, message, newProperties.build()); } /** * This type-parameterized method solves a problem where a {@code properties.getInstance(key)} * expression would have type {@link Object} when {@code key} is a wildcard-parameterized {@link * Class}. That {@link Object}-typed expression would then fail to type check in a {@code * builder.put(key, properties.getInstance(key))} statement. */ private <T> void addToBuilder(ImmutableClassToInstanceMap.Builder<Object> builder, Class<T> key) { builder.put(key, checkNotNull(properties.getInstance(key))); } /** * Like {@link #withProperty(Class, Object)}, with {@code type.equals(String.class)}. * * <p>Additionally, if the event this is called on already has a {@link String} property with * value {@code tag}, or if {@code tag} is {@code null} and the event has no {@link String} * property, then this returns that event (it does not create a new {@link Event} instance). */ public Event withTag(@Nullable String tag) { if (Objects.equals(tag, getProperty(String.class))) { return this; } return withProperty(String.class, tag); } /** Like {@link #withProperty(Class, Object)}, with {@code type.equals(FileOutErr.class)}. */ public Event withStdoutStderr(FileOutErr outErr) { return withProperty(FileOutErr.class, outErr); } /** * Returns the {@link String} property, if any, asssociated with the event. When non-null, this * value typically describes some property of the action that generated the event. */ // TODO(mschaller): change code which relies on this to rely on a more structured value, using // types less prone to interference. @Nullable public String getTag() { return getProperty(String.class); } /** Indicates if a {@link FileOutErr} property is associated with this event. */ public boolean hasStdoutStderr() { return getProperty(FileOutErr.class) != null; } /** * Gets the path to the stdout associated with this event (which the caller must not access), or * null if there is no such path. */ @Nullable public PathFragment getStdOutPathFragment() { FileOutErr outErr = getProperty(FileOutErr.class); return outErr == null ? null : outErr.getOutputPathFragment(); } /** Gets the size of the stdout associated with this event without reading it. */ public long getStdOutSize() throws IOException { FileOutErr outErr = getProperty(FileOutErr.class); return outErr == null ? 0 : outErr.outSize(); } /** Returns the stdout bytes associated with this event if any, and {@code null} otherwise. */ @Nullable public byte[] getStdOut() { FileOutErr outErr = getProperty(FileOutErr.class); if (outErr == null) { return null; } return outErr.outAsBytes(); } /** * Gets the path to the stderr associated with this event (which the caller must not access), or * null if there is no such path. */ @Nullable public PathFragment getStdErrPathFragment() { FileOutErr outErr = getProperty(FileOutErr.class); return outErr == null ? null : outErr.getErrorPathFragment(); } /** Gets the size of the stderr associated with this event without reading it. */ public long getStdErrSize() throws IOException { FileOutErr outErr = getProperty(FileOutErr.class); return outErr == null ? 0 : outErr.errSize(); } /** Returns the stderr bytes associated with this event if any, and {@code null} otherwise. */ @Nullable public byte[] getStdErr() { FileOutErr outErr = getProperty(FileOutErr.class); if (outErr == null) { return null; } return outErr.errAsBytes(); } /** * Returns the location of this event, if any. Returns null iff the event wasn't associated with * any particular location, for example, a progress message. */ @Nullable public Location getLocation() { return getProperty(Location.class); } /** Returns the event formatted as {@code "ERROR foo.bzl:1:2: oops"}. */ @Override public String toString() { Location location = getLocation(); // TODO(adonovan): <no location> is just noise. return kind + " " + (location != null ? location.toString() : "<no location>") + ": " + getMessage(); } @Override public int hashCode() { // We defer the computation of hashCode until it is needed to avoid the overhead of computing it // and then never using it. In particular, we use Event for streaming stdout and stderr, which // are both large and the hashCode is never used. // // This uses the same construction as String.hashCode. We don't lock, so reads and writes to the // field can race. However, integer reads and writes are atomic, and this code guarantees that // all writes have the same value, so the memory location can only be either 0 or the final // value. Note that a reader could see the final value on the first read and 0 on the second // read, so we must take care to only read the field once. int h = hashCode; if (h == 0) { h = Objects.hash( kind, message instanceof String ? message : Arrays.hashCode((byte[]) message), properties); hashCode = h; } return h; } @Override public boolean equals(Object other) { if (other == this) { return true; } if (other == null || !other.getClass().equals(getClass())) { return false; } Event that = (Event) other; return Objects.equals(this.kind, that.kind) && this.message.getClass().equals(that.message.getClass()) && (this.message instanceof String ? Objects.equals(this.message, that.message) : Arrays.equals((byte[]) this.message, (byte[]) that.message)) && Objects.equals(this.properties, that.properties); } /** Constructs an event with the provided {@link EventKind} and {@link String} message. */ public static Event of(EventKind kind, String message) { return new Event(kind, message, ImmutableClassToInstanceMap.of()); } /** * Constructs an event with the provided {@link EventKind}, {@link String} message, and single * property value. * * <p>See {@link #withProperty(Class, Object)} if more than one property value is desired. */ public static <T> Event of( EventKind kind, String message, Class<T> propertyType, T propertyValue) { return new Event(kind, message, ImmutableClassToInstanceMap.of(propertyType, propertyValue)); } /** Constructs an event with the provided {@link EventKind} and {@link byte[]} message. */ public static Event of(EventKind kind, byte[] messageBytes) { return new Event(kind, messageBytes, ImmutableClassToInstanceMap.of()); } /** * Constructs an event with the provided {@link EventKind}, {@link byte[]} message, and single * property value. * * <p>See {@link #withProperty(Class, Object)} if more than one property value is desired. */ public static <T> Event of( EventKind kind, byte[] messageBytes, Class<T> propertyType, T propertyValue) { return new Event( kind, messageBytes, ImmutableClassToInstanceMap.of(propertyType, propertyValue)); } /** * Constructs an event with the provided {@link EventKind} and {@link String} message, with an * optional {@link Location}. */ public static Event of(EventKind kind, @Nullable Location location, String message) { return location == null ? of(kind, message) : of(kind, message, Location.class, location); } /** * Constructs an event with a {@code byte[]} array instead of a {@link String} for its message. * * <p>The bytes must be decodable as UTF-8 text. */ public static Event of(EventKind kind, @Nullable Location location, byte[] messageBytes) { return location == null ? of(kind, messageBytes) : of(kind, messageBytes, Location.class, location); } /** Constructs an event with kind {@link EventKind#FATAL}. */ public static Event fatal(String message) { return of(EventKind.FATAL, message); } /** Constructs an event with kind {@link EventKind#ERROR}, with an optional {@link Location}. */ public static Event error(@Nullable Location location, String message) { return location == null ? of(EventKind.ERROR, message) : of(EventKind.ERROR, message, Location.class, location); } /** Constructs an event with kind {@link EventKind#ERROR}. */ public static Event error(String message) { return of(EventKind.ERROR, message); } /** Constructs an event with kind {@link EventKind#WARNING}, with an optional {@link Location}. */ public static Event warn(@Nullable Location location, String message) { return location == null ? of(EventKind.WARNING, message) : of(EventKind.WARNING, message, Location.class, location); } /** Constructs an event with kind {@link EventKind#WARNING}. */ public static Event warn(String message) { return of(EventKind.WARNING, message); } /** Constructs an event with kind {@link EventKind#INFO}, with an optional {@link Location}. */ public static Event info(@Nullable Location location, String message) { return location == null ? of(EventKind.INFO, message) : of(EventKind.INFO, message, Location.class, location); } /** Constructs an event with kind {@link EventKind#INFO}. */ public static Event info(String message) { return of(EventKind.INFO, message); } /** * Constructs an event with kind {@link EventKind#PROGRESS}, with an optional {@link Location}. */ public static Event progress(@Nullable Location location, String message) { return location == null ? of(EventKind.PROGRESS, message) : of(EventKind.PROGRESS, message, Location.class, location); } /** Constructs an event with kind {@link EventKind#PROGRESS}. */ public static Event progress(String message) { return of(EventKind.PROGRESS, message); } /** Constructs an event with kind {@link EventKind#DEBUG}, with an optional {@link Location}. */ public static Event debug(@Nullable Location location, String message) { return location == null ? of(EventKind.DEBUG, message) : of(EventKind.DEBUG, message, Location.class, location); } /** Constructs an event with kind {@link EventKind#DEBUG}. */ public static Event debug(String message) { return of(EventKind.DEBUG, message); } /** Replays a sequence of events on {@code handler}. */ public static void replayEventsOn(EventHandler handler, Iterable<Event> events) { for (Event event : events) { handler.handle(event); } } /** Converts a list of {@link SyntaxError}s to events and replays them on {@code handler}. */ public static void replayEventsOn(EventHandler handler, List<SyntaxError> errors) { for (SyntaxError error : errors) { handler.handle(Event.error(error.location(), error.message())); } } /** * Converts a list of {@link SyntaxError}s to events, each with a specified property, and replays * them on {@code handler}. */ public static <T> void replayEventsOn( EventHandler handler, List<SyntaxError> errors, Class<T> propertyType, Function<SyntaxError, T> toProperty) { for (SyntaxError error : errors) { handler.handle( Event.error(error.location(), error.message()) .withProperty(propertyType, toProperty.apply(error))); } } /** * Returns a {@link StarlarkThread.PrintHandler} that sends {@link EventKind#DEBUG} events to the * provided {@link EventHandler}. */ public static StarlarkThread.PrintHandler makeDebugPrintHandler(EventHandler h) { return (thread, msg) -> h.handle(Event.debug(thread.getCallerLocation(), msg)); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache.binary; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.cache.Cache; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.binary.BinaryObject; import org.apache.ignite.binary.BinaryObjectBuilder; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cache.CachePeekMode; import org.apache.ignite.cluster.ClusterGroup; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.binary.BinaryMarshaller; import org.apache.ignite.internal.managers.discovery.DiscoveryCustomMessage; import org.apache.ignite.internal.util.IgniteUtils; import org.apache.ignite.internal.util.typedef.G; import org.apache.ignite.lang.IgniteCallable; import org.apache.ignite.resources.IgniteInstanceResource; import org.apache.ignite.spi.discovery.DiscoverySpiCustomMessage; import org.apache.ignite.spi.discovery.DiscoverySpiListener; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.GridTestUtils.DiscoveryHook; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.jetbrains.annotations.Nullable; import org.junit.Test; import static org.apache.ignite.testframework.GridTestUtils.runAsync; import static org.junit.Assert.assertArrayEquals; /** * */ public class BinaryMetadataUpdatesFlowTest extends GridCommonAbstractTest { /** */ private static final String SEQ_NUM_FLD = "f0"; /** */ private volatile DiscoveryHook discoveryHook; /** */ private static final int UPDATES_COUNT = 1_000; /** */ private static final int RESTART_DELAY = 1_000; /** */ private static final int GRID_CNT = 5; /** */ private static final String BINARY_TYPE_NAME = "TestBinaryType"; /** */ private static final int BINARY_TYPE_ID = 708045005; /** */ private final Queue<BinaryUpdateDescription> updatesQueue = new ConcurrentLinkedQueue<>(); /** */ private final List<BinaryUpdateDescription> updatesList = new ArrayList<>(UPDATES_COUNT); /** */ private final CountDownLatch startLatch = new CountDownLatch(1); /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { for (int i = 0; i < UPDATES_COUNT; i++) { FieldType fType = null; Object fVal = null; switch (i % 4) { case 0: fType = FieldType.NUMBER; fVal = getNumberFieldVal(); break; case 1: fType = FieldType.STRING; fVal = getStringFieldVal(); break; case 2: fType = FieldType.ARRAY; fVal = getArrayFieldVal(); break; case 3: fType = FieldType.OBJECT; fVal = new Object(); } BinaryUpdateDescription desc = new BinaryUpdateDescription(i, "f" + (i + 1), fType, fVal); updatesQueue.add(desc); updatesList.add(desc); } } /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); cfg.setPeerClassLoadingEnabled(false); if (discoveryHook != null) { TcpDiscoverySpi discoSpi = new TcpDiscoverySpi() { @Override public void setListener(@Nullable DiscoverySpiListener lsnr) { super.setListener(GridTestUtils.DiscoverySpiListenerWrapper.wrap(lsnr, discoveryHook)); } }; cfg.setDiscoverySpi(discoSpi); cfg.setMetricsUpdateFrequency(1000); } ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(sharedStaticIpFinder); cfg.setMarshaller(new BinaryMarshaller()); cfg.setClientMode("client".equals(gridName) || getTestIgniteInstanceIndex(gridName) >= GRID_CNT); CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME); ccfg.setCacheMode(CacheMode.REPLICATED); cfg.setCacheConfiguration(ccfg); return cfg; } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { super.afterTest(); stopAllGrids(); } /** * Starts computation job. * * @param idx Grid index on which computation job should start. * @param restartIdx The index of the node to be restarted. * @param workersCntr The current number of computation threads. */ private void startComputation(int idx, AtomicInteger restartIdx, AtomicInteger workersCntr) { Ignite ignite = grid(idx); ClusterGroup cg = ignite.cluster().forLocal(); ignite.compute(cg).callAsync(new BinaryObjectAdder(startLatch, idx, updatesQueue, restartIdx, workersCntr)); } /** * @throws Exception If failed. */ @Test public void testFlowNoConflicts() throws Exception { startGridsMultiThreaded(GRID_CNT); doTestFlowNoConflicts(); awaitPartitionMapExchange(); Ignite randomNode = G.allGrids().get(0); IgniteCache<Object, Object> cache = randomNode.cache(DEFAULT_CACHE_NAME); int cacheEntries = cache.size(CachePeekMode.PRIMARY); assertTrue("Cache cannot contain more entries than were put in it;", cacheEntries <= UPDATES_COUNT); assertEquals("There are less than expected entries, data loss occurred;", UPDATES_COUNT, cacheEntries); validateCache(randomNode); } /** * @throws Exception If failed. */ @Test public void testFlowNoConflictsWithClients() throws Exception { startGridsMultiThreaded(GRID_CNT); if (!tcpDiscovery()) return; discoveryHook = new DiscoveryHook() { @Override public void handleDiscoveryMessage(DiscoverySpiCustomMessage msg) { DiscoveryCustomMessage customMsg = msg == null ? null : (DiscoveryCustomMessage) IgniteUtils.field(msg, "delegate"); if (customMsg instanceof MetadataUpdateProposedMessage) { if (((MetadataUpdateProposedMessage) customMsg).typeId() == BINARY_TYPE_ID) GridTestUtils.setFieldValue(customMsg, "typeId", 1); } else if (customMsg instanceof MetadataUpdateAcceptedMessage) { if (((MetadataUpdateAcceptedMessage) customMsg).typeId() == BINARY_TYPE_ID) GridTestUtils.setFieldValue(customMsg, "typeId", 1); } } }; Ignite deafClient = startGrid(GRID_CNT); discoveryHook = null; Ignite regClient = startGrid(GRID_CNT + 1); doTestFlowNoConflicts(); awaitPartitionMapExchange(); validateCache(deafClient); validateCache(regClient); } /** * Validates that all updates are readable on the specified node. * * @param ignite Ignite instance. */ private void validateCache(Ignite ignite) { String name = ignite.name(); for (Cache.Entry entry : ignite.cache(DEFAULT_CACHE_NAME).withKeepBinary()) { BinaryObject binObj = (BinaryObject)entry.getValue(); Integer idx = binObj.field(SEQ_NUM_FLD); BinaryUpdateDescription desc = updatesList.get(idx - 1); Object val = binObj.field(desc.fieldName); String errMsg = "Field " + desc.fieldName + " has unexpeted value (index=" + idx + ", node=" + name + ")"; if (desc.fieldType == FieldType.OBJECT) assertTrue(errMsg, val instanceof BinaryObject); else if (desc.fieldType == FieldType.ARRAY) assertArrayEquals(errMsg, (byte[])desc.val, (byte[])val); else assertEquals(errMsg, desc.val, binObj.field(desc.fieldName)); } } /** * @throws Exception If failed. */ private void doTestFlowNoConflicts() throws Exception { final AtomicBoolean stopFlag = new AtomicBoolean(); final AtomicInteger restartIdx = new AtomicInteger(-1); final AtomicInteger workersCntr = new AtomicInteger(0); try { for (int i = 0; i < GRID_CNT; i++) startComputation(i, restartIdx, workersCntr); IgniteInternalFuture fut = GridTestUtils.runAsync(new NodeRestarter(stopFlag, restartIdx, workersCntr), "worker"); startLatch.countDown(); fut.get(); GridTestUtils.waitForCondition(() -> workersCntr.get() == 0, 5_000); } finally { stopFlag.set(true); } } /** * @throws Exception If failed. */ @Test public void testConcurrentMetadataUpdates() throws Exception { startGrid(0); final Ignite client = startGrid(getConfiguration("client")); final IgniteCache<Integer, Object> cache = client.cache(DEFAULT_CACHE_NAME).withKeepBinary(); int threadsNum = 10; final int updatesNum = 2000; List<IgniteInternalFuture> futs = new ArrayList<>(); for (int i = 0; i < threadsNum; i++) { final int threadId = i; IgniteInternalFuture fut = runAsync(new Runnable() { @Override public void run() { try { for (int j = 0; j < updatesNum; j++) { BinaryObjectBuilder bob = client.binary().builder(BINARY_TYPE_NAME); bob.setField("field" + j, threadId); cache.put(threadId, bob.build()); } } catch (Exception e) { e.printStackTrace(); } } }, "updater-" + i); futs.add(fut); } for (IgniteInternalFuture fut : futs) fut.get(); } /** * Instruction for node to perform <b>add new binary object</b> action on cache in <b>keepBinary</b> mode. * * Instruction includes id the object should be added under, new field to add to binary schema * and {@link FieldType type} of the field. */ private static final class BinaryUpdateDescription { /** */ private int itemId; /** */ private String fieldName; /** */ private FieldType fieldType; /** */ private Object val; /** * @param itemId Item id. * @param fieldName Field name. * @param fieldType Field type. * @param val Field value. */ private BinaryUpdateDescription(int itemId, String fieldName, FieldType fieldType, Object val) { this.itemId = itemId; this.fieldName = fieldName; this.fieldType = fieldType; this.val = val; } } /** * */ private enum FieldType { /** */ NUMBER, /** */ STRING, /** */ ARRAY, /** */ OBJECT } /** * Generates random number to use when creating binary object with field of numeric {@link FieldType type}. */ private static int getNumberFieldVal() { return ThreadLocalRandom.current().nextInt(100); } /** * Generates random string to use when creating binary object with field of string {@link FieldType type}. */ private static String getStringFieldVal() { return "str" + (100 + ThreadLocalRandom.current().nextInt(9)); } /** * Generates random array to use when creating binary object with field of array {@link FieldType type}. */ private static byte[] getArrayFieldVal() { byte[] res = new byte[3]; ThreadLocalRandom.current().nextBytes(res); return res; } /** * @param builder Builder. * @param desc Descriptor with parameters of BinaryObject to build. * @return BinaryObject built by provided description */ private static BinaryObject newBinaryObject(BinaryObjectBuilder builder, BinaryUpdateDescription desc) { builder.setField(SEQ_NUM_FLD, desc.itemId + 1); builder.setField(desc.fieldName, desc.val); return builder.build(); } /** * Compute job executed on each node in cluster which constantly adds new entries to ignite cache * according to {@link BinaryUpdateDescription descriptions} it reads from shared queue. */ private static final class BinaryObjectAdder implements IgniteCallable<Object> { /** */ private final CountDownLatch startLatch; /** */ private final int idx; /** */ private final Queue<BinaryUpdateDescription> updatesQueue; /** */ private final AtomicInteger restartIdx; /** */ private final AtomicInteger workersCntr; /** */ @IgniteInstanceResource private Ignite ignite; /** * @param startLatch Startup latch. * @param idx Ignite instance index. * @param updatesQueue Updates queue. * @param restartIdx The index of the node to be restarted. * @param workersCntr The number of active computation threads. */ BinaryObjectAdder( CountDownLatch startLatch, int idx, Queue<BinaryUpdateDescription> updatesQueue, AtomicInteger restartIdx, AtomicInteger workersCntr ) { this.startLatch = startLatch; this.idx = idx; this.updatesQueue = updatesQueue; this.restartIdx = restartIdx; this.workersCntr = workersCntr; } /** {@inheritDoc} */ @Override public Object call() throws Exception { startLatch.await(); IgniteCache<Object, Object> cache = ignite.cache(DEFAULT_CACHE_NAME).withKeepBinary(); workersCntr.incrementAndGet(); try { while (!updatesQueue.isEmpty()) { BinaryUpdateDescription desc = updatesQueue.poll(); if (desc == null) break; BinaryObjectBuilder builder = ignite.binary().builder(BINARY_TYPE_NAME); BinaryObject bo = newBinaryObject(builder, desc); cache.put(desc.itemId, bo); if (restartIdx.get() == idx) break; } } finally { workersCntr.decrementAndGet(); if (restartIdx.get() == idx) restartIdx.set(-1); } return null; } } /** * Restarts random server node and computation job. */ private final class NodeRestarter implements Runnable { /** Stop thread flag. */ private final AtomicBoolean stopFlag; /** The index of the node to be restarted. */ private final AtomicInteger restartIdx; /** The current number of computation threads. */ private final AtomicInteger workersCntr; /** * @param stopFlag Stop thread flag. * @param restartIdx The index of the node to be restarted. * @param workersCntr The current number of computation threads. */ NodeRestarter(AtomicBoolean stopFlag, AtomicInteger restartIdx, AtomicInteger workersCntr) { this.stopFlag = stopFlag; this.restartIdx = restartIdx; this.workersCntr = workersCntr; } /** {@inheritDoc} */ @Override public void run() { try { startLatch.await(); while (!shouldStop()) { int idx = ThreadLocalRandom.current().nextInt(5); restartIdx.set(idx); while (restartIdx.get() != -1) { if (shouldStop()) return; Thread.sleep(10); } stopGrid(idx); if (shouldStop()) return; startGrid(idx); startComputation(idx, restartIdx, workersCntr); Thread.sleep(RESTART_DELAY); } } catch (Exception ignore) { // No-op. } } /** */ private boolean shouldStop() { return updatesQueue.isEmpty() || stopFlag.get() || Thread.currentThread().isInterrupted(); } } }
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.oauth2.validators; import org.apache.commons.dbcp.BasicDataSource; import org.apache.oltu.oauth2.as.issuer.OAuthIssuer; import org.mockito.Mock; import org.mockito.Mockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.common.testng.WithAxisConfiguration; import org.wso2.carbon.identity.common.testng.WithCarbonHome; import org.wso2.carbon.identity.core.persistence.JDBCPersistenceManager; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.cache.AppInfoCache; import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; import org.wso2.carbon.identity.oauth.dao.OAuthAppDO; import org.wso2.carbon.identity.oauth.internal.OAuthComponentServiceHolder; import org.wso2.carbon.identity.oauth.tokenprocessor.PlainTextPersistenceProcessor; import org.wso2.carbon.identity.oauth2.dao.TokenMgtDAO; import org.wso2.carbon.identity.oauth2.dto.OAuth2ClientApplicationDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; import org.wso2.carbon.identity.oauth2.internal.OAuth2ServiceComponentHolder; import org.wso2.carbon.identity.oauth2.model.AccessTokenDO; import org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer; import org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer; import org.wso2.carbon.identity.oauth2.token.OauthTokenIssuerImpl; import org.wso2.carbon.identity.oauth2.util.OAuth2Util; import org.wso2.carbon.identity.openidconnect.util.TestUtils; import org.wso2.carbon.user.api.RealmConfiguration; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; import java.sql.Connection; import java.sql.Timestamp; import java.util.HashMap; import java.util.Map; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; import static org.testng.Assert.assertNotNull; @WithCarbonHome @WithAxisConfiguration @PowerMockIgnore({"javax.xml.*", "org.xml.sax.*", "org.w3c.dom.*"}) @PrepareForTest({OAuthServerConfiguration.class, JDBCPersistenceManager.class, IdentityDatabaseUtil.class, RealmService.class}) public class TokenValidationHandlerTest extends PowerMockTestCase { private String[] scopeArraySorted = new String[]{"scope1", "scope2", "scope3"}; private String clientId = "dummyClientId"; private String authorizationCode = "testAuthorizationCode"; private String tokenType = "testTokenType"; private AuthenticatedUser authzUser; private Timestamp issuedTime; private Timestamp refreshTokenIssuedTime; private long validityPeriodInMillis; private long refreshTokenValidityPeriodInMillis; private TokenMgtDAO tokenMgtDAO; private static final String DEFAULT_TOKEN_TYPE = "Default"; private static final String JWT_TOKEN_TYPE = "JWT"; private static final String DB_NAME = "jdbc/WSO2IdentityDB"; private static final String H2_SCRIPT_NAME = "token.sql"; private Connection conn = null; @Mock private OAuth2TokenValidator tokenValidator; @Mock private OAuthIssuer oAuthIssuer; @Mock protected OAuthServerConfiguration oAuthServerConfiguration; @Mock private RealmService realmService; @Mock private TenantManager tenantManager; @Mock private RealmConfiguration realmConfiguration; private TokenValidationHandler tokenValidationHandler; @BeforeMethod public void setUp() { authzUser = new AuthenticatedUser(); tokenMgtDAO = new TokenMgtDAO(); issuedTime = new Timestamp(System.currentTimeMillis()); refreshTokenIssuedTime = new Timestamp(System.currentTimeMillis()); validityPeriodInMillis = 3600000L; refreshTokenValidityPeriodInMillis = 3600000L; tokenValidationHandler = TokenValidationHandler.getInstance(); tokenValidationHandler.addTokenValidator("test", tokenValidator); } @Test public void testGetInstance() throws Exception { assertNotNull(tokenValidationHandler); } @Test public void testValidate() throws Exception { OAuth2TokenValidationResponseDTO responseDTO = tokenValidationHandler .validate(new OAuth2TokenValidationRequestDTO()); assertNotNull(responseDTO); } /** * This data provider is added to enable affected test cases to be tested in both * where the IDP_ID column is available and not available in the relevant tables. */ @DataProvider(name = "IdpIDColumnAvailabilityDataProvider") public Object[][] idpIDColumnAvailabilityDataProvider() { return new Object[][]{ {true}, {false} }; } @Test(dataProvider = "IdpIDColumnAvailabilityDataProvider") public void testFindOAuthConsumerIfTokenIsValid(boolean isIDPIdColumnEnabled) throws Exception { OAuth2ServiceComponentHolder.setIDPIdColumnEnabled(isIDPIdColumnEnabled); mockRequiredObjects(); OAuth2TokenValidationRequestDTO oAuth2TokenValidationRequestDTO = new OAuth2TokenValidationRequestDTO(); OAuth2TokenValidationRequestDTO.OAuth2AccessToken oAuth2AccessToken = oAuth2TokenValidationRequestDTO.new OAuth2AccessToken(); oAuth2AccessToken.setIdentifier("testIdentifier"); oAuth2AccessToken.setTokenType("bearer"); oAuth2TokenValidationRequestDTO.setAccessToken(oAuth2AccessToken); when(OAuth2Util.getPersistenceProcessor()).thenReturn(new PlainTextPersistenceProcessor()); OAuth2ClientApplicationDTO response = tokenValidationHandler .findOAuthConsumerIfTokenIsValid(oAuth2TokenValidationRequestDTO); assertNotNull(response); } /** * This data provider is added to enable affected test cases to be tested in both * where the IDP_ID column is available and not available in the relevant tables. */ @DataProvider(name = "CommonDataProvider") public Object[][] commonDataProvider() { return new Object[][]{ {true, "1234"}, {false, "12345"} }; } @Test(dataProvider = "CommonDataProvider") public void testBuildIntrospectionResponse(boolean isIDPIdColumnEnabled, String accessTokenId) throws Exception { OAuth2ServiceComponentHolder.setIDPIdColumnEnabled(isIDPIdColumnEnabled); mockRequiredObjects(); when(realmService.getTenantManager()).thenReturn(tenantManager); doReturn(MultitenantConstants.SUPER_TENANT_ID).when(tenantManager).getTenantId(Mockito.anyString()); OAuthComponentServiceHolder.getInstance().setRealmService(realmService); IdentityTenantUtil.setRealmService(realmService); when(realmService.getBootstrapRealmConfiguration()).thenReturn(realmConfiguration); when(IdentityUtil.getPrimaryDomainName()).thenReturn("PRIMARY"); OAuth2TokenValidationRequestDTO oAuth2TokenValidationRequestDTO = new OAuth2TokenValidationRequestDTO(); OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken = oAuth2TokenValidationRequestDTO.new OAuth2AccessToken(); accessToken.setIdentifier("testAccessToken"); accessToken.setTokenType("bearer"); AccessTokenDO accessTokenDO = new AccessTokenDO(clientId, authzUser, scopeArraySorted, issuedTime, refreshTokenIssuedTime, validityPeriodInMillis, refreshTokenValidityPeriodInMillis, tokenType, authorizationCode); accessTokenDO.setTokenId(accessTokenId); OAuthAppDO oAuthAppDO = new OAuthAppDO(); oAuthAppDO.setTokenType("Default"); oAuthAppDO.setApplicationName("testApp"); AppInfoCache appInfoCache = AppInfoCache.getInstance(); appInfoCache.addToCache("testConsumerKey", oAuthAppDO); tokenMgtDAO.persistAccessToken("testAccessToken", "testConsumerKey", accessTokenDO, accessTokenDO, "TESTDOMAIN"); oAuth2TokenValidationRequestDTO.setAccessToken(accessToken); when(OAuth2Util.getPersistenceProcessor()).thenReturn(new PlainTextPersistenceProcessor()); assertNotNull(tokenValidationHandler.buildIntrospectionResponse(oAuth2TokenValidationRequestDTO)); } protected void mockRequiredObjects() throws Exception { mockStatic(OAuthServerConfiguration.class); when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration); when(OAuthServerConfiguration.getInstance().getOAuthTokenGenerator()).thenReturn(oAuthIssuer); when(OAuthServerConfiguration.getInstance().getSignatureAlgorithm()).thenReturn("SHA256withRSA"); when(OAuthServerConfiguration.getInstance().getHashAlgorithm()).thenReturn("SHA-256"); Map<String, OauthTokenIssuer> oauthTokenIssuerMap = new HashMap<>(); oauthTokenIssuerMap.put(DEFAULT_TOKEN_TYPE, new OauthTokenIssuerImpl()); oauthTokenIssuerMap.put(JWT_TOKEN_TYPE, new JWTTokenIssuer()); when(OAuthServerConfiguration.getInstance().getOauthTokenIssuerMap()).thenReturn(oauthTokenIssuerMap); mockStatic(IdentityDatabaseUtil.class); when(IdentityDatabaseUtil.getDBConnection(false)).thenReturn(getDBConnection()); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(getDBConnection()); } private Connection getDBConnection() throws Exception { if (conn == null) { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.h2.Driver"); dataSource.setUsername("username"); dataSource.setPassword("password"); dataSource.setUrl("jdbc:h2:mem:test" + DB_NAME); try (Connection connection = dataSource.getConnection()) { connection.createStatement() .executeUpdate("RUNSCRIPT FROM '" + TestUtils.getFilePath(H2_SCRIPT_NAME) + "'"); } conn = dataSource.getConnection(); } return conn; } }
package ca.carleton.gcrc.couch.command; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.util.Base64; import java.util.Enumeration; import java.util.HashSet; import java.util.Properties; import java.util.Set; import ca.carleton.gcrc.utils.PropertiesWriter; public class AtlasProperties { static public AtlasProperties fromAtlasDir(File atlasDir) throws Exception { Properties props = new Properties(); readProperties(atlasDir, props); return fromProperties(props); } static public AtlasProperties fromProperties(Properties props) throws Exception { AtlasProperties atlasProps = new AtlasProperties(); atlasProps.setAtlasName( props.getProperty("atlas.name") ); atlasProps.setCouchDbName( props.getProperty("couchdb.dbName") ); atlasProps.setCouchDbSubmissionDbName( props.getProperty("couchdb.submission.dbName") ); atlasProps.setCouchDbAdminUser( props.getProperty("couchdb.admin.user") ); atlasProps.setCouchDbAdminPassword( props.getProperty("couchdb.admin.password") ); // CouchDb URL try { String urlStr = props.getProperty("couchdb.url"); URL url = new URL(urlStr); atlasProps.setCouchDbUrl(url); } catch(Exception e) { throw new Exception("Unable to decode CouchDB URL",e); } // Server port try { String portString = props.getProperty("servlet.url.port"); int port = Integer.parseInt(portString); if( 0 == port ) { throw new Exception("Invalid servlet port: "+portString); } atlasProps.setServerPort(port); } catch(Exception e) { throw new Exception("Unable to interpret servlet port",e); } // Restricted { String restrictedString = props.getProperty("atlas.restricted","false"); boolean r = Boolean.parseBoolean(restrictedString); if( r ){ atlasProps.setRestricted(r); } } // Server Key try { String serverKeyString = props.getProperty("server.key",null); if( null != serverKeyString ){ byte[] serverKey = Base64.getDecoder().decode(serverKeyString); atlasProps.setServerKey(serverKey); } } catch(Exception e) { throw new Exception("Unable to interpret server key",e); } // Submission DB enabled { String enabledString = props.getProperty("couchdb.submission.enabled","false"); boolean enabled = Boolean.parseBoolean(enabledString); if( enabled ){ atlasProps.setCouchDbSubmissionDbEnabled(enabled); } } // Geometry simplification disabled { String disabledString = props.getProperty("geometry.simplification.disabled","false"); boolean disabled = Boolean.parseBoolean(disabledString); if( disabled ){ atlasProps.setGeometrySimplificationDisabled(disabled); } } // Google Map API Key { String key = props.getProperty("google.mapapi.key",""); atlasProps.setGoogleMapApiKey(key); } return atlasProps; } static public void readProperties(File atlasDir, Properties props) throws Exception { // install.properties { File installPropFile = new File(atlasDir,"config/install.properties"); if( installPropFile.exists() && installPropFile.isFile() ){ FileInputStream fis = null; try { fis = new FileInputStream(installPropFile); InputStreamReader reader = new InputStreamReader(fis,"UTF-8"); props.load(reader); } catch(Exception e) { throw new Exception("Unable to read config properties from: "+installPropFile.getAbsolutePath(), e); } finally { if( null != fis ){ try{ fis.close(); } catch(Exception e) { // Ignore } } } } } // sensitive.properties { File sensitivePropFile = new File(atlasDir,"config/sensitive.properties"); if( sensitivePropFile.exists() && sensitivePropFile.isFile() ){ FileInputStream fis = null; try { fis = new FileInputStream(sensitivePropFile); InputStreamReader reader = new InputStreamReader(fis,"UTF-8"); props.load(reader); } catch(Exception e) { throw new Exception("Unable to read config properties from: "+sensitivePropFile.getAbsolutePath(), e); } finally { if( null != fis ){ try{ fis.close(); } catch(Exception e) { // Ignore } } } } } } static public void writeProperties(File atlasDir, Properties props) throws Exception { // Create config directory, if needed File configDir = new File(atlasDir,"config"); try { if( false == configDir.exists() ){ if( false == configDir.mkdir() ) { throw new Exception("Error creating directory: "+configDir.getAbsolutePath()); } } } catch(Exception e) { throw new Exception("Unable to create config directory",e); } // Figure out which properties are saved in the sensitive file Set<String> sensitivePropertyNames = new HashSet<String>(); { sensitivePropertyNames.add("couchdb.admin.password"); sensitivePropertyNames.add("server.key"); sensitivePropertyNames.add("google.mapapi.key"); File sensitivePropFile = new File(atlasDir,"config/sensitive.properties"); if( sensitivePropFile.exists() && sensitivePropFile.isFile() ){ FileInputStream fis = null; try { Properties sensitivePropsCopy = new Properties(); fis = new FileInputStream(sensitivePropFile); InputStreamReader reader = new InputStreamReader(fis,"UTF-8"); sensitivePropsCopy.load(reader); Enumeration<?> keyEnum = sensitivePropsCopy.propertyNames(); while( keyEnum.hasMoreElements() ){ Object keyObj = keyEnum.nextElement(); if( keyObj instanceof String ){ String key = (String)keyObj; sensitivePropertyNames.add(key); } } } catch(Exception e) { // Just ignore } finally { if( null != fis ){ try{ fis.close(); } catch(Exception e) { // Ignore } } } } } // Divide public and sensitive properties Properties publicProps = new Properties(); Properties sensitiveProps = new Properties(); Enumeration<?> namesEnum = props.propertyNames(); while( namesEnum.hasMoreElements() ){ Object keyObj = namesEnum.nextElement(); if( keyObj instanceof String ) { String key = (String)keyObj; String value = props.getProperty(key); if( sensitivePropertyNames.contains(key) ) { sensitiveProps.put(key, value); } else { publicProps.put(key, value); } } } // Write public file { File installPropFile = new File(configDir,"install.properties"); FileOutputStream fos = null; try { fos = new FileOutputStream(installPropFile); OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8"); PropertiesWriter propWriter = new PropertiesWriter(osw); propWriter.write(publicProps); osw.flush(); } catch(Exception e) { throw new Exception("Unable to write config properties to: "+installPropFile.getAbsolutePath(), e); } finally { if( null != fos ){ try{ fos.close(); } catch(Exception e) { // Ignore } } } } // Write sensitive file { File sensitivePropFile = new File(configDir,"sensitive.properties"); FileOutputStream fos = null; try { fos = new FileOutputStream(sensitivePropFile); OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8"); PropertiesWriter propWriter = new PropertiesWriter(osw); propWriter.write(sensitiveProps); osw.flush(); } catch(Exception e) { throw new Exception("Unable to write config properties to: "+sensitivePropFile.getAbsolutePath(), e); } finally { if( null != fos ){ try{ fos.close(); } catch(Exception e) { // Ignore } } } } } private String atlasName; private URL couchDbUrl; private String couchDbName; private boolean couchDbSubmissionDbEnabled; private String couchDbSubmissionDbName; private String couchDbAdminUser; private String couchDbAdminPassword; private int serverPort = 8080; private boolean restricted = false; private byte[] serverKey = null; private boolean geometrySimplificationDisabled = false; private String googleMapApiKey; public String getAtlasName() { return atlasName; } public void setAtlasName(String atlasName) { this.atlasName = atlasName; } public URL getCouchDbUrl() { return couchDbUrl; } public void setCouchDbUrl(URL couchDbUrl) { this.couchDbUrl = couchDbUrl; } public String getCouchDbName() { return couchDbName; } public void setCouchDbName(String couchDbName) { this.couchDbName = couchDbName; } public boolean isCouchDbSubmissionDbEnabled() { return couchDbSubmissionDbEnabled; } public void setCouchDbSubmissionDbEnabled(boolean couchDbSubmissionDbEnabled) { this.couchDbSubmissionDbEnabled = couchDbSubmissionDbEnabled; } public String getCouchDbSubmissionDbName() { return couchDbSubmissionDbName; } public void setCouchDbSubmissionDbName(String couchDbSubmissionDbName) { this.couchDbSubmissionDbName = couchDbSubmissionDbName; } public String getCouchDbAdminUser() { return couchDbAdminUser; } public void setCouchDbAdminUser(String couchDbAdminUser) { this.couchDbAdminUser = couchDbAdminUser; } public String getCouchDbAdminPassword() { return couchDbAdminPassword; } public void setCouchDbAdminPassword(String couchDbAdminPassword) { this.couchDbAdminPassword = couchDbAdminPassword; } public int getServerPort() { return serverPort; } public void setServerPort(int serverPort) { this.serverPort = serverPort; } public boolean isRestricted() { return restricted; } public void setRestricted(boolean restricted) { this.restricted = restricted; } public byte[] getServerKey() { return serverKey; } public void setServerKey(byte[] serverKey) { this.serverKey = serverKey; } public boolean isGeometrySimplificationDisabled() { return geometrySimplificationDisabled; } public void setGeometrySimplificationDisabled(boolean geometrySimplificationDisabled) { this.geometrySimplificationDisabled = geometrySimplificationDisabled; } public String getGoogleMapApiKey() { return googleMapApiKey; } public void setGoogleMapApiKey(String googleMapApiKey) { this.googleMapApiKey = googleMapApiKey; } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.raptor.metadata; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.IDBI; import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.sql.SQLException; import java.util.List; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.UUID; import static com.facebook.presto.raptor.metadata.SchemaDaoUtil.createTablesWithRetry; import static io.airlift.testing.Assertions.assertInstanceOf; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @Test(singleThreaded = true) public class TestShardDao { private TestingShardDao dao; private IDBI dbi; private Handle dummyHandle; @BeforeMethod public void setup() { dbi = new DBI("jdbc:h2:mem:test" + System.nanoTime()); dummyHandle = dbi.open(); dao = dbi.onDemand(TestingShardDao.class); createTablesWithRetry(dbi); } @AfterMethod(alwaysRun = true) public void teardown() { dummyHandle.close(); } @Test public void testExternalBatches() { assertFalse(dao.externalBatchExists("foo")); assertFalse(dao.externalBatchExists("bar")); dao.insertExternalBatch("foo"); assertTrue(dao.externalBatchExists("foo")); assertFalse(dao.externalBatchExists("bar")); try { dao.insertExternalBatch("foo"); fail("expected exception"); } catch (UnableToExecuteStatementException e) { assertInstanceOf(e.getCause(), SQLException.class); assertTrue(((SQLException) e.getCause()).getSQLState().startsWith("23")); } } @Test public void testInsertCreatedShard() { long transactionId = dao.insertTransaction(); dao.insertCreatedShard(UUID.randomUUID(), transactionId); dao.deleteCreatedShards(transactionId); } @Test public void testInsertDeletedShards() { dao.insertDeletedShards(ImmutableList.of(UUID.randomUUID(), UUID.randomUUID())); dao.insertDeletedShards(0); } @Test public void testNodeInsert() { assertEquals(dao.getAllNodesInUse(), ImmutableSet.of()); String nodeName = UUID.randomUUID().toString(); int nodeId = dao.insertNode(nodeName); assertEquals(dao.getNodeId(nodeName), (Integer) nodeId); assertEquals(dao.getAllNodesInUse(), ImmutableSet.of(nodeName)); } @Test public void testInsertShard() { long tableId = createTable("test"); UUID shardUuid = UUID.randomUUID(); long shardId = dao.insertShard(shardUuid, tableId, null, 13, 42, 84, 1234); ShardMetadata shard = dao.getShard(shardUuid); assertNotNull(shard); assertEquals(shard.getTableId(), tableId); assertEquals(shard.getShardId(), shardId); assertEquals(shard.getShardUuid(), shardUuid); assertEquals(shard.getRowCount(), 13); assertEquals(shard.getCompressedSize(), 42); assertEquals(shard.getUncompressedSize(), 84); assertEquals(shard.getXxhash64(), OptionalLong.of(1234)); } @Test public void testInsertShardNodeUsingShardUuid() { int nodeId = dao.insertNode("node"); long tableId = createTable("test"); UUID shard = UUID.randomUUID(); dao.insertShard(shard, tableId, null, 0, 0, 0, 0); dao.insertShardNode(shard, nodeId); assertEquals(dao.getShardNodes(tableId), ImmutableList.of(new ShardNode(shard, "node"))); } @Test public void testNodeShards() { assertEquals(dao.getAllNodesInUse(), ImmutableSet.of()); String nodeName1 = UUID.randomUUID().toString(); int nodeId1 = dao.insertNode(nodeName1); String nodeName2 = UUID.randomUUID().toString(); int nodeId2 = dao.insertNode(nodeName2); assertEquals(dao.getAllNodesInUse(), ImmutableSet.of(nodeName1, nodeName2)); UUID shardUuid1 = UUID.randomUUID(); UUID shardUuid2 = UUID.randomUUID(); UUID shardUuid3 = UUID.randomUUID(); UUID shardUuid4 = UUID.randomUUID(); UUID shardUuid5 = UUID.randomUUID(); MetadataDao metadataDao = dbi.onDemand(MetadataDao.class); int bucketCount = 20; long distributionId = metadataDao.insertDistribution("test", "bigint", bucketCount); for (int i = 0; i < bucketCount; i++) { Integer nodeId = ((i % 2) == 0) ? nodeId1 : nodeId2; dao.insertBuckets(distributionId, ImmutableList.of(i), ImmutableList.of(nodeId)); } long plainTableId = metadataDao.insertTable("test", "plain", false, false, null, 0); long bucketedTableId = metadataDao.insertTable("test", "bucketed", false, false, distributionId, 0); long shardId1 = dao.insertShard(shardUuid1, plainTableId, null, 1, 11, 111, 888_111); long shardId2 = dao.insertShard(shardUuid2, plainTableId, null, 2, 22, 222, 888_222); long shardId3 = dao.insertShard(shardUuid3, bucketedTableId, 8, 3, 33, 333, 888_333); long shardId4 = dao.insertShard(shardUuid4, bucketedTableId, 9, 4, 44, 444, 888_444); long shardId5 = dao.insertShard(shardUuid5, bucketedTableId, 7, 5, 55, 555, 888_555); OptionalInt noBucket = OptionalInt.empty(); OptionalLong noRange = OptionalLong.empty(); ShardMetadata shard1 = new ShardMetadata(plainTableId, shardId1, shardUuid1, noBucket, 1, 11, 111, OptionalLong.of(888_111), noRange, noRange); ShardMetadata shard2 = new ShardMetadata(plainTableId, shardId2, shardUuid2, noBucket, 2, 22, 222, OptionalLong.of(888_222), noRange, noRange); ShardMetadata shard3 = new ShardMetadata(bucketedTableId, shardId3, shardUuid3, OptionalInt.of(8), 3, 33, 333, OptionalLong.of(888_333), noRange, noRange); ShardMetadata shard4 = new ShardMetadata(bucketedTableId, shardId4, shardUuid4, OptionalInt.of(9), 4, 44, 444, OptionalLong.of(888_444), noRange, noRange); ShardMetadata shard5 = new ShardMetadata(bucketedTableId, shardId5, shardUuid5, OptionalInt.of(7), 5, 55, 555, OptionalLong.of(888_555), noRange, noRange); assertEquals(dao.getShards(plainTableId), ImmutableList.of(shardUuid1, shardUuid2)); assertEquals(dao.getShards(bucketedTableId), ImmutableList.of(shardUuid3, shardUuid4, shardUuid5)); assertEquals(dao.getNodeShards(nodeName1, null), ImmutableSet.of(shard3)); assertEquals(dao.getNodeShards(nodeName2, null), ImmutableSet.of(shard4, shard5)); assertEquals(dao.getNodeSizes(), ImmutableSet.of( new NodeSize(nodeName1, 33), new NodeSize(nodeName2, 44 + 55))); dao.insertShardNode(shardId1, nodeId1); dao.insertShardNode(shardId2, nodeId1); dao.insertShardNode(shardId1, nodeId2); assertEquals(dao.getNodeShards(nodeName1, null), ImmutableSet.of(shard1, shard2, shard3)); assertEquals(dao.getNodeShards(nodeName2, null), ImmutableSet.of(shard1, shard4, shard5)); assertEquals(dao.getNodeSizes(), ImmutableSet.of( new NodeSize(nodeName1, 11 + 22 + 33), new NodeSize(nodeName2, 11 + 44 + 55))); dao.dropShardNodes(plainTableId); assertEquals(dao.getNodeShards(nodeName1, null), ImmutableSet.of(shard3)); assertEquals(dao.getNodeShards(nodeName2, null), ImmutableSet.of(shard4, shard5)); assertEquals(dao.getNodeSizes(), ImmutableSet.of( new NodeSize(nodeName1, 33), new NodeSize(nodeName2, 44 + 55))); dao.dropShards(plainTableId); dao.dropShards(bucketedTableId); assertEquals(dao.getShards(plainTableId), ImmutableList.of()); assertEquals(dao.getShards(bucketedTableId), ImmutableList.of()); assertEquals(dao.getNodeSizes(), ImmutableSet.of()); } @Test public void testShardSelection() { assertEquals(dao.getAllNodesInUse(), ImmutableSet.of()); String nodeName1 = UUID.randomUUID().toString(); int nodeId1 = dao.insertNode(nodeName1); assertEquals(dao.getAllNodesInUse(), ImmutableSet.of(nodeName1)); String nodeName2 = UUID.randomUUID().toString(); int nodeId2 = dao.insertNode(nodeName2); assertEquals(dao.getAllNodesInUse(), ImmutableSet.of(nodeName1, nodeName2)); long tableId = createTable("test"); UUID shardUuid1 = UUID.randomUUID(); UUID shardUuid2 = UUID.randomUUID(); UUID shardUuid3 = UUID.randomUUID(); UUID shardUuid4 = UUID.randomUUID(); long shardId1 = dao.insertShard(shardUuid1, tableId, null, 0, 0, 0, 0); long shardId2 = dao.insertShard(shardUuid2, tableId, null, 0, 0, 0, 0); long shardId3 = dao.insertShard(shardUuid3, tableId, null, 0, 0, 0, 0); long shardId4 = dao.insertShard(shardUuid4, tableId, null, 0, 0, 0, 0); List<UUID> shards = dao.getShards(tableId); assertEquals(shards.size(), 4); assertTrue(shards.contains(shardUuid1)); assertTrue(shards.contains(shardUuid2)); assertTrue(shards.contains(shardUuid3)); assertTrue(shards.contains(shardUuid4)); assertEquals(dao.getShardNodes(tableId).size(), 0); dao.insertShardNode(shardId1, nodeId1); dao.insertShardNode(shardId1, nodeId2); dao.insertShardNode(shardId2, nodeId1); dao.insertShardNode(shardId3, nodeId1); dao.insertShardNode(shardId4, nodeId1); dao.insertShardNode(shardId4, nodeId2); assertEquals(dao.getShards(tableId), shards); List<ShardNode> shardNodes = dao.getShardNodes(tableId); assertEquals(shardNodes.size(), 6); assertContainsShardNode(shardNodes, nodeName1, shardUuid1); assertContainsShardNode(shardNodes, nodeName2, shardUuid1); assertContainsShardNode(shardNodes, nodeName1, shardUuid2); assertContainsShardNode(shardNodes, nodeName1, shardUuid3); assertContainsShardNode(shardNodes, nodeName1, shardUuid4); assertContainsShardNode(shardNodes, nodeName2, shardUuid4); } private long createTable(String name) { return dbi.onDemand(MetadataDao.class).insertTable("test", name, false, false, null, 0); } private static void assertContainsShardNode(List<ShardNode> nodes, String nodeName, UUID shardUuid) { assertTrue(nodes.contains(new ShardNode(shardUuid, nodeName))); } }
/******************************************************************************* * (C) Copyright 2016 Hewlett Packard Enterprise Development LP * * 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.hp.ov.sdk.dto.servers.enclosure; import java.io.Serializable; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import com.hp.ov.sdk.dto.servers.HealthStatus; public class EnclosureManager implements Serializable { private static final long serialVersionUID = 1L; private Integer bayNumber; private BayPowerState bayPowerState; private ChangeState changeState; private DevicePresence devicePresence; private String fwBuildDate; private String fwVersion; private String ipAddress; private Boolean linkPortIsolated; private String linkPortSpeedGbs; private PortState linkPortState; private HealthStatus linkPortStatus; private LinkedEnclosure linkedEnclosure; private PortState mgmtPortLinkState; private String mgmtPortSpeedGbs; private MgmtPortMode mgmtPortState; private HealthStatus mgmtPortStatus; private String model; private String negotiatedLinkPortSpeedGbs; private Integer negotiatedMgmtPortSpeedGbs; private String partNumber; private ManagerRole role; private String serialNumber; private String sparePartNumber; private HealthStatus status; private UidState uidState; /** * @return the bayNumber */ public Integer getBayNumber() { return bayNumber; } /** * @param bayNumber the bayNumber to set */ public void setBayNumber(Integer bayNumber) { this.bayNumber = bayNumber; } /** * @return the bayPowerState */ public BayPowerState getBayPowerState() { return bayPowerState; } /** * @param bayPowerState the bayPowerState to set */ public void setBayPowerState(BayPowerState bayPowerState) { this.bayPowerState = bayPowerState; } /** * @return the changeState */ public ChangeState getChangeState() { return changeState; } /** * @param changeState the changeState to set */ public void setChangeState(ChangeState changeState) { this.changeState = changeState; } /** * @return the devicePresence */ public DevicePresence getDevicePresence() { return devicePresence; } /** * @param devicePresence the devicePresence to set */ public void setDevicePresence(DevicePresence devicePresence) { this.devicePresence = devicePresence; } /** * @return the fwBuildDate */ public String getFwBuildDate() { return fwBuildDate; } /** * @param fwBuildDate the fwBuildDate to set */ public void setFwBuildDate(String fwBuildDate) { this.fwBuildDate = fwBuildDate; } /** * @return the fwVersion */ public String getFwVersion() { return fwVersion; } /** * @param fwVersion the fwVersion to set */ public void setFwVersion(String fwVersion) { this.fwVersion = fwVersion; } /** * @return the ipAddress */ public String getIpAddress() { return ipAddress; } /** * @param ipAddress the ipAddress to set */ public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } /** * @return the linkPortIsolated */ public Boolean getLinkPortIsolated() { return linkPortIsolated; } /** * @param linkPortIsolated the linkPortIsolated to set */ public void setLinkPortIsolated(Boolean linkPortIsolated) { this.linkPortIsolated = linkPortIsolated; } /** * @return the linkPortSpeedGbs */ public String getLinkPortSpeedGbs() { return linkPortSpeedGbs; } /** * @param linkPortSpeedGbs the linkPortSpeedGbs to set */ public void setLinkPortSpeedGbs(String linkPortSpeedGbs) { this.linkPortSpeedGbs = linkPortSpeedGbs; } /** * @return the linkPortState */ public PortState getLinkPortState() { return linkPortState; } /** * @param linkPortState the linkPortState to set */ public void setLinkPortState(PortState linkPortState) { this.linkPortState = linkPortState; } /** * @return the linkPortStatus */ public HealthStatus getLinkPortStatus() { return linkPortStatus; } /** * @param linkPortStatus the linkPortStatus to set */ public void setLinkPortStatus(HealthStatus linkPortStatus) { this.linkPortStatus = linkPortStatus; } /** * @return the linkedEnclosure */ public LinkedEnclosure getLinkedEnclosure() { return linkedEnclosure; } /** * @param linkedEnclosure the linkedEnclosure to set */ public void setLinkedEnclosure(LinkedEnclosure linkedEnclosure) { this.linkedEnclosure = linkedEnclosure; } /** * @return the mgmtPortLinkState */ public PortState getMgmtPortLinkState() { return mgmtPortLinkState; } /** * @param mgmtPortLinkState the mgmtPortLinkState to set */ public void setMgmtPortLinkState(PortState mgmtPortLinkState) { this.mgmtPortLinkState = mgmtPortLinkState; } /** * @return the mgmtPortSpeedGbs */ public String getMgmtPortSpeedGbs() { return mgmtPortSpeedGbs; } /** * @param mgmtPortSpeedGbs the mgmtPortSpeedGbs to set */ public void setMgmtPortSpeedGbs(String mgmtPortSpeedGbs) { this.mgmtPortSpeedGbs = mgmtPortSpeedGbs; } /** * @return the mgmtPortState */ public MgmtPortMode getMgmtPortState() { return mgmtPortState; } /** * @param mgmtPortState the mgmtPortState to set */ public void setMgmtPortState(MgmtPortMode mgmtPortState) { this.mgmtPortState = mgmtPortState; } /** * @return the mgmtPortStatus */ public HealthStatus getMgmtPortStatus() { return mgmtPortStatus; } /** * @param mgmtPortStatus the mgmtPortStatus to set */ public void setMgmtPortStatus(HealthStatus mgmtPortStatus) { this.mgmtPortStatus = mgmtPortStatus; } /** * @return the model */ public String getModel() { return model; } /** * @param model the model to set */ public void setModel(String model) { this.model = model; } /** * @return the negotiatedLinkPortSpeedGbs */ public String getNegotiatedLinkPortSpeedGbs() { return negotiatedLinkPortSpeedGbs; } /** * @param negotiatedLinkPortSpeedGbs the negotiatedLinkPortSpeedGbs to set */ public void setNegotiatedLinkPortSpeedGbs(String negotiatedLinkPortSpeedGbs) { this.negotiatedLinkPortSpeedGbs = negotiatedLinkPortSpeedGbs; } /** * @return the negotiatedMgmtPortSpeedGbs */ public Integer getNegotiatedMgmtPortSpeedGbs() { return negotiatedMgmtPortSpeedGbs; } /** * @param negotiatedMgmtPortSpeedGbs the negotiatedMgmtPortSpeedGbs to set */ public void setNegotiatedMgmtPortSpeedGbs(Integer negotiatedMgmtPortSpeedGbs) { this.negotiatedMgmtPortSpeedGbs = negotiatedMgmtPortSpeedGbs; } /** * @return the partNumber */ public String getPartNumber() { return partNumber; } /** * @param partNumber the partNumber to set */ public void setPartNumber(String partNumber) { this.partNumber = partNumber; } /** * @return the role */ public ManagerRole getRole() { return role; } /** * @param role the role to set */ public void setRole(ManagerRole role) { this.role = role; } /** * @return the serialNumber */ public String getSerialNumber() { return serialNumber; } /** * @param serialNumber the serialNumber to set */ public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } /** * @return the sparePartNumber */ public String getSparePartNumber() { return sparePartNumber; } /** * @param sparePartNumber the sparePartNumber to set */ public void setSparePartNumber(String sparePartNumber) { this.sparePartNumber = sparePartNumber; } /** * @return the status */ public HealthStatus getStatus() { return status; } /** * @param status the status to set */ public void setStatus(HealthStatus status) { this.status = status; } /** * @return the uidState */ public UidState getUidState() { return uidState; } /** * @param uidState the uidState to set */ public void setUidState(UidState uidState) { this.uidState = uidState; } @Override public boolean equals(final Object other) { if (other == this) { return true; } if ((other instanceof EnclosureManager) == false) { return false; } final EnclosureManager rhs = ((EnclosureManager) other); return new EqualsBuilder() .append(bayNumber, rhs.bayNumber) .append(bayPowerState, rhs.bayPowerState) .append(changeState, rhs.changeState) .append(devicePresence, rhs.devicePresence) .append(fwBuildDate, rhs.fwBuildDate) .append(fwVersion, rhs.fwVersion) .append(ipAddress, rhs.ipAddress) .append(linkPortIsolated, rhs.linkPortIsolated) .append(linkPortSpeedGbs, rhs.linkPortSpeedGbs) .append(linkPortState, rhs.linkPortState) .append(linkPortStatus, rhs.linkPortStatus) .append(linkedEnclosure, rhs.linkedEnclosure) .append(mgmtPortLinkState, rhs.mgmtPortLinkState) .append(mgmtPortSpeedGbs, rhs.mgmtPortSpeedGbs) .append(mgmtPortState, rhs.mgmtPortState) .append(mgmtPortStatus, rhs.mgmtPortStatus) .append(model, rhs.model) .append(negotiatedLinkPortSpeedGbs, rhs.negotiatedLinkPortSpeedGbs) .append(negotiatedMgmtPortSpeedGbs, rhs.negotiatedMgmtPortSpeedGbs) .append(partNumber, rhs.partNumber) .append(role, rhs.role) .append(serialNumber, rhs.serialNumber) .append(sparePartNumber, rhs.sparePartNumber) .append(status, rhs.status) .append(uidState, rhs.uidState) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .append(bayNumber) .append(bayPowerState) .append(changeState) .append(devicePresence) .append(fwBuildDate) .append(fwVersion) .append(ipAddress) .append(linkPortIsolated) .append(linkPortSpeedGbs) .append(linkPortState) .append(linkPortStatus) .append(linkedEnclosure) .append(mgmtPortLinkState) .append(mgmtPortSpeedGbs) .append(mgmtPortState) .append(mgmtPortStatus) .append(model) .append(negotiatedLinkPortSpeedGbs) .append(negotiatedMgmtPortSpeedGbs) .append(partNumber) .append(role) .append(serialNumber) .append(sparePartNumber) .append(status) .append(uidState) .toHashCode(); } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
package org.apache.hadoop.hive.cassandra.serde; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.serde2.SerDe; import org.apache.hadoop.hive.serde2.SerDeException; import org.apache.hadoop.hive.serde2.SerDeStats; import org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.StructField; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Properties; public abstract class AbstractCassandraSerDe implements SerDe { public static final Logger LOG = LoggerFactory.getLogger(AbstractCassandraSerDe.class); public static final String CASSANDRA_KEYSPACE_NAME = "cassandra.ks.name"; // keyspace public static final String CASSANDRA_KEYSPACE_REPFACTOR = "cassandra.ks.repfactor"; //keyspace replication factor public static final String CASSANDRA_KEYSPACE_STRATEGY = "cassandra.ks.strategy"; //keyspace replica placement strategy public static final String CASSANDRA_KEYSPACE_STRATEGY_OPTIONS = "cassandra.ks.stratOptions"; public static final String DURABLE_WRITES = "durable.writes"; public static final String CASSANDRA_CF_NAME = "cassandra.cf.name"; // column family public static final String CASSANDRA_RANGE_BATCH_SIZE = "cassandra.range.size"; public static final String CASSANDRA_SLICE_PREDICATE_SIZE = "cassandra.slice.predicate.size"; public static final String CASSANDRA_SPLIT_SIZE = "cassandra.input.split.size"; public static final String CASSANDRA_HOST = "cassandra.host"; // initialHost public static final String CASSANDRA_PORT = "cassandra.port"; // rcpPort public static final String CASSANDRA_PARTITIONER = "cassandra.partitioner"; // partitioner public static final String CASSANDRA_COL_MAPPING = "cassandra.columns.mapping"; public static final String CASSANDRA_INDEXED_COLUMNS = "cassandra.indexed.columns"; public static final String CASSANDRA_BATCH_MUTATION_SIZE = "cassandra.batchmutate.size"; public static final String CASSANDRA_SLICE_PREDICATE_COLUMN_NAMES = "cassandra.slice.predicate.column_names"; public static final String CASSANDRA_SLICE_PREDICATE_RANGE_START = "cassandra.slice.predicate.range.start"; public static final String CASSANDRA_SLICE_PREDICATE_RANGE_FINISH = "cassandra.slice.predicate.range.finish"; public static final String CASSANDRA_SLICE_PREDICATE_RANGE_COMPARATOR = "cassandra.slice.predicate.range.comparator"; public static final String CASSANDRA_SLICE_PREDICATE_RANGE_REVERSED = "cassandra.slice.predicate.range.reversed"; public static final String CASSANDRA_SLICE_PREDICATE_RANGE_COUNT = "cassandra.slice.predicate.range.count"; public static final String COLUMN_FAMILY_COMMENT = "comment"; public static final String READ_REPAIR_CHANCE = "read_repair_chance"; public static final String DCLOCAL_READ_REPAIR_CHANCE = "dclocal_read_repair_chance"; public static final String GC_GRACE_SECONDS = "gc_grace_seconds"; public static final String BLOOM_FILTER_FP_CHANCE = "bloom_filter_fp_chance"; public static final String COMPACTION = "compaction"; public static final String COMPRESSION = "compression"; public static final String REPLICATE_ON_WRITE = "replicate_on_write"; public static final String CACHING = "caching"; public static final String CASSANDRA_CONSISTENCY_LEVEL = "cassandra.consistency.level"; public static final String CASSANDRA_THRIFT_MODE = "cassandra.thrift.mode"; public static final int DEFAULT_SPLIT_SIZE = 64 * 1024; public static final int DEFAULT_RANGE_BATCH_SIZE = 1000; public static final int DEFAULT_SLICE_PREDICATE_SIZE = 1000; public static final String DEFAULT_CASSANDRA_HOST = "localhost"; public static final String DEFAULT_CASSANDRA_PORT = "9160"; public static final String DEFAULT_CONSISTENCY_LEVEL = "ONE"; public static final int DEFAULT_BATCH_MUTATION_SIZE = 500; public static final String DELIMITER = ","; /* names of columns from SerdeParameters */ protected List<String> cassandraColumnNames; protected TableMapping mapping; protected ObjectInspector cachedObjectInspector; protected LazySimpleSerDe.SerDeParameters serdeParams; protected String cassandraKeyspace; protected String cassandraColumnFamily; protected List<Text> cassandraColumnNamesText; protected abstract void initCassandraSerDeParameters(Configuration job, Properties tbl, String serdeName) throws SerDeException; /** * Create the object inspector. * * @return object inspector */ public abstract ObjectInspector createObjectInspector(); /* * Turns obj (a Hive Row) into a cassandra data format. */ @Override public Writable serialize(Object obj, ObjectInspector objInspector) throws SerDeException { if (objInspector.getCategory() != ObjectInspector.Category.STRUCT) { throw new SerDeException(getClass().toString() + " can only serialize struct types, but we got: " + objInspector.getTypeName()); } // Prepare the field ObjectInspectors StructObjectInspector soi = (StructObjectInspector) objInspector; List<? extends StructField> fields = soi.getAllStructFieldRefs(); List<Object> list = soi.getStructFieldsDataAsList(obj); List<? extends StructField> declaredFields = (serdeParams.getRowTypeInfo() != null && ((StructTypeInfo) serdeParams.getRowTypeInfo()) .getAllStructFieldNames().size() > 0) ? ((StructObjectInspector) getObjectInspector()).getAllStructFieldRefs() : null; try { return mapping.getWritable(fields, list, declaredFields); } catch (IOException e) { throw new SerDeException("Unable to serialize this object! " + e); } } /** * @see * org.apache.hadoop.hive.serde2.Deserializer#deserialize(org.apache.hadoop.io.Writable) * Turns a Cassandra row into a Hive row. */ public abstract Object deserialize(Writable w) throws SerDeException; /** * Parse cassandra keyspace from table properties. * * @param tbl table properties * @return cassandra keyspace * @throws org.apache.hadoop.hive.serde2.SerDeException error parsing * keyspace */ protected String parseCassandraKeyspace(Properties tbl) throws SerDeException { String result = tbl.getProperty(CASSANDRA_KEYSPACE_NAME); if (result == null) { result = tbl .getProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_NAME); if (result == null) { throw new SerDeException("CassandraKeyspace not defined" + tbl.toString()); } if (result.indexOf(".") != -1) { result = result.substring(0, result.indexOf(".")); } } return result; } /** * Parse cassandra column family name from table properties. * * @param tbl table properties * @return cassandra column family name * @throws org.apache.hadoop.hive.serde2.SerDeException error parsing column * family name */ protected String parseCassandraColumnFamily(Properties tbl) throws SerDeException { String result = tbl.getProperty(CASSANDRA_CF_NAME); if (result == null) { result = tbl .getProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_NAME); if (result == null) { throw new SerDeException("CassandraColumnFamily not defined" + tbl.toString()); } if (result.indexOf(".") != -1) { result = result.substring(result.indexOf(".") + 1); } } return result; } @Override public ObjectInspector getObjectInspector() throws SerDeException { return cachedObjectInspector; } /** * Set the table mapping. We only support transposed mapping and regular * table mapping for now. * * @throws org.apache.hadoop.hive.serde2.SerDeException * */ protected abstract void setTableMapping() throws SerDeException; /** * Trim the white spaces, new lines from the input array. * * @param input a input string array * @return a trimmed string array */ protected static String[] trim(String[] input) { String[] trimmed = new String[input.length]; for (int i = 0; i < input.length; i++) { trimmed[i] = input[i].trim(); } return trimmed; } @Override public SerDeStats getSerDeStats() { return null; } /** * @return the name of the cassandra keyspace as parsed from table * properties */ public String getCassandraKeyspace() { return cassandraKeyspace; } /** * @return the name of the cassandra columnfamily as parsed from table * properties */ public String getCassandraColumnFamily() { return cassandraColumnFamily; } }
/* * 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.prestosql.sql.planner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.airlift.log.Logger; import io.prestosql.Session; import io.prestosql.execution.TableInfo; import io.prestosql.metadata.Metadata; import io.prestosql.metadata.TableMetadata; import io.prestosql.metadata.TableProperties; import io.prestosql.operator.StageExecutionDescriptor; import io.prestosql.server.DynamicFilterService; import io.prestosql.spi.connector.DynamicFilter; import io.prestosql.split.SampledSplitSource; import io.prestosql.split.SplitManager; import io.prestosql.split.SplitSource; import io.prestosql.sql.DynamicFilters; import io.prestosql.sql.planner.plan.AggregationNode; import io.prestosql.sql.planner.plan.AssignUniqueId; import io.prestosql.sql.planner.plan.DeleteNode; import io.prestosql.sql.planner.plan.DistinctLimitNode; import io.prestosql.sql.planner.plan.EnforceSingleRowNode; import io.prestosql.sql.planner.plan.ExchangeNode; import io.prestosql.sql.planner.plan.ExplainAnalyzeNode; import io.prestosql.sql.planner.plan.FilterNode; import io.prestosql.sql.planner.plan.GroupIdNode; import io.prestosql.sql.planner.plan.IndexJoinNode; import io.prestosql.sql.planner.plan.JoinNode; import io.prestosql.sql.planner.plan.LimitNode; import io.prestosql.sql.planner.plan.MarkDistinctNode; import io.prestosql.sql.planner.plan.OutputNode; import io.prestosql.sql.planner.plan.PlanNode; import io.prestosql.sql.planner.plan.PlanNodeId; import io.prestosql.sql.planner.plan.PlanVisitor; import io.prestosql.sql.planner.plan.ProjectNode; import io.prestosql.sql.planner.plan.RemoteSourceNode; import io.prestosql.sql.planner.plan.RowNumberNode; import io.prestosql.sql.planner.plan.SampleNode; import io.prestosql.sql.planner.plan.SemiJoinNode; import io.prestosql.sql.planner.plan.SortNode; import io.prestosql.sql.planner.plan.SpatialJoinNode; import io.prestosql.sql.planner.plan.StatisticsWriterNode; import io.prestosql.sql.planner.plan.TableDeleteNode; import io.prestosql.sql.planner.plan.TableFinishNode; import io.prestosql.sql.planner.plan.TableScanNode; import io.prestosql.sql.planner.plan.TableWriterNode; import io.prestosql.sql.planner.plan.TopNNode; import io.prestosql.sql.planner.plan.TopNRowNumberNode; import io.prestosql.sql.planner.plan.UnionNode; import io.prestosql.sql.planner.plan.UnnestNode; import io.prestosql.sql.planner.plan.ValuesNode; import io.prestosql.sql.planner.plan.WindowNode; import javax.inject.Inject; import java.util.List; import java.util.Map; import java.util.Optional; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.Iterables.getOnlyElement; import static io.prestosql.spi.connector.ConnectorSplitManager.SplitSchedulingStrategy.GROUPED_SCHEDULING; import static io.prestosql.spi.connector.ConnectorSplitManager.SplitSchedulingStrategy.UNGROUPED_SCHEDULING; import static io.prestosql.spi.connector.DynamicFilter.EMPTY; import static io.prestosql.sql.planner.optimizations.PlanNodeSearcher.searchFrom; import static java.util.Objects.requireNonNull; public class DistributedExecutionPlanner { private static final Logger log = Logger.get(DistributedExecutionPlanner.class); private final SplitManager splitManager; private final Metadata metadata; private final DynamicFilterService dynamicFilterService; @Inject public DistributedExecutionPlanner(SplitManager splitManager, Metadata metadata, DynamicFilterService dynamicFilterService) { this.splitManager = requireNonNull(splitManager, "splitManager is null"); this.metadata = requireNonNull(metadata, "metadata is null"); this.dynamicFilterService = requireNonNull(dynamicFilterService, "dynamicFilterService is null"); } public StageExecutionPlan plan(SubPlan root, Session session) { ImmutableList.Builder<SplitSource> allSplitSources = ImmutableList.builder(); try { return doPlan(root, session, allSplitSources); } catch (Throwable t) { allSplitSources.build().forEach(DistributedExecutionPlanner::closeSplitSource); throw t; } } private static void closeSplitSource(SplitSource source) { try { source.close(); } catch (Throwable t) { log.warn(t, "Error closing split source"); } } private StageExecutionPlan doPlan(SubPlan root, Session session, ImmutableList.Builder<SplitSource> allSplitSources) { PlanFragment currentFragment = root.getFragment(); // get splits for this fragment, this is lazy so split assignments aren't actually calculated here Map<PlanNodeId, SplitSource> splitSources = currentFragment.getRoot().accept( new Visitor(session, currentFragment.getStageExecutionDescriptor(), TypeProvider.copyOf(currentFragment.getSymbols()), allSplitSources), null); // create child stages ImmutableList.Builder<StageExecutionPlan> dependencies = ImmutableList.builder(); for (SubPlan childPlan : root.getChildren()) { dependencies.add(doPlan(childPlan, session, allSplitSources)); } // extract TableInfo Map<PlanNodeId, TableInfo> tables = searchFrom(root.getFragment().getRoot()) .where(TableScanNode.class::isInstance) .findAll() .stream() .map(TableScanNode.class::cast) .collect(toImmutableMap(PlanNode::getId, node -> getTableInfo(node, session))); return new StageExecutionPlan( currentFragment, splitSources, dependencies.build(), tables); } private TableInfo getTableInfo(TableScanNode node, Session session) { TableMetadata tableMetadata = metadata.getTableMetadata(session, node.getTable()); TableProperties tableProperties = metadata.getTableProperties(session, node.getTable()); return new TableInfo(tableMetadata.getQualifiedName(), tableProperties.getPredicate()); } private final class Visitor extends PlanVisitor<Map<PlanNodeId, SplitSource>, Void> { private final Session session; private final StageExecutionDescriptor stageExecutionDescriptor; private final TypeProvider typeProvider; private final ImmutableList.Builder<SplitSource> splitSources; private Visitor( Session session, StageExecutionDescriptor stageExecutionDescriptor, TypeProvider typeProvider, ImmutableList.Builder<SplitSource> allSplitSources) { this.session = session; this.stageExecutionDescriptor = stageExecutionDescriptor; this.typeProvider = typeProvider; this.splitSources = allSplitSources; } @Override public Map<PlanNodeId, SplitSource> visitExplainAnalyze(ExplainAnalyzeNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitTableScan(TableScanNode node, Void context) { return visitScanAndFilter(node, Optional.empty()); } private Map<PlanNodeId, SplitSource> visitScanAndFilter(TableScanNode node, Optional<FilterNode> filter) { List<DynamicFilters.Descriptor> dynamicFilters = filter .map(FilterNode::getPredicate) .map(DynamicFilters::extractDynamicFilters) .map(DynamicFilters.ExtractResult::getDynamicConjuncts) .orElse(ImmutableList.of()); DynamicFilter dynamicFilter = EMPTY; if (!dynamicFilters.isEmpty()) { log.debug("Dynamic filters: %s", dynamicFilters); dynamicFilter = dynamicFilterService.createDynamicFilter(session.getQueryId(), dynamicFilters, node.getAssignments(), typeProvider); } // get dataSource for table SplitSource splitSource = splitManager.getSplits( session, node.getTable(), stageExecutionDescriptor.isScanGroupedExecution(node.getId()) ? GROUPED_SCHEDULING : UNGROUPED_SCHEDULING, dynamicFilter); splitSources.add(splitSource); return ImmutableMap.of(node.getId(), splitSource); } @Override public Map<PlanNodeId, SplitSource> visitJoin(JoinNode node, Void context) { Map<PlanNodeId, SplitSource> leftSplits = node.getLeft().accept(this, context); Map<PlanNodeId, SplitSource> rightSplits = node.getRight().accept(this, context); return ImmutableMap.<PlanNodeId, SplitSource>builder() .putAll(leftSplits) .putAll(rightSplits) .build(); } @Override public Map<PlanNodeId, SplitSource> visitSemiJoin(SemiJoinNode node, Void context) { Map<PlanNodeId, SplitSource> sourceSplits = node.getSource().accept(this, context); Map<PlanNodeId, SplitSource> filteringSourceSplits = node.getFilteringSource().accept(this, context); return ImmutableMap.<PlanNodeId, SplitSource>builder() .putAll(sourceSplits) .putAll(filteringSourceSplits) .build(); } @Override public Map<PlanNodeId, SplitSource> visitSpatialJoin(SpatialJoinNode node, Void context) { Map<PlanNodeId, SplitSource> leftSplits = node.getLeft().accept(this, context); Map<PlanNodeId, SplitSource> rightSplits = node.getRight().accept(this, context); return ImmutableMap.<PlanNodeId, SplitSource>builder() .putAll(leftSplits) .putAll(rightSplits) .build(); } @Override public Map<PlanNodeId, SplitSource> visitIndexJoin(IndexJoinNode node, Void context) { return node.getProbeSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitRemoteSource(RemoteSourceNode node, Void context) { // remote source node does not have splits return ImmutableMap.of(); } @Override public Map<PlanNodeId, SplitSource> visitValues(ValuesNode node, Void context) { // values node does not have splits return ImmutableMap.of(); } @Override public Map<PlanNodeId, SplitSource> visitFilter(FilterNode node, Void context) { if (node.getSource() instanceof TableScanNode) { TableScanNode scan = (TableScanNode) node.getSource(); return visitScanAndFilter(scan, Optional.of(node)); } return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitSample(SampleNode node, Void context) { switch (node.getSampleType()) { case BERNOULLI: return node.getSource().accept(this, context); case SYSTEM: Map<PlanNodeId, SplitSource> nodeSplits = node.getSource().accept(this, context); // TODO: when this happens we should switch to either BERNOULLI or page sampling if (nodeSplits.size() == 1) { PlanNodeId planNodeId = getOnlyElement(nodeSplits.keySet()); SplitSource sampledSplitSource = new SampledSplitSource(nodeSplits.get(planNodeId), node.getSampleRatio()); return ImmutableMap.of(planNodeId, sampledSplitSource); } // table sampling on a sub query without splits is meaningless return nodeSplits; default: throw new UnsupportedOperationException("Sampling is not supported for type " + node.getSampleType()); } } @Override public Map<PlanNodeId, SplitSource> visitAggregation(AggregationNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitGroupId(GroupIdNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitMarkDistinct(MarkDistinctNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitWindow(WindowNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitRowNumber(RowNumberNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitTopNRowNumber(TopNRowNumberNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitProject(ProjectNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitUnnest(UnnestNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitTopN(TopNNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitOutput(OutputNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitEnforceSingleRow(EnforceSingleRowNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitAssignUniqueId(AssignUniqueId node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitLimit(LimitNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitDistinctLimit(DistinctLimitNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitSort(SortNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitTableWriter(TableWriterNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitTableFinish(TableFinishNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitStatisticsWriterNode(StatisticsWriterNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitDelete(DeleteNode node, Void context) { return node.getSource().accept(this, context); } @Override public Map<PlanNodeId, SplitSource> visitTableDelete(TableDeleteNode node, Void context) { // node does not have splits return ImmutableMap.of(); } @Override public Map<PlanNodeId, SplitSource> visitUnion(UnionNode node, Void context) { return processSources(node.getSources(), context); } @Override public Map<PlanNodeId, SplitSource> visitExchange(ExchangeNode node, Void context) { return processSources(node.getSources(), context); } private Map<PlanNodeId, SplitSource> processSources(List<PlanNode> sources, Void context) { ImmutableMap.Builder<PlanNodeId, SplitSource> result = ImmutableMap.builder(); for (PlanNode child : sources) { result.putAll(child.accept(this, context)); } return result.build(); } @Override protected Map<PlanNodeId, SplitSource> visitPlan(PlanNode node, Void context) { throw new UnsupportedOperationException("not yet implemented: " + node.getClass().getName()); } } }
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.ec2.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceResult; /** * <p> * Contains the output of ReleaseHosts. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ReleaseHostsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The IDs of the Dedicated Hosts that were successfully released. * </p> */ private com.amazonaws.internal.SdkInternalList<String> successful; /** * <p> * The IDs of the Dedicated Hosts that could not be released, including an error message. * </p> */ private com.amazonaws.internal.SdkInternalList<UnsuccessfulItem> unsuccessful; /** * <p> * The IDs of the Dedicated Hosts that were successfully released. * </p> * * @return The IDs of the Dedicated Hosts that were successfully released. */ public java.util.List<String> getSuccessful() { if (successful == null) { successful = new com.amazonaws.internal.SdkInternalList<String>(); } return successful; } /** * <p> * The IDs of the Dedicated Hosts that were successfully released. * </p> * * @param successful * The IDs of the Dedicated Hosts that were successfully released. */ public void setSuccessful(java.util.Collection<String> successful) { if (successful == null) { this.successful = null; return; } this.successful = new com.amazonaws.internal.SdkInternalList<String>(successful); } /** * <p> * The IDs of the Dedicated Hosts that were successfully released. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setSuccessful(java.util.Collection)} or {@link #withSuccessful(java.util.Collection)} if you want to * override the existing values. * </p> * * @param successful * The IDs of the Dedicated Hosts that were successfully released. * @return Returns a reference to this object so that method calls can be chained together. */ public ReleaseHostsResult withSuccessful(String... successful) { if (this.successful == null) { setSuccessful(new com.amazonaws.internal.SdkInternalList<String>(successful.length)); } for (String ele : successful) { this.successful.add(ele); } return this; } /** * <p> * The IDs of the Dedicated Hosts that were successfully released. * </p> * * @param successful * The IDs of the Dedicated Hosts that were successfully released. * @return Returns a reference to this object so that method calls can be chained together. */ public ReleaseHostsResult withSuccessful(java.util.Collection<String> successful) { setSuccessful(successful); return this; } /** * <p> * The IDs of the Dedicated Hosts that could not be released, including an error message. * </p> * * @return The IDs of the Dedicated Hosts that could not be released, including an error message. */ public java.util.List<UnsuccessfulItem> getUnsuccessful() { if (unsuccessful == null) { unsuccessful = new com.amazonaws.internal.SdkInternalList<UnsuccessfulItem>(); } return unsuccessful; } /** * <p> * The IDs of the Dedicated Hosts that could not be released, including an error message. * </p> * * @param unsuccessful * The IDs of the Dedicated Hosts that could not be released, including an error message. */ public void setUnsuccessful(java.util.Collection<UnsuccessfulItem> unsuccessful) { if (unsuccessful == null) { this.unsuccessful = null; return; } this.unsuccessful = new com.amazonaws.internal.SdkInternalList<UnsuccessfulItem>(unsuccessful); } /** * <p> * The IDs of the Dedicated Hosts that could not be released, including an error message. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setUnsuccessful(java.util.Collection)} or {@link #withUnsuccessful(java.util.Collection)} if you want to * override the existing values. * </p> * * @param unsuccessful * The IDs of the Dedicated Hosts that could not be released, including an error message. * @return Returns a reference to this object so that method calls can be chained together. */ public ReleaseHostsResult withUnsuccessful(UnsuccessfulItem... unsuccessful) { if (this.unsuccessful == null) { setUnsuccessful(new com.amazonaws.internal.SdkInternalList<UnsuccessfulItem>(unsuccessful.length)); } for (UnsuccessfulItem ele : unsuccessful) { this.unsuccessful.add(ele); } return this; } /** * <p> * The IDs of the Dedicated Hosts that could not be released, including an error message. * </p> * * @param unsuccessful * The IDs of the Dedicated Hosts that could not be released, including an error message. * @return Returns a reference to this object so that method calls can be chained together. */ public ReleaseHostsResult withUnsuccessful(java.util.Collection<UnsuccessfulItem> unsuccessful) { setUnsuccessful(unsuccessful); 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 (getSuccessful() != null) sb.append("Successful: ").append(getSuccessful()).append(","); if (getUnsuccessful() != null) sb.append("Unsuccessful: ").append(getUnsuccessful()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ReleaseHostsResult == false) return false; ReleaseHostsResult other = (ReleaseHostsResult) obj; if (other.getSuccessful() == null ^ this.getSuccessful() == null) return false; if (other.getSuccessful() != null && other.getSuccessful().equals(this.getSuccessful()) == false) return false; if (other.getUnsuccessful() == null ^ this.getUnsuccessful() == null) return false; if (other.getUnsuccessful() != null && other.getUnsuccessful().equals(this.getUnsuccessful()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSuccessful() == null) ? 0 : getSuccessful().hashCode()); hashCode = prime * hashCode + ((getUnsuccessful() == null) ? 0 : getUnsuccessful().hashCode()); return hashCode; } @Override public ReleaseHostsResult clone() { try { return (ReleaseHostsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.xdebugger.impl.breakpoints.ui; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.ui.components.JBCheckBox; import com.intellij.ui.components.JBLabel; import com.intellij.ui.popup.util.DetailView; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.xdebugger.XDebuggerBundle; import com.intellij.xdebugger.XExpression; import com.intellij.xdebugger.breakpoints.XBreakpointManager; import com.intellij.xdebugger.breakpoints.XBreakpointType; import com.intellij.xdebugger.breakpoints.ui.XBreakpointCustomPropertiesPanel; import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider; import com.intellij.xdebugger.impl.XDebuggerUtilImpl; import com.intellij.xdebugger.impl.breakpoints.XBreakpointBase; import com.intellij.xdebugger.impl.breakpoints.XBreakpointUtil; import com.intellij.xdebugger.impl.ui.DebuggerUIUtil; import com.intellij.xdebugger.impl.ui.XDebuggerExpressionComboBox; import javax.swing.*; import java.awt.*; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.util.ArrayList; import java.util.List; public class XLightBreakpointPropertiesPanel implements XSuspendPolicyPanel.Delegate { public static final String CONDITION_HISTORY_ID = "breakpointCondition"; @SuppressWarnings("UnusedDeclaration") public boolean showMoreOptions() { return myShowMoreOptions; } private boolean myShowMoreOptions; @Override public void showMoreOptionsIfNeeded() { if (myShowMoreOptions) { if (myDelegate != null) { myDelegate.showMoreOptions(); } } } public interface Delegate { void showMoreOptions(); } private JPanel myConditionPanel; private JPanel myMainPanel; public Delegate getDelegate() { return myDelegate; } public void setDelegate(Delegate delegate) { myDelegate = delegate; } private Delegate myDelegate; private XSuspendPolicyPanel mySuspendPolicyPanel; private XBreakpointActionsPanel myActionsPanel; private XMasterBreakpointPanel myMasterBreakpointPanel; private JPanel myCustomPropertiesPanelWrapper; private JPanel myCustomConditionsPanelWrapper; private JCheckBox myEnabledCheckbox; private JPanel myCustomRightPropertiesPanelWrapper; private JBCheckBox myConditionEnabledCheckbox; private JPanel myCustomTopPropertiesPanelWrapper; private JBLabel myBreakpointNameLabel; private JPanel myConditionCheckboxPanel; private JPanel myLanguageChooserPanel; private JPanel myConditionExpressionPanel; private final List<XBreakpointCustomPropertiesPanel> myCustomPanels; private final List<XBreakpointPropertiesSubPanel> mySubPanels = new ArrayList<>(); private XDebuggerExpressionComboBox myConditionComboBox; private final XBreakpointBase myBreakpoint; private final boolean myShowAllOptions; public void setDetailView(DetailView detailView) { myMasterBreakpointPanel.setDetailView(detailView); } public XLightBreakpointPropertiesPanel(Project project, XBreakpointManager breakpointManager, XBreakpointBase breakpoint, boolean showAllOptions) { myBreakpoint = breakpoint; myShowAllOptions = showAllOptions; XBreakpointType breakpointType = breakpoint.getType(); if (breakpointType.getVisibleStandardPanels().contains(XBreakpointType.StandardPanels.SUSPEND_POLICY)) { mySuspendPolicyPanel.init(project, breakpointManager, breakpoint); mySuspendPolicyPanel.setDelegate(this); mySubPanels.add(mySuspendPolicyPanel); } else { mySuspendPolicyPanel.hide(); } if (breakpointType.getVisibleStandardPanels().contains(XBreakpointType.StandardPanels.DEPENDENCY)) { myMasterBreakpointPanel.init(project, breakpointManager, breakpoint); mySubPanels.add(myMasterBreakpointPanel); } else { myMasterBreakpointPanel.hide(); } XDebuggerEditorsProvider debuggerEditorsProvider = breakpointType.getEditorsProvider(breakpoint, project); if (breakpointType.getVisibleStandardPanels().contains(XBreakpointType.StandardPanels.ACTIONS)) { myActionsPanel.init(project, breakpointManager, breakpoint, debuggerEditorsProvider); mySubPanels.add(myActionsPanel); } else { myActionsPanel.hide(); } myCustomPanels = new ArrayList<>(); if (debuggerEditorsProvider != null) { myConditionEnabledCheckbox = new JBCheckBox(XDebuggerBundle.message("xbreakpoints.condition.checkbox")); myConditionComboBox = new XDebuggerExpressionComboBox(project, debuggerEditorsProvider, CONDITION_HISTORY_ID, myBreakpoint.getSourcePosition(), true, true); myLanguageChooserPanel.add(myConditionComboBox.getLanguageChooser(), BorderLayout.CENTER); myConditionExpressionPanel.add(myConditionComboBox.getComponent(), BorderLayout.CENTER); myConditionEnabledCheckbox.addActionListener(e -> onCheckboxChanged()); DebuggerUIUtil.focusEditorOnCheck(myConditionEnabledCheckbox, myConditionComboBox.getEditorComponent()); } else { myConditionPanel.setVisible(false); } myShowMoreOptions = false; for (XBreakpointPropertiesSubPanel panel : mySubPanels) { if (panel.lightVariant(showAllOptions)) { myShowMoreOptions = true; } } XBreakpointCustomPropertiesPanel customPropertiesPanel = breakpointType.createCustomPropertiesPanel(project); if (customPropertiesPanel != null) { myCustomPropertiesPanelWrapper.add(customPropertiesPanel.getComponent(), BorderLayout.CENTER); myCustomPanels.add(customPropertiesPanel); } else { myCustomPropertiesPanelWrapper.getParent().remove(myCustomPropertiesPanelWrapper); } XBreakpointCustomPropertiesPanel customConditionPanel = breakpointType.createCustomConditionsPanel(); if (customConditionPanel != null) { myCustomConditionsPanelWrapper.add(customConditionPanel.getComponent(), BorderLayout.CENTER); myCustomPanels.add(customConditionPanel); } else { myCustomConditionsPanelWrapper.getParent().remove(myCustomConditionsPanelWrapper); } XBreakpointCustomPropertiesPanel customRightConditionPanel = breakpointType.createCustomRightPropertiesPanel(project); if (customRightConditionPanel != null && (showAllOptions || customRightConditionPanel.isVisibleOnPopup(breakpoint))) { myCustomRightPropertiesPanelWrapper.add(customRightConditionPanel.getComponent(), BorderLayout.CENTER); myCustomPanels.add(customRightConditionPanel); } else { // see IDEA-125745 myCustomRightPropertiesPanelWrapper.getParent().remove(myCustomRightPropertiesPanelWrapper); } XBreakpointCustomPropertiesPanel customTopPropertiesPanel = breakpointType.createCustomTopPropertiesPanel(project); if (customTopPropertiesPanel != null) { myCustomTopPropertiesPanelWrapper.add(customTopPropertiesPanel.getComponent(), BorderLayout.CENTER); myCustomPanels.add(customTopPropertiesPanel); } else { myCustomTopPropertiesPanelWrapper.getParent().remove(myCustomTopPropertiesPanelWrapper); } myMainPanel.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent event) { JComponent compToFocus = null; if (myConditionComboBox != null && myConditionComboBox.getComboBox().isEnabled()) { compToFocus = myConditionComboBox.getEditorComponent(); } else if (breakpointType.getVisibleStandardPanels().contains(XBreakpointType.StandardPanels.ACTIONS)) { compToFocus = myActionsPanel.getDefaultFocusComponent(); } if (compToFocus != null) { IdeFocusManager.findInstance().requestFocus(compToFocus, false); } } }); myEnabledCheckbox.addActionListener(e -> myBreakpoint.setEnabled(myEnabledCheckbox.isSelected())); } private void onCheckboxChanged() { if (myConditionComboBox != null) { myConditionComboBox.setEnabled(myConditionEnabledCheckbox.isSelected()); } } public void saveProperties() { mySubPanels.forEach(XBreakpointPropertiesSubPanel::saveProperties); if (myConditionComboBox != null) { XExpression expression = myConditionComboBox.getExpression(); XExpression condition = !XDebuggerUtilImpl.isEmptyExpression(expression) ? expression : null; myBreakpoint.setConditionEnabled(condition == null || myConditionEnabledCheckbox.isSelected()); myBreakpoint.setConditionExpression(condition); myConditionComboBox.saveTextInHistory(); } for (XBreakpointCustomPropertiesPanel customPanel : myCustomPanels) { customPanel.saveTo(myBreakpoint); } myBreakpoint.setEnabled(myEnabledCheckbox.isSelected()); } public void loadProperties() { mySubPanels.forEach(XBreakpointPropertiesSubPanel::loadProperties); if (myConditionComboBox != null) { XExpression condition = myBreakpoint.getConditionExpressionInt(); myConditionComboBox.setExpression(condition); boolean hideCheckbox = !myShowAllOptions && condition == null; myConditionEnabledCheckbox.setSelected(hideCheckbox || (myBreakpoint.isConditionEnabled() && condition != null)); myConditionCheckboxPanel.removeAll(); if (hideCheckbox) { JBLabel label = new JBLabel(XDebuggerBundle.message("xbreakpoints.condition.checkbox")); label.setBorder(JBUI.Borders.empty(0, 4, 4, 0)); label.setLabelFor(myConditionComboBox.getComboBox()); myConditionCheckboxPanel.add(label); myConditionExpressionPanel.setBorder(JBUI.Borders.emptyLeft(3)); } else { myConditionCheckboxPanel.add(myConditionEnabledCheckbox); myConditionExpressionPanel.setBorder(JBUI.Borders.emptyLeft(UIUtil.getCheckBoxTextHorizontalOffset(myConditionEnabledCheckbox))); } onCheckboxChanged(); } for (XBreakpointCustomPropertiesPanel customPanel : myCustomPanels) { customPanel.loadFrom(myBreakpoint); } myEnabledCheckbox.setSelected(myBreakpoint.isEnabled()); myBreakpointNameLabel.setText(XBreakpointUtil.getShortText(myBreakpoint)); } public JPanel getMainPanel() { return myMainPanel; } public void dispose() { myActionsPanel.dispose(); myCustomPanels.forEach(Disposer::dispose); myCustomPanels.clear(); } }
/* * Copyright 2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.kandula.utility; import java.io.InputStream; import java.net.InetAddress; import java.util.Properties; import org.apache.axis2.AxisFault; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.ConfigurationContextFactory; import org.apache.axis2.deployment.DeploymentException; import org.apache.kandula.faults.AbstractKandulaException; import org.apache.kandula.faults.KandulaGeneralException; public class KandulaConfiguration { static final String PROPERTY_FILE = "endpoints.conf"; // static final String PROTOCOL_PROPERTY = "protocol"; static final String HOST_PROPERTY = "host"; static final String PORT_PROPERTY = "port"; static final String TCPMON_ENABLE = "tcpmon_enable"; static final String PARTICIPANT_REPO = "PARTICIPANT_REPOSITORY"; static final String PARTICIPANT_AXIS2_CONF = "PARTICIPANT_AXIS2_CONF"; static final String KANDULA_LISTENER_REPO = "KANDULA_LISTENER_REPOSITORY"; static final String KANDULA_LISTENER_AXIS2XML = "KANDULA_LISTENER_AXIS2XML"; static final String LISTENER_PORT = "KANDULA_LISTENER_PORT"; static final String COORDINATOR_AXIS2XML = "COORDINATOR_AXIS2XML"; static final String COORDINATOR_REPOSITORY = "COORDINATOR_REPOSITORY"; private static KandulaConfiguration instance = null; Properties properties = null; String location = null; String participantRepository = null; String participantAxis2Xml = null; String kandulaListenerRepository = null; String kandulaListenerAxis2Xml = null; String kandulaListenerPort = null; String coordinatorRepo; String coordinatorAxis2Conf; String debug = "false"; private ConfigurationContext coordinatorConfigurationContext = null; private ConfigurationContext participantConfigurationContext = null; private KandulaConfiguration() { String port = null; String host = null; InputStream in = getClass().getClassLoader().getResourceAsStream(PROPERTY_FILE); properties = new Properties(); try { properties.load(in); in.close(); host = properties.getProperty(HOST_PROPERTY); port = properties.getProperty(PORT_PROPERTY); participantRepository = properties.getProperty(PARTICIPANT_REPO); // if (participantRepository == null) { // participantRepository = "."; // } if (properties.getProperty("tcpmon_enable").equals("true")) { debug = "true"; } participantAxis2Xml = properties.getProperty(PARTICIPANT_AXIS2_CONF); // if (participantAxis2Xml == null) { // participantAxis2Xml = "axis2.xml"; // } kandulaListenerRepository = properties.getProperty(KANDULA_LISTENER_REPO); // if (kandulaListenerRepository == null) { // kandulaListenerRepository = "."; // } kandulaListenerAxis2Xml = properties.getProperty(KANDULA_LISTENER_AXIS2XML); // if (kandulaListenerAxis2Xml == null) { // kandulaListenerRepository += "/axis2.xml"; // } coordinatorAxis2Conf = properties.getProperty(COORDINATOR_AXIS2XML); // if (coordinatorAxis2Conf == null) { // coordinatorAxis2Conf = "axis2.xml"; // } coordinatorRepo = properties.getProperty(COORDINATOR_REPOSITORY); // if (coordinatorRepo == null) { // coordinatorAxis2Conf = "."; // } kandulaListenerPort = properties.getProperty(LISTENER_PORT); if (kandulaListenerPort == null) { kandulaListenerPort = "5050"; } if (port == null) { port = "8080"; } if (host == null) { host = InetAddress.getLocalHost().getHostAddress(); } location = "http://" + host + ":" + port; System.out.println(location); } catch (Exception e) { if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new RuntimeException(e); } } public static KandulaConfiguration getInstance() { if (instance == null) instance = new KandulaConfiguration(); return instance; } /** * @return a ConfigurationContext according to the coordinator Axis2.xml & repository configured. * @throws AbstractKandulaException */ public ConfigurationContext getPariticipantAxis2ConfigurationContext() throws AbstractKandulaException { if (participantConfigurationContext == null) { try { if (coordinatorAxis2Conf != null && coordinatorAxis2Conf != "") { participantConfigurationContext = ConfigurationContextFactory .createConfigurationContextFromFileSystem(participantRepository, participantAxis2Xml); } } catch (DeploymentException e) { throw new KandulaGeneralException(e); } catch (AxisFault e1) { throw new KandulaGeneralException(e1); } } return participantConfigurationContext; } public String getParticipantRepository() { return participantRepository; } public String getParticipantAxis2Conf() { return participantAxis2Xml; } public ConfigurationContext getCoordinatorAxis2ConfigurationContext() throws AbstractKandulaException { if (coordinatorConfigurationContext == null) { try { if (coordinatorAxis2Conf != null && coordinatorAxis2Conf != "") { coordinatorConfigurationContext = ConfigurationContextFactory .createConfigurationContextFromFileSystem(coordinatorRepo, coordinatorAxis2Conf); } } catch (DeploymentException e) { throw new KandulaGeneralException(e); } catch (AxisFault e1) { throw new KandulaGeneralException(e1); } } return coordinatorConfigurationContext; } public String getCoordinatorRepo() { return coordinatorRepo; } public String getCoordinatorAxis2Conf() { return coordinatorAxis2Conf; } public String getKadulaListenerPort() { return kandulaListenerPort; } public String getKadulaListenerPortForEPR() { if (debug.equals("true")) return (Integer.parseInt(kandulaListenerPort) + 1) + ""; else return kandulaListenerPort; } /** * @return Returns the kandulaListenerRepository. */ public String getKandulaListenerRepository() { return kandulaListenerRepository; } public String getKandulaListenerAxis2Xml() { return kandulaListenerAxis2Xml; } public String getLocationForEPR() { return location; } // public static EndpointReferenceFactory getInstance() { // if (instance == null) // instance = new EndpointReferenceFactory(); // return instance; // } }
/* * Copyright (c) 2011 Michigan State University - Facility for Rare Isotope Beams */ package edu.msu.nscl.olog.boundry; import edu.msu.nscl.olog.OlogException; import edu.msu.nscl.olog.ResourceBinder; import edu.msu.nscl.olog.control.OlogImpl; import edu.msu.nscl.olog.UserManager; import edu.msu.nscl.olog.control.PerformanceInterceptor; import edu.msu.nscl.olog.entity.XmlAttachment; import edu.msu.nscl.olog.entity.XmlAttachments; import java.io.*; import java.security.NoSuchAlgorithmException; import java.util.logging.Logger; import javax.inject.Inject; import javax.interceptor.Interceptors; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.*; import javax.ws.rs.core.Response.Status; import org.glassfish.jersey.media.multipart.FormDataBodyPart; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; /** * Top level Jersey HTTP methods for the .../attachments URL * * @author Eric Berryman */ @Path("/attachments/") public class AttachmentResource { @Context private UriInfo uriInfo; @Context private SecurityContext securityContext; @Inject ResourceBinder rb; @Inject OlogImpl cm; private Logger audit = Logger.getLogger(this.getClass().getPackage().getName() + ".audit"); private Logger log = Logger.getLogger(this.getClass().getName()); /** Creates a new instance of AttachmentsResource */ public AttachmentResource() { } /** * GET method for retrieving attachments identified by <tt>id</tt>. * * @param logId log id * @return HTTP Response */ @GET @Path("{logId}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Interceptors(PerformanceInterceptor.class) public Response read(@PathParam("logId") Long logId) throws UnsupportedEncodingException, NoSuchAlgorithmException { String user = securityContext.getUserPrincipal() != null ? securityContext.getUserPrincipal().getName() : ""; XmlAttachments result; try { result = cm.findAttachmentsById(logId); Response r = Response.ok(result).build(); audit.info(user + "|" + uriInfo.getPath() + "|GET|OK|" + r.getStatus()); return r; } catch (OlogException e) { log.warning(user + "|" + uriInfo.getPath() + "|GET|ERROR|" + e.getResponseStatusCode() + "|cause=" + e); return e.toResponse(); } } /** * GET method for retrieving the list of attachments for a given log. * * @return */ @GET @Path("{logId}/{fileName}") @Interceptors(PerformanceInterceptor.class) public Response getFile(@PathParam("logId") Long logId, @PathParam("fileName") String fileName ) { String user = securityContext.getUserPrincipal() != null ? securityContext.getUserPrincipal().getName() : ""; edu.msu.nscl.olog.entity.Attachment result; try { String filePath = logId.toString(); result = cm.getAttachment(filePath, fileName); Response r; if (result == null) { r = Response.status(Response.Status.NOT_FOUND).build(); } else { r = Response.ok((Object)result.getContent()).type(result.getMimeType()).build(); } audit.info( user+"|" + uriInfo.getPath() + "|GET|OK|" + r.getStatus()); return r; } catch (OlogException e) { log.warning(user + "|" + uriInfo.getPath() + "|GET|ERROR|" + e.getResponseStatusCode() + "|cause=" + e); return e.toResponse(); } } /** * GET method for retrieving the list of attachments for a given log. * * @param logId * @param fileName * @return */ @GET @Path("{logId}/{fileName}:thumbnail") @Interceptors(PerformanceInterceptor.class) public Response getThumbnail(@PathParam("logId") Long logId, @PathParam("fileName") String fileName ) { String user = securityContext.getUserPrincipal() != null ? securityContext.getUserPrincipal().getName() : ""; edu.msu.nscl.olog.entity.Attachment result; try { String filePath = "thumbnails/"+logId.toString(); result = cm.getAttachment(filePath, fileName); Response r; if (result == null) { r = Response.status(Response.Status.NOT_FOUND).build(); } else { r = Response.ok((Object)result.getContent()).type(result.getMimeType()).build(); } audit.info( user+"|" + uriInfo.getPath() + "|GET|OK|" + r.getStatus()); return r; } catch (OlogException e) { log.warning(user + "|" + uriInfo.getPath() + "|GET|ERROR|" + e.getResponseStatusCode() + "|cause=" + e); return e.toResponse(); } } /** * POST method for adding a new Attachment to a log entry. * * @param req * @param headers * @param logId the id of the log entry that the property is being added to * @param uploadedInputStream * @param disposition * @param body * @return */ @POST @Path("{logId}") @Consumes(MediaType.MULTIPART_FORM_DATA) @Interceptors(PerformanceInterceptor.class) public Response addAttachment(@Context HttpServletRequest req, @Context HttpHeaders headers, @PathParam("logId") Long logId, @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition disposition, @FormDataParam("file") FormDataBodyPart body) { UserManager um = rb.getUserManager(); um.setUser(securityContext.getUserPrincipal(), securityContext.isUserInRole("Administrator")); um.setHostAddress(req.getHeader("X-Forwarded-For") == null ? req.getRemoteAddr() : req.getHeader("X-Forwarded-For")); edu.msu.nscl.olog.entity.Attachment attachment = new edu.msu.nscl.olog.entity.Attachment(); XmlAttachment result; try { if (!um.userHasAdminRole()) { cm.checkUserBelongsToGroupOfLog(um.getUserName(), logId); } if(disposition.getFileName().equalsIgnoreCase("blob")){ attachment.setFileName(body.getParent().getContentDisposition().getFileName()); }else{ attachment.setFileName(disposition.getFileName()); } attachment.setMimeType(body.getMediaType()); attachment.setContent(uploadedInputStream); attachment.setEncoding(nonNull(body.getHeaders().getFirst("Content-Transfer-Encoding"))); result = cm.createAttachment(attachment, logId); Response r = Response.ok(result).build(); audit.info(um.getUserName() + "|" + uriInfo.getPath() + "|POST|OK|" + r.getStatus()); return r; } catch (OlogException e) { log.warning(um.getUserName() + "|" + uriInfo.getPath() + "|POST|ERROR|" + e.getResponseStatusCode() + "|cause=" + e); return e.toResponse(); } catch (UnsupportedEncodingException | NoSuchAlgorithmException e) { log.warning(um.getUserName() + "|" + uriInfo.getPath() + "|POST|ERROR|" + Status.BAD_REQUEST + "|cause=" + e); return new OlogException(Status.BAD_REQUEST,e.toString()).toResponse(); } } /** * PUT method for adding a new Attachment to a log entry. * * @param req * @param headers * @param fileName * @param logId * @param uploadedInputStream * @param disposition * @param body * @return */ @PUT @Path("{logId}/{fileName}") @Consumes(MediaType.MULTIPART_FORM_DATA) @Interceptors(PerformanceInterceptor.class) public Response addReplaceAttachment(@Context HttpServletRequest req, @Context HttpHeaders headers, @PathParam("fileName") String fileName, @PathParam("logId") Long logId, @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition disposition, @FormDataParam("file") FormDataBodyPart body) { UserManager um = rb.getUserManager(); um.setUser(securityContext.getUserPrincipal(), securityContext.isUserInRole("Administrator")); um.setHostAddress(req.getHeader("X-Forwarded-For") == null ? req.getRemoteAddr() : req.getHeader("X-Forwarded-For")); edu.msu.nscl.olog.entity.Attachment attachment = new edu.msu.nscl.olog.entity.Attachment(); try { if (!um.userHasAdminRole()) { cm.checkUserBelongsToGroupOfLog(um.getUserName(), logId); } //TODO: Check PathParam fileName? attachment.setFileName(disposition.getFileName()); attachment.setMimeType(body.getMediaType()); attachment.setContent(uploadedInputStream); //attachment.setFileSize(incommingAttachment.getContentDisposition().getParameter(null))); attachment.setEncoding(nonNull(body.getHeaders().getFirst("Content-Transfer-Encoding"))); //TODO: Should be destructive (replace) //cm.removeExistingAttachment(fileName,logId); cm.createAttachment(attachment, logId); String output = "File uploaded to : " + logId.toString()+"/"+disposition.getFileName(); Response r = Response.status(200).entity(output).build(); audit.info(um.getUserName() + "|" + uriInfo.getPath() + "|PUT|OK|" + r.getStatus() + " | " + output); return r; } catch (OlogException e) { log.warning(um.getUserName() + "|" + uriInfo.getPath() + "|PUT|ERROR|" + e.getResponseStatusCode() + "|cause=" + e); return e.toResponse(); } catch (UnsupportedEncodingException | NoSuchAlgorithmException e) { log.warning(um.getUserName() + "|" + uriInfo.getPath() + "|POST|ERROR|" + Status.BAD_REQUEST + "|cause=" + e); return new OlogException(Status.BAD_REQUEST,e.toString()).toResponse(); } } /** * DELETE method for removing an attachment from a log entry. * * @param String attachment being deleted * @param Long logId the id of the log entry that the property is being added to * @return */ @DELETE @Path("{logId}/{fileName}") @Interceptors(PerformanceInterceptor.class) public Response removeAttachment(@Context HttpServletRequest req, @Context HttpHeaders headers, @PathParam("fileName") String fileName, @PathParam("logId") Long logId) throws UnsupportedEncodingException, NoSuchAlgorithmException { UserManager um = rb.getUserManager(); um.setUser(securityContext.getUserPrincipal(), securityContext.isUserInRole("Administrator")); try { if (!um.userHasAdminRole()) { cm.checkUserBelongsToGroupOfLog(um.getUserName(), logId); cm.checkUserBelongsToGroup(um.getUserName(), cm.findLogById(logId)); } cm.removeAttachment(fileName,logId); Response r = Response.ok().build(); audit.info(um.getUserName() + "|" + uriInfo.getPath() + "|DELETE|OK|" + r.getStatus()); return r; } catch (OlogException e) { log.warning(um.getUserName() + "|" + uriInfo.getPath() + "|DELETE|ERROR|" + e.getResponseStatusCode() + "|cause=" + e); return e.toResponse(); } } /** * Return a not null string. * * @param s String * @return empty string if it is null otherwise the string passed in as * parameter. */ private static String nonNull(String s) { if (s == null) { return ""; } return s; } }
package com.htmlhifive.testexplorer.api; import static org.mockito.Mockito.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.htmlhifive.testexplorer.entity.Config; import com.htmlhifive.testexplorer.entity.ConfigRepository; import com.htmlhifive.testexplorer.entity.ProcessedImage; import com.htmlhifive.testexplorer.entity.ProcessedImageRepository; import com.htmlhifive.testexplorer.entity.Repositories; import com.htmlhifive.testexplorer.entity.RepositoryMockCreator; import com.htmlhifive.testexplorer.entity.Screenshot; import com.htmlhifive.testexplorer.entity.ScreenshotRepository; import com.htmlhifive.testexplorer.entity.TestEnvironment; import com.htmlhifive.testexplorer.entity.TestExecution; import com.htmlhifive.testexplorer.entity.TestExecutionRepository; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/spring/test-context.xml") public class ImageControllerTest { @Autowired private ImageController imageController; @Autowired private TestExecutionRepository testExecutionRepo; @Autowired private ScreenshotRepository screenshotRepo; @Autowired private ConfigRepository configRepo; @Autowired private ProcessedImageRepository processedImageRepo; private ArrayList<Config> configs; private ArrayList<Screenshot> screenshots; private ArrayList<TestExecution> testExecutions; private ArrayList<TestEnvironment> testEnvironments; /** * Initialize some mock objects for testing. This method is called before each test method. */ @Before public void initializeDefaultMockObjects() { RepositoryMockCreator r = new RepositoryMockCreator(new Repositories(configRepo, processedImageRepo, screenshotRepo, testExecutionRepo)); configs = r.getConfigs(); screenshots = r.getScreenshots(); new ArrayList<ProcessedImage>(); testExecutions = r.getTestExecutions(); testEnvironments = r.getTestEnvironments(); } @Test public void testGetImageNotFound() { HttpServletResponse response = mock(HttpServletResponse.class); this.imageController.getImage(-1, response); verify(response).setStatus(HttpServletResponse.SC_NOT_FOUND); } @Test public void testGetImageFileError() { HttpServletResponse response = mock(HttpServletResponse.class); this.imageController.getImage(0, response); verify(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void testGetImageOk() throws IOException { HttpServletResponse response = mock(HttpServletResponse.class); ImageController spy = spy(this.imageController); spy.imageFileUtil = spy(spy.imageFileUtil); Screenshot sc = screenshotRepo.findOne(0); doReturn(new File("src/test/resources/images/edge_detector_0.png")). when(spy.imageFileUtil).getFile(sc); when(response.getOutputStream()).thenReturn(mock(ServletOutputStream.class)); spy.getImage(0, response); verify(response).setContentType("image/png"); } @Test public void testGetDiffImageNotFoundSource() { HttpServletResponse response = mock(HttpServletResponse.class); this.imageController.getDiffImage(-1, 0, response); verify(response).setStatus(HttpServletResponse.SC_NOT_FOUND); } @Test public void testGetDiffImageNotFoundTarget() { HttpServletResponse response = mock(HttpServletResponse.class); this.imageController.getDiffImage(0, -1, response);; verify(response).setStatus(HttpServletResponse.SC_NOT_FOUND); } @Test public void testGetDiffImageFileError() { HttpServletResponse response = mock(HttpServletResponse.class); this.imageController.getDiffImage(0, 1, response); verify(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void testGetDiffImageOk() throws IOException { HttpServletResponse response = mock(HttpServletResponse.class); ImageController spy = spy(this.imageController); spy.imageFileUtil = spy(spy.imageFileUtil); Screenshot sc = screenshotRepo.findOne(0); doReturn(new File("src/test/resources/images/edge_detector_0.png")). when(spy.imageFileUtil).getFile(sc); when(response.getOutputStream()).thenReturn(mock(ServletOutputStream.class)); spy.getDiffImage(0, 0, response); verify(response).setContentType("image/png"); } @Test public void testGetDiffImageOkDifferent() throws IOException { HttpServletResponse response = mock(HttpServletResponse.class); ImageController spy = spy(this.imageController); spy.imageFileUtil = spy(spy.imageFileUtil); Screenshot sc0 = screenshotRepo.findOne(0); doReturn(new File("src/test/resources/images/edge_detector_0.png")). when(spy.imageFileUtil).getFile(sc0); Screenshot sc1 = screenshotRepo.findOne(1); doReturn(new File("src/test/resources/images/edge_detector_0_edge.png")). when(spy.imageFileUtil).getFile(sc1); when(response.getOutputStream()).thenReturn(mock(ServletOutputStream.class)); spy.getDiffImage(0, 1, response); verify(response).setContentType("image/png"); } @Test public void testGetProcessedNotFound() { HttpServletResponse response = mock(HttpServletResponse.class); HashMap<String,String> params = new HashMap<String, String>(); params.put("id", "-1"); params.put("algorithm", "edge"); params.put("colorIndex", "-1"); this.imageController.getProcessed(-1, "edge", params, response); verify(response).setStatus(HttpServletResponse.SC_NOT_FOUND); } @Test public void testGetProcessedUnknownMethod() { HttpServletResponse response = mock(HttpServletResponse.class); HashMap<String,String> params = new HashMap<String, String>(); params.put("id", "-1"); params.put("algorithm", "aaaaaa"); params.put("colorIndex", "-1"); this.imageController.getProcessed(-1, "aaaaaa", params, response); verify(response).setStatus(HttpServletResponse.SC_BAD_REQUEST); } @Test public void testGetProcessedFileError() { HttpServletResponse response = mock(HttpServletResponse.class); HashMap<String,String> params = new HashMap<String, String>(); params.put("id", "0"); params.put("algorithm", "edge"); params.put("colorIndex", "-1"); this.imageController.getProcessed(0, "edge", params, response); verify(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void testGetProcessedEdgeNoColorIndex() throws IOException { HttpServletResponse response = mock(HttpServletResponse.class); HashMap<String,String> params = new HashMap<String, String>(); params.put("id", "0"); params.put("algorithm", "edge"); ImageController spy = spy(this.imageController); spy.imageFileUtil = spy(spy.imageFileUtil); Screenshot sc = screenshotRepo.findOne(0); doReturn(new File("src/test/resources/images/edge_detector_0.png")). when(spy.imageFileUtil).getFile(sc); when(response.getOutputStream()).thenReturn(mock(ServletOutputStream.class)); spy.getProcessed(0, "edge", params, response); verify(response).setContentType("image/png"); } @Test public void testGetProcessedEdgeColorIndex0() throws IOException { HttpServletResponse response = mock(HttpServletResponse.class); HashMap<String,String> params = new HashMap<String, String>(); params.put("id", "0"); params.put("algorithm", "edge"); params.put("colorIndex", "0"); ImageController spy = spy(this.imageController); spy.imageFileUtil = spy(spy.imageFileUtil); Screenshot sc = screenshotRepo.findOne(0); doReturn(new File("src/test/resources/images/edge_detector_0.png")). when(spy.imageFileUtil).getFile(sc); when(response.getOutputStream()).thenReturn(mock(ServletOutputStream.class)); spy.getProcessed(0, "edge", params, response); verify(response).setContentType("image/png"); } @Test public void testGetProcessedEdgeColorIndex1() throws IOException { HttpServletResponse response = mock(HttpServletResponse.class); HashMap<String,String> params = new HashMap<String, String>(); params.put("id", "0"); params.put("algorithm", "edge"); params.put("colorIndex", "1"); ImageController spy = spy(this.imageController); spy.imageFileUtil = spy(spy.imageFileUtil); Screenshot sc = screenshotRepo.findOne(0); doReturn(new File("src/test/resources/images/edge_detector_0.png")). when(spy.imageFileUtil).getFile(sc); when(response.getOutputStream()).thenReturn(mock(ServletOutputStream.class)); spy.getProcessed(0, "edge", params, response); verify(response).setContentType("image/png"); } @Test public void testGetProcessedEdgeColorIndexInvalid() throws IOException { HttpServletResponse response = mock(HttpServletResponse.class); HashMap<String,String> params = new HashMap<String, String>(); params.put("id", "0"); params.put("algorithm", "edge"); params.put("colorIndex", "invalid"); ImageController spy = spy(this.imageController); spy.imageFileUtil = spy(spy.imageFileUtil); Screenshot sc = screenshotRepo.findOne(0); doReturn(new File("src/test/resources/images/edge_detector_0.png")). when(spy.imageFileUtil).getFile(sc); when(response.getOutputStream()).thenReturn(mock(ServletOutputStream.class)); spy.getProcessed(0, "edge", params, response); verify(response).setContentType("image/png"); } @Test public void testGetDiffImageFileExists() throws IOException { HttpServletResponse response = mock(HttpServletResponse.class); ImageController spy = spy(this.imageController); spy.imageFileUtil = spy(spy.imageFileUtil); doReturn("src/test/resources/images/edge_detector_0.png"). when(spy.imageFileUtil).getAbsoluteFilePath(any(String.class)); when(response.getOutputStream()).thenReturn(mock(ServletOutputStream.class)); spy.getDiffImage(0, 0, response); verify(response).setContentType("image/png"); } @Test public void testGetDiffImageFileDirectory() throws IOException { HttpServletResponse response = mock(HttpServletResponse.class); ImageController spy = spy(this.imageController); spy.imageFileUtil = spy(spy.imageFileUtil); doReturn("src/test/resources/images/"). when(spy.imageFileUtil).getAbsoluteFilePath(any(String.class)); when(response.getOutputStream()).thenReturn(mock(ServletOutputStream.class)); spy.getDiffImage(0, 0, response); verify(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test @After public void testCleanup() throws InterruptedException { /* must be ok to call multiple times*/ this.imageController.destory(); this.imageController.destory(); this.imageController.destory(); } }
/* * Copyright Debezium Authors. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package io.debezium.connector.mysql; import java.util.Map; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.connect.data.SchemaBuilder; import org.apache.kafka.connect.data.Struct; import org.apache.kafka.connect.errors.ConnectException; import io.debezium.annotation.NotThreadSafe; import io.debezium.util.Collect; /** * Information about the source of information, which includes the position in the source binary log we have previously processed. * <p> * The {@link #partition() source partition} information describes the database whose log is being consumed. Typically, the * database is identified by the host address port number of the MySQL server and the name of the database. Here's a JSON-like * representation of an example database: * * <pre> * { * "db" : "myDatabase" * } * </pre> * * <p> * The {@link #offset() source offset} information describes how much of the database's binary log the source the change detector * has processed. Here's a JSON-like representation of an example: * * <pre> * { * "file" = "mysql-bin.000003", * "pos" = 105586, * "row" = 0 * } * </pre> * * @author Randall Hauch */ @NotThreadSafe final class SourceInfo { public static final String SERVER_ID_KEY = "server-id"; public static final String SERVER_NAME_KEY = "name"; public static final String SERVER_PARTITION_KEY = "server"; public static final String BINLOG_FILENAME_OFFSET_KEY = "file"; public static final String BINLOG_POSITION_OFFSET_KEY = "pos"; public static final String BINLOG_EVENT_ROW_NUMBER_OFFSET_KEY = "row"; public static final String BINLOG_EVENT_TIMESTAMP_KEY = "ts"; /** * A {@link Schema} definition for a {@link Struct} used to store the {@link #partition()} and {@link #offset()} information. */ public static final Schema SCHEMA = SchemaBuilder.struct() .name("io.debezium.connector.mysql.Source") .field(SERVER_NAME_KEY, Schema.STRING_SCHEMA) .field(SERVER_ID_KEY, Schema.INT64_SCHEMA) .field(BINLOG_EVENT_TIMESTAMP_KEY, Schema.INT64_SCHEMA) .field(BINLOG_FILENAME_OFFSET_KEY, Schema.STRING_SCHEMA) .field(BINLOG_POSITION_OFFSET_KEY, Schema.INT64_SCHEMA) .field(BINLOG_EVENT_ROW_NUMBER_OFFSET_KEY, Schema.INT32_SCHEMA) .build(); private String binlogFilename; private long binlogPosition = 4; private int eventRowNumber = 0; private String serverName; private long serverId = 0; private long binlogTs = 0; private Map<String, String> sourcePartition; public SourceInfo() { } /** * Set the database identifier. This is typically called once upon initialization. * * @param logicalId the logical identifier for the database; may not be null */ public void setServerName(String logicalId) { this.serverName = logicalId; sourcePartition = Collect.hashMapOf(SERVER_PARTITION_KEY, serverName); } /** * Get the Kafka Connect detail about the source "partition", which describes the portion of the source that we are * consuming. Since we're reading the binary log for a single database, the source partition specifies the * {@link #setServerName(String) database server}. * <p> * The resulting map is mutable for efficiency reasons (this information rarely changes), but should not be mutated. * * @return the source partition information; never null */ public Map<String, String> partition() { return sourcePartition; } /** * Get the Kafka Connect detail about the source "offset", which describes the position within the source where we last * have last read. * * @return a copy of the current offset; never null */ public Map<String, ?> offset() { return Collect.hashMapOf(BINLOG_FILENAME_OFFSET_KEY, binlogFilename, BINLOG_POSITION_OFFSET_KEY, binlogPosition, BINLOG_EVENT_ROW_NUMBER_OFFSET_KEY, eventRowNumber); } /** * Get a {@link Schema} representation of the source {@link #partition()} and {@link #offset()} information. * * @return the source partition and offset {@link Schema}; never null * @see #struct() */ public Schema schema() { return SCHEMA; } /** * Get a {@link Struct} representation of the source {@link #partition()} and {@link #offset()} information. The Struct * complies with the {@link #SCHEMA} for the MySQL connector. * * @return the source partition and offset {@link Struct}; never null * @see #schema() */ public Struct struct() { assert serverName != null; Struct result = new Struct(SCHEMA); result.put(SERVER_NAME_KEY, serverName); result.put(SERVER_ID_KEY, serverId); result.put(BINLOG_FILENAME_OFFSET_KEY, binlogFilename); result.put(BINLOG_POSITION_OFFSET_KEY, binlogPosition); result.put(BINLOG_EVENT_ROW_NUMBER_OFFSET_KEY, eventRowNumber); result.put(BINLOG_EVENT_TIMESTAMP_KEY, binlogTs); return result; } /** * Set the current row number within a given event, and then get the Kafka Connect detail about the source "offset", which * describes the position within the source where we have last read. * * @param eventRowNumber the 0-based row number within the last event that was successfully processed * @return a copy of the current offset; never null */ public Map<String, ?> offset(int eventRowNumber) { setRowInEvent(eventRowNumber); return offset(); } /** * Set the name of the MySQL binary log file. * * @param binlogFilename the name of the binary log file; may not be null */ public void setBinlogFilename(String binlogFilename) { this.binlogFilename = binlogFilename; } /** * Set the position within the MySQL binary log file. * * @param binlogPosition the position within the binary log file */ public void setBinlogPosition(long binlogPosition) { this.binlogPosition = binlogPosition; } /** * Set the index of the row within the event appearing at the {@link #binlogPosition() position} within the * {@link #binlogFilename() binary log file}. * * @param rowNumber the 0-based row number */ public void setRowInEvent(int rowNumber) { this.eventRowNumber = rowNumber; } /** * Set the server ID as found within the MySQL binary log file. * * @param serverId the server ID found within the binary log file */ public void setBinlogServerId(long serverId) { this.serverId = serverId; } /** * Set the timestamp as found within the MySQL binary log file. * * @param timestamp the timestamp found within the binary log file */ public void setBinlogTimestamp(long timestamp) { this.binlogTs = timestamp; } /** * Set the source offset, as read from Kafka Connect. This method does nothing if the supplied map is null. * * @param sourceOffset the previously-recorded Kafka Connect source offset * @throws ConnectException if any offset parameter values are missing, invalid, or of the wrong type */ public void setOffset(Map<String, ?> sourceOffset) { if (sourceOffset != null) { // We have previously recorded an offset ... binlogFilename = (String) sourceOffset.get(BINLOG_FILENAME_OFFSET_KEY); if (binlogFilename == null) { throw new ConnectException("Source offset '" + BINLOG_FILENAME_OFFSET_KEY + "' parameter is missing"); } binlogPosition = longOffsetValue(sourceOffset, BINLOG_POSITION_OFFSET_KEY); eventRowNumber = (int) longOffsetValue(sourceOffset, BINLOG_EVENT_ROW_NUMBER_OFFSET_KEY); } } private long longOffsetValue(Map<String, ?> values, String key) { Object obj = values.get(key); if (obj == null) return 0; if (obj instanceof Number) return ((Number) obj).longValue(); try { return Long.parseLong(obj.toString()); } catch (NumberFormatException e) { throw new ConnectException("Source offset '" + key + "' parameter value " + obj + " could not be converted to a long"); } } /** * Get the name of the MySQL binary log file that has been processed. * * @return the name of the binary log file; null if it has not been {@link #setBinlogFilename(String) set} */ public String binlogFilename() { return binlogFilename; } /** * Get the position within the MySQL binary log file that has been processed. * * @return the position within the binary log file; null if it has not been {@link #setBinlogPosition(long) set} */ public long binlogPosition() { return binlogPosition; } /** * Get the row within the event at the {@link #binlogPosition() position} within the {@link #binlogFilename() binary log file} * . * * @return the 0-based row number */ public int eventRowNumber() { return eventRowNumber; } /** * Get the logical identifier of the database that is the source of the events. * @return the database name; null if it has not been {@link #setServerName(String) set} */ public String serverName() { return serverName; } }
/* * Copyright 2012-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cedac.security.oauth2.provider.client; import com.lordofthejars.nosqlunit.annotation.UsingDataSet; import com.lordofthejars.nosqlunit.mongodb.InMemoryMongoDb; import com.lordofthejars.nosqlunit.mongodb.MongoDbRule; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.Mongo; import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.provider.ClientAlreadyExistsException; import org.springframework.security.oauth2.provider.ClientDetails; import org.springframework.security.oauth2.provider.NoSuchClientException; import org.springframework.security.oauth2.provider.client.BaseClientDetails; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import static com.lordofthejars.nosqlunit.mongodb.InMemoryMongoDb.InMemoryMongoRuleBuilder.newInMemoryMongoDbRule; import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * @author mauro.franceschini * @since 1.0.0 */ @UsingDataSet public class MongoClientDetailsServiceTests { @ClassRule public static InMemoryMongoDb inMemoryMongoDb = newInMemoryMongoDbRule().targetPath("target/test-db").build(); @Rule public MongoDbRule embeddedMongoDbRule = newMongoDbRule().defaultEmbeddedMongoDb("client_details"); private MongoClientDetailsService fixture; private DBCollection collection; @Before public void setUp() throws Exception { Mongo mongo = embeddedMongoDbRule.getDatabaseOperation().connectionManager(); collection = mongo.getDB("client_details").getCollection("client_details"); fixture = new MongoClientDetailsService(mongo, "client_details"); fixture.afterPropertiesSet(); } @Test(expected = NoSuchClientException.class) public void testLoadingClientForNonExistingClientId() { fixture.loadClientByClientId("nonExistingClientId"); } @Test public void testLoadingClientIdWithNoDetails() { collection.insert(new BasicDBObject("clientId", "clientIdWithNoDetails")); ClientDetails clientDetails = fixture.loadClientByClientId("clientIdWithNoDetails"); assertEquals("clientIdWithNoDetails", clientDetails.getClientId()); assertFalse(clientDetails.isSecretRequired()); assertNull(clientDetails.getClientSecret()); assertFalse(clientDetails.isScoped()); assertEquals(0, clientDetails.getScope().size()); assertEquals(2, clientDetails.getAuthorizedGrantTypes().size()); assertNull(clientDetails.getRegisteredRedirectUri()); assertEquals(0, clientDetails.getAuthorities().size()); assertEquals(null, clientDetails.getAccessTokenValiditySeconds()); assertEquals(null, clientDetails.getAccessTokenValiditySeconds()); } @Test public void testLoadingClientIdWithAdditionalInformation() { collection.insert(new BasicDBObject("clientId", "clientIdWithAddInfo") .append("additionalInformation", new BasicDBObject("foo", "bar"))); ClientDetails clientDetails = fixture.loadClientByClientId("clientIdWithAddInfo"); assertEquals("clientIdWithAddInfo", clientDetails.getClientId()); assertEquals(Collections.singletonMap("foo", "bar"), clientDetails.getAdditionalInformation()); } @Test public void testLoadingClientIdWithSingleDetails() { collection.insert(new BasicDBObject("clientId", "clientIdWithSingleDetails").append("clientSecret", "mySecret") .append("resourceIds", Arrays.asList("myResource")).append("scope", Arrays.asList("myScope")) .append("authorizedGrantTypes", Arrays.asList("myAuthorizedGrantType")) .append("registeredRedirectUris", Arrays.asList("myRedirectUri")) .append("authorities", Arrays.asList("myAuthority")).append("accessTokenValidity", 100) .append("refreshTokenValidity", 200).append("autoapprove", "true")); ClientDetails clientDetails = fixture.loadClientByClientId("clientIdWithSingleDetails"); assertEquals("clientIdWithSingleDetails", clientDetails.getClientId()); assertTrue(clientDetails.isSecretRequired()); assertEquals("mySecret", clientDetails.getClientSecret()); assertTrue(clientDetails.isScoped()); assertEquals(1, clientDetails.getScope().size()); assertEquals("myScope", clientDetails.getScope().iterator().next()); assertEquals(1, clientDetails.getResourceIds().size()); assertEquals("myResource", clientDetails.getResourceIds().iterator().next()); assertEquals(1, clientDetails.getAuthorizedGrantTypes().size()); assertEquals("myAuthorizedGrantType", clientDetails.getAuthorizedGrantTypes().iterator().next()); assertEquals("myRedirectUri", clientDetails.getRegisteredRedirectUri().iterator().next()); assertEquals(1, clientDetails.getAuthorities().size()); assertEquals("myAuthority", clientDetails.getAuthorities().iterator().next().getAuthority()); assertEquals(new Integer(100), clientDetails.getAccessTokenValiditySeconds()); assertEquals(new Integer(200), clientDetails.getRefreshTokenValiditySeconds()); } @Test public void testLoadingClientIdWithMultipleDetails() { collection .insert(new BasicDBObject("clientId", "clientIdWithMultipleDetails").append("clientSecret", "mySecret") .append("resourceIds", Arrays.asList("myResource1", "myResource2")) .append("scope", Arrays.asList("myScope1", "myScope2")).append("authorizedGrantTypes", Arrays.asList("myAuthorizedGrantType1", "myAuthorizedGrantType2")) .append("registeredRedirectUris", Arrays.asList("myRedirectUri1", "myRedirectUri2")) .append("authorities", Arrays.asList("myAuthority1", "myAuthority2")) .append("accessTokenValidity", 100).append("refreshTokenValidity", 200) .append("autoapprove", Arrays.asList("read", "write"))); ClientDetails clientDetails = fixture.loadClientByClientId("clientIdWithMultipleDetails"); assertEquals("clientIdWithMultipleDetails", clientDetails.getClientId()); assertTrue(clientDetails.isSecretRequired()); assertEquals("mySecret", clientDetails.getClientSecret()); assertTrue(clientDetails.isScoped()); assertEquals(2, clientDetails.getResourceIds().size()); Iterator<String> resourceIds = clientDetails.getResourceIds().iterator(); assertEquals("myResource1", resourceIds.next()); assertEquals("myResource2", resourceIds.next()); assertEquals(2, clientDetails.getScope().size()); Iterator<String> scope = clientDetails.getScope().iterator(); assertEquals("myScope1", scope.next()); assertEquals("myScope2", scope.next()); assertEquals(2, clientDetails.getAuthorizedGrantTypes().size()); Iterator<String> grantTypes = clientDetails.getAuthorizedGrantTypes().iterator(); assertEquals("myAuthorizedGrantType1", grantTypes.next()); assertEquals("myAuthorizedGrantType2", grantTypes.next()); assertEquals(2, clientDetails.getRegisteredRedirectUri().size()); Iterator<String> redirectUris = clientDetails.getRegisteredRedirectUri().iterator(); assertEquals("myRedirectUri1", redirectUris.next()); assertEquals("myRedirectUri2", redirectUris.next()); assertEquals(2, clientDetails.getAuthorities().size()); Iterator<GrantedAuthority> authorities = clientDetails.getAuthorities().iterator(); assertEquals("myAuthority1", authorities.next().getAuthority()); assertEquals("myAuthority2", authorities.next().getAuthority()); assertEquals(new Integer(100), clientDetails.getAccessTokenValiditySeconds()); assertEquals(new Integer(200), clientDetails.getRefreshTokenValiditySeconds()); assertTrue(clientDetails.isAutoApprove("read")); } @Test public void testAddClientWithNoDetails() { BaseClientDetails clientDetails = new BaseClientDetails(); clientDetails.setClientId("addedClientIdWithNoDetails"); fixture.addClientDetails(clientDetails); DBObject map = collection.findOne(new BasicDBObject("clientId", "addedClientIdWithNoDetails")); assertEquals("addedClientIdWithNoDetails", map.get("clientId")); assertFalse(map.containsField("clientSecret")); } @Test(expected = ClientAlreadyExistsException.class) public void testInsertDuplicateClient() { BaseClientDetails clientDetails = new BaseClientDetails(); clientDetails.setClientId("duplicateClientIdWithNoDetails"); fixture.addClientDetails(clientDetails); fixture.addClientDetails(clientDetails); } @Test public void testUpdateClientSecret() { BaseClientDetails clientDetails = new BaseClientDetails(); clientDetails.setClientId("newClientIdWithNoDetails"); fixture.setPasswordEncoder(new PasswordEncoder() { public boolean matches(CharSequence rawPassword, String encodedPassword) { return true; } public String encode(CharSequence rawPassword) { return "BAR"; } }); fixture.addClientDetails(clientDetails); fixture.updateClientSecret(clientDetails.getClientId(), "foo"); DBObject map = collection.findOne(new BasicDBObject("clientId", "newClientIdWithNoDetails")); assertEquals("newClientIdWithNoDetails", map.get("clientId")); assertTrue(map.containsField("clientSecret")); assertEquals("BAR", map.get("clientSecret")); } @Test public void testUpdateClientRedirectURI() { BaseClientDetails clientDetails = new BaseClientDetails(); clientDetails.setClientId("newClientIdWithNoDetails"); fixture.addClientDetails(clientDetails); String[] redirectURI = { "http://localhost:8080", "http://localhost:9090" }; clientDetails.setRegisteredRedirectUri(new HashSet<String>(Arrays.asList(redirectURI))); fixture.updateClientDetails(clientDetails); DBObject map = collection.findOne(new BasicDBObject("clientId", "newClientIdWithNoDetails")); assertEquals("newClientIdWithNoDetails", map.get("clientId")); assertTrue(map.containsField("registeredRedirectUris")); assertEquals(new HashSet<String>(Arrays.asList("http://localhost:8080", "http://localhost:9090")), map.get("registeredRedirectUris")); } @Test(expected = NoSuchClientException.class) public void testUpdateNonExistentClient() { BaseClientDetails clientDetails = new BaseClientDetails(); clientDetails.setClientId("nosuchClientIdWithNoDetails"); fixture.updateClientDetails(clientDetails); } @Test public void testRemoveClient() { BaseClientDetails clientDetails = new BaseClientDetails(); clientDetails.setClientId("deletedClientIdWithNoDetails"); fixture.addClientDetails(clientDetails); fixture.removeClientDetails(clientDetails.getClientId()); long count = collection.count(new BasicDBObject("clientId", "deletedClientIdWithNoDetails")); assertEquals(0, count); } @Test(expected = NoSuchClientException.class) public void testRemoveNonExistentClient() { BaseClientDetails clientDetails = new BaseClientDetails(); clientDetails.setClientId("nosuchClientIdWithNoDetails"); fixture.removeClientDetails(clientDetails.getClientId()); } @Test public void testFindClients() { BaseClientDetails clientDetails = new BaseClientDetails(); clientDetails.setClientId("aclient"); fixture.addClientDetails(clientDetails); int count = fixture.listClientDetails().size(); assertEquals(1, count); } }
/** * Copyright 2014 Netflix, 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 rx.internal.operators; import static org.junit.Assert.*; import java.util.*; import java.util.concurrent.TimeUnit; import org.junit.*; import rx.*; import rx.Observable; import rx.Observer; import rx.functions.*; import rx.observers.TestSubscriber; import rx.schedulers.TestScheduler; import rx.subjects.PublishSubject; public class OperatorWindowWithStartEndObservableTest { private TestScheduler scheduler; private Scheduler.Worker innerScheduler; @Before public void before() { scheduler = new TestScheduler(); innerScheduler = scheduler.createWorker(); } @Test public void testObservableBasedOpenerAndCloser() { final List<String> list = new ArrayList<String>(); final List<List<String>> lists = new ArrayList<List<String>>(); Observable<String> source = Observable.unsafeCreate(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> observer) { push(observer, "one", 10); push(observer, "two", 60); push(observer, "three", 110); push(observer, "four", 160); push(observer, "five", 210); complete(observer, 500); } }); Observable<Object> openings = Observable.unsafeCreate(new Observable.OnSubscribe<Object>() { @Override public void call(Subscriber<? super Object> observer) { push(observer, new Object(), 50); push(observer, new Object(), 200); complete(observer, 250); } }); Func1<Object, Observable<Object>> closer = new Func1<Object, Observable<Object>>() { @Override public Observable<Object> call(Object opening) { return Observable.unsafeCreate(new Observable.OnSubscribe<Object>() { @Override public void call(Subscriber<? super Object> observer) { push(observer, new Object(), 100); complete(observer, 101); } }); } }; Observable<Observable<String>> windowed = source.window(openings, closer); windowed.subscribe(observeWindow(list, lists)); scheduler.advanceTimeTo(500, TimeUnit.MILLISECONDS); assertEquals(2, lists.size()); assertEquals(lists.get(0), list("two", "three")); assertEquals(lists.get(1), list("five")); } @Test public void testObservableBasedCloser() { final List<String> list = new ArrayList<String>(); final List<List<String>> lists = new ArrayList<List<String>>(); Observable<String> source = Observable.unsafeCreate(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> observer) { push(observer, "one", 10); push(observer, "two", 60); push(observer, "three", 110); push(observer, "four", 160); push(observer, "five", 210); complete(observer, 250); } }); Func0<Observable<Object>> closer = new Func0<Observable<Object>>() { int calls; @Override public Observable<Object> call() { return Observable.unsafeCreate(new Observable.OnSubscribe<Object>() { @Override public void call(Subscriber<? super Object> observer) { int c = calls++; if (c == 0) { push(observer, new Object(), 100); } else if (c == 1) { push(observer, new Object(), 100); } else { complete(observer, 101); } } }); } }; Observable<Observable<String>> windowed = source.window(closer); windowed.subscribe(observeWindow(list, lists)); scheduler.advanceTimeTo(500, TimeUnit.MILLISECONDS); assertEquals(3, lists.size()); assertEquals(lists.get(0), list("one", "two")); assertEquals(lists.get(1), list("three", "four")); assertEquals(lists.get(2), list("five")); } private List<String> list(String... args) { List<String> list = new ArrayList<String>(); for (String arg : args) { list.add(arg); } return list; } private <T> void push(final Observer<T> observer, final T value, int delay) { innerScheduler.schedule(new Action0() { @Override public void call() { observer.onNext(value); } }, delay, TimeUnit.MILLISECONDS); } private void complete(final Observer<?> observer, int delay) { innerScheduler.schedule(new Action0() { @Override public void call() { observer.onCompleted(); } }, delay, TimeUnit.MILLISECONDS); } private Action1<Observable<String>> observeWindow(final List<String> list, final List<List<String>> lists) { return new Action1<Observable<String>>() { @Override public void call(Observable<String> stringObservable) { stringObservable.subscribe(new Observer<String>() { @Override public void onCompleted() { lists.add(new ArrayList<String>(list)); list.clear(); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onNext(String args) { list.add(args); } }); } }; } @Test public void testNoUnsubscribeAndNoLeak() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> open = PublishSubject.create(); final PublishSubject<Integer> close = PublishSubject.create(); TestSubscriber<Observable<Integer>> ts = TestSubscriber.create(); source.window(open, new Func1<Integer, Observable<Integer>>() { @Override public Observable<Integer> call(Integer t) { return close; } }).unsafeSubscribe(ts); open.onNext(1); source.onNext(1); assertTrue(open.hasObservers()); assertTrue(close.hasObservers()); close.onNext(1); assertFalse(close.hasObservers()); source.onCompleted(); ts.assertCompleted(); ts.assertNoErrors(); ts.assertValueCount(1); assertFalse(ts.isUnsubscribed()); assertFalse(open.hasObservers()); assertFalse(close.hasObservers()); } @Test public void testUnsubscribeAll() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> open = PublishSubject.create(); final PublishSubject<Integer> close = PublishSubject.create(); TestSubscriber<Observable<Integer>> ts = TestSubscriber.create(); source.window(open, new Func1<Integer, Observable<Integer>>() { @Override public Observable<Integer> call(Integer t) { return close; } }).unsafeSubscribe(ts); open.onNext(1); assertTrue(open.hasObservers()); assertTrue(close.hasObservers()); ts.unsubscribe(); assertFalse(open.hasObservers()); assertFalse(close.hasObservers()); } }
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.rules.android; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.ResourceSet; import com.google.devtools.build.lib.analysis.AnalysisUtils; import com.google.devtools.build.lib.analysis.FileProvider; import com.google.devtools.build.lib.analysis.OutputGroupInfo; import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder; import com.google.devtools.build.lib.analysis.RuleContext; import com.google.devtools.build.lib.analysis.Runfiles; import com.google.devtools.build.lib.analysis.RunfilesProvider; import com.google.devtools.build.lib.analysis.TransitiveInfoCollection; import com.google.devtools.build.lib.analysis.TransitiveInfoProvider; import com.google.devtools.build.lib.analysis.actions.CustomCommandLine; import com.google.devtools.build.lib.analysis.actions.SpawnAction; import com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget; import com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget.Mode; import com.google.devtools.build.lib.analysis.test.InstrumentedFilesCollector.InstrumentationSpec; import com.google.devtools.build.lib.collect.IterablesChain; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.collect.nestedset.Order; import com.google.devtools.build.lib.packages.AttributeMap; import com.google.devtools.build.lib.packages.BuildType; import com.google.devtools.build.lib.packages.BuiltinProvider; import com.google.devtools.build.lib.packages.Info; import com.google.devtools.build.lib.packages.NativeProvider; import com.google.devtools.build.lib.packages.Rule; import com.google.devtools.build.lib.packages.RuleClass.ConfiguredTargetFactory.RuleErrorException; import com.google.devtools.build.lib.packages.TriState; import com.google.devtools.build.lib.rules.android.DataBinding.DataBindingContext; import com.google.devtools.build.lib.rules.android.ZipFilterBuilder.CheckHashMismatchMode; import com.google.devtools.build.lib.rules.cpp.CcLinkParams; import com.google.devtools.build.lib.rules.cpp.CcLinkingInfo; import com.google.devtools.build.lib.rules.java.ClasspathConfiguredFragment; import com.google.devtools.build.lib.rules.java.JavaCcLinkParamsProvider; import com.google.devtools.build.lib.rules.java.JavaCommon; import com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider; import com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider.ClasspathType; import com.google.devtools.build.lib.rules.java.JavaCompilationArtifacts; import com.google.devtools.build.lib.rules.java.JavaCompilationHelper; import com.google.devtools.build.lib.rules.java.JavaInfo; import com.google.devtools.build.lib.rules.java.JavaPluginInfoProvider; import com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider; import com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider.OutputJar; import com.google.devtools.build.lib.rules.java.JavaSemantics; import com.google.devtools.build.lib.rules.java.JavaSkylarkApiProvider; import com.google.devtools.build.lib.rules.java.JavaSourceJarsProvider; import com.google.devtools.build.lib.rules.java.JavaTargetAttributes; import com.google.devtools.build.lib.rules.java.JavaUtil; import com.google.devtools.build.lib.rules.java.proto.GeneratedExtensionRegistryProvider; import com.google.devtools.build.lib.syntax.Type; import com.google.devtools.build.lib.util.FileType; import com.google.devtools.build.lib.vfs.PathFragment; import java.util.Collection; import java.util.List; /** * A helper class for android rules. * * <p>Helps create the java compilation as well as handling the exporting of the java compilation * artifacts to the other rules. */ public class AndroidCommon { public static final InstrumentationSpec ANDROID_COLLECTION_SPEC = JavaCommon.JAVA_COLLECTION_SPEC.withDependencyAttributes( "deps", "data", "exports", "runtime_deps", "binary_under_test"); private static final ImmutableSet<String> TRANSITIVE_ATTRIBUTES = ImmutableSet.of("deps", "exports"); private static final ResourceSet DEX_RESOURCE_SET = ResourceSet.createWithRamCpuIo(4096.0, 5.0, 0.0); public static final <T extends TransitiveInfoProvider> Iterable<T> getTransitivePrerequisites( RuleContext ruleContext, Mode mode, final Class<T> classType) { IterablesChain.Builder<T> builder = IterablesChain.builder(); AttributeMap attributes = ruleContext.attributes(); for (String attr : TRANSITIVE_ATTRIBUTES) { if (attributes.has(attr, BuildType.LABEL_LIST)) { builder.add(ruleContext.getPrerequisites(attr, mode, classType)); } } return builder.build(); } public static final <T extends Info> Iterable<T> getTransitivePrerequisites( RuleContext ruleContext, Mode mode, NativeProvider<T> key) { IterablesChain.Builder<T> builder = IterablesChain.builder(); AttributeMap attributes = ruleContext.attributes(); for (String attr : TRANSITIVE_ATTRIBUTES) { if (attributes.has(attr, BuildType.LABEL_LIST)) { builder.add(ruleContext.getPrerequisites(attr, mode, key)); } } return builder.build(); } public static final <T extends Info> Iterable<T> getTransitivePrerequisites( RuleContext ruleContext, Mode mode, BuiltinProvider<T> key) { IterablesChain.Builder<T> builder = IterablesChain.builder(); AttributeMap attributes = ruleContext.attributes(); for (String attr : TRANSITIVE_ATTRIBUTES) { if (attributes.has(attr, BuildType.LABEL_LIST)) { builder.add(ruleContext.getPrerequisites(attr, mode, key)); } } return builder.build(); } private final RuleContext ruleContext; private final JavaCommon javaCommon; private final boolean asNeverLink; private NestedSet<Artifact> filesToBuild; private NestedSet<Artifact> transitiveNeverlinkLibraries = NestedSetBuilder.emptySet(Order.STABLE_ORDER); private JavaCompilationArgsProvider javaCompilationArgs = JavaCompilationArgsProvider.EMPTY; private NestedSet<Artifact> jarsProducedForRuntime; private Artifact classJar; private Artifact nativeHeaderOutput; private Artifact iJar; private Artifact srcJar; private Artifact genClassJar; private Artifact genSourceJar; private Artifact resourceSourceJar; private Artifact outputDepsProto; private GeneratedExtensionRegistryProvider generatedExtensionRegistryProvider; private final JavaSourceJarsProvider.Builder javaSourceJarsProviderBuilder = JavaSourceJarsProvider.builder(); private final JavaRuleOutputJarsProvider.Builder javaRuleOutputJarsProviderBuilder = JavaRuleOutputJarsProvider.builder(); private Artifact manifestProtoOutput; private AndroidIdlHelper idlHelper; public AndroidCommon(JavaCommon javaCommon) { this(javaCommon, JavaCommon.isNeverLink(javaCommon.getRuleContext())); } /** * Creates a new AndroidCommon. * * @param common the JavaCommon instance * @param asNeverLink Boolean to indicate if this rule should be treated as a compile time dep by * consuming rules. */ public AndroidCommon(JavaCommon common, boolean asNeverLink) { this.ruleContext = common.getRuleContext(); this.asNeverLink = asNeverLink; this.javaCommon = common; } /** * Collects the transitive neverlink dependencies. * * @param ruleContext the context of the rule neverlink deps are to be computed for * @param deps the targets to be treated as dependencies * @param runtimeJars the runtime jars produced by the rule (non-transitive) * @return a nested set of the neverlink deps. */ public static NestedSet<Artifact> collectTransitiveNeverlinkLibraries( RuleContext ruleContext, Iterable<? extends TransitiveInfoCollection> deps, ImmutableList<Artifact> runtimeJars) { NestedSetBuilder<Artifact> builder = NestedSetBuilder.naiveLinkOrder(); for (AndroidNeverLinkLibrariesProvider provider : AnalysisUtils.getProviders(deps, AndroidNeverLinkLibrariesProvider.class)) { builder.addTransitive(provider.getTransitiveNeverLinkLibraries()); } if (JavaCommon.isNeverLink(ruleContext)) { builder.addAll(runtimeJars); for (JavaCompilationArgsProvider provider : JavaInfo.getProvidersFromListOfTargets(JavaCompilationArgsProvider.class, deps)) { builder.addTransitive(provider.getRuntimeJars()); } } return builder.build(); } /** * Creates an action that converts {@code jarToDex} to a dex file. The output will be stored in * the {@link com.google.devtools.build.lib.actions.Artifact} {@code dxJar}. */ public static void createDexAction( RuleContext ruleContext, Artifact jarToDex, Artifact classesDex, List<String> dexOptions, boolean multidex, Artifact mainDexList) { CustomCommandLine.Builder commandLine = CustomCommandLine.builder(); commandLine.add("--dex"); // Multithreaded dex does not work when using --multi-dex. if (!multidex) { // Multithreaded dex tends to run faster, but only up to about 5 threads (at which point the // law of diminishing returns kicks in). This was determined experimentally, with 5-thread dex // performing about 25% faster than 1-thread dex. commandLine.add("--num-threads=5"); } commandLine.addAll(dexOptions); if (multidex) { commandLine.add("--multi-dex"); if (mainDexList != null) { commandLine.addPrefixedExecPath("--main-dex-list=", mainDexList); } } commandLine.addPrefixedExecPath("--output=", classesDex); commandLine.addExecPath(jarToDex); SpawnAction.Builder builder = new SpawnAction.Builder() .useDefaultShellEnvironment() .setExecutable(AndroidSdkProvider.fromRuleContext(ruleContext).getDx()) .addInput(jarToDex) .addOutput(classesDex) .setProgressMessage("Converting %s to dex format", jarToDex.getExecPathString()) .setMnemonic("AndroidDexer") .addCommandLine(commandLine.build()) .setResources(DEX_RESOURCE_SET); if (mainDexList != null) { builder.addInput(mainDexList); } ruleContext.registerAction(builder.build(ruleContext)); } public static AndroidIdeInfoProvider createAndroidIdeInfoProvider( RuleContext ruleContext, AndroidIdlHelper idlHelper, OutputJar resourceJar, Artifact aar, ResourceApk resourceApk, Artifact zipAlignedApk, Iterable<Artifact> apksUnderTest, NativeLibs nativeLibs) { AndroidIdeInfoProvider.Builder ideInfoProviderBuilder = new AndroidIdeInfoProvider.Builder() .setIdlClassJar(idlHelper.getIdlClassJar()) .setIdlSourceJar(idlHelper.getIdlSourceJar()) .setResourceJar(resourceJar) .setAar(aar) .setNativeLibs(nativeLibs.getMap()) .addIdlImportRoot(idlHelper.getIdlImportRoot()) .addIdlSrcs(idlHelper.getIdlSources()) .addIdlGeneratedJavaFiles(idlHelper.getIdlGeneratedJavaSources()) .addAllApksUnderTest(apksUnderTest); if (zipAlignedApk != null) { ideInfoProviderBuilder.setApk(zipAlignedApk); } // If the rule defines resources, put those in the IDE info. if (AndroidResources.definesAndroidResources(ruleContext.attributes())) { ideInfoProviderBuilder .setDefinesAndroidResources(true) // Sets the possibly merged manifest and the raw manifest. .setGeneratedManifest(resourceApk.getManifest()) .setManifest(ruleContext.getPrerequisiteArtifact("manifest", Mode.TARGET)) .setJavaPackage(getJavaPackage(ruleContext)) .setResourceApk(resourceApk.getArtifact()); } return ideInfoProviderBuilder.build(); } /** * Gets the Java package for the current target. * * @deprecated If no custom_package is specified, this method will derive the Java package from * the package path, even if that path is not a valid Java path. Use {@link * AndroidManifest#getAndroidPackage(RuleContext)} instead. */ @Deprecated public static String getJavaPackage(RuleContext ruleContext) { AttributeMap attributes = ruleContext.attributes(); if (attributes.isAttributeValueExplicitlySpecified("custom_package")) { return attributes.get("custom_package", Type.STRING); } return getDefaultJavaPackage(ruleContext.getRule()); } private static String getDefaultJavaPackage(Rule rule) { PathFragment nameFragment = rule.getPackage().getNameFragment(); String packageName = JavaUtil.getJavaFullClassname(nameFragment); if (packageName != null) { return packageName; } else { // This is a workaround for libraries that don't follow the standard Bazel package format return nameFragment.getPathString().replace('/', '.'); } } static PathFragment getSourceDirectoryRelativePathFromResource(Artifact resource) { PathFragment resourceDir = AndroidResources.findResourceDir(resource); if (resourceDir == null) { return null; } return trimTo(resource.getRootRelativePath(), resourceDir); } /** * Finds the rightmost occurrence of the needle and returns subfragment of the haystack from left * to the end of the occurrence inclusive of the needle. * * <pre> * `Example: * Given the haystack: * res/research/handwriting/res/values/strings.xml * And the needle: * res * Returns: * res/research/handwriting/res * </pre> */ static PathFragment trimTo(PathFragment haystack, PathFragment needle) { if (needle.equals(PathFragment.EMPTY_FRAGMENT)) { return haystack; } List<String> needleSegments = needle.getSegments(); // Compute the overlap offset for duplicated parts of the needle. int[] overlap = new int[needleSegments.size() + 1]; // Start overlap at -1, as it will cancel out the increment in the search. // See http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm for the // details. overlap[0] = -1; for (int i = 0, j = -1; i < needleSegments.size(); j++, i++, overlap[i] = j) { while (j >= 0 && !needleSegments.get(i).equals(needleSegments.get(j))) { // Walk the overlap until the bound is found. j = overlap[j]; } } // TODO(corysmith): reverse the search algorithm. // Keep the index of the found so that the rightmost index is taken. List<String> haystackSegments = haystack.getSegments(); int found = -1; for (int i = 0, j = 0; i < haystackSegments.size(); i++) { while (j >= 0 && !haystackSegments.get(i).equals(needleSegments.get(j))) { // Not matching, walk the needle index to attempt another match. j = overlap[j]; } j++; // Needle index is exhausted, so the needle must match. if (j == needleSegments.size()) { // Record the found index + 1 to be inclusive of the end index. found = i + 1; // Subtract one from the needle index to restart the search process j = j - 1; } } if (found != -1) { // Return the subsection of the haystack. return haystack.subFragment(0, found); } throw new IllegalArgumentException(String.format("%s was not found in %s", needle, haystack)); } public static NestedSetBuilder<Artifact> collectTransitiveNativeLibs(RuleContext ruleContext) { NestedSetBuilder<Artifact> transitiveNativeLibs = NestedSetBuilder.naiveLinkOrder(); Iterable<AndroidNativeLibsInfo> infos = getTransitivePrerequisites(ruleContext, Mode.TARGET, AndroidNativeLibsInfo.PROVIDER); for (AndroidNativeLibsInfo nativeLibsZipsInfo : infos) { transitiveNativeLibs.addTransitive(nativeLibsZipsInfo.getNativeLibs()); } return transitiveNativeLibs; } static boolean getExportsManifest(RuleContext ruleContext) { // AndroidLibraryBaseRule has exports_manifest but AndroidBinaryBaseRule does not. // ResourceContainers are built for both, so we must check if exports_manifest is present. if (!ruleContext.attributes().has("exports_manifest", BuildType.TRISTATE)) { return false; } TriState attributeValue = ruleContext.attributes().get("exports_manifest", BuildType.TRISTATE); // If the rule does not have the Android configuration fragment, we default to false. boolean exportsManifestDefault = ruleContext.isLegalFragment(AndroidConfiguration.class) && ruleContext.getFragment(AndroidConfiguration.class).getExportsManifestDefault(); return attributeValue == TriState.YES || (attributeValue == TriState.AUTO && exportsManifestDefault); } /** Returns the artifact for the debug key for signing the APK. */ static Artifact getApkDebugSigningKey(RuleContext ruleContext) { return ruleContext.getHostPrerequisiteArtifact("debug_key"); } private void compileResources( JavaSemantics javaSemantics, ResourceApk resourceApk, Artifact resourcesJar, JavaCompilationArtifacts.Builder artifactsBuilder, JavaTargetAttributes.Builder attributes, NestedSetBuilder<Artifact> filesBuilder) throws InterruptedException, RuleErrorException { // The resource class JAR should already have been generated. Preconditions.checkArgument( resourceApk .getResourceJavaClassJar() .equals( ruleContext.getImplicitOutputArtifact( AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR))); packResourceSourceJar(javaSemantics, resourcesJar); // Add the compiled resource jar to the classpath of the main compilation. attributes.addDirectJars( NestedSetBuilder.create(Order.STABLE_ORDER, resourceApk.getResourceJavaClassJar())); // Add the compiled resource jar to the classpath of consuming targets. // We don't actually use the ijar. That is almost the same as the resource class jar // except for <clinit>, but it takes time to build and waiting for that to build would // just delay building the rest of the library. artifactsBuilder.addCompileTimeJarAsFullJar(resourceApk.getResourceJavaClassJar()); // Add the compiled resource jar as a declared output of the rule. filesBuilder.add(resourceSourceJar); filesBuilder.add(resourceApk.getResourceJavaClassJar()); } private void packResourceSourceJar(JavaSemantics javaSemantics, Artifact resourcesJar) throws InterruptedException { resourceSourceJar = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCES_SOURCE_JAR); JavaTargetAttributes.Builder javacAttributes = new JavaTargetAttributes.Builder(javaSemantics).addSourceJar(resourcesJar); JavaCompilationHelper javacHelper = new JavaCompilationHelper(ruleContext, javaSemantics, getJavacOpts(), javacAttributes); javacHelper.createSourceJarAction(resourceSourceJar, null); } public JavaTargetAttributes init( JavaSemantics javaSemantics, AndroidSemantics androidSemantics, ResourceApk resourceApk, boolean addCoverageSupport, boolean collectJavaCompilationArgs, boolean isBinary, NestedSet<Artifact> excludedRuntimeArtifacts, boolean generateExtensionRegistry) throws InterruptedException, RuleErrorException { classJar = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_CLASS_JAR); idlHelper = new AndroidIdlHelper(ruleContext, classJar); ImmutableList<Artifact> bootclasspath; if (getAndroidConfig(ruleContext).desugarJava8()) { bootclasspath = ImmutableList.<Artifact>builder() .addAll( ruleContext .getPrerequisite("$desugar_java8_extra_bootclasspath", Mode.HOST) .getProvider(FileProvider.class) .getFilesToBuild()) .add(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar()) .build(); } else { bootclasspath = ImmutableList.of(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar()); } ImmutableList.Builder<String> javacopts = ImmutableList.builder(); javacopts.addAll(androidSemantics.getCompatibleJavacOptions(ruleContext)); resourceApk .asDataBindingContext() .supplyJavaCoptsUsing(ruleContext, isBinary, javacopts::addAll); JavaTargetAttributes.Builder attributes = javaCommon .initCommon(idlHelper.getIdlGeneratedJavaSources(), javacopts.build()) .setBootClassPath(bootclasspath); resourceApk .asDataBindingContext() .supplyAnnotationProcessor( ruleContext, (plugin, additionalOutputs) -> { attributes.addPlugin(plugin); attributes.addAdditionalOutputs(additionalOutputs); }); if (excludedRuntimeArtifacts != null) { attributes.addExcludedArtifacts(excludedRuntimeArtifacts); } JavaCompilationArtifacts.Builder artifactsBuilder = new JavaCompilationArtifacts.Builder(); NestedSetBuilder<Artifact> jarsProducedForRuntime = NestedSetBuilder.<Artifact>stableOrder(); NestedSetBuilder<Artifact> filesBuilder = NestedSetBuilder.<Artifact>stableOrder(); Artifact resourcesJar = resourceApk.getResourceJavaSrcJar(); if (resourcesJar != null) { filesBuilder.add(resourcesJar); compileResources( javaSemantics, resourceApk, resourcesJar, artifactsBuilder, attributes, filesBuilder); // Combined resource constants needs to come even before our own classes that may contain // local resource constants. artifactsBuilder.addRuntimeJar(resourceApk.getResourceJavaClassJar()); jarsProducedForRuntime.add(resourceApk.getResourceJavaClassJar()); } JavaCompilationHelper helper = initAttributes( attributes, javaSemantics, resourceApk.asDataBindingContext().processDeps(ruleContext)); if (ruleContext.hasErrors()) { return null; } if (addCoverageSupport) { androidSemantics.addCoverageSupport( ruleContext, this, javaSemantics, true, attributes, artifactsBuilder); if (ruleContext.hasErrors()) { return null; } } initJava( javaSemantics, helper, artifactsBuilder, collectJavaCompilationArgs, filesBuilder, generateExtensionRegistry); if (ruleContext.hasErrors()) { return null; } if (generatedExtensionRegistryProvider != null) { jarsProducedForRuntime.add(generatedExtensionRegistryProvider.getClassJar()); } this.jarsProducedForRuntime = jarsProducedForRuntime.add(classJar).build(); return helper.getAttributes(); } private JavaCompilationHelper initAttributes( JavaTargetAttributes.Builder attributes, JavaSemantics semantics, ImmutableList<Artifact> additionalArtifacts) { JavaCompilationHelper helper = new JavaCompilationHelper( ruleContext, semantics, javaCommon.getJavacOpts(), attributes, additionalArtifacts, /*disableStrictDeps=*/ false); helper.addLibrariesToAttributes(javaCommon.targetsTreatedAsDeps(ClasspathType.COMPILE_ONLY)); attributes.setTargetLabel(ruleContext.getLabel()); ruleContext.checkSrcsSamePackage(true); return helper; } private void initJava( JavaSemantics javaSemantics, JavaCompilationHelper helper, JavaCompilationArtifacts.Builder javaArtifactsBuilder, boolean collectJavaCompilationArgs, NestedSetBuilder<Artifact> filesBuilder, boolean generateExtensionRegistry) throws InterruptedException { JavaTargetAttributes attributes = helper.getAttributes(); if (ruleContext.hasErrors()) { // Avoid leaving filesToBuild set to null, otherwise we'll get a NullPointerException masking // the real error. filesToBuild = filesBuilder.build(); return; } Artifact jar = null; if (attributes.hasSources() || attributes.hasResources()) { // We only want to add a jar to the classpath of a dependent rule if it has content. javaArtifactsBuilder.addRuntimeJar(classJar); jar = classJar; } filesBuilder.add(classJar); manifestProtoOutput = helper.createManifestProtoOutput(classJar); // The gensrc jar is created only if the target uses annotation processing. Otherwise, // it is null, and the source jar action will not depend on the compile action. if (helper.usesAnnotationProcessing()) { genClassJar = helper.createGenJar(classJar); genSourceJar = helper.createGensrcJar(classJar); helper.createGenJarAction(classJar, manifestProtoOutput, genClassJar); } srcJar = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_SOURCE_JAR); javaSourceJarsProviderBuilder .addSourceJar(srcJar) .addAllTransitiveSourceJars(javaCommon.collectTransitiveSourceJars(srcJar)); helper.createSourceJarAction(srcJar, genSourceJar); nativeHeaderOutput = helper.createNativeHeaderJar(classJar); outputDepsProto = helper.createOutputDepsProtoArtifact(classJar, javaArtifactsBuilder); helper.createCompileActionWithInstrumentation( classJar, manifestProtoOutput, genSourceJar, outputDepsProto, javaArtifactsBuilder, nativeHeaderOutput); if (generateExtensionRegistry) { generatedExtensionRegistryProvider = javaSemantics.createGeneratedExtensionRegistry( ruleContext, javaCommon, filesBuilder, javaArtifactsBuilder, javaRuleOutputJarsProviderBuilder, javaSourceJarsProviderBuilder); } filesToBuild = filesBuilder.build(); if ((attributes.hasSources()) && jar != null) { iJar = helper.createCompileTimeJarAction(jar, javaArtifactsBuilder); } JavaCompilationArtifacts javaArtifacts = javaArtifactsBuilder.build(); javaCommon.setJavaCompilationArtifacts(javaArtifacts); javaCommon.setJavaCompilationArtifacts(javaArtifacts); javaCommon.setClassPathFragment( new ClasspathConfiguredFragment( javaCommon.getJavaCompilationArtifacts(), attributes, asNeverLink, helper.getBootclasspathOrDefault())); transitiveNeverlinkLibraries = collectTransitiveNeverlinkLibraries( ruleContext, javaCommon.getDependencies(), javaCommon.getJavaCompilationArtifacts().getRuntimeJars()); if (collectJavaCompilationArgs) { boolean hasSources = attributes.hasSources(); this.javaCompilationArgs = collectJavaCompilationArgs(asNeverLink, hasSources); } } public RuleConfiguredTargetBuilder addTransitiveInfoProviders( RuleConfiguredTargetBuilder builder, Artifact aar, ResourceApk resourceApk, Artifact zipAlignedApk, Iterable<Artifact> apksUnderTest, NativeLibs nativeLibs, boolean isNeverlink, boolean isLibrary) { idlHelper.addTransitiveInfoProviders(builder, classJar, manifestProtoOutput); if (generatedExtensionRegistryProvider != null) { builder.add(GeneratedExtensionRegistryProvider.class, generatedExtensionRegistryProvider); } OutputJar resourceJar = null; if (resourceApk.getResourceJavaClassJar() != null && resourceSourceJar != null) { resourceJar = new OutputJar( resourceApk.getResourceJavaClassJar(), null /* ijar */, manifestProtoOutput, ImmutableList.of(resourceSourceJar)); javaRuleOutputJarsProviderBuilder.addOutputJar(resourceJar); } JavaRuleOutputJarsProvider ruleOutputJarsProvider = javaRuleOutputJarsProviderBuilder .addOutputJar(classJar, iJar, manifestProtoOutput, ImmutableList.of(srcJar)) .setJdeps(outputDepsProto) .setNativeHeaders(nativeHeaderOutput) .build(); JavaSourceJarsProvider sourceJarsProvider = javaSourceJarsProviderBuilder.build(); JavaCompilationArgsProvider compilationArgsProvider = javaCompilationArgs; JavaInfo.Builder javaInfoBuilder = JavaInfo.Builder.create(); javaCommon.addTransitiveInfoProviders( builder, javaInfoBuilder, filesToBuild, classJar, ANDROID_COLLECTION_SPEC); javaCommon.addGenJarsProvider(builder, javaInfoBuilder, genClassJar, genSourceJar); resourceApk.asDataBindingContext().addProvider(builder, ruleContext); JavaInfo javaInfo = javaInfoBuilder .addProvider(JavaCompilationArgsProvider.class, compilationArgsProvider) .addProvider(JavaRuleOutputJarsProvider.class, ruleOutputJarsProvider) .addProvider(JavaSourceJarsProvider.class, sourceJarsProvider) .addProvider(JavaPluginInfoProvider.class, JavaCommon.getTransitivePlugins(ruleContext)) .setRuntimeJars(javaCommon.getJavaCompilationArtifacts().getRuntimeJars()) .setJavaConstraints(ImmutableList.of("android")) .setNeverlink(isNeverlink) .build(); resourceApk.addToConfiguredTargetBuilder( builder, ruleContext.getLabel(), /* includeSkylarkApiProvider = */ true, isLibrary); return builder .setFilesToBuild(filesToBuild) .addSkylarkTransitiveInfo( JavaSkylarkApiProvider.NAME, JavaSkylarkApiProvider.fromRuleContext()) .addNativeDeclaredProvider(javaInfo) .addProvider(RunfilesProvider.class, RunfilesProvider.simple(getRunfiles())) .addNativeDeclaredProvider( createAndroidIdeInfoProvider( ruleContext, idlHelper, resourceJar, aar, resourceApk, zipAlignedApk, apksUnderTest, nativeLibs)) .addOutputGroup( OutputGroupInfo.HIDDEN_TOP_LEVEL, collectHiddenTopLevelArtifacts(ruleContext)) .addOutputGroup( JavaSemantics.SOURCE_JARS_OUTPUT_GROUP, sourceJarsProvider.getTransitiveSourceJars()); } private Runfiles getRunfiles() { // TODO(bazel-team): why return any Runfiles in the neverlink case? if (asNeverLink) { return new Runfiles.Builder( ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles()) .addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES) .build(); } return JavaCommon.getRunfiles( ruleContext, javaCommon.getJavaSemantics(), javaCommon.getJavaCompilationArtifacts(), asNeverLink); } /** * Collects Java compilation arguments for this target. * * @param isNeverLink Whether the target has the 'neverlink' attr. * @param hasSrcs If false, deps are exported (deprecated behaviour) */ private JavaCompilationArgsProvider collectJavaCompilationArgs( boolean isNeverLink, boolean hasSrcs) { boolean exportDeps = !hasSrcs && ruleContext .getFragment(AndroidConfiguration.class) .allowSrcsLessAndroidLibraryDeps(ruleContext); return javaCommon.collectJavaCompilationArgs(isNeverLink, exportDeps); } public ImmutableList<String> getJavacOpts() { return javaCommon.getJavacOpts(); } public ImmutableList<Artifact> getRuntimeJars() { return javaCommon.getJavaCompilationArtifacts().getRuntimeJars(); } /** * Returns Jars produced by this rule that may go into the runtime classpath. By contrast {@link * #getRuntimeJars()} returns the complete runtime classpath needed by this rule, including * dependencies. */ public NestedSet<Artifact> getJarsProducedForRuntime() { return jarsProducedForRuntime; } public Artifact getClassJar() { return classJar; } public Artifact getInstrumentedJar() { return javaCommon.getJavaCompilationArtifacts().getInstrumentedJar(); } public NestedSet<Artifact> getTransitiveNeverLinkLibraries() { return transitiveNeverlinkLibraries; } public boolean isNeverLink() { return asNeverLink; } public CcLinkingInfo getCcLinkingInfo() { return getCcLinkingInfo( javaCommon.targetsTreatedAsDeps(ClasspathType.BOTH), ImmutableList.<String>of()); } public static CcLinkingInfo getCcLinkingInfo( final Iterable<? extends TransitiveInfoCollection> deps, final Collection<String> linkOpts) { CcLinkParams linkOptsParams = CcLinkParams.builder().addLinkOpts(linkOpts).build(); CcLinkingInfo linkOptsProvider = CcLinkingInfo.Builder.create() .setStaticModeParamsForDynamicLibrary(linkOptsParams) .setStaticModeParamsForExecutable(linkOptsParams) .setDynamicModeParamsForDynamicLibrary(linkOptsParams) .setDynamicModeParamsForExecutable(linkOptsParams) .build(); ImmutableList<CcLinkingInfo> ccLinkingInfos = ImmutableList.<CcLinkingInfo>builder() .add(linkOptsProvider) .addAll( Streams.stream(AnalysisUtils.getProviders(deps, JavaCcLinkParamsProvider.class)) .map(JavaCcLinkParamsProvider::getCcLinkingInfo) .collect(ImmutableList.toImmutableList())) .addAll( Streams.stream( AnalysisUtils.getProviders(deps, AndroidCcLinkParamsProvider.PROVIDER)) .map(AndroidCcLinkParamsProvider::getLinkParams) .collect(ImmutableList.toImmutableList())) .addAll(AnalysisUtils.getProviders(deps, CcLinkingInfo.PROVIDER)) .build(); return CcLinkingInfo.merge(ccLinkingInfos); } /** Returns {@link AndroidConfiguration} in given context. */ public static AndroidConfiguration getAndroidConfig(RuleContext context) { return context.getConfiguration().getFragment(AndroidConfiguration.class); } private NestedSet<Artifact> collectHiddenTopLevelArtifacts(RuleContext ruleContext) { NestedSetBuilder<Artifact> builder = NestedSetBuilder.stableOrder(); for (OutputGroupInfo provider : getTransitivePrerequisites(ruleContext, Mode.TARGET, OutputGroupInfo.SKYLARK_CONSTRUCTOR)) { builder.addTransitive(provider.getOutputGroup(OutputGroupInfo.HIDDEN_TOP_LEVEL)); } return builder.build(); } /** * Returns a {@link JavaCommon} instance with Android data binding support. * * <p>Binaries need both compile-time and runtime support, while libraries only need compile-time * support. * * <p>No rule needs <i>any</i> support if data binding is disabled. */ static JavaCommon createJavaCommonWithAndroidDataBinding( RuleContext ruleContext, JavaSemantics semantics, DataBindingContext dataBindingContext, boolean isLibrary) { ImmutableList<Artifact> srcs = dataBindingContext.addAnnotationFileToSrcs( ruleContext.getPrerequisiteArtifacts("srcs", RuleConfiguredTarget.Mode.TARGET).list(), ruleContext); ImmutableList<TransitiveInfoCollection> compileDeps; ImmutableList<TransitiveInfoCollection> runtimeDeps; ImmutableList<TransitiveInfoCollection> bothDeps; if (isLibrary) { compileDeps = JavaCommon.defaultDeps(ruleContext, semantics, ClasspathType.COMPILE_ONLY); compileDeps = AndroidIdlHelper.maybeAddSupportLibs(ruleContext, compileDeps); runtimeDeps = JavaCommon.defaultDeps(ruleContext, semantics, ClasspathType.RUNTIME_ONLY); bothDeps = JavaCommon.defaultDeps(ruleContext, semantics, ClasspathType.BOTH); } else { // Binary: compileDeps = ImmutableList.copyOf( ruleContext.getPrerequisites("deps", RuleConfiguredTarget.Mode.TARGET)); runtimeDeps = compileDeps; bothDeps = compileDeps; } return new JavaCommon(ruleContext, semantics, srcs, compileDeps, runtimeDeps, bothDeps); } /** * Gets the transitive support APKs required by this rule through the {@code support_apks} * attribute. */ static NestedSet<Artifact> getSupportApks(RuleContext ruleContext) { NestedSetBuilder<Artifact> supportApks = NestedSetBuilder.stableOrder(); for (TransitiveInfoCollection dep : ruleContext.getPrerequisites("support_apks", Mode.TARGET)) { ApkInfo apkProvider = dep.get(ApkInfo.PROVIDER); FileProvider fileProvider = dep.getProvider(FileProvider.class); // If ApkInfo is present, do not check FileProvider for .apk files. For example, // android_binary creates a FileProvider containing both the signed and unsigned APKs. if (apkProvider != null) { supportApks.add(apkProvider.getApk()); } else if (fileProvider != null) { // The rule definition should enforce that only .apk files are allowed, however, it can't // hurt to double check. supportApks.addAll(FileType.filter(fileProvider.getFilesToBuild(), AndroidRuleClasses.APK)); } } return supportApks.build(); } /** * Used for instrumentation tests. Filter out classes from the instrumentation JAR that are also * present in the target JAR. During an instrumentation test, ART will load jars from both APKs * into the same classloader. If the same class exists in both jars, there will be runtime * crashes. * * <p>R.class files that share the same package are also filtered out to prevent * surprising/incorrect references to resource IDs. */ public static void createZipFilterAction( RuleContext ruleContext, Artifact in, Artifact filter, Artifact out, CheckHashMismatchMode checkHashMismatch) { new ZipFilterBuilder(ruleContext) .setInputZip(in) .addFilterZips(ImmutableList.of(filter)) .setOutputZip(out) .addFileTypeToFilter(".class") .setCheckHashMismatchMode(checkHashMismatch) .addExplicitFilter("R\\.class") .addExplicitFilter("R\\$.*\\.class") // These files are generated by databinding in both the target and the instrumentation app // with different contents. We want to keep the one from the target app. .addExplicitFilter("/BR\\.class$") .addExplicitFilter("/databinding/[^/]+Binding\\.class$") .build(); } }
// Copyright 2019 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.outputfilter; import static org.junit.Assert.fail; import com.google.common.base.Joiner; import com.google.devtools.build.lib.buildtool.util.BuildIntegrationTestCase; import com.google.devtools.build.lib.events.Event; import com.google.devtools.build.lib.events.EventCollector; import com.google.devtools.build.lib.events.EventKind; import com.google.devtools.build.lib.runtime.BlazeRuntime; import com.google.devtools.build.lib.runtime.CommandEnvironment; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for the {@code --output_filter} option. */ @RunWith(JUnit4.class) public class OutputFilterTest extends BuildIntegrationTestCase { private EventCollector stderr = new EventCollector(EventKind.STDERR); // Cast warnings are silenced by default. private void enableCastWarnings() throws Exception { addOptions("--javacopt=\"-Xlint:cast\""); } // Deprecation warnings are silenced by default. private void enableDeprecationWarnings() throws Exception { addOptions("--javacopt=\"-Xlint:deprecation\""); } @Override protected BlazeRuntime.Builder getRuntimeBuilder() throws Exception { return super.getRuntimeBuilder().addBlazeModule(new OutputFilteringModule()); } @Before public final void writeFiles() throws Exception { write("java/a/BUILD", "java_library(name = 'a',", " srcs = ['A.java']," + " deps = ['//java/b'])"); write("java/a/A.java", "package a;", "public class A {", " public static void a() { b.B.b(); }", "}"); write("java/b/BUILD", "java_library(name = 'b',", " srcs = ['B.java']," + " deps = ['//java/c'])"); write("java/b/B.java", "package b;", "public class B {", " @Deprecated public static void b() {}", " public static void x() { c.C.c(); }", "}"); write("java/c/BUILD", "java_library(name = 'c',", " srcs = ['C.java'])"); write("java/c/C.java", "package c;", "public class C {", " @Deprecated public static void c() {}", "}"); write("java/d/BUILD", "java_library(name = 'd',", " srcs = ['D.java'],", " deps = ['//java/e'])"); write( "java/d/D.java", "package d;", "import java.lang.Integer;", "import java.util.ArrayList;", "public class D {", " public static void d() {", " int i = (int) 0;", " e.E.e();", " }", "}"); write("java/e/BUILD", "java_library(name = 'e',", " srcs = ['E.java'])"); write( "java/e/E.java", "package e;", "import java.lang.Integer;", "import java.util.LinkedList;", "public class E {", " public static void e() {", " int i = (int) 0;", " }", "}"); write("javatests/a/BUILD", "java_library(name = 'a',", " srcs = ['ATest.java']," + " deps = ['//java/a', '//javatests/b'])"); write("javatests/a/ATest.java", "package a;", "public class ATest {", " public static void aTest() { a.A.a(); }", "}"); write("javatests/b/BUILD", "java_library(name = 'b',", " srcs = ['BTest.java']," + " deps = ['//java/b', '//javatests/c'])"); write("javatests/b/BTest.java", "package b;", "public class BTest {", " public static void bTest() { c.CTest.c(); }", "}"); write("javatests/c/BUILD", "java_library(name = 'c',", " srcs = ['CTest.java'])"); write("javatests/c/CTest.java", "package c;", "public class CTest {", " @Deprecated public static void c() {}", "}"); write("javatests/d/BUILD", "java_library(name = 'd',", " srcs = ['DTest.java'],", " deps = ['//java/d', '//javatests/e'])"); write("javatests/d/DTest.java", "package d;", "public class DTest {", " public static void dTest() { d.D.d(); }", "}"); write("javatests/e/BUILD", "java_library(name = 'e',", " srcs = ['ETest.java'])"); write( "javatests/e/ETest.java", "package e;", "import java.lang.Integer;", "import java.util.LinkedList;", "public class ETest {", " public static void eTest() {", " int i = (int) 0;", " }", "}"); // Always enable cast warnings. enableCastWarnings(); } @Test public void testExplicitFilter() throws Exception { enableDeprecationWarnings(); addOptions("--output_filter=^//java/a"); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//java/a"); assertEvent(deprecationMessages("b", "B", "b")); assertNoEvent(deprecationMessages("c", "C", "c")); } @Test public void testExplicitFilterNoJavacoptOverride() throws Exception { addOptions("--output_filter=^//java/d"); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//java/d"); assertEvent("D.java:6: warning: [cast] redundant cast to int"); assertNoEvent("E.java:6: warning: [cast] redundant cast to int"); } @Test public void testPackagesAOF_A() throws Exception { enableDeprecationWarnings(); addOptions("--auto_output_filter=packages"); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//java/a"); assertEvent(deprecationMessages("b", "B", "b")); assertNoEvent(deprecationMessages("c", "C", "c")); } @Test public void testPackagesAOF_B() throws Exception { enableDeprecationWarnings(); addOptions("--auto_output_filter=packages"); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//java/b"); assertNoEvent(deprecationMessages("b", "B", "b")); assertEvent(deprecationMessages("c", "C", "c")); } @Test public void testPackagesAOF_C() throws Exception { enableDeprecationWarnings(); addOptions("--auto_output_filter=packages"); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//java/c"); assertNoEvent(deprecationMessages("b", "B", "b")); assertNoEvent(deprecationMessages("c", "C", "c")); } @Test public void testPackagesAOF_D() throws Exception { addOptions("--auto_output_filter=packages"); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//java/d"); assertEvent("D.java:6: warning: [cast] redundant cast to int"); assertNoEvent("E.java:6: warning: [cast] redundant cast to int"); } @Test public void testPackagesAOF_AB() throws Exception { enableDeprecationWarnings(); addOptions("--auto_output_filter=packages"); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//java/a", "//java/b"); assertEvent(deprecationMessages("b", "B", "b")); assertEvent(deprecationMessages("c", "C", "c")); } @Test public void testPackagesAOF_AC() throws Exception { enableDeprecationWarnings(); addOptions("--auto_output_filter=packages"); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//java/a", "//java/c"); assertEvent(deprecationMessages("b", "B", "b")); assertNoEvent(deprecationMessages("c", "C", "c")); } @Test public void testPackagesAOF_BC() throws Exception { enableDeprecationWarnings(); addOptions("--auto_output_filter=packages"); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//java/b", "//java/c"); assertNoEvent(deprecationMessages("b", "B", "b")); assertEvent(deprecationMessages("c", "C", "c")); } @Test public void testPackagesAOF_ABC() throws Exception { enableDeprecationWarnings(); addOptions("--auto_output_filter=packages"); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//java/a", "//java/b", "//java/c"); assertEvent(deprecationMessages("b", "B", "b")); assertEvent(deprecationMessages("c", "C", "c")); } @Test public void testPackagesAOF_JavaTestsA() throws Exception { enableDeprecationWarnings(); addOptions("--auto_output_filter=packages"); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//javatests/a"); assertEvent(deprecationMessages("b", "B", "b")); assertNoEvent(deprecationMessages("c", "C", "c")); assertNoEvent(deprecationMessages("c", "CTest", "c")); } @Test public void testPackagesAOF_JavaTestsAB() throws Exception { enableDeprecationWarnings(); addOptions("--auto_output_filter=packages"); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//javatests/a", "//java/b"); assertEvent(deprecationMessages("b", "B", "b")); assertEvent(deprecationMessages("c", "C", "c")); assertEvent(deprecationMessages("c", "CTest", "c")); } @Test public void testPackagesAOF_JavaTestsD() throws Exception { addOptions("--auto_output_filter=packages"); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//javatests/d"); assertEvent("D.java:6: warning: [cast] redundant cast to int"); assertNoEvent("E.java:6: warning: [cast] redundant cast to int"); assertNoEvent("ETest.java:6: warning: [cast] redundant cast to int"); } @Test public void testEmptyFilter() throws Exception { enableDeprecationWarnings(); addOptions("--output_filter="); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//java/a"); assertEvent(deprecationMessages("b", "B", "b")); assertEvent(deprecationMessages("c", "C", "c")); } @Test public void testNoMatchFilter() throws Exception { enableDeprecationWarnings(); addOptions("--output_filter=DONT_MATCH"); CommandEnvironment env = runtimeWrapper.newCommand(); env.getReporter().addHandler(stderr); buildTarget("//java/a"); assertNoEvent(deprecationMessages("b", "B", "b")); assertNoEvent(deprecationMessages("c", "C", "c")); } private void assertEvent(String... choices) { for (Event event : stderr) { for (String msg : choices) { if (event.getMessage().contains(msg)) { return; } } } fail(String.format("Expected one of [%s] in output: %s", Joiner.on(',').join(choices), Joiner.on('\n').join(stderr) )); } private void assertNoEvent(String... choices) { for (Event event : stderr) { for (String msg : choices) { if (event.getMessage().contains(msg)) { fail("Event '" + msg + "' was found in output: \n" + Joiner.on('\n').join(stderr)); } } } } private String[] deprecationMessages(String pkg, String clazz, String method) { return new String[] { String.format("%s() in %s.%s has been deprecated", method, pkg, clazz), // javac6 String.format("%s() in %s has been deprecated", method, clazz) // javac7 }; } }
/* * ModeShape (http://www.modeshape.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.modeshape.jcr; import org.modeshape.common.annotation.Immutable; import org.modeshape.common.i18n.I18n; /** * The internationalized string constants for the <code>org.modeshape.jcr*</code> packages. */ @Immutable public final class JcrI18n { public static I18n initializing; public static I18n engineStarting; public static I18n engineStarted; public static I18n couldNotStartEngine; public static I18n engineStopping; public static I18n engineStopped; public static I18n repositoryCannotBeRestored; public static I18n repositoryCannotBeRestartedAfterRestore; public static I18n repositoryIsCurrentlyBeingRestored; public static I18n repositoryIsBeingRestoredAndCannotBeStarted; public static I18n repositoryCannotBeStartedWithoutTransactionalSupport; public static I18n workspaceCacheShouldNotBeTransactional; public static I18n repositoryReferencesNonExistantSource; public static I18n indexRebuildingStarted; public static I18n indexRebuildingComplete; public static I18n indexRebuildingOfWorkspaceStarted; public static I18n indexRebuildingOfWorkspaceComplete; public static I18n unableToInitializeSystemWorkspace; public static I18n repositoryWasNeverInitializedAfterMinutes; public static I18n repositoryWasInitializedByOtherProcess; public static I18n repositoryWasNeverUpgradedAfterMinutes; public static I18n failureDuringUpgradeOperation; public static I18n errorShuttingDownIndexProvider; public static I18n indexProviderMissingPlanner; public static I18n cannotConvertValue; public static I18n loginFailed; public static I18n noPrivilegeToGetLoginContextFromCredentials; public static I18n credentialsMustProvideJaasMethod; public static I18n mustBeInPrivilegedAction; public static I18n loginConfigNotFound; public static I18n credentialsMustReturnLoginContext; public static I18n usingAnonymousUser; public static I18n unknownCredentialsImplementation; public static I18n defaultWorkspaceName; public static I18n nodeNotFound; public static I18n pathNotFound; public static I18n pathNotFoundRelativeTo; public static I18n pathCannotHaveSameNameSiblingIndex; public static I18n cannotCopySubgraphIntoRoot; public static I18n cannotCloneSubgraphIntoRoot; public static I18n cannotCopyOrCloneReferenceOutsideGraph; public static I18n cannotCopyOrCloneCorruptReference; public static I18n permissionDenied; public static I18n repositoryMustBeConfigured; public static I18n sourceInUse; public static I18n repositoryDoesNotExist; public static I18n fileDoesNotExist; public static I18n failedToReadPropertiesFromManifest; public static I18n failedToReadPropertyFromManifest; public static I18n errorLoadingNodeTypeDefintions; public static I18n errorStartingRepositoryCheckConfiguration; public static I18n completedStartingRepository; public static I18n startingAllRepositoriesWasInterrupted; public static I18n unableToFindNodeTypeDefinitionsOnClasspathOrFileOrUrl; public static I18n unableToFindResourceOnClasspathOrFileOrUrl; public static I18n unableToImportInitialContent; public static I18n fileMustExistAndBeReadable; public static I18n existsAndMustBeWritableDirectory; public static I18n problemInitializingBackupArea; public static I18n problemsWritingDocumentToBackup; public static I18n problemsWritingBinaryToBackup; public static I18n problemsReadingBinaryFromBackup; public static I18n problemsGettingBinaryKeysFromBinaryStore; public static I18n problemsRestoringBinaryFromBackup; public static I18n interruptedWhilePerformingBackup; public static I18n problemObtainingDocumentsToBackup; public static I18n backupOperationWasCancelled; public static I18n problemsClosingBackupFiles; public static I18n invalidJcrUrl; public static I18n unableToInitializeAuthenticationProvider; public static I18n errorInAuthenticationProvider; public static I18n unableToInitializeSequencer; public static I18n unableToInitializeTextExtractor; public static I18n unableToInitializeConnector; public static I18n unableToInitializeIndexProvider; public static I18n requiredFieldNotSetInConnector; public static I18n fileConnectorCannotWriteToDirectory; public static I18n fileConnectorTopLevelDirectoryMissingOrCannotBeRead; public static I18n fileConnectorNodeIdentifierIsNotWithinScopeOfConnector; public static I18n fileConnectorIsReadOnly; public static I18n fileConnectorCannotStoreFileThatIsExcluded; public static I18n fileConnectorNamespaceIgnored; public static I18n couldNotStoreProperties; public static I18n couldNotStoreProperty; public static I18n couldNotGetMimeType; public static I18n connectorIsReadOnly; public static I18n indexProviderAlreadyExists; public static I18n indexProviderDoesNotExist; public static I18n indexAlreadyExists; public static I18n indexDoesNotExist; public static I18n indexMustHaveName; public static I18n indexMustHaveProviderName; public static I18n errorRefreshingIndexDefinitions; public static I18n errorNotifyingProviderOfInitialIndexDefinitions; public static I18n errorNotifyingProviderOfIndexChanges; public static I18n rootNodeHasNoParent; public static I18n rootNodeIsNotProperty; public static I18n childNodeAlreadyExists; public static I18n noNamespaceWithPrefix; public static I18n noNamespaceWithUri; public static I18n unableToChangeTheDefaultNamespace; public static I18n unableToRegisterReservedNamespacePrefix; public static I18n unableToRegisterReservedNamespaceUri; public static I18n unableToRegisterNamespaceUsingXmlPrefix; public static I18n unableToRegisterNamespaceWithInvalidPrefix; public static I18n errorRegisteringPersistentNamespace; public static I18n unableToUnregisterReservedNamespacePrefix; public static I18n unableToUnregisterReservedNamespaceUri; public static I18n unableToUnregisterPrefixForNamespaceThatIsNotRegistered; public static I18n unableToUnregisterPrefixForNamespaceUsedByNodeType; public static I18n errorWhileInitializingTheNamespaceRegistry; public static I18n errorCleaningUpLocks; public static I18n errorRefreshingLocks; public static I18n lockNotFound; public static I18n cleaningUpLocks; public static I18n cleanedUpLocks; public static I18n invalidRelativePath; public static I18n invalidAbsolutePath; public static I18n invalidPathParameter; public static I18n invalidNamePattern; public static I18n invalidNodeTypeNameParameter; public static I18n noPrimaryItemNameDefinedOnPrimaryType; public static I18n primaryItemNameForPrimaryTypeIsNotValid; public static I18n primaryItemDoesNotExist; public static I18n itemNotFoundWithUuid; public static I18n itemAlreadyExistsWithUuid; public static I18n itemNotFoundAtPath; public static I18n itemNotFoundAtPathRelativeToReferenceNode; public static I18n identifierPathContainedUnsupportedIdentifierFormat; public static I18n identifierPathNeverReferencesProperty; public static I18n propertyNotFoundOnNode; public static I18n propertyNotFoundAtPathRelativeToReferenceNode; public static I18n nodeNotFoundAtPathRelativeToReferenceNode; public static I18n childNotFoundUnderNode; public static I18n errorWhileFindingNodeWithUuid; public static I18n errorWhileFindingNodeWithPath; public static I18n unableToAddChildUnderParent; public static I18n childNameDoesNotSatisfyParentChildNodeDefinition; public static I18n childPrimaryTypeDoesNotSatisfyParentChildNodeDefinition; public static I18n parentChildNodeDefinitionDoesNotAllowSameNameSiblings; public static I18n parentChildNodeDefinitionIsProtected; public static I18n nodeDefinitionCouldNotBeDeterminedForNode; public static I18n noSnsDefinitionForNode; public static I18n missingNodeTypeForExistingNode; public static I18n unableToCreateNodeWithInternalPrimaryType; public static I18n unableToCreateNodeWithPrimaryTypeThatDoesNotExist; public static I18n unableToCreateNodeWithNoDefaultPrimaryTypeOnChildNodeDefinition; public static I18n unableToSaveNodeThatWasCreatedSincePreviousSave; public static I18n unableToSetMultiValuedPropertyUsingSingleValue; public static I18n cannotSetProtectedPropertyValue; public static I18n unableToSetSingleValuedPropertyUsingMultipleValues; public static I18n invalidMethodForSingleValuedProperty; public static I18n invalidMethodForMultiValuedProperty; public static I18n indexOutsidePropertyValuesBoundaries; public static I18n unableToRefreshBranchBecauseChangesDependOnChangesToNodesOutsideOfBranch; public static I18n unableToSaveBranchBecauseChangesDependOnChangesToNodesOutsideOfBranch; public static I18n unableToConvertPropertyValueToType; public static I18n unableToConvertPropertyValueAtIndexToType; public static I18n allPropertyValuesMustHaveSameType; public static I18n cannotRemoveNodeFromClone; public static I18n cannotRemoveNodeFromCloneDueToChangesInSession; public static I18n constraintViolatedOnReference; public static I18n unableToBindToJndi; public static I18n jndiReadOnly; public static I18n invalidOptionProvided; public static I18n noOptionValueProvided; public static I18n valueMayNotContainNull; public static I18n propertyNoLongerSatisfiesConstraints; public static I18n propertyNoLongerHasValidDefinition; public static I18n propertyIsProtected; public static I18n cannotRemoveRootNode; public static I18n cannotRemoveParentNodeOfTarget; public static I18n invalidPropertyType; public static I18n rootNodeCannotBeDestinationOfMovedNode; public static I18n unableToMoveRootNode; public static I18n unableToRemoveRootNode; public static I18n unableToRemoveSystemNodes; public static I18n unableToModifySystemNodes; public static I18n unableToMoveNodeToBeChildOfDecendent; public static I18n nodeHasAlreadyBeenRemovedFromThisSession; public static I18n unableToShareNodeWithinSubgraph; public static I18n unableToShareNodeWithinSameParent; public static I18n shareAlreadyExistsWithinParent; public static I18n unableToMoveNodeDueToCycle; public static I18n unableToMoveSourceContainExternalNodes; public static I18n unableToMoveTargetContainExternalNodes; public static I18n unableToMoveSourceTargetMismatch; public static I18n unableToMoveProjection; public static I18n unableToCopySourceTargetMismatch; public static I18n unableToCopySourceNotExternal; public static I18n unableToCloneSameWsContainsExternalNode; public static I18n unableToCloneExternalNodesRequireRoot; public static I18n aclsOnExternalNodesNotAllowed; public static I18n typeNotFound; public static I18n supertypeNotFound; public static I18n errorImportingNodeTypeContent; public static I18n errorDuringInitialImport; public static I18n nodeTypesNotFoundInXml; public static I18n invalidGarbageCollectionInitialTime; public static I18n failedToQueryForDerivedContent; public static I18n systemSourceNameOptionValueDoesNotReferenceExistingSource; public static I18n systemSourceNameOptionValueDoesNotReferenceValidWorkspace; public static I18n systemSourceNameOptionValueIsNotFormattedCorrectly; public static I18n searchIndexDirectoryOptionSpecifiesFileNotDirectory; public static I18n searchIndexDirectoryOptionSpecifiesDirectoryThatCannotBeRead; public static I18n searchIndexDirectoryOptionSpecifiesDirectoryThatCannotBeWrittenTo; public static I18n searchIndexDirectoryOptionSpecifiesDirectoryThatCannotBeCreated; public static I18n errorUpdatingQueryIndexes; public static I18n invalidAliasForComponent; public static I18n unableToSetFieldOnInstance; public static I18n missingFieldOnInstance; public static I18n missingComponentType; public static I18n repositoryConfigurationContainsDeprecatedField; public static I18n typeMissingWhenRegisteringEngineInJndi; public static I18n repositoryNameNotProvidedWhenRegisteringRepositoryInJndi; public static I18n invalidRepositoryNameWhenRegisteringRepositoryInJndi; public static I18n emptyRepositoryNameProvidedWhenRegisteringRepositoryInJndi; // Used in AbstractJcrNode#getAncestor public static I18n noNegativeDepth; public static I18n tooDeep; public static I18n SPEC_NAME_DESC; // New implementation public static I18n errorObtainingWorkspaceNames; public static I18n errorObtainingDefaultWorkspaceName; public static I18n errorUpdatingWorkspaceNames; public static I18n errorUpdatingRepositoryMetadata; public static I18n workspaceNameIsInvalid; public static I18n errorVerifyingWorkspaceName; // Query-related messages public static I18n notStoredQuery; public static I18n invalidQueryLanguage; public static I18n queryCannotBeParsedUsingLanguage; public static I18n queryInLanguageIsNotValid; public static I18n queryIsDisabledInRepository; public static I18n queryResultsDoNotIncludeScore; public static I18n queryResultsDoNotIncludeColumn; public static I18n selectorNotUsedInQuery; public static I18n selectorUsedInEquiJoinCriteriaDoesNotExistInQuery; public static I18n multipleSelectorsAppearInQueryRequireSpecifyingSelectorName; public static I18n multipleSelectorsAppearInQueryUnableToCallMethod; public static I18n multipleCallsToGetRowsOrNodesIsNotAllowed; public static I18n equiJoinWithOneJcrPathPseudoColumnIsInvalid; public static I18n equiJoinWithOneNodeIdPseudoColumnIsInvalid; public static I18n noSuchVariableInQuery; // Type registration messages public static I18n invalidNodeTypeName; public static I18n badNodeTypeName; public static I18n noSuchNodeType; public static I18n nodeTypeAlreadyExists; public static I18n invalidPrimaryTypeName; public static I18n invalidMixinSupertype; public static I18n invalidSupertypeName; public static I18n supertypesConflict; public static I18n ambiguousPrimaryItemName; public static I18n invalidPrimaryItemName; public static I18n autocreatedNodesNeedDefaults; public static I18n residualPropertyDefinitionsCannotBeMandatory; public static I18n residualPropertyDefinitionsCannotBeAutoCreated; public static I18n residualNodeDefinitionsCannotBeMandatory; public static I18n residualNodeDefinitionsCannotBeAutoCreated; public static I18n cannotOverrideProtectedDefinition; public static I18n cannotMakeMandatoryDefinitionOptional; public static I18n constraintsChangedInSubtype; public static I18n cannotRedefineProperty; public static I18n autocreatedPropertyNeedsDefault; public static I18n singleValuedPropertyNeedsSingleValuedDefault; public static I18n couldNotFindDefinitionOfRequiredPrimaryType; public static I18n cannotRedefineChildNodeWithIncompatibleDefinition; public static I18n cannotRemoveItemWithProtectedDefinition; public static I18n errorCheckingNodeTypeUsage; public static I18n noChildNodeDefinitions; public static I18n noChildNodeDefinition; public static I18n noPropertyDefinition; public static I18n noSnsDefinition; public static I18n missingMandatoryProperty; public static I18n missingMandatoryChild; public static I18n valueViolatesConstraintsOnDefinition; public static I18n valuesViolateConstraintsOnDefinition; public static I18n referenceValueViolatesConstraintsOnDefinition; public static I18n referenceValuesViolateConstraintsOnDefinition; public static I18n weakReferenceValueViolatesConstraintsOnDefinition; public static I18n weakReferenceValuesViolateConstraintsOnDefinition; public static I18n allNodeTypeTemplatesMustComeFromSameSession; public static I18n nodeNotReferenceable; public static I18n nodeNotReferenceableUuid; public static I18n noPendingChangesAllowed; public static I18n noPendingChangesAllowedForNode; public static I18n nodeNotInTheSameSession; public static I18n cannotUnregisterSupertype; public static I18n cannotUnregisterRequiredPrimaryType; public static I18n cannotUnregisterDefaultPrimaryType; public static I18n cannotUnregisterInUseType; public static I18n cannotAddMixin; public static I18n invalidMixinTypeForNode; public static I18n notOrderable; public static I18n cannotUseMixinTypeAsPrimaryType; public static I18n unableToChangePrimaryTypeDueToPropertyDefinition; public static I18n unableToChangePrimaryTypeDueToParentsChildDefinition; public static I18n primaryTypeCannotBeAbstract; public static I18n setPrimaryTypeOnRootNodeIsNotSupported; public static I18n suppliedNodeTypeIsNotMixinType; public static I18n cannotRemoveShareableMixinThatIsShared; public static I18n errorReadingNodeTypesFromRemote; public static I18n problemReadingNodeTypesFromRemote; public static I18n errorSynchronizingNodeTypes; public static I18n errorRefreshingNodeTypesFromSystem; public static I18n problemRefreshingNodeTypesFromSystem; public static I18n errorRefreshingNodeTypes; public static I18n errorsParsingNodeTypeDefinitions; public static I18n errorsParsingStreamOfNodeTypeDefinitions; public static I18n warningsParsingNodeTypeDefinitions; public static I18n warningsParsingStreamOfNodeTypeDefinitions; public static I18n referentialIntegrityException; // Lock messages public static I18n nodeNotLockable; public static I18n cannotRemoveLockToken; public static I18n nodeIsLocked; public static I18n alreadyLocked; public static I18n parentAlreadyLocked; public static I18n descendantAlreadyLocked; public static I18n notLocked; public static I18n lockTokenNotHeld; public static I18n lockTokenAlreadyHeld; public static I18n invalidLockToken; public static I18n changedNodeCannotBeLocked; public static I18n changedNodeCannotBeUnlocked; public static I18n uuidRequiredForLock; // JcrObservationManager messages public static I18n cannotCreateUuid; public static I18n cannotPerformNodeTypeCheck; public static I18n sessionIsNotActive; // Versioning messages public static I18n nodeIsCheckedIn; public static I18n cannotCreateChildOnCheckedInNodeSinceOpvOfChildDefinitionIsNotIgnore; public static I18n cannotRemoveChildOnCheckedInNodeSinceOpvOfChildDefinitionIsNotIgnore; public static I18n cannotRemoveFromProtectedNode; public static I18n cannotRemoveVersion; public static I18n pendingMergeConflicts; public static I18n invalidVersion; public static I18n invalidVersionLabel; public static I18n invalidVersionName; public static I18n versionLabelAlreadyExists; public static I18n labeledNodeNotFound; public static I18n requiresVersionable; public static I18n cannotRestoreRootVersion; public static I18n cannotCheckinNodeWithAbortProperty; public static I18n cannotCheckinNodeWithAbortChildNode; public static I18n noExistingVersionForRestore; public static I18n invalidVersionForRestore; public static I18n versionNotInMergeFailed; public static I18n unrootedVersionsInRestore; public static I18n errorDuringCheckinNode; public static I18n noVersionHistoryForTransientVersionableNodes; public static I18n versionHistoryForNewlyVersionableNodesNotAvailableUntilSave; public static I18n versionHistoryNotEmpty; public static I18n nodeIsShareable; public static I18n creatingWorkspacesIsNotAllowedInRepository; public static I18n workspaceHasBeenDeleted; public static I18n unableToDestroyPredefinedWorkspaceInRepository; public static I18n unableToDestroyDefaultWorkspaceInRepository; public static I18n unableToDestroySystemWorkspaceInRepository; public static I18n workspaceNotFound; public static I18n unableToRestoreAtAbsPathNodeAlreadyExists; public static I18n unableToFindRepositoryConfigurationSchema; public static I18n unableToLoadRepositoryConfigurationSchema; public static I18n errorsInRepositoryConfiguration; // Engine public static I18n engineIsNotRunning; public static I18n engineAtJndiLocationIsNotRunning; public static I18n repositoryConfigurationIsNotValid; public static I18n startingOfRepositoryWasCancelled; public static I18n startingOfRepositoryWasInterrupted; public static I18n failedToShutdownDeployedRepository; public static I18n repositoryIsAlreadyDeployed; public static I18n repositoryIsNotRunningOrHasBeenShutDown; public static I18n repositoryNotFoundInEngineAtJndiLocation; public static I18n repositoriesNotFoundInEngineAtJndiLocation; public static I18n potentialClasspathErrorAtJndiLocation; public static I18n errorStartingRepository; public static I18n storageRelatedConfigurationChangesWillTakeEffectAfterShutdown; public static I18n errorShuttingDownJcrRepositoryFactory; public static I18n repositoryNameDoesNotMatchConfigurationName; public static I18n errorWhileShuttingDownRepositoryInJndi; public static I18n errorWhileShuttingDownEngineInJndi; public static I18n nodeModifiedBySessionWasRemovedByAnotherSession; public static I18n nodeCreatedBySessionUsedExistingKey; public static I18n errorRemovingISPNCache; public static I18n failedWhileRollingBackDestroyToRuntimeError; public static I18n unexpectedException; public static I18n errorDeterminingCurrentTransactionAssumingNone; public static I18n errorWhileRollingBackActiveTransactionUsingWorkspaceThatIsBeingDeleted; public static I18n configurationError; public static I18n configurationWarning; public static I18n errorDuringGarbageCollection; public static I18n errorMarkingBinaryValuesUnused; public static I18n errorMarkingBinaryValuesUsed; public static I18n errorStoringMimeType; public static I18n errorStoringExtractedText; public static I18n errorReadingExtractedText; public static I18n unableToCreateDirectoryForBinaryStore; public static I18n unableToReadTemporaryDirectory; public static I18n unableToWriteTemporaryDirectory; public static I18n unableToPersistBinaryValueToFileSystemStore; public static I18n unableToDeleteTemporaryFile; public static I18n unableToFindBinaryValue; public static I18n unableToFindBinaryValueInCache; public static I18n tempDirectorySystemPropertyMustBeSet; public static I18n errorReadingBinaryValue; public static I18n errorStoringBinaryValue; public static I18n errorLockingBinaryValue; public static I18n errorKillingRepository; public static I18n errorKillingEngine; // Lucene query engine ... public static I18n errorRetrievingExtractedTextFile; public static I18n errorExtractingTextFromBinary; public static I18n errorAddingBinaryTextToIndex; public static I18n missingQueryVariableValue; public static I18n errorClosingLuceneReaderForIndex; public static I18n ignoringIndexingProperty; public static I18n locationForIndexesIsNotDirectory; public static I18n locationForIndexesCannotBeRead; public static I18n locationForIndexesCannotBeWritten; public static I18n errorWhileCommittingIndexChanges; public static I18n errorWhileRollingBackIndexChanges; public static I18n missingVariableValue; public static I18n unableToReadMediaTypeRegistry; public static I18n unableToInitializeMimeTypeDetector; public static I18n noMimeTypeDetectorsFound; public static I18n invalidInitialContentValue; public static I18n cannotLoadInitialContentFile; public static I18n errorWhileReadingInitialContentFile; public static I18n errorWhileParsingInitialContentFile; public static I18n errorDuringInitialInitialization; public static I18n cannotLoadCndFile; public static I18n errorReadingCndFile; public static I18n invalidUrl; public static I18n timeoutWhileShuttingRepositoryDown; public static I18n repositoryNotFound; public static I18n federationNodeKeyDoesNotBelongToSource; public static I18n invalidProjectionPath; public static I18n invalidProjectionExpression; public static I18n projectedPathPointsTowardsInternalNode; public static I18n errorStoringProjection; public static I18n errorRemovingProjection; public static I18n reindexMissingNoIndexesExist; public static I18n noReindex; public static I18n reindexAll; public static I18n noIndexesExist; public static I18n errorCreatingDatabaseTable; public static I18n cannotLocateConnectionFactory; public static I18n cannotLocateQueue; public static I18n unexpectedJMSException; public static I18n incorrectJMSMessageType; public static I18n unknownIndexName; public static I18n cannotReadJMSMessage; public static I18n errorWhileShuttingDownListener; public static I18n errorWhileStartingUpListener; public static I18n enablingDocumentOptimization; public static I18n beginChildrenOptimization; public static I18n completeChildrenOptimization; public static I18n errorDuringChildrenOptimization; public static I18n mBeanAlreadyRegistered; public static I18n cannotRegisterMBean; public static I18n cannotUnRegisterMBean; public static I18n upgrade3_6_0Running; public static I18n upgrade3_6_0CannotUpdateNodeTypes; public static I18n upgrade3_6_0CannotUpdateLocks; public static I18n upgrade4_0_0_Alpha1_Running; public static I18n upgrade4_0_0_Alpha1_Failed; public static I18n cannotStartJournal; public static I18n cannotStopJournal; public static I18n journalHasNotCompletedReconciliation; private JcrI18n() { } static { try { I18n.initialize(JcrI18n.class); } catch (final Exception err) { // CHECKSTYLE IGNORE check FOR NEXT 1 LINES System.err.println(err); } } }
package org.usip.osp.persistence; import java.io.*; import java.util.List; import java.util.Vector; import javax.persistence.*; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.hibernate.annotations.Proxy; import org.usip.osp.baseobjects.USIP_OSP_Properties; import org.usip.osp.baseobjects.USIP_OSP_Util; import org.usip.osp.baseobjects.User; import org.usip.osp.communications.Emailer; import org.usip.osp.networking.SessionObjectBase; /* * This file is part of the USIP Open Simulation Platform.<br> * * The USIP Open Simulation Platform is free software; you can * redistribute it and/or modify it under the terms of the new BSD Style license * associated with this distribution.<br> * * The USIP Open Simulation Platform is distributed WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. <BR> * */ @Entity @Proxy(lazy = false) public class OSPErrors { public static final int ERROR_INCONSEQUENTIAL = 0; public static final int ERROR_MILD = 1; public static final int ERROR_ANNOYING = 2; public static final int ERROR_SEVERE = 3; public static final int ERROR_SHOWSTOPPER = 4; public static final int SOURCE_OTHER = 0; public static final int SOURCE_JSP = 1; public static final int SOURCE_JAVA = 2; public OSPErrors(){ } /** Database id of this Simulation. */ @Id @GeneratedValue private Long id; /** Schema in which this error occurred. */ private String dBschema; /** User id of the user who encountered this error. */ private Long userId; /** User requested email when this is resolved. */ private boolean userRequestedEmail = false; /** Email of the user encountering this error */ private String userEmail = ""; /** Notes left by the user */ @Lob private String userNotes = ""; /** Date of this error */ private java.util.Date errorDate = new java.util.Date(); /** Error message*/ @Lob private String errorMessage = ""; /** Stacktrace of this error */ @Lob private String errorText = ""; /** Severity, as recorded by the player */ private int errorSeverity = 0; /** Source of error: web, java, or other. */ private int errorSource = 0; /** Indicates if this error has been sent */ private boolean errorSentByEmail; /** Date email on this error was sent */ private java.util.Date emailDate = new java.util.Date(); /** Notes left by the admin on this error */ @Lob private String adminNotes; /** Initials of the admin marking this error as processed */ private String adminInitials; /** Number of this error in our issue tracker */ private String errorNumber; /** Whether this error has been marked as dealt with. */ private boolean errorProcessed = false; /** * Pull this error out of the database. * * @param error_id * @return */ public static OSPErrors getById(Long error_id) { MultiSchemaHibernateUtil.beginTransaction( MultiSchemaHibernateUtil.principalschema, true); OSPErrors err = (OSPErrors) MultiSchemaHibernateUtil.getSession( MultiSchemaHibernateUtil.principalschema, true).get( OSPErrors.class, error_id); MultiSchemaHibernateUtil .commitAndCloseTransaction(MultiSchemaHibernateUtil.principalschema); return err; } /** * Saves this error to the database. */ public void saveMe(){ MultiSchemaHibernateUtil.beginTransaction(MultiSchemaHibernateUtil.principalschema, true); MultiSchemaHibernateUtil.getSession(MultiSchemaHibernateUtil.principalschema, true).saveOrUpdate(this); MultiSchemaHibernateUtil.commitAndCloseTransaction(MultiSchemaHibernateUtil.principalschema); } /** * * @param request * @return */ public static OSPErrors processForm(HttpServletRequest request){ OSPErrors returnError = new OSPErrors(); SchemaInformationObject sio = null; try { String error_id = request.getParameter("error_id"); if ((error_id != null) && (!(error_id.equalsIgnoreCase("null")))){ returnError = OSPErrors.getById(new Long(error_id)); String user_notes = request.getParameter("user_notes"); String user_email = request.getParameter("user_email"); String user_err_level = request.getParameter("user_err_level"); returnError.setUserNotes(user_notes); returnError.setUserEmail(user_email); if ((user_err_level != null) && (!(user_err_level.equalsIgnoreCase("null")))){ returnError.setErrorSeverity(new Long(user_err_level).intValue()); } returnError.saveMe(); sio = SchemaInformationObject.lookUpSIOByName(returnError.getdBschema()); } } catch (Exception e){ e.printStackTrace(); } returnError.emailErrors(sio, true); return returnError; } /** * Takes the initial error encountered on a jsp and logs it to the database. * @param exception * @param request * @return */ public static OSPErrors storeWebErrors(Throwable exception, HttpServletRequest request){ OSPErrors err = new OSPErrors(); err.setErrorSource(SOURCE_JSP); err.setErrorMessage("Error Message: " + exception.toString()); SessionObjectBase sob = USIP_OSP_Util.getSessionObjectBaseIfFound(request); return saveAndEmailError(err, exception, sob); } /** * Used to attempt to email notice of an internal error. * * @param exception * @return */ public static OSPErrors storeInternalErrors(Throwable exception, SessionObjectBase sob){ OSPErrors err = new OSPErrors(); err.setErrorSource(SOURCE_JAVA); err.setErrorMessage("Error Message: " + exception.toString()); return saveAndEmailError(err, exception, sob); } /** * Provides a warning of something abnormal. * * @param warningText * @param sob * @return */ public static OSPErrors storeInternalWarning(String warningText, SessionObjectBase sob){ OSPErrors err = new OSPErrors(); err.setErrorSource(SOURCE_JAVA); err.setErrorMessage("Warning Message: " + warningText); return saveAndEmailError(err, null, sob); } /** * Saved the error to the database and send an email announcement of it. * @param err * @param exception * @param sob * @return */ public static OSPErrors saveAndEmailError(OSPErrors err, Throwable exception, SessionObjectBase sob){ SchemaInformationObject sio = null; String schema = null; Long userId = null; if (sob != null){ schema = sob.schema; userId = sob.user_id; } if (sob == null){ sio = SchemaInformationObject.getFirstUpEmailServer(); schema = sio.getSchema_name(); // the first user created is always the first admin. userId = new Long(1); } return saveAndEmailError(err, exception, schema, userId); } public static OSPErrors saveAndEmailError(OSPErrors err, Throwable exception, String schema, Long userId){ SchemaInformationObject sio = null; try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); if (exception != null) { exception.printStackTrace(pw); } err.setErrorText(sw.getBuffer().toString()); sw.close(); pw.close(); // Must have logged in, so record additional information if found. if (userId != null){ err.setUserId(userId); err.setdBschema(schema); User user = User.getById(schema, userId); if (user != null){ err.setUserEmail(user.getUserName()); } sio = SchemaInformationObject.lookUpSIOByName(schema); } } catch (Exception e){ Logger.getRootLogger().error("ERROR IN ERROR SYSTEM!"); e.printStackTrace(); } err.saveMe(); if (sio != null){ err.emailErrors(sio, false); } return err; } /** * Emails the error, if email has been enabled. * * @param sio * @param fromUser * @return */ public boolean emailErrors(SchemaInformationObject sio, boolean fromUser){ String subject = "ERROR on " + USIP_OSP_Properties.getValue("server_name"); if (sio == null){ sio = SchemaInformationObject.getFirstUpEmailServer(); subject += ", 1st email sending"; } else { subject += ", error on " + sio.getSchema_name(); } subject += ", error number " + this.getId(); if (fromUser) { subject = "User email on " + subject; } String lt = USIP_OSP_Util.lineTerminator; String message = "Error Date " + this.getErrorDate() + lt; message += this.getErrorMessage() + lt + lt; message += this.getErrorText(); if (fromUser){ message += "respond to " + this.getUserEmail() + lt; message += "who stated: " + this.getUserNotes() + lt; } System.out.println(message); if (sio.isEmailEnabled()){ Emailer.postMail(sio, sio.getEmailTechAddress(), subject, message, message, sio.getEmailNoreplyAddress(), null, new Vector(), new Vector()); return true; } else { System.out.println(message); return false; } } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getdBschema() { return dBschema; } public void setdBschema(String dBschema) { this.dBschema = dBschema; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public boolean isUserRequestedEmail() { return userRequestedEmail; } public void setUserRequestedEmail(boolean userRequestedEmail) { this.userRequestedEmail = userRequestedEmail; } public String getUserNotes() { return userNotes; } public void setUserNotes(String userNotes) { this.userNotes = userNotes; } public java.util.Date getErrorDate() { return errorDate; } public void setErrorDate(java.util.Date errorDate) { this.errorDate = errorDate; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public String getErrorText() { return errorText; } public void setErrorText(String errorText) { this.errorText = errorText; } public int getErrorSeverity() { return errorSeverity; } public void setErrorSeverity(int errorSeverity) { this.errorSeverity = errorSeverity; } public int getErrorSource() { return errorSource; } public void setErrorSource(int errorSource) { this.errorSource = errorSource; } public boolean isErrorSentByEmail() { return errorSentByEmail; } public void setErrorSentByEmail(boolean errorSentByEmail) { this.errorSentByEmail = errorSentByEmail; } public java.util.Date getEmailDate() { return emailDate; } public void setEmailDate(java.util.Date emailDate) { this.emailDate = emailDate; } public String getAdminNotes() { return adminNotes; } public void setAdminNotes(String adminNotes) { this.adminNotes = adminNotes; } public String getAdminInitials() { return adminInitials; } public void setAdminInitials(String adminInitials) { this.adminInitials = adminInitials; } public String getErrorNumber() { return errorNumber; } public void setErrorNumber(String errorNumber) { this.errorNumber = errorNumber; } public boolean isErrorProcessed() { return errorProcessed; } public void setErrorProcessed(boolean errorProcessed) { this.errorProcessed = errorProcessed; } /** Returns all of the errors on this system, processed or unprocessed depending on * what is passed in. * * @param schema * @param processedErrors * @return */ public static List<OSPErrors> getAllErrors(boolean processedErrors){ String hqlString = "from OSPErrors where errorProcessed is false"; if (processedErrors){ hqlString = "from OSPErrors where errorProcessed is true"; } MultiSchemaHibernateUtil.beginTransaction( MultiSchemaHibernateUtil.principalschema, true); List<OSPErrors> returnList = MultiSchemaHibernateUtil.getSession( MultiSchemaHibernateUtil.principalschema, true).createQuery(hqlString).list(); //$NON-NLS-1$ MultiSchemaHibernateUtil .commitAndCloseTransaction(MultiSchemaHibernateUtil.principalschema); return returnList; } }
package org.broadinstitute.sting.utils.codecs.beagle; /* * Copyright (c) 2010 The Broad Institute * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import org.broad.tribble.Feature; import org.broad.tribble.exception.CodecLineParsingException; import org.broad.tribble.readers.AsciiLineReader; import org.broad.tribble.readers.LineReader; import org.broadinstitute.sting.gatk.refdata.ReferenceDependentFeatureCodec; import org.broadinstitute.sting.utils.GenomeLoc; import org.broadinstitute.sting.utils.GenomeLocParser; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Pattern; /** * TODO GUILLERMO DEL ANGEL * * <p> * Codec Description * </p> * * <p> * See also: @see <a href="http://vcftools.sourceforge.net/specs.html">VCF specification</a><br> * </p> * </p> * * <h2>File format example</h2> * <pre> * line 1 * line 2 * line 3 * </pre> * * @author Mark DePristo * @since 2010 */ public class BeagleCodec implements ReferenceDependentFeatureCodec<BeagleFeature> { private String[] header; public enum BeagleReaderType {PROBLIKELIHOOD, GENOTYPES, R2}; private BeagleReaderType readerType; private int valuesPerSample; private int initialSampleIndex; private int markerPosition; private ArrayList<String> sampleNames; private int expectedTokensPerLine; private static final String delimiterRegex = "\\s+"; /** * The parser to use when resolving genome-wide locations. */ private GenomeLocParser genomeLocParser; /** * Set the parser to use when resolving genetic data. * @param genomeLocParser The supplied parser. */ public void setGenomeLocParser(GenomeLocParser genomeLocParser) { this.genomeLocParser = genomeLocParser; } public Feature decodeLoc(String line) { return decode(line); } public static String[] readHeader(final File source) throws IOException { FileInputStream is = new FileInputStream(source); try { return readHeader(new AsciiLineReader(is), null); } finally { is.close(); } } public Object readHeader(LineReader reader) { int[] lineCounter = new int[1]; try { header = readHeader(reader, lineCounter); Boolean getSamples = true; markerPosition = 0; //default value for all readers if (header[0].matches("I")) { // Phased genotype Beagle files start with "I" readerType = BeagleReaderType.GENOTYPES; valuesPerSample = 2; initialSampleIndex = 2; markerPosition = 1; } else if (header[0].matches("marker")) { readerType = BeagleReaderType.PROBLIKELIHOOD; valuesPerSample = 3; initialSampleIndex = 3; } else { readerType = BeagleReaderType.R2; getSamples = false; // signal we don't have a header lineCounter[0] = 0; // not needed, but for consistency: valuesPerSample = 0; initialSampleIndex = 0; } sampleNames = new ArrayList<String>(); if (getSamples) { for (int k = initialSampleIndex; k < header.length; k += valuesPerSample) sampleNames.add(header[k]); expectedTokensPerLine = sampleNames.size()*valuesPerSample+initialSampleIndex; } else { expectedTokensPerLine = 2; } } catch(IOException e) { throw new IllegalArgumentException("Unable to read from file.", e); } return header; } private static String[] readHeader(final LineReader source, int[] lineCounter) throws IOException { String[] header = null; int numLines = 0; //find the 1st line that's non-empty and not a comment String line; while( (line = source.readLine()) != null ) { numLines++; if ( line.trim().isEmpty() ) { continue; } //parse the header header = line.split(delimiterRegex); break; } // check that we found the header if ( header == null ) { throw new IllegalArgumentException("No header in " + source); } if(lineCounter != null) { lineCounter[0] = numLines; } return header; } private static Pattern MARKER_PATTERN = Pattern.compile("(.+):([0-9]+)"); @Override public Class<BeagleFeature> getFeatureType() { return BeagleFeature.class; } public BeagleFeature decode(String line) { String[] tokens; // split the line tokens = line.split(delimiterRegex); if (tokens.length != expectedTokensPerLine) throw new CodecLineParsingException("Incorrect number of fields in Beagle input on line "+line); BeagleFeature bglFeature = new BeagleFeature(); final GenomeLoc loc = genomeLocParser.parseGenomeLoc(tokens[markerPosition]); //GenomeLocParser.parseGenomeLoc(values.get(0)); - TODO switch to this //parse the location: common to all readers bglFeature.setChr(loc.getContig()); bglFeature.setStart((int) loc.getStart()); bglFeature.setEnd((int) loc.getStop()); // Parse R2 if needed if (readerType == BeagleReaderType.R2) { bglFeature.setR2value(Double.valueOf(tokens[1])); } else if (readerType == BeagleReaderType.GENOTYPES) { // read phased Genotype pairs HashMap<String, ArrayList<String>> sampleGenotypes = new HashMap<String, ArrayList<String>>(); for ( int i = 2; i < tokens.length; i+=2 ) { String sampleName = sampleNames.get(i/2-1); if ( ! sampleGenotypes.containsKey(sampleName) ) { sampleGenotypes.put(sampleName, new ArrayList<String>()); } sampleGenotypes.get(sampleName).add(tokens[i]); sampleGenotypes.get(sampleName).add(tokens[i+1]); } bglFeature.setGenotypes(sampleGenotypes); } else { // read probabilities/likelihood trios and alleles bglFeature.setAlleleA(tokens[1], true); bglFeature.setAlleleB(tokens[2], false); HashMap<String, ArrayList<String>> sampleProbLikelihoods = new HashMap<String, ArrayList<String>>(); for ( int i = 3; i < tokens.length; i+=3 ) { String sampleName = sampleNames.get(i/3-1); if ( ! sampleProbLikelihoods.containsKey(sampleName) ) { sampleProbLikelihoods.put(sampleName, new ArrayList<String>()); } sampleProbLikelihoods.get(sampleName).add(tokens[i]); sampleProbLikelihoods.get(sampleName).add(tokens[i+1]); sampleProbLikelihoods.get(sampleName).add(tokens[i+2]); } bglFeature.setProbLikelihoods(sampleProbLikelihoods); } return bglFeature; } public boolean canDecode(final String potentialInput) { return false; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.crypto; import java.io.EOFException; import java.io.FileDescriptor; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.EnumSet; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ByteBufferPositionedReadable; import org.apache.hadoop.fs.ByteBufferReadable; import org.apache.hadoop.fs.CanSetDropBehind; import org.apache.hadoop.fs.CanSetReadahead; import org.apache.hadoop.fs.CanUnbuffer; import org.apache.hadoop.fs.HasEnhancedByteBufferAccess; import org.apache.hadoop.fs.HasFileDescriptor; import org.apache.hadoop.fs.PositionedReadable; import org.apache.hadoop.fs.ReadOption; import org.apache.hadoop.fs.Seekable; import org.apache.hadoop.fs.StreamCapabilities; import org.apache.hadoop.fs.Syncable; import org.apache.hadoop.io.ByteBufferPool; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.DataOutputBuffer; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.apache.hadoop.fs.contract.ContractTestUtils.assertCapabilities; public class TestCryptoStreams extends CryptoStreamsTestBase { /** * Data storage. * {@link #getOutputStream(int)} will write to this buf. * {@link #getInputStream(int)} will read from this buf. */ private byte[] buf; private int bufLen; @BeforeClass public static void init() throws Exception { Configuration conf = new Configuration(); codec = CryptoCodec.getInstance(conf); } @AfterClass public static void shutdown() throws Exception { } @Override protected OutputStream getOutputStream(int bufferSize, byte[] key, byte[] iv) throws IOException { DataOutputBuffer out = new DataOutputBuffer() { @Override public void flush() throws IOException { buf = getData(); bufLen = getLength(); } @Override public void close() throws IOException { buf = getData(); bufLen = getLength(); } }; return new CryptoOutputStream(new FakeOutputStream(out), codec, bufferSize, key, iv); } @Override protected InputStream getInputStream(int bufferSize, byte[] key, byte[] iv) throws IOException { DataInputBuffer in = new DataInputBuffer(); in.reset(buf, 0, bufLen); return new CryptoInputStream(new FakeInputStream(in), codec, bufferSize, key, iv); } private class FakeOutputStream extends OutputStream implements Syncable, CanSetDropBehind, StreamCapabilities{ private final byte[] oneByteBuf = new byte[1]; private final DataOutputBuffer out; private boolean closed; public FakeOutputStream(DataOutputBuffer out) { this.out = out; } @Override public void write(byte b[], int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } checkStream(); out.write(b, off, len); } @Override public void flush() throws IOException { checkStream(); out.flush(); } @Override public void close() throws IOException { if (closed) { return; } out.close(); closed = true; } @Override public void write(int b) throws IOException { oneByteBuf[0] = (byte)(b & 0xff); write(oneByteBuf, 0, oneByteBuf.length); } @Override public void setDropBehind(Boolean dropCache) throws IOException, UnsupportedOperationException { } @Override public void hflush() throws IOException { checkStream(); flush(); } @Override public void hsync() throws IOException { checkStream(); flush(); } @Override public boolean hasCapability(String capability) { switch (capability.toLowerCase()) { case StreamCapabilities.HFLUSH: case StreamCapabilities.HSYNC: case StreamCapabilities.DROPBEHIND: return true; default: return false; } } private void checkStream() throws IOException { if (closed) { throw new IOException("Stream is closed!"); } } } static class FakeInputStream extends InputStream implements Seekable, PositionedReadable, ByteBufferReadable, HasFileDescriptor, CanSetDropBehind, CanSetReadahead, HasEnhancedByteBufferAccess, CanUnbuffer, StreamCapabilities, ByteBufferPositionedReadable { private final byte[] oneByteBuf = new byte[1]; private int pos = 0; private final byte[] data; private final int length; private boolean closed = false; FakeInputStream(DataInputBuffer in) { data = in.getData(); length = in.getLength(); } @Override public void seek(long pos) throws IOException { if (pos > length) { throw new IOException("Cannot seek after EOF."); } if (pos < 0) { throw new IOException("Cannot seek to negative offset."); } checkStream(); this.pos = (int)pos; } @Override public long getPos() throws IOException { return pos; } @Override public int available() throws IOException { return length - pos; } @Override public int read(byte b[], int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } checkStream(); if (pos < length) { int n = (int) Math.min(len, length - pos); System.arraycopy(data, pos, b, off, n); pos += n; return n; } return -1; } private void checkStream() throws IOException { if (closed) { throw new IOException("Stream is closed!"); } } @Override public int read(ByteBuffer buf) throws IOException { checkStream(); if (pos < length) { int n = (int) Math.min(buf.remaining(), length - pos); if (n > 0) { buf.put(data, pos, n); } pos += n; return n; } return -1; } @Override public long skip(long n) throws IOException { checkStream(); if ( n > 0 ) { if( n + pos > length ) { n = length - pos; } pos += n; return n; } return n < 0 ? -1 : 0; } @Override public void close() throws IOException { closed = true; } @Override public int read(long position, byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } if (position > length) { throw new IOException("Cannot read after EOF."); } if (position < 0) { throw new IOException("Cannot read to negative offset."); } checkStream(); if (position < length) { int n = (int) Math.min(len, length - position); System.arraycopy(data, (int)position, b, off, n); return n; } return -1; } @Override public int read(long position, ByteBuffer buf) throws IOException { if (buf == null) { throw new NullPointerException(); } else if (!buf.hasRemaining()) { return 0; } if (position > length) { throw new IOException("Cannot read after EOF."); } if (position < 0) { throw new IOException("Cannot read to negative offset."); } checkStream(); if (position < length) { int n = (int) Math.min(buf.remaining(), length - position); buf.put(data, (int) position, n); return n; } return -1; } @Override public void readFully(long position, ByteBuffer buf) throws IOException { if (buf == null) { throw new NullPointerException(); } else if (!buf.hasRemaining()) { return; } if (position > length) { throw new IOException("Cannot read after EOF."); } if (position < 0) { throw new IOException("Cannot read to negative offset."); } checkStream(); if (position + buf.remaining() > length) { throw new EOFException("Reach the end of stream."); } buf.put(data, (int) position, buf.remaining()); } @Override public void readFully(long position, byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } if (position > length) { throw new IOException("Cannot read after EOF."); } if (position < 0) { throw new IOException("Cannot read to negative offset."); } checkStream(); if (position + len > length) { throw new EOFException("Reach the end of stream."); } System.arraycopy(data, (int)position, b, off, len); } @Override public void readFully(long position, byte[] buffer) throws IOException { readFully(position, buffer, 0, buffer.length); } @Override public ByteBuffer read(ByteBufferPool bufferPool, int maxLength, EnumSet<ReadOption> opts) throws IOException, UnsupportedOperationException { if (bufferPool == null) { throw new IOException("Please specify buffer pool."); } ByteBuffer buffer = bufferPool.getBuffer(true, maxLength); int pos = buffer.position(); int n = read(buffer); if (n >= 0) { buffer.position(pos); return buffer; } return null; } @Override public void releaseBuffer(ByteBuffer buffer) { } @Override public void setReadahead(Long readahead) throws IOException, UnsupportedOperationException { } @Override public void setDropBehind(Boolean dropCache) throws IOException, UnsupportedOperationException { } @Override public void unbuffer() { } @Override public boolean hasCapability(String capability) { switch (capability.toLowerCase()) { case StreamCapabilities.READAHEAD: case StreamCapabilities.DROPBEHIND: case StreamCapabilities.UNBUFFER: case StreamCapabilities.READBYTEBUFFER: case StreamCapabilities.PREADBYTEBUFFER: return true; default: return false; } } @Override public FileDescriptor getFileDescriptor() throws IOException { return null; } @Override public boolean seekToNewSource(long targetPos) throws IOException { if (targetPos > length) { throw new IOException("Attempted to read past end of file."); } if (targetPos < 0) { throw new IOException("Cannot seek after EOF."); } checkStream(); this.pos = (int)targetPos; return false; } @Override public int read() throws IOException { int ret = read( oneByteBuf, 0, 1 ); return ( ret <= 0 ) ? -1 : (oneByteBuf[0] & 0xff); } } /** * This tests {@link StreamCapabilities#hasCapability(String)} for the * the underlying streams. */ @Test(timeout = 120000) public void testHasCapability() throws Exception { // verify hasCapability returns what FakeOutputStream is set up for CryptoOutputStream cos = (CryptoOutputStream) getOutputStream(defaultBufferSize, key, iv); assertCapabilities(cos, new String[] { StreamCapabilities.HFLUSH, StreamCapabilities.HSYNC, StreamCapabilities.DROPBEHIND }, new String[] { StreamCapabilities.READAHEAD, StreamCapabilities.UNBUFFER } ); // verify hasCapability for input stream CryptoInputStream cis = (CryptoInputStream) getInputStream(defaultBufferSize, key, iv); assertCapabilities(cis, new String[] { StreamCapabilities.DROPBEHIND, StreamCapabilities.READAHEAD, StreamCapabilities.UNBUFFER, StreamCapabilities.READBYTEBUFFER, StreamCapabilities.PREADBYTEBUFFER }, new String[] { StreamCapabilities.HFLUSH, StreamCapabilities.HSYNC } ); } }
/* * Copyright (C) 2008 Google 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.google.gxp.compiler.scala; import static com.google.gxp.compiler.base.OutputLanguage.SCALA; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gxp.compiler.alerts.AlertSink; import com.google.gxp.compiler.alerts.SourcePosition; import com.google.gxp.compiler.alerts.common.NothingToCompileError; import com.google.gxp.compiler.base.BooleanType; import com.google.gxp.compiler.base.BoundImplementsDeclaration; import com.google.gxp.compiler.base.BundleType; import com.google.gxp.compiler.base.ClassImport; import com.google.gxp.compiler.base.Constructor; import com.google.gxp.compiler.base.ContentType; import com.google.gxp.compiler.base.DefaultingImportVisitor; import com.google.gxp.compiler.base.FormalTypeParameter; import com.google.gxp.compiler.base.Implementable; import com.google.gxp.compiler.base.ImplementsDeclaration; import com.google.gxp.compiler.base.ImplementsVisitor; import com.google.gxp.compiler.base.Import; import com.google.gxp.compiler.base.ImportVisitor; import com.google.gxp.compiler.base.InstanceType; import com.google.gxp.compiler.base.Interface; import com.google.gxp.compiler.base.JavaAnnotation; import com.google.gxp.compiler.base.NativeImplementsDeclaration; import com.google.gxp.compiler.base.NativeType; import com.google.gxp.compiler.base.NullRoot; import com.google.gxp.compiler.base.PackageImport; import com.google.gxp.compiler.base.Parameter; import com.google.gxp.compiler.base.Root; import com.google.gxp.compiler.base.RootVisitor; import com.google.gxp.compiler.base.Template; import com.google.gxp.compiler.base.TemplateName; import com.google.gxp.compiler.base.TemplateType; import com.google.gxp.compiler.base.ThrowsDeclaration; import com.google.gxp.compiler.base.Tree; import com.google.gxp.compiler.base.Type; import com.google.gxp.compiler.base.TypeVisitor; import com.google.gxp.compiler.base.UnboundImplementsDeclaration; import com.google.gxp.compiler.base.UnexpectedNodeException; import com.google.gxp.compiler.codegen.BaseCodeGenerator; import com.google.gxp.compiler.codegen.BracesCodeGenerator; import java.io.IOException; import java.util.List; import java.util.Set; /** * Base class for the two scala code generators. Contains functionallity * common to both. */ public abstract class BaseScalaCodeGenerator<T extends Tree<Root>> extends BracesCodeGenerator<T> { protected final String runtimeMessageSource; /** * @param tree the MessageExtractedTree to compile. * @param runtimeMessageSource the message source to use at runtime, or null * if none was provided. This is a (typically dotted) prefix used when * loading message resources at runtime. */ protected BaseScalaCodeGenerator(T tree, String runtimeMessageSource) { super(tree); this.runtimeMessageSource = runtimeMessageSource; } public void generateCode(final Appendable appendable, final AlertSink alertSink) throws IOException { alertSink.addAll(tree.getAlerts()); root.acceptVisitor(new RootVisitor<Void>() { public Void visitInterface(Interface iface) { validateFormalTypeParameters(alertSink, iface.getFormalTypeParameters()); new InterfaceWorker(appendable, alertSink, iface).run(); return null; } public Void visitNullRoot(NullRoot nullRoot) { alertSink.add(new NothingToCompileError(nullRoot.getSourcePosition())); return null; } public Void visitTemplate(Template template) { validateFormalTypeParameters(alertSink, template.getFormalTypeParameters()); createTemplateWorker(appendable, alertSink, template, runtimeMessageSource).run(); return null; } }); } private void validateFormalTypeParameters(AlertSink alertSink, List<FormalTypeParameter> formalTypeParameters) { for (FormalTypeParameter formalTypeParameter : formalTypeParameters) { SCALA.validateName(alertSink, formalTypeParameter, formalTypeParameter.getName()); } } protected abstract static class Worker extends BracesCodeGenerator.Worker { protected Worker(Appendable appendable, AlertSink alertSink) { super(appendable, alertSink); } private static final String HEADER_FORMAT = loadFormat("header"); protected void appendHeader(Root root) { super.appendHeader(root); TemplateName name = root.getName(); String sourceName = root.getSourcePosition().getSourceName(); String packageName = (name == null) ? "" : name.getPackageName(); // passing a null SourcePosition insures that we never get tail comments formatLine((SourcePosition)null, HEADER_FORMAT, sourceName, packageName); } private final ImportVisitor<Void> IMPORT_VISITOR = new DefaultingImportVisitor<Void>(){ public Void defaultVisitImport(Import imp) { // do nothing return null; } public Void visitClassImport(ClassImport imp) { formatLine(imp.getSourcePosition(), "import %s", imp.getClassName().toString()); return null; } public Void visitPackageImport(PackageImport imp) { formatLine(imp.getSourcePosition(), "import %s._", imp.getPackageName()); return null; } }; protected void appendImports(Root root) { for (String imp : root.getSchema().getScalaImports()) { appendLine(root.getSourcePosition(), "import " + imp); } for (Import imp : root.getImports()) { imp.acceptVisitor(IMPORT_VISITOR); } } protected void appendAnnotations(Iterable<JavaAnnotation> annotations) { for (JavaAnnotation annotation : annotations) { appendLine(annotation.getSourcePosition(), ScalaUtil.validateAnnotation(alertSink, annotation)); } } protected static final String GXP_OUT_VAR = "gxp$out"; protected static final String GXP_CONTEXT_VAR = "gxp_context"; protected static final String GXP_SIG = COMMA_JOINER.join(GXP_OUT_VAR + ": java.lang.Appendable", GXP_CONTEXT_VAR + ": com.google.gxp.base.GxpContext"); protected String getClassName(TemplateName name) { return (name == null) ? null : name.getBaseName(); } protected String toScalaType(Type type) { return type.acceptTypeVisitor(new TypeVisitor<String>() { public String visitBooleanType(BooleanType type) { return "boolean"; } public String visitBundleType(BundleType type) { StringBuilder sb = new StringBuilder("com.google.gxp.base.GxpAttrBundle["); sb.append(type.getSchema().getScalaType()); sb.append("]"); return sb.toString(); } public String visitContentType(ContentType type) { return type.getSchema().getScalaType(); } public String visitInstanceType(InstanceType type) { return type.getTemplateName().toString() + ".Interface"; } public String visitNativeType(NativeType type) { return ScalaUtil.validateType(alertSink, type); } public String visitTemplateType(TemplateType type) { return type.getTemplateName().toString(); } }); } protected Function<Parameter, String> parameterToCallName = new Function<Parameter, String>() { public String apply(Parameter param) { StringBuilder sb = new StringBuilder(); sb.append(param.getPrimaryName()); sb.append(": "); sb.append(toScalaType(param.getType())); return sb.toString(); } }; protected List<String> toBoundedTypeDecls(boolean includeExtends, Iterable<FormalTypeParameter> formalTypeParameters) { List<String> result = Lists.newArrayList(); for (FormalTypeParameter formalTypeParameter : formalTypeParameters) { if (!includeExtends || formalTypeParameter.getExtendsType() == null) { result.add(formalTypeParameter.getName()); } else { String type = ScalaUtil.validateConjunctiveType( alertSink, formalTypeParameter.getExtendsType()); result.add(formalTypeParameter.getName() + " <: " + type); } } return result; } protected void appendScalaFormalTypeParameters( StringBuilder sb, boolean includeExtends, List<FormalTypeParameter> formalTypeParameters) { if (!formalTypeParameters.isEmpty()) { sb.append("["); COMMA_JOINER.appendTo(sb, toBoundedTypeDecls(includeExtends, formalTypeParameters)); sb.append("]"); } } protected static String loadFormat(String name) { return BaseCodeGenerator.loadFormat("scala/" + name); } } protected static class InterfaceWorker extends Worker { protected final Interface iface; protected InterfaceWorker(Appendable appendable, AlertSink alertSink, Interface iface) { super(appendable, alertSink); this.iface = Preconditions.checkNotNull(iface); } public void run() { for (Parameter param : Iterables.filter(iface.getParameters(), Implementable.NOT_INSTANCE_PARAM)) { SCALA.validateName(alertSink, param, param.getPrimaryName()); } appendHeader(iface); appendImports(iface); appendLine(); appendInterface(); appendLine(); appendFooter(); } @Override protected SourcePosition getDefaultSourcePosition() { return iface.getSourcePosition(); } protected void appendInterface() { appendAnnotations(iface.getJavaAnnotations(JavaAnnotation.Element.INTERFACE)); StringBuilder sb = new StringBuilder("trait "); sb.append(getClassName(iface.getName())); appendScalaFormalTypeParameters(sb, true, iface.getFormalTypeParameters()); sb.append(" {"); appendLine(iface.getSourcePosition(), sb.toString()); appendLine(getWriteMethodSignature()); appendLine(getGetGxpClosureMethodSignature()); appendGetDefaultMethods(); appendConstructorMethods(); appendLine("}"); } private String getWriteMethodSignature() { StringBuilder sb = new StringBuilder("def write("); sb.append(GXP_SIG); for (Parameter param : Iterables.filter(iface.getParameters(), Implementable.NOT_INSTANCE_PARAM)) { sb.append(", "); sb.append(parameterToCallName.apply(param)); } sb.append("): Unit"); return sb.toString(); } private String getGetGxpClosureMethodSignature() { StringBuilder sb = new StringBuilder(); sb.append("def getGxpClosure("); COMMA_JOINER.appendTo(sb, Iterables.transform( Iterables.filter(iface.getParameters(), Implementable.NOT_INSTANCE_PARAM), parameterToCallName)); sb.append("): "); sb.append(iface.getSchema().getScalaType()); return sb.toString(); } private void appendGetDefaultMethods() { for (Parameter param : iface.getParameters()) { if (param.hasDefaultFlag()) { formatLine(param.getSourcePosition(), "def %s(): %s", getDefaultMethodName(param), toScalaType(param.getType())); } } } private void appendConstructorMethods() { for (Parameter param : iface.getParameters()) { if (param.hasConstructorFlag()) { formatLine(param.getSourcePosition(), "public %s %s(String %s);", toScalaType(param.getType()), getConstructorMethodName(param), param.getPrimaryName()); } } } } protected abstract TemplateWorker createTemplateWorker( Appendable appendable, AlertSink alertSink, Template template, String runtimeMessageSource); protected abstract static class TemplateWorker extends Worker { protected final Template template; protected TemplateWorker(Appendable appendable, AlertSink alertSink, Template template) { super(appendable, alertSink); this.template = Preconditions.checkNotNull(template); } public void run() { for (Parameter param : template.getAllParameters()) { SCALA.validateName(alertSink, param, param.getPrimaryName()); } appendHeader(template); appendImports(template); appendLine(); appendClass(); appendLine(); appendFooter(); } protected String getFullClassName(TemplateName templateName) { return (templateName == null) ? null : templateName.toString(); } protected abstract String getBaseClassName(); protected abstract void appendClass(); protected Function<Parameter, String> parameterToAnnotatedCallParameter = new Function<Parameter, String>() { public String apply(Parameter param) { StringBuilder sb = new StringBuilder(); sb.append("final "); for (JavaAnnotation annotation : param.getJavaAnnotations()) { sb.append(ScalaUtil.validateAnnotation(alertSink, annotation)); sb.append(" "); } sb.append(toScalaType(param.getType())); sb.append(" "); sb.append(param.getPrimaryName()); return sb.toString(); } }; private final ImplementsVisitor<String> javaNameImplementsVisitor = new ImplementsVisitor<String>() { public String visitUnboundImplementsDeclaration(UnboundImplementsDeclaration uid) { throw new UnexpectedNodeException(uid); } public String visitBoundImplementsDeclaration(BoundImplementsDeclaration bid) { return bid.getImplementable().getName().toString(); } public String visitNativeImplementsDeclaration(NativeImplementsDeclaration nid) { return toScalaType(nid.getNativeType()); } }; private final Function<ImplementsDeclaration, String> getInterfaceFromImplementsDeclaration = new Function<ImplementsDeclaration, String>() { public String apply(ImplementsDeclaration implementsDeclaration) { return implementsDeclaration.acceptImplementsVisitor(javaNameImplementsVisitor); } }; private void appendImplementsDeclaration(StringBuilder sb, List<ImplementsDeclaration> implementsDeclarations) { if (!implementsDeclarations.isEmpty()) { sb.append(" extends "); COMMA_JOINER.appendTo(sb, Iterables.transform(implementsDeclarations, getInterfaceFromImplementsDeclaration)); } } protected abstract void appendWriteMethodBody(); protected void appendWriteMethod() { appendLine(getWriteMethodSignature(true) + " {"); appendWriteMethodBody(); appendLine("}"); } /** * Get the base name of a fully qualified type name. */ protected String getBaseName(String fullName) { String[] parts = fullName.split("\\."); return parts[parts.length - 1]; } protected void appendGetGxpClosureMethod(boolean isStatic) { String scalaType = template.getSchema().getScalaType(); String tunnelingScalaType = "Tunneling" + getBaseName(scalaType); if (isStatic) { appendLine(); formatLine("private abstract static class %s", tunnelingScalaType); appendLine(" extends GxpTemplate.TunnelingGxpClosure"); formatLine(" implements %s {", scalaType); appendLine("}"); } appendLine(); appendLine(getGetGxpClosureMethodSignature(isStatic) + " {"); formatLine("return new %s() {", tunnelingScalaType); StringBuilder sb = new StringBuilder("public void writeImpl(" + GXP_SIG + ")"); sb.append(" {"); appendLine(sb); sb = new StringBuilder(); sb.append(isStatic ? getFullClassName(template.getName()) : "Instance.this"); sb.append(".write(" + GXP_OUT_VAR + ", " + GXP_CONTEXT_VAR); for (Parameter param : (isStatic ? template.getAllParameters() : template.getParameters())) { sb.append(", "); sb.append(param.getPrimaryName()); } sb.append(");"); appendLine(sb); appendLine("}"); appendLine("};"); appendLine("}"); } private static final String GET_ARG_LIST_FORMAT = loadFormat("getArgList"); protected void appendGetArgListMethod() { // create the constant StringBuilder sb = new StringBuilder( "private static final java.util.List<String> GXP$ARGLIST = "); List<String> parameterNames = Lists.newArrayList(); for (Parameter param : template.getAllParameters()) { parameterNames.add(SCALA.toStringLiteral(param.getPrimaryName())); } if (parameterNames.isEmpty()) { sb.append("java.util.Collections.emptyList();"); } else { sb.append("java.util.Collections.unmodifiableList(java.util.Arrays.asList("); COMMA_JOINER.appendTo(sb, parameterNames); sb.append("));"); } appendLine(); appendLine(sb); // create the accessor appendLine(); appendLine(GET_ARG_LIST_FORMAT); } protected enum Access { _public("public"), _private("private"), _protected("protected"); private final String s; Access(String s) { this.s = s; } public String toString() { return s; } } private String getWriteMethodSignature(boolean isStatic) { return getWriteMethodSignature(Access._public, isStatic, "write"); } protected String getWriteMethodSignature(Access access, boolean isStatic, String methodName) { Iterable<Parameter> params = isStatic ? template.getAllParameters() : template.getParameters(); StringBuilder sb = new StringBuilder(access.toString()); if (isStatic) { sb.append(" static"); if (!template.getFormalTypeParameters().isEmpty()) { sb.append(" "); } appendScalaFormalTypeParameters(sb, true, template.getFormalTypeParameters()); } sb.append(" void "); sb.append(methodName); sb.append("(" + GXP_SIG); for (Parameter param : params) { sb.append(", "); sb.append(parameterToCallName.apply(param)); } sb.append(")"); return sb.toString(); } private String getGetGxpClosureMethodSignature(boolean isStatic) { Iterable<Parameter> params = isStatic ? template.getAllParameters() : template.getParameters(); StringBuilder sb = new StringBuilder("public"); if (isStatic) { sb.append(" static"); if (!template.getFormalTypeParameters().isEmpty()) { sb.append(" "); } appendScalaFormalTypeParameters(sb, true, template.getFormalTypeParameters()); } sb.append(" "); sb.append(template.getSchema().getScalaType()); sb.append(" getGxpClosure("); COMMA_JOINER.appendTo(sb, Iterables.transform(params, parameterToCallName)); sb.append(")"); return sb.toString(); } protected void appendInterface() { appendLine(); appendLine("/**\n" + " * Interface that defines a strategy for writing this GXP\n" + " */"); appendAnnotations(template.getJavaAnnotations(JavaAnnotation.Element.INTERFACE)); StringBuilder sb = new StringBuilder("public interface Interface"); appendScalaFormalTypeParameters(sb, true, template.getFormalTypeParameters()); appendImplementsDeclaration(sb, template.getImplementsDeclarations()); sb.append(" {"); appendLine(sb); appendLine(getWriteMethodSignature(false) + ";"); appendLine(); appendLine(getGetGxpClosureMethodSignature(false) + ";"); for (Parameter param : template.getParameters()) { if (param.getDefaultValue() != null) { appendLine(); formatLine("%s %s();", toScalaType(param.getType()), getDefaultMethodName(param)); } } for (Parameter param : template.getParameters()) { if (param.getConstructor() != null) { appendLine(); formatLine("%s %s(String %s);", toScalaType(param.getType()), getConstructorMethodName(param), param.getPrimaryName()); } } appendLine("}"); } protected void appendInstance() { StringBuilder sb; Constructor constructor = template.getConstructor(); List<Parameter> cParams = constructor.getParameters(); appendLine(); appendLine("/**\n" + " * Instantiable instance of this GXP\n" + " */"); appendAnnotations(template.getJavaAnnotations(JavaAnnotation.Element.INSTANCE)); sb = new StringBuilder("public static class Instance"); appendScalaFormalTypeParameters(sb, true, template.getFormalTypeParameters()); sb.append(" implements Interface"); appendScalaFormalTypeParameters(sb, false, template.getFormalTypeParameters()); sb.append(" {"); appendLine(sb); for (Parameter param : cParams) { formatLine("private final %s %s;", toScalaType(param.getType()), param.getPrimaryName()); } appendLine(); appendAnnotations(constructor.getJavaAnnotations()); sb = new StringBuilder("public Instance("); COMMA_JOINER.appendTo(sb, Iterables.transform(cParams, parameterToAnnotatedCallParameter)); sb.append(") {"); appendLine(sb); for (Parameter param : cParams) { formatLine("this.%s = %s;", param.getPrimaryName(), param.getPrimaryName()); } appendLine("}"); appendLine(); appendLine(getWriteMethodSignature(false) + " {"); sb = new StringBuilder(getFullClassName(template.getName())); sb.append(".write(" + GXP_OUT_VAR + ", " + GXP_CONTEXT_VAR); for (Parameter param : template.getAllParameters()) { sb.append(", "); sb.append(paramToCallName.apply(param)); } sb.append(");"); appendLine(sb); appendLine("}"); appendGetGxpClosureMethod(false); for (Parameter param : template.getParameters()) { if (param.getDefaultValue() != null) { appendLine(); formatLine("public %s %s() {", toScalaType(param.getType()), getDefaultMethodName(param)); formatLine("return %s.%s();", getFullClassName(template.getName()), getDefaultMethodName(param)); appendLine("}"); } } for (Parameter param : template.getParameters()) { if (param.getConstructor() != null) { appendLine(); formatLine("public %s %s(String %s) {", toScalaType(param.getType()), getConstructorMethodName(param), param.getPrimaryName()); formatLine("return %s.%s(%s);", getFullClassName(template.getName()), getConstructorMethodName(param), param.getPrimaryName()); appendLine("}"); } } appendLine("}"); } } }
/* * 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.jackrabbit.oak.scalability; import joptsimple.OptionParser; import joptsimple.OptionSpec; import java.io.File; import static java.util.Arrays.asList; public class ScalabilityOptions { private final OptionSpec<File> base; private final OptionSpec<String> host; private final OptionSpec<Integer> port; private final OptionSpec<String> dbName; private final OptionSpec<Boolean> dropDBAfterTest; private final OptionSpec<String> rdbjdbcuri; private final OptionSpec<String> rdbjdbcuser; private final OptionSpec<String> rdbjdbcpasswd; private final OptionSpec<String> rdbjdbctableprefix; private final OptionSpec<Boolean> mmap; private final OptionSpec<Integer> cache; private final OptionSpec<Integer> fdsCache; private final OptionSpec<Boolean> withStorage; private final OptionSpec<Integer> coldSyncInterval; private final OptionSpec<Boolean> coldUseDataStore; private final OptionSpec<Boolean> coldShareDataStore; private final OptionSpec<Boolean> coldOneShotRun; private final OptionSpec<Boolean> coldSecure; private final OptionSpec<?> help; private final OptionSpec<String> nonOption; private final OptionSpec<File> csvFile; public OptionSpec<Integer> getColdSyncInterval() { return coldSyncInterval; } public OptionSpec<File> getBase() { return base; } public OptionSpec<String> getHost() { return host; } public OptionSpec<Integer> getPort() { return port; } public OptionSpec<String> getDbName() { return dbName; } public OptionSpec<Boolean> getDropDBAfterTest() { return dropDBAfterTest; } public OptionSpec<String> getRdbjdbcuri() { return rdbjdbcuri; } public OptionSpec<String> getRdbjdbcuser() { return rdbjdbcuser; } public OptionSpec<String> getRdbjdbcpasswd() { return rdbjdbcpasswd; } public OptionSpec<String> getRdbjdbctableprefix() { return rdbjdbctableprefix; } public OptionSpec<Boolean> getMmap() { return mmap; } public OptionSpec<Integer> getCache() { return cache; } public OptionSpec<Integer> getFdsCache() { return fdsCache; } public OptionSpec<Boolean> getWithStorage() { return withStorage; } public OptionSpec<Boolean> getColdUseDataStore() { return coldUseDataStore; } public OptionSpec<Boolean> getColdShareDataStore() { return coldShareDataStore; } public OptionSpec<Boolean> getColdOneShotRun() { return coldOneShotRun; } public OptionSpec<Boolean> getColdSecure() { return coldSecure; } public OptionSpec<?> getHelp() { return help; } public OptionSpec<String> getNonOption() { return nonOption; } public OptionSpec<File> getCsvFile() { return csvFile; } public ScalabilityOptions(OptionParser parser) { base = parser.accepts("base", "Base directory") .withRequiredArg().ofType(File.class) .defaultsTo(new File("target")); host = parser.accepts("host", "MongoDB host") .withRequiredArg().defaultsTo("localhost"); port = parser.accepts("port", "MongoDB port") .withRequiredArg().ofType(Integer.class).defaultsTo(27017); dbName = parser.accepts("db", "MongoDB database") .withRequiredArg(); dropDBAfterTest = parser.accepts("dropDBAfterTest", "Whether to drop the MongoDB database after the test") .withOptionalArg().ofType(Boolean.class).defaultsTo(true); rdbjdbcuri = parser.accepts("rdbjdbcuri", "RDB JDBC URI") .withOptionalArg().defaultsTo("jdbc:h2:./target/benchmark"); rdbjdbcuser = parser.accepts("rdbjdbcuser", "RDB JDBC user") .withOptionalArg().defaultsTo(""); rdbjdbcpasswd = parser.accepts("rdbjdbcpasswd", "RDB JDBC password") .withOptionalArg().defaultsTo(""); rdbjdbctableprefix = parser.accepts("rdbjdbctableprefix", "RDB JDBC table prefix") .withOptionalArg().defaultsTo(""); mmap = parser.accepts("mmap", "TarMK memory mapping") .withOptionalArg().ofType(Boolean.class) .defaultsTo("64".equals(System.getProperty("sun.arch.data.model"))); cache = parser.accepts("cache", "cache size (MB)") .withRequiredArg().ofType(Integer.class).defaultsTo(100); fdsCache = parser.accepts("blobCache", "cache size (MB)") .withRequiredArg().ofType(Integer.class).defaultsTo(32); withStorage = parser .accepts("storage", "Index storage enabled").withOptionalArg() .ofType(Boolean.class); csvFile = parser.accepts("csvFile", "File to write a CSV version of the benchmark data.") .withOptionalArg().ofType(File.class); coldSyncInterval = parser.accepts("coldSyncInterval", "interval between sync cycles in sec (Segment-Tar-Cold only)") .withRequiredArg().ofType(Integer.class).defaultsTo(5); coldUseDataStore = parser .accepts("useDataStore", "Whether to use a datastore in the cold standby topology (Segment-Tar-Cold only)") .withOptionalArg().ofType(Boolean.class) .defaultsTo(Boolean.TRUE); coldShareDataStore = parser .accepts("shareDataStore", "Whether to share the datastore for primary and standby in the cold standby topology (Segment-Tar-Cold only)") .withOptionalArg().ofType(Boolean.class) .defaultsTo(Boolean.FALSE); coldOneShotRun = parser .accepts("oneShotRun", "Whether to do a continuous sync between client and server or sync only once (Segment-Tar-Cold only)") .withOptionalArg().ofType(Boolean.class) .defaultsTo(Boolean.TRUE); coldSecure = parser .accepts("secure", "Whether to enable secure communication between primary and standby in the cold standby topology (Segment-Tar-Cold only)") .withOptionalArg().ofType(Boolean.class) .defaultsTo(Boolean.FALSE); help = parser.acceptsAll(asList("h", "?", "help"), "show help").forHelp(); nonOption = parser.nonOptions(); } }
/* * Copyright (c) 2017, Adam <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.api.widgets; import java.awt.Rectangle; import java.util.Collection; import net.runelite.api.FontTypeFace; import net.runelite.api.Point; /** * Represents an on-screen UI element that is drawn on the canvas. * <p> * It should be noted that most RuneLite-added elements are not Widgets, but are * an Overlay. Notable exceptions include bank tag tabs and chatbox inputs * <p> * Examples of Widgets include: * <ul> * <li>The fairy ring configuration selector</li> * <li>The mini-map</li> * <li>The bank inventory</li> * </ul> * <p> * For a more complete idea of what is classified as a widget, see {@link WidgetID}. */ public interface Widget { /** * Gets the widgets ID. * * @see WidgetID */ int getId(); /** * Gets the type of the widget. * * @see WidgetType */ int getType(); /** * Sets the type of the widget. * * @see WidgetType */ void setType(int type); /** * Gets the type of content displayed by the widget. */ int getContentType(); /** * Sets the type of content displayed by the widget. */ void setContentType(int contentType); /** * Gets the current click configuration of the widget. * @see WidgetConfig * * @see WidgetConfig */ int getClickMask(); /** * Sets the click configuration of the widget. * * @see WidgetConfig */ void setClickMask(int mask); /** * Gets the parent widget, if this widget is a child. * * @return the parent widget, or null */ Widget getParent(); /** * Gets the ID of the parent widget. * * @return the parent ID, or -1 if this widget is not a child */ int getParentId(); /** * Gets a dynamic child by index * * @throws IndexOutOfBoundsException if the index is outside of the child array */ Widget getChild(int index); /** * Gets the dynamic children of this widget in a sparse array */ Widget[] getChildren(); /** * Sets the dynamic children sparse array */ void setChildren(Widget[] children); /** * Gets all dynamic children. * * @return the dynamic children */ Widget[] getDynamicChildren(); /** * Gets all static children. * * @return the static children */ Widget[] getStaticChildren(); /** * Gets all nested children. * * @return the nested children */ Widget[] getNestedChildren(); /** * Gets the relative x-axis coordinate to the widgets parent. * * @return the relative x-axis coordinate */ int getRelativeX(); /** * Sets the relative x-axis coordinate to the widgets parent. * * You do not want to use this. Use {@link #setOriginalX(int)}, {@link #setXPositionMode(int)} * and {@link #revalidate()}. Almost any interaction with this widget from a clientscript will * recalculate this value. */ @Deprecated void setRelativeX(int x); /** * Gets the relative y-axis coordinate to the widgets parent. * * @return the relative coordinate */ int getRelativeY(); /** * Sets the relative y-axis coordinate to the widgets parent. * * You do not want to use this. Use {@link #setOriginalY(int)}, {@link #setYPositionMode(int)} * and {@link #revalidate()}. Almost any interaction with this widget from a clientscript will * recalculate this value. */ @Deprecated void setRelativeY(int y); /** * Gets the text displayed on this widget. * * @return the displayed text */ String getText(); /** * Sets the text displayed on this widget. * * @param text the text to display */ void setText(String text); /** * Gets the color as an RGB value. * * @return RGB24 color * @see java.awt.Color#getRGB() */ int getTextColor(); /** * Sets the RGB color of the displayed text or rectangle. * * @param textColor RGB24 color * @see java.awt.Color#getRGB() */ void setTextColor(int textColor); /** * Gets the transparency of the rectangle * * @return 0 = fully opaque, 255 = fully transparent */ int getOpacity(); /** * Sets the transparency of the rectangle * * @param transparency 0 = fully opaque, 255 = fully transparent */ void setOpacity(int transparency); /** * Gets the name "op base" of the widget. * <p> * The name of the widget is used in the tooltip when an action is * available. For example, the widget that activates quick prayers * has the name "Quick-prayers" so when hovering there is a tooltip * that says "Activate Quick-prayers". * * @return the name */ String getName(); /** * Sets the name of the widget. * * @param name the new name */ void setName(String name); /** * Gets the model ID displayed in the widget. * * @return the model ID */ int getModelId(); /** * Gets the sprite ID displayed in the widget. * * @return the sprite ID * @see net.runelite.api.SpriteID */ int getSpriteId(); /** * Sets the sprite ID displayed in the widget. * * @param spriteId the sprite ID * @see net.runelite.api.SpriteID */ void setSpriteId(int spriteId); /** * Checks whether this widget or any of its parents are hidden. * * This must be ran on the client thread * * @return true if this widget or any parent is hidden, false otherwise */ boolean isHidden(); /** * Checks whether this widget is hidden, not taking into account * any parent hidden states. * * @return true if this widget is hidden, false otherwise */ boolean isSelfHidden(); /** * Sets the self-hidden state of this widget. * * @param hidden new hidden state */ void setHidden(boolean hidden); /** * The index of this widget in it's parent's children array */ int getIndex(); /** * Gets the location the widget is being drawn on the canvas. * <p> * This method accounts for the relative coordinates and bounds * of any parent widgets. * * @return the upper-left coordinate of where this widget is drawn */ Point getCanvasLocation(); /** * Gets the width of the widget. * <p> * If this widget is storing any {@link WidgetItem}s, this value is * used to store the number of item slot columns. * * @return the width */ int getWidth(); /** * Sets the width of the widget. * * You do not want to use this. Use {@link #setOriginalWidth(int)}, {@link #setWidthMode(int)} * and {@link #revalidate()}. Almost any interaction with this widget from a clientscript will * recalculate this value. */ @Deprecated void setWidth(int width); /** * Gets the height of the widget. * * @return the height */ int getHeight(); /** * Sets the height of the widget. * * You do not want to use this. Use {@link #setOriginalHeight(int)}, {@link #setHeightMode(int)} * and {@link #revalidate()}. Almost any interaction with this widget from a clientscript will * recalculate this value. */ @Deprecated void setHeight(int height); /** * Gets the area where the widget is drawn on the canvas. * * @return the occupied area of the widget */ Rectangle getBounds(); /** * Gets any items that are being displayed in the widget. * * @return any items displayed, or null if there are no items */ Collection<WidgetItem> getWidgetItems(); /** * Gets a widget item at a specific index. * * @param index index of the item * @return the widget item at index, or null if an item at index * does not exist * @throws IndexOutOfBoundsException if the index is out of bounds */ WidgetItem getWidgetItem(int index); /** * Gets the item ID displayed by the widget. * * @return the item ID */ int getItemId(); /** * Sets the item ID displayed by the widget. * * @param itemId the item ID */ void setItemId(int itemId); /** * Gets the quantity of the item displayed by the widget. * * @return the item quantity */ int getItemQuantity(); /** * Sets the item quantity displayed by the widget. * * @param quantity the quantity of the item */ void setItemQuantity(int quantity); /** * Checks if the passed canvas points is inside of this widget's * {@link #getBounds() bounds} * * @param point the canvas point * @return true if this widget contains the point, false otherwise */ boolean contains(Point point); /** * Gets the amount of pixels the widget is scrolled in the X axis */ int getScrollX(); /** * Sets the amount of pixels the widget is scrolled in the X axis */ void setScrollX(int scrollX); /** * Gets the amount of pixels the widget is scrolled in the Y axis */ int getScrollY(); /** * sets the amount of pixels the widget is scrolled in the Y axis */ void setScrollY(int scrollY); /** * Gets the size of the widget's viewport in the X axis */ int getScrollWidth(); /** * Sets the size of the widget's viewport in the X axis */ void setScrollWidth(int width); /** * Gets the size of the widget's viewport in the Y axis */ int getScrollHeight(); /** * Sets the size of the widget's viewport in the Y axis */ void setScrollHeight(int height); /** * Gets the X coordinate of this widget before being adjusted by * {@link #getXPositionMode()}}. */ int getOriginalX(); /** * Sets the X input to the {@link WidgetPositionMode}. {@link #revalidate()} must be * called for the new values to take effect. * * @see #setXPositionMode(int) */ void setOriginalX(int originalX); /** * Gets the Y coordinate of this widget before being adjusted by * {@link #getYPositionMode()}} */ int getOriginalY(); /** * Sets the Y input to the {@link WidgetPositionMode}. {@link #revalidate()} must be * called for the new values to take effect. * * @see #setYPositionMode(int) */ void setOriginalY(int originalY); /** * Gets the height coordinate of this widget before being adjusted by * {@link #getHeightMode()} */ int getOriginalHeight(); /** * Sets the height input to the {@link WidgetSizeMode}. {@link #revalidate()} must be * called for the new values to take effect. * * @see #setHeightMode(int) */ void setOriginalHeight(int originalHeight); /** * Gets the width coordinate of this widget before being adjusted by * {@link #getWidthMode()} */ int getOriginalWidth(); /** * Sets the width input to the {@link WidgetSizeMode}. {@link #revalidate()} must be * called for the new values to take effect. * * @see #setWidthMode(int) */ void setOriginalWidth(int originalWidth); /** * Gets the menu options available on the widget as a sparse array. */ String[] getActions(); /** * Creates a dynamic widget child * * @param index the index of the new widget in the children list or -1 to append to the back * @param type the type of the widget */ Widget createChild(int index, int type); /** * Removes all of this widget's dynamic children */ void deleteAllChildren(); /** * Creates a menu option on the widget * * @param index The index of the menu * @param action The verb to be displayed next to the widget's name in the context menu */ void setAction(int index, String action); /** * Sets a script to be ran when the a menu action is clicked. * hasListener must be true for this to take effect * * @param args A ScriptID, then the args for the script */ void setOnOpListener(Object... args); /** * Sets a script to be ran when the dialog is canceled * * @param args A ScriptID, then the args for the script */ void setOnDialogAbortListener(Object... args); /** * Sets a script to be ran on key input * * @param args A ScriptID, then the args for the script */ void setOnKeyListener(Object... args); /** * Sets a script to be ran when the mouse enters the widget bounds * * @param args A ScriptID, then the args for the script */ void setOnMouseOverListener(Object... args); /** * Sets a script to be ran every frame when the mouse is in the widget bounds * * @param args A ScriptID, then the args for the script */ void setOnMouseRepeatListener(Object... args); /** * Sets a script to be ran when the mouse leaves the widget bounds * * @param args A ScriptID, then the args for the script */ void setOnMouseLeaveListener(Object... args); /** * Sets a script to be ran every frame * * @param args A ScriptID, then the args for the script */ void setOnTimerListener(Object... args); /** * Sets a script to be ran when the target mode has been activated for this widget * * @param args A ScriptID, then the args for the script */ void setOnTargetEnterListener(Object... args); /** * Sets a script to be ran when the target mode has been deactivated for this widget * * @param args A ScriptID, then the args for the script */ void setOnTargetLeaveListener(Object... args); /** * If this widget has any listeners on it */ boolean hasListener(); /** * Sets if the widget has any listeners. This should be called whenever a setXListener function is called */ void setHasListener(boolean hasListener); /** * This is true if the widget is from an if3 interface, or is dynamically created */ boolean isIf3(); /** * Recomputes this widget's x/y/w/h, excluding scroll */ void revalidate(); /** * Recomputes this widget's group's x/y/w/h including scroll */ void revalidateScroll(); /** * Array of widget key listeners */ Object[] getOnKeyListener(); /** * Array of widget load listeners */ Object[] getOnLoadListener(); /** * Returns the archive id of the font used * * @see net.runelite.api.FontID */ int getFontId(); /** * Sets the archive id of the font * * @see net.runelite.api.FontID */ void setFontId(int id); /** * Returns the border type of item/sprite on the widget * 0 - No border * 1 - 1px black border * 2 - 1px black under 1px white border (selected item) */ int getBorderType(); /** * @see #getBorderType */ void setBorderType(int thickness); /** * Returns if text is shadowed */ boolean getTextShadowed(); /** * Sets if text should be shadowed */ void setTextShadowed(boolean shadowed); /** * Returns the widget drag dead zone */ int getDragDeadZone(); /** * Sets the widget drag dead zone */ void setDragDeadZone(int deadZone); /** * Returns the widget drag dead time */ int getDragDeadTime(); /** * Sets the widget drag dead time */ void setDragDeadTime(int deadTime); /** * Returns widget {@link net.runelite.api.widgets.ItemQuantityMode}. */ int getItemQuantityMode(); /** * Sets the widget {@link net.runelite.api.widgets.ItemQuantityMode} */ void setItemQuantityMode(int itemQuantityMode); /** * Gets the mode that the X position is calculated from the original X position * * @see WidgetPositionMode */ int getXPositionMode(); /** * Sets the mode that the X position is calculated from the original X position. * {@link #revalidate()} must be called for new values to take effect. * * @see WidgetPositionMode */ void setXPositionMode(int xpm); /** * Gets the mode that the Y position is calculated from the original Y position * * @see WidgetPositionMode */ int getYPositionMode(); /** * Sets the mode that the Y position is calculated from the original Y position. * {@link #revalidate()} must be called for new values to take effect. * * @see WidgetPositionMode */ void setYPositionMode(int ypm); /** * Gets the X axis text position mode * * @see WidgetTextAlignment */ int getXTextAlignment(); /** * Sets the X axis text position mode * * @see WidgetTextAlignment */ void setXTextAlignment(int xta); /** * Gets the Y axis text position mode * * @see WidgetTextAlignment */ int getYTextAlignment(); /** * Sets the Y axis text position mode * * @see WidgetTextAlignment */ void setYTextAlignment(int yta); /** * Gets the mode controlling widget width * * @see WidgetSizeMode */ int getWidthMode(); /** * Sets the mode controlling widget width. * {@link #revalidate()} must be called for new values to take effect. * * @see WidgetSizeMode */ void setWidthMode(int widthMode); /** * Gets the mode controlling widget width * * @see WidgetSizeMode */ int getHeightMode(); /** * Sets the mode controlling widget width. * {@link #revalidate()} must be called for new values to take effect. * * @see WidgetSizeMode */ void setHeightMode(int heightMode); /** * Gets the font that this widget uses */ FontTypeFace getFont(); /** * Gets if the rectangle is filled or just stroked */ boolean isFilled(); /** * Sets if the rectangle is filled or just stroked */ void setFilled(boolean filled); /** * Verb for spell targets */ String getTargetVerb(); /** * Verb for spell targets */ void setTargetVerb(String targetVerb); /** * Can widgets under this widgets be clicked in this widgets bounding box */ boolean getNoClickThrough(); /** * Can widgets under this widgets be clicked in this widgets bounding box */ void setNoClickThrough(boolean noClickThrough); /** * Can widgets under this widgets be scrolled in this widgets bounding box */ boolean getNoScrollThrough(); /** * Can widgets under this widgets be scrolled in this widgets bounding box */ void setNoScrollThrough(boolean noScrollThrough); }
package org.g_node.nix; import org.bytedeco.javacpp.DoublePointer; import org.bytedeco.javacpp.Loader; import org.bytedeco.javacpp.annotation.*; import org.g_node.nix.internal.*; import org.g_node.nix.base.EntityWithSources; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.function.Predicate; /** * <h1>Tag</h1> * A tag class that defines a single point or region of interest. * <p> * Besides the {@link DataArray} the tag entities can be considered as the other * core entities of the data model. * They are meant to attach annotations directly to the data and to establish meaningful * links between different kinds of stored data. * Most importantly tags allow the definition of points or regions of interest in data * that is stored in other {@link DataArray} entities. The data array entities the * tag applies to are defined by its property {@link Tag#getReferences(Predicate)}. * <p> * Further the referenced data is defined by an origin vector called {@link Tag#getPosition()} * and an optional {@link Tag#getExtent()} vector that defines its size. * Therefore position and extent of a tag, together with the references field * defines a group of points or regions of interest collected from a subset of all * available {@link DataArray} entities. * <p> * Further tags have a field called {@link Tag#getFeatures()} which makes it possible to associate * other data with the tag. Semantically a feature of a tag is some additional data that * contains additional information about the points of hyperslabs defined by the tag. * This could be for example data that represents a stimulus (e.g. an image or a * signal) that was applied in a certain interval during the recording. * * @see DataArray * @see Feature * @see MultiTag */ @Properties(value = { @Platform(include = {"<nix/Tag.hpp>"}), @Platform(value = "linux", link = BuildLibs.NIX_1, preload = BuildLibs.HDF5_7), @Platform(value = "windows", link = BuildLibs.NIX, preload = {BuildLibs.HDF5, BuildLibs.MSVCP120, BuildLibs.MSVCR120, BuildLibs.SZIP, BuildLibs.ZLIB})}) @Namespace("nix") public class Tag extends EntityWithSources { static { Loader.load(); } //-------------------------------------------------- // Constructors //-------------------------------------------------- /** * Constructor that creates an uninitialized Tag. * <p> * Calling any method on an uninitialized Tag will throw a {@link RuntimeException} * exception. */ public Tag() { allocate(); } private native void allocate(); //-------------------------------------------------- // Base class methods //-------------------------------------------------- public native @Cast("bool") boolean isNone(); /** * Get id of the tag. * * @return ID string. */ public native @Name("id") @StdString String getId(); private native @Cast("time_t") long createdAt(); /** * Get the creation date of the tag. * * @return The creation date of the tag. */ public Date getCreatedAt() { return DateUtils.convertSecondsToDate(createdAt()); } private native @Cast("time_t") long updatedAt(); /** * Get the date of the last update. * * @return The date of the last update. */ public Date getUpdatedAt() { return DateUtils.convertSecondsToDate(updatedAt()); } /** * Sets the time of the last update to the current time if the field is not set. */ public native void setUpdatedAt(); /** * Sets the time of the last update to the current time. */ public native void forceUpdatedAt(); /** * Sets the creation time to the current time if the field is not set. */ public native void setCreatedAt(); private native void forceCreatedAt(@Cast("time_t") long time); /** * Sets the creation date to the provided value even if the attribute is set. * * @param date The creation date to set. */ public void forceCreatedAt(Date date) { forceCreatedAt(DateUtils.convertDateToSeconds(date)); } /** * Setter for the type of the tag. * * @param type The type of the tag. */ public native @Name("type") void setType(@StdString String type); /** * Getter for the type of the tag. * * @return The type of the tag. */ public native @Name("type") @StdString String getType(); /** * Getter for the name of the tag. * * @return The name of the tag. */ public native @Name("name") @StdString String getName(); private native void definition(@Const @ByVal None t); private native void definition(@StdString String definition); /** * Setter for the definition of the tag. If <tt>null</tt> is passed definition is removed. * * @param definition definition of tag. */ public void setDefinition(String definition) { if (definition != null) { definition(definition); } else { definition(new None()); } } private native @ByVal OptionalUtils.OptionalString definition(); /** * Getter for the definition of the tag. * * @return The definition of the tag. */ public String getDefinition() { OptionalUtils.OptionalString defintion = definition(); if (defintion.isPresent()) { return defintion.getString(); } return null; } private native @ByVal Section metadata(); /** * Get metadata associated with this entity. * * @return The associated section, if no such section exists <tt>null</tt> is returned. * @see Section */ public @Name("metadata") Section getMetadata() { Section section = metadata(); if (section.isNone()) { section = null; } return section; } /** * Associate the entity with some metadata. * <p> * Calling this method will replace previously stored information. * * @param metadata The {@link Section} that should be associated * with this entity. * @see Section */ public native @Name("metadata") void setMetadata(@Const @ByRef Section metadata); /** * Associate the entity with some metadata. * <p> * Calling this method will replace previously stored information. * * @param id The id of the {@link Section} that should be associated * with this entity. * @see Section */ public native @Name("metadata") void setMetadata(@StdString String id); private native void metadata(@Const @ByVal None t); /** * Removes metadata associated with the entity. * * @see Section */ public void removeMetadata() { metadata(new None()); } /** * Get the number of sources associated with this entity. * * @return The number sources. * @see Source */ public native @Name("sourceCount") long getSourceCount(); /** * Checks if a specific source is associated with this entity. * * @param id The source id to check. * @return True if the source is associated with this entity, false otherwise. * @see Source */ public native @Cast("bool") boolean hasSource(@StdString String id); /** * Checks if a specific source is associated with this entity. * * @param source The source to check. * @return True if the source is associated with this entity, false otherwise. * @see Source */ public native @Cast("bool") boolean hasSource(@Const @ByRef Source source); private native @Name("getSource") @ByVal Source fetchSource(@StdString String id); /** * Returns an associated source identified by its id. * * @param id The id of the associated source. * @see Source */ public Source getSource(String id) { Source source = fetchSource(id); if (source.isNone()) { source = null; } return source; } private native @Name("getSource") @ByVal Source fetchSource(@Cast("size_t") long index); /** * Retrieves an associated source identified by its index. * * @param index The index of the associated source. * @return The source with the given id. If it doesn't exist an exception * will be thrown. * @see Source */ public Source getSource(long index) { Source source = fetchSource(index); if (source.isNone()) { source = null; } return source; } private native @ByVal VectorUtils.SourceVector sources(); /** * Get all sources associated with this entity. * * @return All associated sources that match the given filter as a vector. * @see Source */ public List<Source> getSources() { return sources().getSources(); } private native void sources(@Const @ByRef VectorUtils.SourceVector sources); /** * Set all sources associations for this entity. * <p> * All previously existing associations will be overwritten. * * @param sources A vector with all sources. * @see Source */ public void setSources(List<Source> sources) { sources(new VectorUtils.SourceVector(sources)); } /** * Associate a new source with the entity. * <p> * If a source with the given id already is associated with the * entity, the call will have no effect. * * @param id The id of the source. * @see Source */ public native void addSource(@StdString String id); /** * Associate a new source with the entity. * <p> * Calling this method will have no effect if the source is already associated to this entity. * * @param source The source to add. * @see Source */ public native void addSource(@Const @ByRef Source source); /** * Remove a source from the list of associated sources. * <p> * This method just removes the association between the entity and the source. * The source itself will not be deleted from the file. * * @param id The id of the source to remove. * @return True if the source was removed, false otherwise. * @see Source */ public native @Cast("bool") boolean removeSource(@StdString String id); /** * Remove a source from the list of associated sources. * <p> * This method just removes the association between the entity and the source. * The source itself will not be deleted from the file. * * @param source The source to remove. * @return True if the source was removed, false otherwise. * @see Source */ public native @Cast("bool") boolean removeSource(@Const @ByRef Source source); //-------------------------------------------------- // Element getters and setters //-------------------------------------------------- private native @ByVal VectorUtils.StringVector units(); /** * Gets the units of the tag. * <p> * The units are applied to all values for position and extent in order to calculate the * right position vectors in referenced data arrays. * * @return All units of the tag as a list. */ public List<String> getUnits() { return units().getStrings(); } private native void units(@Const @ByRef VectorUtils.StringVector units); private native void units(@Const @ByVal None t); /** * Sets the units of a tag. * * @param units All units as a list. If <tt>null</tt> removes the units. */ public void setUnits(List<String> units) { if (units != null) { units(new VectorUtils.StringVector(units)); } else { units(new None()); } } private native @Name("position") @StdVector DoublePointer fetchPosition(); /** * Gets the position of a tag. * <p> * The position is a vector that points into referenced DataArrays. * * @return The position array. */ public double[] getPosition() { return VectorUtils.convertPointerToArray(fetchPosition()); } /** * Sets the position of a tag. * * @param position The position vector list. */ public native @Name("position") void setPosition(@StdVector double[] position); private native @StdVector DoublePointer extent(); /** * Gets the extent of a tag. * <p> * Given a specified position vector, the extent vector defined the size * of a region of interest in the referenced DataArray entities. * * @return The extent of the tag. */ public double[] getExtent() { return VectorUtils.convertPointerToArray(extent()); } private native void extent(@StdVector double[] extent); private native void extent(@Const @ByVal None t); /** * Sets the extent of a tag. * * @param extent The extent vector list. */ public void setExtent(double[] extent) { if (extent != null) { extent(extent); } else { extent(new None()); } } //-------------------------------------------------- // Methods concerning references. //-------------------------------------------------- /** * Checks whether a DataArray is referenced by the tag. * * @param id The id of the DataArray to check. * @return True if the data array is referenced, false otherwise. * @see DataArray */ public native @Cast("bool") boolean hasReference(@StdString String id); /** * Checks whether a DataArray is referenced by the tag. * * @param reference The DataArray to check. * @return True if the data array is referenced, false otherwise. * @see DataArray */ public native @Cast("bool") boolean hasReference(@Const @ByRef DataArray reference); /** * Gets the number of referenced DataArray entities of the tag. * * @return The number of referenced data arrays. * @see DataArray */ public native @Name("referenceCount") long getReferenceCount(); private native @Name("getReference") @ByVal DataArray fetchReference(@StdString String id); /** * Gets a specific referenced DataArray from the tag. * * @param id The id of the referenced DataArray. * @return The referenced data array. * @see DataArray */ public DataArray getReference(String id) { DataArray da = fetchReference(id); if (da.isNone()) { da = null; } return da; } private native @Name("getReference") @ByVal DataArray fetchReference(@Cast("size_t") long index); /** * Gets a referenced DataArray by its index. * * @param index The index of the DataArray. * @return The referenced data array. * @see DataArray */ public DataArray getReference(long index) { DataArray da = fetchReference(index); if (da.isNone()) { da = null; } return da; } /** * Add a DataArray to the list of referenced data of the tag. * * @param reference The DataArray to add. * @see DataArray */ public native void addReference(@Const @ByRef DataArray reference); /** * Add a DataArray to the list of referenced data of the tag. * * @param id The id of the DataArray to add. * @see DataArray */ public native void addReference(@StdString String id); /** * Remove a DataArray from the list of referenced data of the tag. * <p> * This method just removes the association between the data array and the * tag, the data array itself will not be removed from the file. * * @param reference The DataArray to remove. * @return True if the DataArray was removed, false otherwise. * @see DataArray */ public native @Cast("bool") boolean removeReference(@Const @ByRef DataArray reference); /** * Remove a DataArray from the list of referenced data of the tag. * <p> * This method just removes the association between the data array and the * tag, the data array itself will not be removed from the file. * * @param id The id of the DataArray to remove. * @return True if the DataArray was removed, false otherwise. * @see DataArray */ public native @Cast("bool") boolean removeReference(@StdString String id); private native @ByVal VectorUtils.DataArrayVector references(); /** * Get all referenced data arrays associated with this tag. * <p> * Always uses filter that accepts all sources. * * @return The filtered dimensions as a vector. * @see DataArray */ public List<DataArray> getReferences() { return references().getDataArrays(); } /** * Get referenced data arrays associated with this tag. * <p> * The parameter filter can be used to filter data arrays by various * criteria. * * @param filter A filter function. * @return A list containing the matching data arrays. * @see DataArray */ public List<DataArray> getReferences(Predicate<DataArray> filter) { List<DataArray> result = new ArrayList<>(); for (DataArray dataArray : getReferences()) { if (filter.test(dataArray)) { result.add(dataArray); } } return result; } private native void references(@Const @ByRef VectorUtils.DataArrayVector references); /** * Sets all referenced DataArray entities. * <p> * Previously referenced data arrays, that are not in the references vector * will be removed. * * @param references All referenced arrays. * @see DataArray */ public void setReferences(List<DataArray> references) { references(new VectorUtils.DataArrayVector(references)); } //-------------------------------------------------- // Methods concerning features. //-------------------------------------------------- /** * Checks if a specific feature exists on the tag. * * @param id The id of a feature. * @return True if the feature exists, false otherwise. * @see Feature */ public native @Cast("bool") boolean hasFeature(@StdString String id); /** * Checks if a specific feature exists on the tag. * * @param feature The Feature to check. * @return True if the feature exists, false otherwise. * @see Feature */ public native @Cast("bool") boolean hasFeature(@Const @ByRef Feature feature); /** * Gets the number of features in this block. * * @return The number of features. * @see Feature */ public native @Name("featureCount") long getFeatureCount(); private native @Name("getFeature") @ByVal Feature fetchFeature(@StdString String id); /** * Retrieves a specific feature from the tag. * * @param id The id of the feature. * @return The feature with the specified id. If it doesn't exist * an exception will be thrown. * @see Feature */ public Feature getFeature(String id) { Feature feature = fetchFeature(id); if (feature.isNone()) { feature = null; } return feature; } private native @Name("getFeature") @ByVal Feature fetchFeature(@Cast("size_t") long index); /** * Retrieves a specific feature from the tag. * * @param index The index of the feature. * @return The feature with the specified index. * @see Feature */ public Feature getFeature(long index) { Feature feature = fetchFeature(index); if (feature.isNone()) { feature = null; } return feature; } private native @ByVal VectorUtils.FeatureVector features(); /** * Get all Features of this tag. * * @return A vector containing the matching features. * @see Feature */ public List<Feature> getFeatures() { return features().getFeatures(); } /** * Get all Features of this tag. * <p> * The parameter filter can be used to filter features by various * criteria. * * @param filter A filter function. * @return A list containing the matching features. * @see Feature */ public List<Feature> getFeatures(Predicate<Feature> filter) { List<Feature> result = new ArrayList<>(); for (Feature feature : getFeatures()) { if (filter.test(feature)) { result.add(feature); } } return result; } private native @Name("createFeature") @ByVal Feature makeFeature(@Const @ByRef DataArray data, @Cast("nix::LinkType") int linkType); /** * Create a new feature. * * @param data The data array of this feature. * @param linkType The link type of this feature. * @return The created feature object. * @see Feature */ public Feature createFeature(DataArray data, int linkType) { Feature feature = makeFeature(data, linkType); if (feature.isNone()) { feature = null; } return feature; } private native @Name("createFeature") @ByVal Feature makeFeature(@StdString String dataArrayId, @Cast("nix::LinkType") int linkType); /** * Create a new feature. * * @param dataArrayId The id of the data array of this feature. * @param linkType The link type of this feature. * @return The created feature object. * @see Feature */ public Feature createFeature(String dataArrayId, int linkType) { Feature feature = makeFeature(dataArrayId, linkType); if (feature.isNone()) { feature = null; } return feature; } /** * Deletes a feature from the tag. * * @param id The id of the feature to remove. * @return True if the feature was removed, false otherwise. * @see Feature */ public native @Cast("bool") boolean deleteFeature(@StdString String id); /** * Deletes a feature from the tag. * * @param feature The feature to remove. * @return True if the feature was removed, false otherwise. * @see Feature */ public native @Cast("bool") boolean deleteFeature(@Const @ByRef Feature feature); //-------------------------------------------------- // Methods for data retrieval //-------------------------------------------------- /** * Returns the data associated with a certain reference. * * @param referenceIndex The index of the reference of which * the data should be returned. * @return the data * @see DataView */ public native @ByVal DataView retrieveData(@Cast("size_t") long referenceIndex); /** * Returns the data stored in the selected Feature. * * @param featureIndex The index of the requested feature. * @return The data stored in the Feature. * @see DataView */ public native @ByVal DataView retrieveFeatureData(@Cast("size_t") long featureIndex); //-------------------------------------------------- // Overrides //-------------------------------------------------- @Override public String toString() { return "Tag: {name = " + this.getName() + ", type = " + this.getType() + ", id = " + this.getId() + "}"; } }
/* * 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.accumulo.core.security; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.TreeSet; import org.apache.accumulo.core.data.ArrayByteSequence; import org.apache.accumulo.core.data.ByteSequence; import org.apache.accumulo.core.util.BadArgumentException; import org.apache.accumulo.core.util.TextUtil; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparator; /** * Validate the column visibility is a valid expression and set the visibility for a Mutation. See {@link ColumnVisibility#ColumnVisibility(byte[])} for the * definition of an expression. */ public class ColumnVisibility { Node node = null; private byte[] expression; /** * Accessor for the underlying byte string. * * @return byte array representation of a visibility expression */ public byte[] getExpression() { return expression; } /** * The node types in a parse tree for a visibility expression. */ public static enum NodeType { EMPTY, TERM, OR, AND, } /** * All empty nodes are equal and represent the same value. */ private static final Node EMPTY_NODE = new Node(NodeType.EMPTY, 0); /** * A node in the parse tree for a visibility expression. */ public static class Node { /** * An empty list of nodes. */ public final static List<Node> EMPTY = Collections.emptyList(); NodeType type; int start; int end; List<Node> children = EMPTY; public Node(NodeType type, int start) { this.type = type; this.start = start; this.end = start + 1; } public Node(int start, int end) { this.type = NodeType.TERM; this.start = start; this.end = end; } public void add(Node child) { if (children == EMPTY) children = new ArrayList<Node>(); children.add(child); } public NodeType getType() { return type; } public List<Node> getChildren() { return children; } public int getTermStart() { return start; } public int getTermEnd() { return end; } public ByteSequence getTerm(byte expression[]) { if (type != NodeType.TERM) throw new RuntimeException(); if (expression[start] == '"') { // its a quoted term int qStart = start + 1; int qEnd = end - 1; return new ArrayByteSequence(expression, qStart, qEnd - qStart); } return new ArrayByteSequence(expression, start, end - start); } } /** * A node comparator. Nodes sort according to node type, terms sort * lexicographically. AND and OR nodes sort by number of children, or if * the same by corresponding children. */ public static class NodeComparator implements Comparator<Node>, Serializable { private static final long serialVersionUID = 1L; byte[] text; /** * Creates a new comparator. * * @param text expression string, encoded in UTF-8 */ public NodeComparator(byte[] text) { this.text = text; } @Override public int compare(Node a, Node b) { int diff = a.type.ordinal() - b.type.ordinal(); if (diff != 0) return diff; switch (a.type) { case EMPTY: return 0; // All empty nodes are the same case TERM: return WritableComparator.compareBytes(text, a.start, a.end - a.start, text, b.start, b.end - b.start); case OR: case AND: diff = a.children.size() - b.children.size(); if (diff != 0) return diff; for (int i = 0; i < a.children.size(); i++) { diff = compare(a.children.get(i), b.children.get(i)); if (diff != 0) return diff; } } return 0; } } /* * Convience method that delegates to normalize with a new NodeComparator constructed using the supplied expression. */ public static Node normalize(Node root, byte[] expression) { return normalize(root, expression, new NodeComparator(expression)); } // @formatter:off /* * Walks an expression's AST in order to: * 1) roll up expressions with the same operant (`a&(b&c) becomes a&b&c`) * 2) sorts labels lexicographically (permutations of `a&b&c` are re-ordered to appear as `a&b&c`) * 3) dedupes labels (`a&b&a` becomes `a&b`) */ // @formatter:on public static Node normalize(Node root, byte[] expression, NodeComparator comparator) { if (root.type != NodeType.TERM) { TreeSet<Node> rolledUp = new TreeSet<Node>(comparator); java.util.Iterator<Node> itr = root.children.iterator(); while (itr.hasNext()) { Node c = normalize(itr.next(), expression, comparator); if (c.type == root.type) { rolledUp.addAll(c.children); itr.remove(); } } rolledUp.addAll(root.children); root.children.clear(); root.children.addAll(rolledUp); // need to promote a child if it's an only child if (root.children.size() == 1) { return root.children.get(0); } } return root; } /* * Walks an expression's AST and appends a string representation to a supplied StringBuilder. This method adds parens where necessary. */ public static void stringify(Node root, byte[] expression, StringBuilder out) { if (root.type == NodeType.TERM) { out.append(new String(expression, root.start, root.end - root.start, StandardCharsets.UTF_8)); } else { String sep = ""; for (Node c : root.children) { out.append(sep); boolean parens = (c.type != NodeType.TERM && root.type != c.type); if (parens) out.append("("); stringify(c, expression, out); if (parens) out.append(")"); sep = root.type == NodeType.AND ? "&" : "|"; } } } /** * Generates a byte[] that represents a normalized, but logically equivalent, form of this evaluator's expression. * * @return normalized expression in byte[] form */ public byte[] flatten() { Node normRoot = normalize(node, expression); StringBuilder builder = new StringBuilder(expression.length); stringify(normRoot, expression, builder); return builder.toString().getBytes(StandardCharsets.UTF_8); } private static class ColumnVisibilityParser { private int index = 0; private int parens = 0; public ColumnVisibilityParser() {} Node parse(byte[] expression) { if (expression.length > 0) { Node node = parse_(expression); if (node == null) { throw new BadArgumentException("operator or missing parens", new String(expression, StandardCharsets.UTF_8), index - 1); } if (parens != 0) { throw new BadArgumentException("parenthesis mis-match", new String(expression, StandardCharsets.UTF_8), index - 1); } return node; } return null; } Node processTerm(int start, int end, Node expr, byte[] expression) { if (start != end) { if (expr != null) throw new BadArgumentException("expression needs | or &", new String(expression, StandardCharsets.UTF_8), start); return new Node(start, end); } if (expr == null) throw new BadArgumentException("empty term", new String(expression, StandardCharsets.UTF_8), start); return expr; } Node parse_(byte[] expression) { Node result = null; Node expr = null; int wholeTermStart = index; int subtermStart = index; boolean subtermComplete = false; while (index < expression.length) { switch (expression[index++]) { case '&': { expr = processTerm(subtermStart, index - 1, expr, expression); if (result != null) { if (!result.type.equals(NodeType.AND)) throw new BadArgumentException("cannot mix & and |", new String(expression, StandardCharsets.UTF_8), index - 1); } else { result = new Node(NodeType.AND, wholeTermStart); } result.add(expr); expr = null; subtermStart = index; subtermComplete = false; break; } case '|': { expr = processTerm(subtermStart, index - 1, expr, expression); if (result != null) { if (!result.type.equals(NodeType.OR)) throw new BadArgumentException("cannot mix | and &", new String(expression, StandardCharsets.UTF_8), index - 1); } else { result = new Node(NodeType.OR, wholeTermStart); } result.add(expr); expr = null; subtermStart = index; subtermComplete = false; break; } case '(': { parens++; if (subtermStart != index - 1 || expr != null) throw new BadArgumentException("expression needs & or |", new String(expression, StandardCharsets.UTF_8), index - 1); expr = parse_(expression); subtermStart = index; subtermComplete = false; break; } case ')': { parens--; Node child = processTerm(subtermStart, index - 1, expr, expression); if (child == null && result == null) throw new BadArgumentException("empty expression not allowed", new String(expression, StandardCharsets.UTF_8), index); if (result == null) return child; if (result.type == child.type) for (Node c : child.children) result.add(c); else result.add(child); result.end = index - 1; return result; } case '"': { if (subtermStart != index - 1) throw new BadArgumentException("expression needs & or |", new String(expression, StandardCharsets.UTF_8), index - 1); while (index < expression.length && expression[index] != '"') { if (expression[index] == '\\') { index++; if (expression[index] != '\\' && expression[index] != '"') throw new BadArgumentException("invalid escaping within quotes", new String(expression, StandardCharsets.UTF_8), index - 1); } index++; } if (index == expression.length) throw new BadArgumentException("unclosed quote", new String(expression, StandardCharsets.UTF_8), subtermStart); if (subtermStart + 1 == index) throw new BadArgumentException("empty term", new String(expression, StandardCharsets.UTF_8), subtermStart); index++; subtermComplete = true; break; } default: { if (subtermComplete) throw new BadArgumentException("expression needs & or |", new String(expression, StandardCharsets.UTF_8), index - 1); byte c = expression[index - 1]; if (!Authorizations.isValidAuthChar(c)) throw new BadArgumentException("bad character (" + c + ")", new String(expression, StandardCharsets.UTF_8), index - 1); } } } Node child = processTerm(subtermStart, index, expr, expression); if (result != null) { result.add(child); result.end = index; } else result = child; if (result.type != NodeType.TERM) if (result.children.size() < 2) throw new BadArgumentException("missing term", new String(expression, StandardCharsets.UTF_8), index); return result; } } private void validate(byte[] expression) { if (expression != null && expression.length > 0) { ColumnVisibilityParser p = new ColumnVisibilityParser(); node = p.parse(expression); } else { node = EMPTY_NODE; } this.expression = expression; } /** * Creates an empty visibility. Normally, elements with empty visibility can be seen by everyone. Though, one could change this behavior with filters. * * @see #ColumnVisibility(String) */ public ColumnVisibility() { this(new byte[] {}); } /** * Creates a column visibility for a Mutation. * * @param expression * An expression of the rights needed to see this mutation. The expression is a sequence of characters from the set [A-Za-z0-9_-] along with the * binary operators "&amp;" and "|" indicating that both operands are necessary, or that either is necessary. The following are valid expressions for * visibility: * * <pre> * A * A|B * (A|B)&amp;(C|D) * orange|(red&amp;yellow) * * </pre> * * <P> * The following are not valid expressions for visibility: * * <pre> * A|B&amp;C * A=B * A|B| * A&amp;|B * () * ) * dog|!cat * </pre> * * <P> * You can use any character you like in your column visibility expression with quoting. If your quoted term contains '&quot;' or '\' then escape * them with '\'. The {@link #quote(String)} method will properly quote and escape terms for you. * * <pre> * &quot;A#C&quot;<span />&amp;<span />B * </pre> * */ public ColumnVisibility(String expression) { this(expression.getBytes(StandardCharsets.UTF_8)); } /** * Creates a column visibility for a Mutation. * * @param expression visibility expression * @see #ColumnVisibility(String) */ public ColumnVisibility(Text expression) { this(TextUtil.getBytes(expression)); } /** * Creates a column visibility for a Mutation from a string already encoded in UTF-8 bytes. * * @param expression visibility expression, encoded as UTF-8 bytes * @see #ColumnVisibility(String) */ public ColumnVisibility(byte[] expression) { validate(expression); } @Override public String toString() { return "[" + new String(expression, StandardCharsets.UTF_8) + "]"; } /** * See {@link #equals(ColumnVisibility)} */ @Override public boolean equals(Object obj) { if (obj instanceof ColumnVisibility) return equals((ColumnVisibility) obj); return false; } /** * Compares two ColumnVisibilities for string equivalence, not as a meaningful comparison of terms and conditions. * * @param otherLe other column visibility * @return true if this visibility equals the other via string comparison */ public boolean equals(ColumnVisibility otherLe) { return Arrays.equals(expression, otherLe.expression); } @Override public int hashCode() { return Arrays.hashCode(expression); } /** * Gets the parse tree for this column visibility. * * @return parse tree node */ public Node getParseTree() { return node; } /** * Properly quotes terms in a column visibility expression. If no quoting is needed, then nothing is done. * * <p> * Examples of using quote : * * <pre> * import static org.apache.accumulo.core.security.ColumnVisibility.quote; * . * . * . * ColumnVisibility cv = new ColumnVisibility(quote(&quot;A#C&quot;) + &quot;&amp;&quot; + quote(&quot;FOO&quot;)); * </pre> * * @param term term to quote * @return quoted term (unquoted if unnecessary) */ public static String quote(String term) { return new String(quote(term.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); } /** * Properly quotes terms in a column visibility expression. If no quoting is needed, then nothing is done. * * @param term term to quote, encoded as UTF-8 bytes * @return quoted term (unquoted if unnecessary), encoded as UTF-8 bytes * @see #quote(String) */ public static byte[] quote(byte[] term) { boolean needsQuote = false; for (int i = 0; i < term.length; i++) { if (!Authorizations.isValidAuthChar(term[i])) { needsQuote = true; break; } } if (!needsQuote) return term; return VisibilityEvaluator.escape(term, true); } }
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.metrics; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.management.AttributeNotFoundException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.ReflectionException; import com.yammer.metrics.stats.Snapshot; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.hbase.metrics.histogram.MetricsHistogram; import org.apache.hadoop.metrics.util.MetricsBase; import org.apache.hadoop.metrics.util.MetricsDynamicMBeanBase; import org.apache.hadoop.metrics.util.MetricsRegistry; /** * Extends the Hadoop MetricsDynamicMBeanBase class to provide JMX support for * custom HBase MetricsBase implementations. MetricsDynamicMBeanBase ignores * registered MetricsBase instance that are not instances of one of the * org.apache.hadoop.metrics.util implementations. * */ @Deprecated @InterfaceAudience.Private public class MetricsMBeanBase extends MetricsDynamicMBeanBase { private static final Log LOG = LogFactory.getLog("org.apache.hadoop.hbase.metrics"); protected final MetricsRegistry registry; protected final String description; protected int registryLength; /** HBase MetricsBase implementations that MetricsDynamicMBeanBase does * not understand */ protected Map<String, MetricsBase> extendedAttributes = new ConcurrentHashMap<String, MetricsBase>(); protected MBeanInfo extendedInfo; protected MetricsMBeanBase( MetricsRegistry mr, String description ) { super(copyMinusHBaseMetrics(mr), description); this.registry = mr; this.description = description; this.init(); } /* * @param mr MetricsRegistry. * @return A copy of the passed MetricsRegistry minus the hbase metrics */ private static MetricsRegistry copyMinusHBaseMetrics(final MetricsRegistry mr) { MetricsRegistry copy = new MetricsRegistry(); for (MetricsBase metric : mr.getMetricsList()) { if (metric instanceof MetricsRate || metric instanceof MetricsString || metric instanceof MetricsHistogram || metric instanceof ExactCounterMetric) { continue; } copy.add(metric.getName(), metric); } return copy; } protected void init() { List<MBeanAttributeInfo> attributes = new ArrayList<MBeanAttributeInfo>(); MBeanInfo parentInfo = super.getMBeanInfo(); List<String> parentAttributes = new ArrayList<String>(); for (MBeanAttributeInfo attr : parentInfo.getAttributes()) { attributes.add(attr); parentAttributes.add(attr.getName()); } this.registryLength = this.registry.getMetricsList().size(); for (MetricsBase metric : this.registry.getMetricsList()) { if (metric.getName() == null || parentAttributes.contains(metric.getName())) continue; // add on custom HBase metric types if (metric instanceof MetricsRate) { attributes.add( new MBeanAttributeInfo(metric.getName(), "java.lang.Float", metric.getDescription(), true, false, false) ); extendedAttributes.put(metric.getName(), metric); } else if (metric instanceof MetricsString) { attributes.add( new MBeanAttributeInfo(metric.getName(), "java.lang.String", metric.getDescription(), true, false, false) ); extendedAttributes.put(metric.getName(), metric); LOG.info("MetricsString added: " + metric.getName()); } else if (metric instanceof MetricsHistogram) { String metricName = metric.getName() + MetricsHistogram.NUM_OPS_METRIC_NAME; attributes.add(new MBeanAttributeInfo(metricName, "java.lang.Long", metric.getDescription(), true, false, false)); extendedAttributes.put(metricName, metric); metricName = metric.getName() + MetricsHistogram.MIN_METRIC_NAME; attributes.add(new MBeanAttributeInfo(metricName, "java.lang.Long", metric.getDescription(), true, false, false)); extendedAttributes.put(metricName, metric); metricName = metric.getName() + MetricsHistogram.MAX_METRIC_NAME; attributes.add(new MBeanAttributeInfo(metricName, "java.lang.Long", metric.getDescription(), true, false, false)); extendedAttributes.put(metricName, metric); metricName = metric.getName() + MetricsHistogram.MEAN_METRIC_NAME; attributes.add(new MBeanAttributeInfo(metricName, "java.lang.Float", metric.getDescription(), true, false, false)); extendedAttributes.put(metricName, metric); metricName = metric.getName() + MetricsHistogram.STD_DEV_METRIC_NAME; attributes.add(new MBeanAttributeInfo(metricName, "java.lang.Float", metric.getDescription(), true, false, false)); extendedAttributes.put(metricName, metric); metricName = metric.getName() + MetricsHistogram.MEDIAN_METRIC_NAME; attributes.add(new MBeanAttributeInfo(metricName, "java.lang.Float", metric.getDescription(), true, false, false)); extendedAttributes.put(metricName, metric); metricName = metric.getName() + MetricsHistogram.SEVENTY_FIFTH_PERCENTILE_METRIC_NAME; attributes.add(new MBeanAttributeInfo(metricName, "java.lang.Float", metric.getDescription(), true, false, false)); extendedAttributes.put(metricName, metric); metricName = metric.getName() + MetricsHistogram.NINETY_FIFTH_PERCENTILE_METRIC_NAME; attributes.add(new MBeanAttributeInfo(metricName, "java.lang.Float", metric.getDescription(), true, false, false)); extendedAttributes.put(metricName, metric); metricName = metric.getName() + MetricsHistogram.NINETY_NINETH_PERCENTILE_METRIC_NAME; attributes.add(new MBeanAttributeInfo(metricName, "java.lang.Float", metric.getDescription(), true, false, false)); extendedAttributes.put(metricName, metric); } // else, its probably a hadoop metric already registered. Skip it. } LOG.info("new MBeanInfo"); this.extendedInfo = new MBeanInfo( this.getClass().getName(), this.description, attributes.toArray( new MBeanAttributeInfo[0] ), parentInfo.getConstructors(), parentInfo.getOperations(), parentInfo.getNotifications() ); } private void checkAndUpdateAttributes() { if (this.registryLength != this.registry.getMetricsList().size()) this.init(); } @Override public Object getAttribute( String name ) throws AttributeNotFoundException, MBeanException, ReflectionException { if (name == null) { throw new IllegalArgumentException("Attribute name is NULL"); } /* * Ugly. Since MetricsDynamicMBeanBase implementation is private, * we need to first check the parent class for the attribute. * In case that the MetricsRegistry contents have changed, this will * allow the parent to update it's internal structures (which we rely on * to update our own. */ try { return super.getAttribute(name); } catch (AttributeNotFoundException ex) { checkAndUpdateAttributes(); MetricsBase metric = this.extendedAttributes.get(name); if (metric != null) { if (metric instanceof MetricsRate) { return ((MetricsRate) metric).getPreviousIntervalValue(); } else if (metric instanceof MetricsString) { return ((MetricsString)metric).getValue(); } else if (metric instanceof MetricsHistogram) { MetricsHistogram hist = (MetricsHistogram) metric; if (name.endsWith(MetricsHistogram.NUM_OPS_METRIC_NAME)) { return hist.getCount(); } else if (name.endsWith(MetricsHistogram.MIN_METRIC_NAME)) { return hist.getMin(); } else if (name.endsWith(MetricsHistogram.MAX_METRIC_NAME)) { return hist.getMax(); } else if (name.endsWith(MetricsHistogram.MEAN_METRIC_NAME)) { return (float) hist.getMean(); } else if (name.endsWith(MetricsHistogram.STD_DEV_METRIC_NAME)) { return (float) hist.getStdDev(); } else if (name.endsWith(MetricsHistogram.MEDIAN_METRIC_NAME)) { Snapshot s = hist.getSnapshot(); return (float) s.getMedian(); } else if (name.endsWith(MetricsHistogram.SEVENTY_FIFTH_PERCENTILE_METRIC_NAME)) { Snapshot s = hist.getSnapshot(); return (float) s.get75thPercentile(); } else if (name.endsWith(MetricsHistogram.NINETY_FIFTH_PERCENTILE_METRIC_NAME)) { Snapshot s = hist.getSnapshot(); return (float) s.get95thPercentile(); } else if (name.endsWith(MetricsHistogram.NINETY_NINETH_PERCENTILE_METRIC_NAME)) { Snapshot s = hist.getSnapshot(); return (float) s.get99thPercentile(); } } else { LOG.warn( String.format("unknown metrics type %s for attribute %s", metric.getClass().getName(), name) ); } } } throw new AttributeNotFoundException(); } @Override public MBeanInfo getMBeanInfo() { return this.extendedInfo; } }
// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.cloudera.recordservice.hive; import java.util.List; import java.util.Map; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.StructField; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.hadoop.hive.serde2.typeinfo.CharTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory; import org.apache.hadoop.hive.serde2.typeinfo.VarcharTypeInfo; import com.cloudera.recordservice.mr.RecordServiceRecord; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * Object Inspector for rows (structs) in a format returned by the RecordService. * A key responsibility of the object inspector is to extract column values from * a row, mapping them back to Hive column names. * ObjectInspectors are hierarchical - There is an object inspector for a row (or struct) * and each column (field) has its own object inspector. For complex types, struct * object inspectors are used for inspecting fields with struct data types as well as * rows. * TODO: Complex types are NYI. Support Decimal. */ public class RecordServiceObjectInspector extends StructObjectInspector { // List of all fields in the table. private final List<RecordServiceStructField> fields_; // Map of column name to field metadata. private final Map<String, RecordServiceStructField> fieldsByName_; public RecordServiceObjectInspector(StructTypeInfo rowTypeInfo) { List<String> fieldNames = rowTypeInfo.getAllStructFieldNames(); fields_ = Lists.newArrayListWithExpectedSize(fieldNames.size()); fieldsByName_ = Maps.newHashMap(); for (int fieldIdx = 0; fieldIdx < fieldNames.size(); ++fieldIdx) { final String name = fieldNames.get(fieldIdx); final TypeInfo fieldInfo = rowTypeInfo.getAllStructFieldTypeInfos().get(fieldIdx); RecordServiceStructField fieldImpl = new RecordServiceStructField(name, getFieldObjectInspector(fieldInfo), fieldIdx); fields_.add(fieldImpl); fieldsByName_.put(name.toLowerCase(), fieldImpl); } } /** * Given a Hive column type, returns the ObjectInspector that will be used to * get data from the field. Currently using the the standard Writable object * inspectors. * TODO: Support all types */ private ObjectInspector getFieldObjectInspector(final TypeInfo typeInfo) { if (typeInfo.equals(TypeInfoFactory.doubleTypeInfo)) { return PrimitiveObjectInspectorFactory.writableDoubleObjectInspector; } else if (typeInfo.equals(TypeInfoFactory.booleanTypeInfo)) { return PrimitiveObjectInspectorFactory.writableBooleanObjectInspector; } else if (typeInfo.equals(TypeInfoFactory.floatTypeInfo)) { return PrimitiveObjectInspectorFactory.writableFloatObjectInspector; } else if (typeInfo.equals(TypeInfoFactory.intTypeInfo)) { return PrimitiveObjectInspectorFactory.writableIntObjectInspector; } else if (typeInfo.equals(TypeInfoFactory.longTypeInfo)) { return PrimitiveObjectInspectorFactory.writableLongObjectInspector; } else if (typeInfo.equals(TypeInfoFactory.stringTypeInfo)) { return PrimitiveObjectInspectorFactory.writableStringObjectInspector; } else if (typeInfo instanceof DecimalTypeInfo) { return PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector( (DecimalTypeInfo) typeInfo); } else if (typeInfo instanceof VarcharTypeInfo) { return PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector( (VarcharTypeInfo) typeInfo); } else if (typeInfo instanceof CharTypeInfo) { return PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector( (CharTypeInfo) typeInfo); } else { throw new UnsupportedOperationException("Unknown field type: " + typeInfo); } } /** * Given a field name, returns the StructField. Not performance critical. */ @Override public StructField getStructFieldRef(String fieldName) { return fieldsByName_.get(fieldName.toLowerCase()); } /** * Given a field reference, return the data for the specified row. * This is on the hot path. It is called once for every column in the schema * for every row. * TODO: Make this more performant. */ @Override public Object getStructFieldData(Object recordData, StructField fieldRef) { if (recordData == null) return null; RecordServiceStructField field = (RecordServiceStructField) fieldRef; // If this field is not selected in the projection, return null. if (!field.isProjected()) return null; RecordServiceRecord record = (RecordServiceRecord) recordData; // Only initialize the projection index if it has not yet been set because // this is expensive. if (!field.isProjectedColIdxSet()) { int colIdx = record.getSchema().getColIdxFromColName(fieldRef.getFieldName()); field.setProjectedColIdx(colIdx); if (!field.isProjected()) return null; } return record.getColumnValue(field.getProjectedIdx()); } @Override public List<Object> getStructFieldsDataAsList(Object data) { throw new UnsupportedOperationException("Not Yet Implemented."); } /** * Returns all the fields for this record. */ @Override public List<? extends StructField> getAllStructFieldRefs() { return fields_; } @Override public String getTypeName() { return TypeInfo.class.getName(); } @Override public Category getCategory() { return Category.STRUCT; } /** * A description of a field in of a row in RecordService format (similar to the * RecordService's TColumnDesc. Also contains the object inspector that will be * used to extract the value from this column in a record. */ static class RecordServiceStructField implements StructField { private final String fieldName_; private final ObjectInspector inspector_; // The index of this field in the struct (may not be the same as the index // of the field in the RecordService schema). private final int fieldIdx_; // The index of this field in a projection. -1 if not set or if not records // have been received from the RecordService. Will not be set for metadata only // operations (ie DESCRIBE TABLE). private int projectedColIdx_ = -1; boolean isProjectedColIdxSet_ = false; public RecordServiceStructField(final String fieldName, final ObjectInspector inspector, final int fieldIndex) { fieldName_ = fieldName; inspector_ = inspector; fieldIdx_ = fieldIndex; } public int getProjectedIdx() { return projectedColIdx_; } /** * Sets the projected column index. Can only be called once. */ public void setProjectedColIdx(int projectedColIdx) { Preconditions.checkState(!isProjectedColIdxSet_); isProjectedColIdxSet_ = true; projectedColIdx_ = projectedColIdx; } public boolean isProjectedColIdxSet() { return isProjectedColIdxSet_; } /** * Returns true if this column is selected as part of the projection * or if it is unknown whether the column is projected (setProjectedColIdx * has not been called). */ public boolean isProjected() { return !isProjectedColIdxSet_ || projectedColIdx_ >= 0; } @Override public String getFieldComment() { return ""; } @Override public String getFieldName() { return fieldName_; } @Override public ObjectInspector getFieldObjectInspector() { return inspector_; } @Override public int getFieldID() { return fieldIdx_; } } @Override public boolean equals(Object o) { if (o == null || o.getClass() != getClass()) { return false; } else if (o == this) { return true; } else { List<RecordServiceStructField> other = ((RecordServiceObjectInspector) o).fields_; if (other.size() != fields_.size()) { return false; } for(int i = 0; i < fields_.size(); ++i) { StructField left = other.get(i); StructField right = fields_.get(i); if (!(left.getFieldName().equals(right.getFieldName()) && left.getFieldObjectInspector().equals (right.getFieldObjectInspector()))) { return false; } } return true; } } }